Compare commits

...
41 Commits
Author SHA1 Message Date
Seth eba3c3bf0c Add the v3.2.7 changelog entry for the macOS fixes and set the version
AI Assisted
2026-12-05 00:24:11 -08:00
Seth ec45430eda Stop each console before its assert in the pointer test, so a failing run leaves no server up
AI Assisted
2026-12-05 00:10:45 -08:00
Seth 615e98e11e Fail the macOS smoke run when the dashboard frame never connects, and update the checklist
AI Assisted
2026-12-05 00:10:45 -08:00
Seth a9e0bf49f0 Drop the nothing-changed-yet line from Quick task's post-build review cards
AI Assisted
2026-12-05 00:10:45 -08:00
Seth 31edc2d5c9 Stack User Preferences' card width choices two to a row when the dialog is narrow
AI Assisted
2026-12-05 00:10:45 -08:00
Seth 8b5932c351 Forget the old console on a project switch, so its end never covers what shows next
AI Assisted
2026-12-05 00:10:45 -08:00
Seth 59d226c2a6 Show the app's icon in the macOS Dock and bring its window to the front
AI Assisted
2026-12-05 00:10:45 -08:00
Seth ddbc85f73d Tell a failed macOS folder picker from a cancel, and start Browse at a folder that exists
AI Assisted
2026-12-05 00:10:45 -08:00
Seth 91479b21a1 Let Ctrl+V reach the agent on macOS, and leave Cmd+V to the webview's own paste
AI Assisted
2026-12-05 00:10:45 -08:00
Seth b629f5ef04 Ask the login shell for PATH first, then its interactive config only if a tool is missing
AI Assisted
2026-12-05 00:10:44 -08:00
Seth 8c028c1ce0 Run the quit cleanup on a plain kill, Ctrl+C and a closing terminal
AI Assisted
2026-12-05 00:10:44 -08:00
Seth 6a93395148 End the agent's process group and the consoles it opened on every quit
AI Assisted
2026-12-05 00:10:44 -08:00
Seth 98bdbc97c3 Sign the macOS app's dashboard frame in by a path prefix, since WebKit gives it no cookie
AI Assisted
2026-12-05 00:10:44 -08:00
Seth 1d007737b1 Make every URL the console page uses page-relative, guarded by a source test
AI Assisted
2026-12-05 00:10:44 -08:00
Seth 4ced32be5c Send the page-closed signal as a keepalive fetch, since WebKit's beacon carries Origin: null
AI Assisted
2026-12-05 00:10:44 -08:00
jparkerweb 603c871720 Merge pull request #22 from jparkerweb/sync/upstream-v3.2.6
Sync upstream v3.2.6: Loop checkboxes, Notes drag handle, US English replies
2026-12-04 22:36:13 -08:00
jparkerweb 658c813428 Sync upstream v3.2.6: Loop checkboxes, Notes drag handle, US English replies, app update fetch (v3.2.6)
- Implement's and Review's confirm panes carry a Loop checkbox in place of
  the dashboard's loop cards; loop end-screen buttons show a spinner.
- The stacked Notes panel gets a drag handle.
- Every skill prompt and the console contracts say to reply in US English.
- The desktop app offers Update to latest when the skills are newer, and
  plan2code update refetches an app that install.json does not record.
- Devin Balanced maps to Sonnet 5.5 Medium.
2026-12-04 22:35:28 -08:00
jparkerweb 9629961f36 Merge pull request #21 from jparkerweb/fix/install-refs-v3.2.5
Publish the slim install refs: drop the prepare script, carry LICENSE and NOTICE (v3.2.5)
2026-12-04 06:48:46 -08:00
jparkerweb a03b825951 Publish the slim install refs: drop the prepare script, carry LICENSE and NOTICE (v3.2.5)
AI Assisted
2026-12-03 20:36:09 -08:00
jparkerweb 44434d5264 Merge pull request #20 from jparkerweb/sync/upstream-v3.2.4
Sync upstream v3.2.4: slim install refs and a crash-safe installer
2026-12-03 19:23:44 -08:00
jparkerweb f997a82c4d Sync upstream v3.2.4: slim install refs, a crash-safe installer, Change project restarts the agent (v3.2.4)
AI Assisted
2026-12-03 15:17:47 -08:00
jparkerweb 50319aa332 Merge pull request #19 from jparkerweb/docs/real-app-screenshots
Replace app placeholder pictures with real captures (v3.2.3)
2026-12-03 09:13:16 -08:00
jparkerweb 7b4e8811e4 Release 3.2.3: real desktop app pictures and a redrawn banner
AI Assisted
2026-12-02 20:35:56 -08:00
jparkerweb bc2325e061 Replace the desktop app placeholder pictures with real captures, redraw the banner
AI Assisted
2026-12-02 20:33:49 -08:00
jparkerweb ccf82c4eb7 Remember the terminal or web console choice, refresh the launcher model menus (v3.2.2)
AI Assisted
2026-11-30 20:08:23 -08:00
jparkerweb f1d087ba47 Read the sync password from a local .env, and record the v3.2.1 reverse port
AI Assisted
2026-11-29 22:16:04 -08:00
jparkerweb d059dbf30c Drop the file table and code-signing note from release notes in the publish skill 2026-11-29 21:55:57 -08:00
jparkerweb 3b822a3efa Commit and push from one card on the git board, without the extra confirms
AI Assisted
2026-11-29 21:51:45 -08:00
jparkerweb ee530d36c0 Quiet the Tidy up banner once a tidy-up finds nothing
AI Assisted
2026-11-29 21:15:46 -08:00
jparkerweb 634e4df10e Add text size buttons to the console's top bar (v3.2.1)
AI Assisted
2026-11-29 20:48:03 -08:00
jparkerweb 8277c8b548 Record the latest reverse port in the sync skill
AI Assisted
2026-11-29 12:42:11 -08:00
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
247 changed files with 29200 additions and 1738 deletions

No files matched your search

@@ -45,7 +45,7 @@ One row per file of every game but Ghoul Rush (which has its own files: [core](.
| `public/activities/snake-music.js` | Snake's ten music tracks as data (no imports): `SNAKE_MUSIC`, `{ bpm, rush, voices, patterns, order }` each, named `snake<Place>` and listed in `MUSIC_TRACKS` in `snake.js`. A round deals them in a fresh order, one to each level, so a run hears a different track at every level and none twice. They were picked on the pages in `prototypes/music/snake` (rhythm-first folk and world tunes led by something plucked or reedy, mostly dark or modal), and their bars are not all sixteen steps: 6/8 is 12, 7/8 is 14, ten beats is 20, twelve beats is 24, each pattern a whole number of its bars; merged by `snake-sfx.js` |
| `public/activities/light-trails/1.mp3` to `5.mp3` | Light Trails' five background songs, named `trailsSong1` to `trailsSong5` under `songs` in `trails-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 7.6 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm |
| `public/activities/flock-dash/1.mp3` to `5.mp3` | Flock Dash's five background songs, named `flockSong1` to `flockSong5` under `songs` in `flock-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg the way Light Trails' were (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 6.4 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm; `flock.js` deals all five in a fresh order each round with `dealMusic()`, plays each in full one after another and deals again after the last, never opening on the song that just ended |
| `public/screens/activities.js` | Activities: `#btn-activities` (the die right of the megaphone), `#activities-modal`, the one frame timer (`requestAnimationFrame`, swappable with `setTickSource()` for the page tests), the keys (arrows, W/A/S/D, space, P, Esc; stopped at the dialog so none reach the page behind; `CHEAT_CODE`, typed on a game's board, turns on endless lives through the game's `cheat(on)` until the round starts over, and `dropCheats()` turns it off on leaving for the picker or closing; `STAGE_CODE`, the same arrows then S, calls the game's `stageSelect()` where it has one, Ghoul Rush's practice stage select) and `pauseAll()`, which a new question, a finish, a hidden page, a window blur and a close all go through and which never resumes a game (it also sends a pointer game a cancel, dropping a drag). Canvas pointer events (down, move, up, cancel, with pointer capture) go to a game with `pointer()`, and key releases to a game with `release()`; a press on a paused board resumes without starting a drag. While paused, any game key or a board click resumes, except while a round is `held`: a question or finish that pauses a round on an open window holds it, the banner adds `#activities-unpause` (**Unpause game**) beside **Go to it**, and only that button plays on (`play()` refuses a held round), since a key or click already on its way used to dismiss the banner unread. Go to it, or closing the window any other way, lets the hold go, and a banner with nothing left to say drops it. Every start and play-on first counts down 3, 2, 1 (`COUNT_FROM`, 700 ms a number, `setCountdownMs()` for the page tests, which set 0 unless they test it): the game is already `running`, the frame timer just does not tick it, and game keys, overlay clicks and board presses wait, while P and Esc still pause. With two or more games listed the window opens on the picker (`view`: `"picker"` or `"game"`, `applyView()`): a picker of game rows in two columns (`drawPicker()`: an Order bar with **Recently played** and **A to Z**, saved in `activityOrder`, and the game count; one grid of `.activities-row` buttons from `orderGames()`, with never-picked games under a **Not played yet** heading that spans both columns; covers in `COVERS` drawn as SVG with `cv-*` token classes, since the page's policy refuses a style attribute) with each game's blurb, a best chip (thousands separators) and a **Last played** or **Paused at N** tag, arrows walking the rows and the course cards by position (`moveFocus()`: left and right through the list, up and down to the nearest button in the next line; an Order button keeps its arrows), and `#activities-back` (**All games**) back to it. One game at a time: `pick()` drops the last game from `games` when another is picked, and `openActivities()` goes straight back into a paused round. The last pick is kept as `lastActivity` and gets the focus; `lowerIsBetter` games keep the lowest round as the best; the header shows the current game's best (`paintTitle()`). `renderActivities()` in the render pass compares `myTurn()` and `finish()` with the last render and shows the banner with **Go to it**. Loads a game with `import()` when it is picked and keeps it until another is picked; `setActivityList()` lets a test list a stub second game, which brings up the picker |
| `public/screens/activities.js` | Activities: `#btn-activities` (the die, right of the text size control), `#activities-modal`, the one frame timer (`requestAnimationFrame`, swappable with `setTickSource()` for the page tests), the keys (arrows, W/A/S/D, space, P, Esc; stopped at the dialog so none reach the page behind; `CHEAT_CODE`, typed on a game's board, turns on endless lives through the game's `cheat(on)` until the round starts over, and `dropCheats()` turns it off on leaving for the picker or closing; `STAGE_CODE`, the same arrows then S, calls the game's `stageSelect()` where it has one, Ghoul Rush's practice stage select) and `pauseAll()`, which a new question, a finish, a hidden page, a window blur and a close all go through and which never resumes a game (it also sends a pointer game a cancel, dropping a drag). Canvas pointer events (down, move, up, cancel, with pointer capture) go to a game with `pointer()`, and key releases to a game with `release()`; a press on a paused board resumes without starting a drag. While paused, any game key or a board click resumes, except while a round is `held`: a question or finish that pauses a round on an open window holds it, the banner adds `#activities-unpause` (**Unpause game**) beside **Go to it**, and only that button plays on (`play()` refuses a held round), since a key or click already on its way used to dismiss the banner unread. Go to it, or closing the window any other way, lets the hold go, and a banner with nothing left to say drops it. Every start and play-on first counts down 3, 2, 1 (`COUNT_FROM`, 700 ms a number, `setCountdownMs()` for the page tests, which set 0 unless they test it): the game is already `running`, the frame timer just does not tick it, and game keys, overlay clicks and board presses wait, while P and Esc still pause. With two or more games listed the window opens on the picker (`view`: `"picker"` or `"game"`, `applyView()`): a picker of game rows in two columns (`drawPicker()`: an Order bar with **Recently played** and **A to Z**, saved in `activityOrder`, and the game count; one grid of `.activities-row` buttons from `orderGames()`, with never-picked games under a **Not played yet** heading that spans both columns; covers in `COVERS` drawn as SVG with `cv-*` token classes, since the page's policy refuses a style attribute) with each game's blurb, a best chip (thousands separators) and a **Last played** or **Paused at N** tag, arrows walking the rows and the course cards by position (`moveFocus()`: left and right through the list, up and down to the nearest button in the next line; an Order button keeps its arrows), and `#activities-back` (**All games**) back to it. One game at a time: `pick()` drops the last game from `games` when another is picked, and `openActivities()` goes straight back into a paused round. The last pick is kept as `lastActivity` and gets the focus; `lowerIsBetter` games keep the lowest round as the best; the header shows the current game's best (`paintTitle()`). `renderActivities()` in the render pass compares `myTurn()` and `finish()` with the last render and shows the banner with **Go to it**. Loads a game with `import()` when it is picked and keeps it until another is picked; `setActivityList()` lets a test list a stub second game, which brings up the picker |
| `public/styles/activities.css` | the Activities rules: the die in the top bar, the Notebook-sized dialog, the board and its state overlay, the your-turn banner in the highlight color, the picker and the notes |
**Building an Activities game:** the rules every game follows, so a new one plays like the rest.
@@ -57,3 +57,4 @@ One row per file of every game but Ghoul Rush (which has its own files: [core](.
- **The window owns pausing.** A game never resumes itself; `screens/activities.js` decides when a key or click plays on, including the hold on a question or finish (see the row above), so a game needs nothing of its own for it. Full screen is the window's too (`setFull()`: the button, `F`, and a turn or finish putting it back; `fitFull()` sizes the game to the whole screen (black bars where its shape leaves room) and docks the overlaid panel in a bar that holds it, `data-dock="side"` or `"below"`, or floats it, `"float"`, shrunk to the score while a round plays and the pointer is still; and tells the desktop app `activities-full`); a game only sees a bigger `resize()`, so a new game needs nothing for it, as long as its `resize()` sets the canvas's CSS size.
- **Every moment has a sound, and moving things hum.** A game plays a one-shot through the `tone` it is handed for each event worth hearing (a hit, a pickup, a level, a new best, game over) and keeps continuous things (an engine, a motor, wind, water, a fuse, a monster close by) going with `hum(id, name, level, pitch)` from its `tick`, pitch following speed. Never a one-shot every frame: a repeating cue is throttled by a timer in the round. Its own sounds live in `activities/<id>-sfx.js`, named with the game id; the shared kit is in `tones.js`. `create()` defaults `tone` and `hum` to no-ops, since the suites make games with neither, and a sound never changes the game's state.
- **Its logic tests pin the dice.** A game rolls `Math.random` for roads, spawns and layouts, and an unlucky roll once failed a test on CI at random (Ghoul Rush's Eye, Bounce Road twice). Import `./seed-random.mjs` FIRST in every `scripts/test-web-console-activities*.mjs` file: it seeds `Math.random` (set `PLAN2CODE_TEST_SEED` to try another roll), so a test sees the same world on every run.
- **Its tests run only on request.** Game test files (`scripts/test-web-console-activities*.mjs`, and `test-web-console-page-activities.mjs` for the Activities window) are listed in `npm run test:games`, never in `npm test`: the games are an add-on and the owner runs them by hand when a game changes. A new game test file goes in `test:games` (and in `test-lanes.json`'s `skipFast`); `test-skill-scripts.mjs` fails if it lands in `npm test`.
@@ -4,7 +4,7 @@
Key design points:
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Reset this tab". The four columns teach Pick a card, Answer then Send, Watch the terminal (the in-app wording names the terminal panel) and Get help; the session meter's one-time tip lives in the meter popover (`looks.meterTipSeen`). `looks.skillLaunched` is set by the first skill launch from this machine (`launchSkill()`) and, like `welcomeSeen`, is never reset: until it is set the dashboard holds the role line and draws Learning "Not set up" at the bottom, and after it one quiet line offers the two optional extras. Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `screens/help-dialog.js`.
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences (see User Preferences below). `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `DEFAULT_ACCENT` in `palette.js` is `ocean`.
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences (see User Preferences below). `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `#text-size` (right of the megaphone, left of the die) is `[-]`, a size label and `[+]`: seven steps in `TEXT_SIZES` (`palette.js`, 80 to 150%), saved as `looks.textSize`, painted as `data-text-size` on `<html>` (the server writes it into the first paint too) and read by `tokens.css`, whose `--fs-*` steps multiply by `--text-scale`; the label returns to 100%, and a button at an end of the range is `aria-disabled`. `DEFAULT_ACCENT` in `palette.js` is `ocean`.
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (the `/version` route in `routes.mjs`). `renderHelpVersion()` in `screens/help-dialog.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
- **User Preferences is four tabs in a side list.** Appearance (Theme, Card width, Highlight color, Role), Agents & models, System (Cleanup, and Desktop app inside the app only) and Sounds & activities (Sounds, Activities), a sideways strip below 720 px. The tabs are the static `<section class="prefs-panel">` panels in `#looks-modal`, each fieldset in exactly one (its `data-section`, listed in `PREFS_TABS`), wired by the shared `public/tabs.js` (`wireTabs()`, the same helper Help uses: `helpKeyTarget()` re-exports its `tabKeyTarget()`). `public/prefs.js` is the pure part: `PREFS_TABS`, `prefsOpenTab()` (the gear and the dashboard's Set up preferences both open Appearance; nothing is remembered between opens) and `prefsResetScope()` (Reset this tab, with an "Reset. Undo" mark for eight seconds, resets only the shown tab's looks keys, and is hidden on Agents & models and System). `screens/prefs-dialog.js` owns `openPrefs(tab)`, the one way in, the Saved mark and the unsaved prompt; `screens/looks.js` keeps the look and sound controls, which save to `looks.json` as they change; `screens/agents-view.js` mounts the Agents & models tab, a master-detail split over today's `models.json` and `agents.json` (formats unchanged) whose per-agent form has its own Save and Discard: Save sends the last saved list with only that form's draft swapped in, so another form's half-typed edit is never written. The split's components live under `screens/agents/` (data, list editor, summary, form); the mount owns all state and every fetch and hands them one `ctx`.
- **Models in User Preferences.** `GET` / `POST /models` in `routes.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `files.mjs`), edited from each built-in agent's form on the Agents & models tab. `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
@@ -16,10 +16,11 @@ Key design points:
- **`GET /agents-doc` is the other route that reads a project file** (the dashboard's AGENTS.md tab, right after Dashboard, shown while the project has an `AGENTS.md`). A dashboard session only; it serves `AGENTS.md` or one markdown file directly under `.agents-docs/` (`?file=`, default `AGENTS.md`; `readAgentsDoc()` in `sessions.mjs` allows exactly those two shapes and `realpath`s the file inside the root), as `text/markdown` with `no-store`, or a `204` for anything else. The page links `.agents-docs/` files in place through `md()`'s `link` option (`renderAgentsDoc()` in `screens/docs.js`).
- **`GET /overview` reads a project file too.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or with `?file=map` / `?file=draft` the spec's `pathfinder/map.md` / live `PLAN-DRAFT-*.md` (the dashboard's Map and Plan draft tabs, shown only while the spec has no overview; `readSpecFile()` picks the file and names it in `x-spec-file`), or an empty `204` when there is no such file (normal for most specs, and no failed request in the browser console). A dashboard session honors `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readSpecFile()` (which `readOverview()` wraps) resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all get the same 204, as do an unscanned `?spec=` and an unknown `?file=`.
- **The Prototypes tab reads a spec's `prototypes/` folder.** `GET /prototypes` lists its `.md` and `.html` files (204 when none), `GET /prototype?name=` serves one `.md`, and `POST /open-prototype` (origin-checked) hands one `.html` to the system's default opener through `openFile()` in `open-link.mjs` (one argument, no shell). The spec is chosen as `/overview` chooses it (`specInView()`); `listPrototypes()`, `readPrototype()` and `prototypeHtmlPath()` in `sessions.mjs` take a bare file name only and refuse any file whose realpath is not directly in the folder. The page shows the tab after the spec file tabs, on the dashboard and in a session alike (`loadPrototypes()`, called from `loadOverview()`).
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json`, `interface.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
- **User Preferences → System → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`, `app`, `app.json`, `agents.json`, `prototypes`, `learning`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed, refused, refusal }`. So Cleanup is the one place the server deletes in a project, and it keeps a completed spec git could not give back: `completedSpecs()` marks each `completed:` item `tracked` only when `git ls-files` lists it and `git ls-files --others` lists nothing inside (outside a repository, or gitignored as `specs--completed/` is by default, it is untracked), and `removeCleanup()` refuses an untracked one into `refused`, with `refusal` the line the page's status shows. Nothing records a backup copy, so tracked by git is the only way through. The page always shows the list before **Delete these**.
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
- **Terminal or web console is remembered, not asked every run.** Each of the 21 non-dashboard skill Interface lines runs `node "<D>/console.mjs" interface` first and follows the `rule` it prints: a cue in the request (`--web`, `Use the web console for this session.`, `--terminal`, or plain words asking for one) wins for that session, then the saved default, and only with neither does the agent ask, saving the answer with `interface --set web|terminal` (`ask` clears it). The default is one per-user file, `INTERFACE_FILE` = `~/.plan2code/console/interface.json` (`{ interface, at }`, read by `savedInterface()` in `files.mjs`; anything unreadable or unknown reads as `null`). It is deliberately not a `looks.json` key: the page re-POSTs its whole in-memory looks object, which would put back a stale value. The rule text lives only in `interfaceRule()` in `cmd-small.mjs`, so every prompt shares one copy that cannot drift; mid-session switching is `console-interface.md` → Switching mid-session. Tests: `interface …` and `every skill but the dashboard picks its interface through the interface command`. Next-step commands a prompt prints (NEXT STEP lines, resume footers and Pathfinder's `trail.md`) stay bare with an "add `--web` for the web console" note beside them: a baked-in `--web` would override a terminal default. The page's `handoffText()` appends `--web` itself for console sessions.
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` (after `interface`, before anything else) BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never grayed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the sixteen opted-in skills (`defaultSetting()`); a saved Off stays off.
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
- **No git process.** `repoRoots()` in `sessions.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
@@ -60,11 +61,13 @@ 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.
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-relative-urls`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files tables (the server and contract in [the console file](./AGENTS-architecture-console.md), a `public/` file in [the page file](./AGENTS-architecture-console-page.md), a game file in [Activities](./AGENTS-architecture-activities.md) or the Ghoul Rush files), which the docs-table test (same file) checks.
**Every URL the page uses is page-relative** (`fetch("state")`, `href="app.css"`, never a leading `/`), and so is every link the server hands it (`uploads/<id>.jpg`): the macOS app's frame gets no cookie and is signed in by the path prefix `/f/<key>/` (`takeFramePrefix()` in `routes.mjs`), so a slash-leading URL misses the prefix and gets a 403 there, and only there. `scripts/test-web-console-relative-urls.mjs` names each one, and `scripts/test-web-console-page-frame.mjs` runs the page under the prefix; a game module is resolved against the page (`new URL(entry.module, document.baseURI)`), since `import()` takes no bare path.
@@ -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 |
@@ -20,19 +21,21 @@ One row per file under `src/web-console/public/` (the games and their sound are
| `public/render.js` | Markdown to DOM, safely: no HTML string is ever produced, only nodes built with `createElement` and `textContent`; also the shared page helpers (`el`, `md`, `copyButton`, `lightDismiss`) |
| `public/selectors.js` | what the page reads off its state: the questions, the finish, the scan, who has the ball |
| `public/send-state.js` | whether Send is available, and what its button says |
| `public/skills.js` | the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (`SKILL_CATALOG`, `START_POSES`, `CONSOLE_WORKFLOWS` and the rest, in `answers.js`) are lookups on it. Each entry also carries `weight` (what its launch and `run` score on the meter, or null), `started` and `ran` (the meter's labels for them, or null), `resume` (`"overview"`, `"folder"` or null: what the resume command takes after the skill's command) and an optional `card.help` (Help's line for the card when it differs from `blurb`). `WORKFLOWS` (every entry's workflow, in order) and `isWorkflow()` are what the CLI checks a `--workflow` against. The meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS`, `resumeCommand()`, Help's card list and `cmd-help`'s workflow list are all derived from it, so a new skill is one entry here, not an edit to each of those |
| `public/skills.js` | the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (`SKILL_CATALOG`, `START_POSES`, `CONSOLE_WORKFLOWS` and the rest, in `answers.js`) are lookups on it. Each entry also carries `weight` (what its launch and `run` score on the meter, or null), `started` and `ran` (the meter's labels for them, or null), `resume` (`"overview"`, `"folder"` or null: what the resume command takes after the skill's command) and an optional `card.help` (Help's line for the card when it differs from `blurb`). An optional `loop` names the card-less app-only loop entry a confirm pane offers; those entries carry only availability facts, with `card: null`. `WORKFLOWS` (every entry's workflow, in order) and `isWorkflow()` are what the CLI checks a `--workflow` against. The meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS`, `resumeCommand()`, Help's card list and `cmd-help`'s workflow list are all derived from it, so a new skill is one entry here, not an edit to each of those |
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click; seven cues (not Planny snoring or waking) play the file picked in Preferences, saved flat as `soundFile<Event>` (`soundFileQuestion`) out of the 19 files `sound-01` to `sound-19` in `public/sounds/` |
| `public/spec-states.js` | the spec states (`diagnosed`, `fixed`, `upgrade`, `upgraded`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
| `public/card-rows.js` | how many cards a dashboard group draws per row (`steadyColumns(count, width)`): one card width per group, what fits or one column more or fewer to leave no card alone on a row (one empty corner is fine from three across), a last row still short centered; `screens/dashboard.js` applies it as `--dash-cols` and `is-centered` on draw and on resize; tested in `scripts/test-web-console-card-rows.mjs` |
| `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/dashboard.js` | the dashboard: cards, the spec picker, the confirm pane's launch options (the Review box and the Loop box; app-only entries have no dashboard cards), 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 (app only), opened from the Loop box on Review's confirm pane: 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 (app only), opened from the Loop box on Implement's confirm pane: 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 |
+6 -5
View File
@@ -9,16 +9,17 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| File | Role |
|---|---|
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep`, `forget` (copy a cited note attachment into `specs/<idea>/attachments/`), `delete-spec`, `handoff new`, `delete-handoff` (both on `handoffs.mjs`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`; `help <topic>` prints one contract file, `help topics` lists them). `post --wait <N>` posts and waits in one command |
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep`, `forget` (copy a cited note attachment into `specs/<idea>/attachments/`), `delete-spec`, `handoff new`, `delete-handoff` (both on `handoffs.mjs`), `status`, `stop`, `interface` (the saved terminal or web console default and the rule each skill follows; `--set` changes it), `help` (a compact summary for an agent that found the binary but not `console.md`; `help <topic>` prints one contract file, `help topics` lists them). `post --wait <N>` posts and waits in one command |
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
| `cmd-chat.mjs` | the `chat` command: hand over Quick questions now, never waiting |
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files; the usage's workflow list and its build sessions come from `WORKFLOWS` and `isBuild()` in `skills.js` |
| `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,11 +41,11 @@ 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/`) |
| `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 `^{}`, `install-v*` and pre-release tags skipped), `parseLsRemoteSnapshot()`, `installRefForRelease()` and `chooseReleaseRef()` (the launcher's and the installer's logical release ref and the `install-vX.Y.Z` fetch ref npx gets, from one snapshot), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags --heads` 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/`) |
| `console.md` | the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (`post --wait`, the exit codes, handling a send, `settle`), posting, the payload and its kinds, documents (including `file` blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters |
| `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, and recovery |
| `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` · `console-interface.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, recovery, and the interface pick (when to ask, switching mid-session) |
| `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `loop` for a build the desktop app's Implementation Loop runs with `--loop` (where it reports a `loopOutcome` instead of asking for sign-off), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`, `pr-prep`, `test`, `dead-code`, `ui-prototype`). Each skill's Interface line reads `<D>/console.md` and its own notes file right after `open`; a test checks every skill names one that exists |
| `building.md` · `building-review.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`, `file` blocks re-read with `refresh`), the chat check between tasks, questions mid-build and stop requests; `building-review.md` is the review run on the page (the sign-off's `review` verdict, **Review it now**, Implement + Review's Stage 2, Finalize's Step 2.5), read only when asked for |
+21 -8
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)
@@ -61,6 +62,8 @@ plan2code/
│ └── public/ # Page assets served to the browser
├── scripts/ # Development scripts
│ ├── bench-web-console.mjs # Start-path timing
│ ├── bench-install-update.mjs # Isolated install/update benchmark, with optional local `--repo-url`
│ ├── publish-install-refs.mjs, install-ref-fixtures.mjs, install-e2e-fixture.mjs # Slim install-ref publisher and its local release fixture builders
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs a local Chrome or Edge, through `playwright-core`)
│ ├── browser.mjs # The one place a browser is launched (Chrome, then Edge, through `playwright-core`; `PLAN2CODE_TEST_BROWSER` forces one); page tests, the screenshots and the bench use it
│ ├── css-snapshot.mjs # Dev-only: every element's computed style on every screen, both themes; take one before a stylesheet move and `--compare` after
@@ -89,7 +92,8 @@ plan2code/
├── docs/ # Landing page `index.html` served at plan2code.jparkerweb.com (GitHub Pages, `CNAME`) and assets
│ └── screenshots/ # Web console screenshots, <shot>-light.webp and <shot>-dark.webp (generated)
├── specs/ # Feature specs (if any in-progress)
├── install.js # Interactive installer (Node.js)
├── install.js # Interactive installer entry point (Node.js)
├── src/installer/ # Shared install/update modules: timing, canonical skills, console staging, skills CLI resolution
├── package.json # Root package (husky only, private: true)
├── version.json # Version metadata
├── CHANGELOG.md, QUICK-REFERENCE.md, LICENSE
@@ -102,7 +106,8 @@ plan2code/
| File | Purpose |
|------|---------|
| `install.js` | Interactive installer — builds `skills/` from `src/`, then delegates installation to the skills CLI |
| `install.js` | Interactive installer/update entry point — builds `skills/` from `src/`, coordinates the shared modules below and delegates link refresh to the pinned `skills` CLI |
| `src/installer/` | Shared zero-dependency installer seams: timing JSONL, canonical skill staging/manifests/rollback, shared console staging/commit, exact `skills` CLI resolution and npx-cache reuse |
| `src/plan2code-*.md` | Source workflow prompts (the "source of truth") |
| `skills/` | Generated Agent Skills, gitignored build output regenerated by the installer (and `npm run build:skills`) before every `skills add` |
| `scripts/validate-char-count.js` | Pre-commit validator ensuring all source prompts ≤ 20,000 chars |
@@ -118,18 +123,26 @@ 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. 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.
Install and update follow release refs, never unreleased `main` by accident. `release-app.yml`'s `publish` job ends with `scripts/publish-install-refs.mjs`: one synthetic slim runtime commit is pushed as immutable `refs/tags/install-vX.Y.Z` and as the fast-forward tip of `refs/heads/release` (no force). It refuses to move `release` to a version that is not newer than the one it installs (`--allow-older` for a deliberate rollback), exits 0 with nothing pushed when the release is already fully published (a second trigger), and refuses a `package.json` with a script npm runs when preparing a git package (`prepare`, `build`, `install`, `preinstall`, `postinstall`, `prepack`), which would make every user's npx do a full dev install. The README's first install is `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release`, so it fetches the slim payload rather than the full source tree; a payload carries `.plan2code-install-ref.json` beside `install.js`, so `redirectToRelease()` skips its `git ls-remote` for it.
### Agents file
Canonical skills (`src/installer/canonical-skills.js`, called by `installCanonicalSkills()`): the store is staged, checked and swapped in with a journal; retired skills go only after the swap worked; a skill folder Windows will not let go of is written over in place (its old files copied aside for a rollback); a failed roll back names the skills left missing; stages and backups another live install owns are left alone; `.DS_Store`, `Thumbs.db` and `desktop.ini` never count as a change. Links come from one `skills add`: the current `skills` pin takes the store itself as the source, but the legacy `1.5.x` pin (Node below 22.20.0) is given the built `skills/` folder (`agentLinkSource()`), because 1.5.x skips every agent when the source is the canonical store. With no cached pin, `skillsCliReachable()` checks the CLI runs before anything is replaced; a cached copy missing a dependency is retried once through npx. After a successful install from an npx copy, `removeNpxLeftovers()` drops the built `skills/` and day-old Plan2Code `_npx/<hash>` folders. Uninstall also removes the store's manifest, journal and stage or backup folders, and the console's `<version>.install-*` / `.backup-*` leftovers.
`~/.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.
`plan2code update` resolves one promptless `git ls-remote --tags --heads` snapshot through `src/web-console/update-check.mjs`: a default update always takes the newest plain `vX.Y.Z` (the release the banner and the app report), fetched as its `install-vX.Y.Z` when that tag exists, exact `--tag vX.Y.Z` uses the matching install tag when present, and a release without one falls back to the plain heavyweight tag. `--main` installs the tip of `main`, a branch `--tag` stays on that branch, and both force-reinstall because unreleased work can carry the last release's version. `PLAN2CODE_INSTALL_REF` is the intentional fetch ref; `PLAN2CODE_RELEASE_REF` is the logical release when they differ. `plan2code uninstall` runs the newest release's installer the same way, falling back to `main` only when no release can be found.
`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.
Launchers older than the release channel can still fetch `main`, so `install.js` keeps `redirectToRelease()`: `fetchedCommit()` reads npm's hidden lock file, `releaseRedirectRef()` leaves release tags, install tags, peeled commits, `release`, intentional launcher refs and non-main branches where they are, and only unreleased/unknown main-tip work is rerun at the newest release (its install tag when advertised). The redirect lives on `main` for old launchers to find, so it must stay there. The console's release check and the app's notice still mean the highest plain logical `vX.Y.Z`, never an `install-v*` ref. The app's Update skills still pins to the app's own tag.
`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.
@@ -188,7 +201,7 @@ Reference files are NOT subject to the 20,000 character limit. The review workfl
## Shared Console
The web console is built once into `skills/_console/<version>/` and installed by `installSharedConsole()` in `install.js` to `<console home>/<version>/` (`~/.plan2code/console`, or `PLAN2CODE_CONSOLE_HOME`, which tests set). Each skill carries only `src/web-console-stub/console.mjs`, with the version baked in at build. The stub tries `<home>/<version>/` first, then the `console-dir` pointer, and needs a matching `version.txt`; with neither it prints one line and exits 5. Only an installed console's `open` writes `console-dir` (a source checkout's does not, or every stub would point at the checkout). `install()` and `installProjectSkills()` call `installSharedConsole({ sweep: false })` before `skills add` and `sweepOldConsoles()` only after it succeeds, so a failed update leaves the old stubs able to find their old console. A test that runs a built skill's `console.mjs` must point `PLAN2CODE_CONSOLE_HOME` at a folder whose `console-dir` names `skills/_console/<version>/`, and a shared console finds skill files in `~/.agents/skills/`.
The web console is built once into `skills/_console/<version>/` and installed by `installSharedConsole()` in `install.js` to `<console home>/<version>/` (`~/.plan2code/console`, or `PLAN2CODE_CONSOLE_HOME`, which tests set). Each skill carries only `src/web-console-stub/console.mjs`, with the version baked in at build. The stub tries `<home>/<version>/` first, then the `console-dir` pointer, and needs a matching `version.txt`; with neither it prints one line and exits 5. Only an installed console's `open` writes `console-dir` (a source checkout's does not, or every stub would point at the checkout). `installSharedConsole()` stages and commits through `src/installer/console-stage.js` (a validated `<version>.install-*` copy with a manifest and a `.complete` marker written last, renamed in with a `<version>.backup-*`, copied in place when a lock refuses the rename). `install()` stages and commits the console itself before canonical skill replacement, and `installProjectSkills()` calls `installSharedConsole({ sweep: false })` before `skills add`; both run `sweepOldConsoles()` (old version folders and other versions' leftover stages and backups) only after it succeeds, so a failed update leaves the old stubs able to find their old console. A test that runs a built skill's `console.mjs` must point `PLAN2CODE_CONSOLE_HOME` at a folder whose `console-dir` names `skills/_console/<version>/`, and a shared console finds skill files in `~/.agents/skills/`.
## Repo-Local Skills (`.claude/skills/`)
@@ -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.
+45 -14
View File
@@ -4,10 +4,12 @@
## Common Commands
```bash
# Install dev dependencies (sets up husky pre-commit hooks only; each sub-package
# below needs its own npm install. Running `npm test` needs Node 20+; users of
# Install dev dependencies, then turn on the husky pre-commit hooks, once per clone. Never put
# this in a `prepare` script: the install ref publisher refuses it, since npm would install
# every dev dependency on each user's machine. (Each sub-package below needs its own npm install. Running `npm test` needs Node 20+; users of
# the installed skills still need only Node 18+)
npm install
npm run setup:hooks
# Run the interactive installer
node install.js
@@ -29,9 +31,14 @@ npm run test:fast
# Full check (takes minutes; every page suite drives a browser): list check, char limits,
# skills/ build, browser-module parse check, dashboard skill-table check, web console +
# launcher + getting-started node:test suites
# launcher + getting-started node:test suites. Never the Activities game tests: they are an
# add-on, run only on request with npm run test:games
npm test
# The Activities game tests (every scripts/test-web-console-activities*.mjs and
# test-web-console-page-activities.mjs), on request only: npm test never runs them
npm run test:games
# Put every text file git sees back to LF (also runs by itself as pretest and in
# the pre-commit hook); --check only lists
npm run fix:eol
@@ -43,17 +50,26 @@ node --test --test-name-pattern "<regex>" scripts/test-web-console-<area>.mjs
# playwright-core, which `npm install` already provides)
node scripts/bench-web-console.mjs [--runs 7] [--workflow dashboard]
# Install/update benchmark (isolated HOME/npm cache; GitHub by default, or a local
# bare repo with --repo-url for offline evidence)
node scripts/bench-install-update.mjs --baseline <ref> --candidate <ref> --mode cold-npx --runs 3 --json <report>
# Refresh the web console screenshots in docs/screenshots/ (needs a local Chrome or Edge).
# Rerun after any change a person would see on the console page, and open every image
# before committing: right screen, both themes, no username or home path in frame.
# PLAN2CODE_TEST_BROWSER=chrome|msedge forces which browser the page tests and these scripts use
node scripts/capture-screenshots.mjs # every screen
node scripts/capture-screenshots.mjs --only dashboard # one screen (dashboard-utilities scrolls to the utility cards)
# The desktop app's five pictures (app-launch, app-terminal, loop-setup, loop-banner, loop-stop; dark only):
# the app's own page (plan2code-app/ui) in Chrome with a stand-in for its Rust side, framing a real staged
# console. Needs plan2code-app's vendor files (`npm install` and `node scripts/vendor.mjs` there)
node scripts/capture-screenshots.mjs --app
node scripts/capture-screenshots.mjs --app --only loop-stop # one of them
# After a full capture, rebuild what the landing page derives from it (hero 1280px variants, the 1200x630
# social card) and, until the owner has real desktop app pictures, the labeled placeholders (never overwrites a real file)
# social card), and the README banner (docs/banner.jpg) when the tagline, license or a step pose changes
node scripts/make-site-images.mjs
node scripts/make-social-card.mjs
node scripts/make-app-placeholders.mjs
node scripts/make-banner.mjs
# Compare every element's computed style on every screen before and after a stylesheet change
# (dev-only, not in npm test): take a baseline first, then compare after each move
@@ -89,9 +105,11 @@ 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 |
| 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. `npm run test:games` runs every game test; `npm test` runs none |
| 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/` |
| A URL the page uses, or a link the server builds for it | `node --test scripts/test-web-console-relative-urls.mjs scripts/test-web-console-page-frame.mjs` |
| 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` |
@@ -101,6 +119,8 @@ The same areas as one-command rows live in the [Test map](./AGENTS-test-map.md),
| A new skill or console workflow | First update the hand-written tables that list every workflow: the `SUBAGENT_WORKFLOWS` count and the meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS` in `test-web-console-logic.mjs`, `notesFor` in `test-web-console-speed.mjs`, the event list in `src/web-console/console-meter.md` (checked by `test-web-console-chat-stress.mjs`) and a `BUDGETS.notes` entry in `test-console-wire-budgets.mjs`. Then run those four suites plus `test-web-console-skills.mjs` and `test-web-console-spec-states.mjs`; the PR Prep and Test build missed all five tables and only the full suite caught them |
| Docs or comments only | `node --test scripts/test-us-english.mjs scripts/test-line-endings.mjs` |
**Games are never part of the full run.** The Activities games are an add-on, so `npm test` leaves out every game test file (`test-web-console-activities*.mjs` and `test-web-console-page-activities.mjs`, about a third of all tests and most of them browser page tests); they live in `npm run test:games`, run by hand when a game changes. `test-skill-scripts.mjs` checks that every `scripts/test-*.mjs` is named once across the two scripts and that no game test is in `npm test`, so a new game test file goes in `test:games` and a new other test file in `test`.
Run the full `npm test` when the change touches something many suites lean on: `web-console-test-helpers.mjs` or `page-test-helpers.mjs`, `looks.js` / `prefs.js` / `static.mjs` (the `SERVABLE` list), `skills.js`, `install.js`, the server's shared modules (`console.mjs`, `routes.mjs`); after a sync merge or a version bump; before opening a PR or cutting a release; and whenever you cannot say which suites a change reaches.
The root `npm test` does not run the metrics or bot vitest suites; run them in their package. `npm run dev` in metrics and bot is `tsup --watch`. The web console and launcher suites isolate themselves with `PLAN2CODE_CONSOLE_HOME`, `PLAN2CODE_MODELS_DIR` and `PLAN2CODE_NO_BROWSER=1` (`scripts/web-console-test-helpers.mjs`), so they never open a browser or touch your real console home. The web console suites are split by area so `node --test` runs them in parallel. `npm test` runs them through `scripts/node-test.mjs`, which caps the files run at once at one per spare core (8 at most): each page test file drives a browser, and more at once than the cores can carry fails page tests at random (a flat 8 did on 3 and 4 core CI runners). Page tests (`test-web-console-page-*.mjs`) read styles and set scrolls only through `styleOf()`, `stylesOf()` and `scrollCard()` from `page-test-helpers.mjs`, which retry until the element is still on the page; `test-web-console-shape.mjs` fails a raw `locator.evaluate` that does either.
@@ -148,18 +168,18 @@ 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`, 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) |
| `--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 release the launcher resolves from one `git ls-remote` snapshot: immutable slim `install-vX.Y.Z` when advertised, plain `vX.Y.Z` as the compatibility fallback (`--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
1. **Builds `skills/` from `src/`** — one Agent Skill per source prompt, including uncommitted source edits.
2. **Checks the skills CLI is reachable** with `npx --yes skills@1.7.6 --version` (the version is pinned: `SKILLS_CLI_VERSION` in `install.js`).
3. **Sweeps pre-2.2 install paths** and removes installed `plan2code-*` skills so renamed or retired prompts cannot survive as orphans.
4. **Delegates installation** to `npx --yes skills@1.7.6 add "<repo>/skills" -g -s <skill names> -y`.
5. **Installs the global `plan2code` command** (only when step 4 succeeded). Advanced → `L` runs the same flow without `-g` and without the launcher.
1. **Builds `skills/` from `src/`** — one Agent Skill per source prompt (`buildSkills()`), so uncommitted `src/` edits are picked up; verbatim files are copied from their source with `copyFileSync` (much faster than writing bytes on Windows), generated ones written
2. **Resolves the pinned `skills` CLI** (`src/installer/skills-cli.js`): exact `skills@1.5.18` below Node 22.20.0, exact `skills@1.7.6` at or above it; an exact cached npx copy is run directly, otherwise npx fetches that pin
3. **Stages and commits the shared console** (`src/installer/console-stage.js`) as one checksummed versioned folder under the console home, with `.complete` written last
4. **Sweeps pre-2.2 install paths** (`cleanLegacyPaths()`), files the `skills` CLI knows nothing about
5. **Stages every skill once into the canonical store** (`src/installer/canonical-skills.js`) with a manifest, journal and rollback, commits the store, removes retired skills, then runs one canonical-source `skills add` to refresh agent links
The skills CLI owns distribution from step 4 onward. It stores canonical skills under `~/.agents/skills/` and links them into agents that maintain their own skill directory. Plan2Code no longer maintains platform-specific output formats.
The canonical store is `~/.agents/skills/<skill-name>/` for a global install. Copying there happens once per skill; the `skills` CLI is used for link/unlink semantics, not as a repeated copy mechanism. There are no longer any platform-specific file formats in this repo.
**Invocation choices:**
@@ -169,6 +189,17 @@ The skills CLI owns distribution from step 4 onward. It stores canonical skills
| No `-a` / `--agent '*'` | Uses the CLI's supported default agent set instead of requesting incompatible scope/agent combinations. |
| Captured output | Suppresses the CLI's duplicated banners while preserving real failures; unsupported-scope noise is filtered. |
## Installer/benchmark environment variables
| Variable | Use |
|---|---|
| `PLAN2CODE_BENCH_JSON` | JSONL timing-event output for installer benchmarks |
| `PLAN2CODE_LS_REMOTE_FILE` | test hook replacing the launcher/update-check `git ls-remote` call |
| `PLAN2CODE_INSTALL_REF` | the intentional fetch ref stamped by the launcher/redirect and benchmark |
| `PLAN2CODE_RELEASE_REF` | the logical `vX.Y.Z` release when the fetch ref is `install-vX.Y.Z` |
| `PLAN2CODE_RELEASE_BASE` | test-only release-asset download base |
| `HOME`, `USERPROFILE`, `npm_config_prefix`, `npm_config_cache`, `PLAN2CODE_CONSOLE_HOME` | benchmark/test isolation boundaries; never point them at real user state |
## Skill Format
| Item | Value |
+8 -2
View File
@@ -5,18 +5,24 @@ Which checks cover which files, read by PR Prep and Test (`test-map.mjs read` ch
| Area | Paths | Run | Shared |
|---|---|---|---|
| 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 |
| 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` (every game test: `npm run test:games`, never part of `npm test`) | 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 |
| Installer update | `install.js`, `src/installer/**`, `scripts/test-install-update.mjs` | `node --test scripts/test-install-update.mjs` | yes |
| Installer refs and end-to-end install | `src/web-console/update-check.mjs`, `src/launcher/plan2code.js`, `scripts/install-ref-fixtures.mjs`, `scripts/install-e2e-fixture.mjs`, `scripts/test-install-refs.mjs`, `scripts/test-install-e2e.mjs` | `node --test scripts/test-install-refs.mjs scripts/test-install-e2e.mjs scripts/test-launcher.mjs` | yes |
| Installer benchmark | `scripts/bench-install-update.mjs`, `src/installer/timing.js` | `node --test scripts/test-install-bench.mjs` | yes |
| Install-ref publisher | `scripts/publish-install-refs.mjs`, `.github/workflows/release-app.yml` | `node --test scripts/test-publish-install-refs.mjs` | yes |
| 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 |
| App smoke scripts | `plan2code-app/scripts/smoke-*.mjs` | `node scripts/node-test.mjs scripts/test-app-smoke-agent.mjs scripts/test-app-smoke-frame.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 |
@@ -33,9 +33,9 @@ If `devin` is on PATH (`command -v devin` in bash, `Get-Command devin` in PowerS
devin models list
```
Show its raw output to the maintainer before any interpretation — the format is not a stable contract. The output is long (hundreds of ids across about twenty families), so save it to a scratch file outside the repo, say where, and show the family headings in full. From it, take the explicit ids at Low, Medium and High effort only, plus `adaptive`. Skip every id the Validation rules forbid (`xhigh`, `max`, `fast`, `priority` endings), and also skip `none`-effort ids, ids with no effort suffix (such as `swe-1-7`, which is a Max model), and `fusion-*` combinations.
Show its raw output to the maintainer before any interpretation — the format is not a stable contract. The output is long (hundreds of ids across about twenty families), so save it to a scratch file outside the repo, say where, and show the family headings in full. From it, take the explicit ids at Low, Medium and High effort only, plus `adaptive`. Skip every id the Validation rules forbid (`xhigh`, `max`, `fast`, `priority` endings), and also skip `none`-effort ids, ids with no effort suffix (such as `swe-1-7`, which is a Max model), and `fusion-*` combinations. A `fusion-*` id the file already ships still counts as offered while the output lists it verbatim, so it is never reported **gone**.
The 30-entry cap means the file can never hold every family at three efforts. Propose additions by family — newest and most-used first — and say how many entries that leaves.
The 30-entry cap means the file can never hold every family at three efforts. List every family the file lacks, and propose an addition only when independent evidence supports it: third-party coding-agent benchmarks and real user reports, not the vendor's launch claims or the release date. Name the deciding sources. A model too new for that evidence waits for a later run. At the cap, propose what to drop to make room (superseded or weaker-evidenced entries, Low efforts first), and say how many entries that leaves. Never answer "no change" only because the list is full.
If `devin` is not on PATH or the command fails, say so with the error, and switch to **guided manual edits** for Devin: ask the maintainer which ids to add, remove or relabel, one at a time, and carry those into Step 7 as the proposed list.
@@ -51,7 +51,7 @@ Look up Codex's current model documentation (locate it on each run). Propose `co
### Step 4c: Check the strengths mapping
`models.json` also has a top-level `strengths` object: for an agent id, the loop's `thrifty`, `balanced` and `best` words, each `{ "model", "effort"? }`. After Steps 3 to 4b settled the refreshed lists, check that every `strengths` row still names a `model` that is in that agent's refreshed list (an `effort` is kept only for an agent that takes one, and is `low`, `medium` or `high`). For a row whose model is **gone**, propose a replacement from the same family, one step lighter or stronger as the word implies (Thrifty lighter, Best stronger), and show it in Step 7's table as a `strengths.<agent>.<word>` change. Never add a mapping for an agent that has none: only agents already under `strengths` are checked.
`models.json` also has a top-level `strengths` object: for an agent id, the loop's `thrifty`, `balanced` and `best` words, each `{ "model", "effort"? }`. After Steps 3 to 4b settled the refreshed lists, check that every `strengths` row still names a `model` that is in that agent's refreshed list (an `effort` is kept only for an agent that takes one, and is `low`, `medium` or `high`). For a row whose model is **gone**, propose a replacement from the same family, one step lighter or stronger as the word implies (Thrifty lighter, Best stronger), and show it in Step 7's table as a `strengths.<agent>.<word>` change. A model that is still offered can also be replaced, but only when the same evidence as in Step 3 shows the candidate does that word's job better at a cost it can bear. Show both prices. Never add a mapping for an agent that has none: only agents already under `strengths` are checked.
### Step 5: Re-check the agent list against vendor docs
@@ -76,10 +76,12 @@ For `models.json`, compare the discovered list with the current one by `id` and
| --- | --- | --- | --- | --- |
| added | `new-id` | — | New label | `devin models list` |
| gone | `old-id` | Old label | — | not in `devin models list` |
| dropped | `kept-id` | Old label | — | still offered; removed to make room (reason) |
| relabeled | `same-id` | Old label | New label | Claude Code docs: <page> |
- **added:** offered by the CLI, not in the file.
- **gone:** in the file, no longer offered.
- **dropped:** in the file and still offered, removed to stay within the 30-entry cap (Step 3).
- **relabeled:** same `id`, a better or changed label. Propose a label in the file's existing style: the description only (see Step 2), never repeating the id.
For `agents.json`, show one table with one row per changed field:
@@ -90,7 +92,7 @@ For `agents.json`, show one table with one row per changed field:
| added | `cursor` | new template | | template entry | <vendor docs page> |
| gone | `gemini` | whole entry | template | | skills no longer confirmed |
Summarize unchanged entries as a count under each table ("19 Devin entries unchanged", "3 built-ins unchanged") instead of listing them. If approving every **added** Devin row would take the list past 30 entries, say so above the table and by how many. Call out any likely rename before approval (see the rename warning under Validation rules). If all tables are empty, say the files are current and stop.
Summarize unchanged entries as a count under each table ("19 Devin entries unchanged", "3 built-ins unchanged") instead of listing them. If the approved **added** and **dropped** Devin rows together would take the list past 30 entries, say so above the table and by how many, and write nothing until the total fits. Call out any likely rename before approval (see the rename warning under Validation rules). If all tables are empty, say the files are current and stop.
### Step 8 — Approve each change
@@ -101,7 +103,7 @@ Ask about each row, one at a time: **yes**, **no**, or **edit** (they type the v
Apply only the approved rows:
- Keep `_note` in `models.json` and `schema` in `agents.json` verbatim.
- Keep the existing order. Remove a **gone** entry where it stands, change a **changed** or **relabeled** value in place, and append each **added** entry at the end of its list.
- Keep each list in logical order: grouped by vendor family, lighter models before stronger ones, Medium before High, with Claude's `default` first. Remove a **gone** or **dropped** entry where it stands, change a **changed** or **relabeled** value in place, and insert each **added** entry where it belongs in that order, not at the end.
- Write two-space-indented JSON with a trailing newline, matching each file's current formatting.
### Step 10 — Validate
+6 -16
View File
@@ -82,25 +82,15 @@ If `$CHANGELOG_VERSION` > `$RELEASE_VERSION`, compute:
- `title = "v$CHANGELOG_VERSION"` (plan2code keeps the `v` prefix in release titles)
- `notes` = the header line `# What's New 🎉`, one blank line, the **fixed header** below (with `$CHANGELOG_VERSION` filled in), one blank line, then the **highlights**, one blank line, then `$SECTION` verbatim (`$SECTION` already starts with the `## vX.Y.Z` heading). Build this as a real multi-line string with **actual newlines** — the `\n\n` shorthand shown elsewhere means "a blank line," never the literal two-character sequence `\` + `n`. Getting this wrong would run the header and the first CHANGELOG heading together with a stray `\n\n` in the published body.
**The fixed header** (the same on every release, so a visitor to the release page finds the install and update commands and the right file without reading the changelog):
**The fixed header** (the same on every release, so a visitor to the release page finds the install and update commands without reading the changelog):
````markdown
**Install:** `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release`
**Update:** `plan2code update`
The installer downloads the right app for your system and puts it in place for you, so you only need the files below for a manual download.
| Your system | File |
| --- | --- |
| Windows (64-bit Intel or AMD) | `plan2code-app-$CHANGELOG_VERSION-windows-x64.exe` |
| macOS (Apple silicon) | `plan2code-app-$CHANGELOG_VERSION-macos-arm64` |
| macOS (Intel) | `plan2code-app-$CHANGELOG_VERSION-macos-x64` |
| Linux (64-bit Intel or AMD) | `plan2code-app-$CHANGELOG_VERSION-linux-x64` |
| Any system: check a download | `plan2code-app-$CHANGELOG_VERSION-SHA256SUMS.txt` |
The app files are not code-signed. See [the desktop app guide](https://github.com/jparkerweb/plan2code/blob/main/docs/desktop-app.md#the-app-is-not-code-signed) for what your system may ask and how to answer.
````
Do not add the manual-download file table, the installer paragraph or the "not code-signed" note to the notes: the maintainer does not want them in release bodies.
Check the install command against the README's "See it" line before publishing; if it has changed, the README wins.
**The highlights** (written fresh for each release, from `$SECTION`): a `### Highlights` heading and exactly three bullets, each one plain sentence about what a person can now do or no longer trips over (no file names, no internal terms). The full list follows below them. When `$SECTION` already opens with its own `### Highlights` block (the changelog format from 3.1.0 on), reuse those bullets as they are: add no second Highlights block.
@@ -128,7 +118,7 @@ If the user supplies a suffix, set `title = "v$CHANGELOG_VERSION " + <suffix>` (
### Step 9 - Publish (on approval)
The release is created by the `release-app` workflow, **last**, not by this skill. The workflow builds the app on four systems, attaches every file to a draft release, and only then publishes it, so the `vX.Y.Z` tag (which the app's update check watches) never exists before its binaries do; its last step then fast-forwards the `release` branch (what the README installs from) to the new tag, and fails loudly if the tag is not ahead of the branch. Creating the release here with `gh release create` would put the tag up first and leave users offered an upgrade with nothing to download. Do not do that.
The release is created by the `release-app` workflow, **last**, not by this skill. The workflow builds the app on four systems, attaches every file to a draft release, and only then publishes it, so the `vX.Y.Z` tag (which the app's update check watches) never exists before its binaries do; its last step runs `scripts/publish-install-refs.mjs`, which publishes one synthetic slim runtime commit as immutable `install-vX.Y.Z` and as the fast-forward `release` branch tip (what the README installs from), and fails loudly if either ref cannot be published safely. Creating the release here with `gh release create` would put the tag up first and leave users offered an upgrade with nothing to download. Do not do that.
On approval, write `$notes` to a temp file, never inline (multiline text on the command line is a quoting bug). `$notes` must already hold **real newlines** (per Step 8) because `printf '%s'` / `WriteAllText` write it byte-for-byte, and the file MUST be **UTF-8** because the notes contain emoji. Then start the workflow on `main`, passing the file as the `notes` input (`-F key=@file` reads the file's contents):
@@ -159,7 +149,7 @@ gh run list --repo jparkerweb/plan2code --workflow release-app.yml --event workf
gh run watch <databaseId> --repo jparkerweb/plan2code --exit-status
```
If the run list shows a run that started before the dispatch, wait a few seconds and list again. If the run fails, show which job failed and stop: no release or tag exists yet (a failed run leaves at most an unpublished draft, which a re-run reuses). Never publish a release by hand to get around a failed build.
If the run list shows a run that started before the dispatch, wait a few seconds and list again. If the run fails, show which job failed and stop. A failure in a build job leaves no release or tag (at most an unpublished draft, which a re-run reuses). A failure in the last step, **Publish the install refs**, is different: the release and `vX.Y.Z` are already public, only `install-vX.Y.Z` and the `release` branch move are missing. Users still update correctly (a default update falls back to the plain tag, just slower), but say so, and recover with `gh run rerun <databaseId> --repo jparkerweb/plan2code --failed`, which keeps the same commit; re-running this skill stops at Step 7 because the release exists, and a fresh dispatch fails once `main` has moved. Never publish a release by hand to get around a failed build.
### Step 10 - Verify
@@ -169,7 +159,7 @@ Confirm the release now exists, is published (not a draft) and carries the files
gh release view "$tag" --repo jparkerweb/plan2code --json url,isDraft,assets -q '.url, .isDraft, (.assets | length)'
```
Expect `false` for the draft flag and five assets (four binaries and the SHA256SUMS file). Report the release URL to the user.
Expect `false` for the draft flag and five assets (four binaries and the SHA256SUMS file). Then verify the install refs too: `git ls-remote --tags origin refs/tags/install-$tag` names the new immutable tag, and `git ls-remote --heads origin release` names the same synthetic commit. If either is missing, the refs step failed: recover as Step 9 says (`gh run rerun <databaseId> --failed`). Report the release URL to the user.
## Rules
+26 -1
View File
@@ -12,7 +12,32 @@ the workflow. Follow this launcher exactly.
## What you (the agent) must do
1. **Ask the user for the password.** Request the decryption passphrase (via
0. **Try the local key first.** The repo root may hold a git-ignored `.env`
file with a `SYNC_REPO_KEY=` line: the sync password. If the file exists and
defines that key, do NOT ask the user. Decrypt with it, reading it inside the
command so its value never appears in the conversation or in a command line:
- **bash:**
```bash
SKILL_PASSWORD="$(node -e "const m=require('fs').readFileSync('.env','utf8').match(/^SYNC_REPO_KEY=(.*)$/m);process.stdout.write(m?m[1].trim().replace(/^(['\"])(.*)\1\$/,'\$2'):'')")" node ./.claude/skills/sync-repo/decrypt.mjs ./.claude/skills/sync-repo/sync-repo.enc
```
- If the file is missing, the key is absent or empty, or decryption fails
(exit code 1), fall through to step 1 and ask the user as usual. Say in one
line which of those happened. Never print, echo or summarize the key's value,
and never write it anywhere. `.env` stays out of git (it is in `.gitignore`);
never stage or commit it.
- When the file or the key is missing (not when the key merely failed to
decrypt), tell the user how to set it up for next time, in a few lines:
create a file named `.env` in the repo root containing the single line
`SYNC_REPO_KEY=<the sync password>`, and make sure `.env` is listed in
`.gitignore` (add it if not) so it is never committed. Reading it from
`.env` is preferred because the password then stays out of the transcript.
Entering the password in the agent window (step 1) still works, so do not
block on the setup: continue with step 1 right away. If the key is present
but did not decrypt, say it looks wrong and to correct it in `.env`.
- Later steps that need the password (`set-synced.mjs`) read it the same way.
1. **Ask the user for the password** (only when step 0 did not work). Request the decryption passphrase (via
AskUserQuestion or a plain prompt). Do NOT proceed without it. Tell the user
it will be passed to a local script via an environment variable, never written
to disk, and warn them that — because you must run the command — the password
+1 -1
View File
@@ -1 +1 @@
U0VOQwEIwpvqLDLCPqABsj78HHjAP4LCF3YHi+TAqmTZKXEX0MOp3crSM09XMVuneNhoOk05JYSSIrr2qJG4TJVmRAU7AFHtTXVH2+JHQw5Hd9oQ8t72lH5bmCtAZ1QRIAbCuaHFbWF7Lq1nRsIPuK9S5++Z6uTDJU8b/PBnQT+hX7FZtAvMoXS3O+lAbzTa5XoGQWh/FOESEk18Ro/K+raioOva/FB6hvRycyXYv9V+KlkzKhPEVtQKkulswwTUN+rfsu9s+D4u5MLy+UdbZ1kB1JJAdc/nkhk6JM1ZOPaq+Ka2XV6iuIq+ayfmmC/OvwVOM364CwNvW33ic6R6kXcMCNh4LfOu0+9qmZOFg16KvCfNRgnCbQwGHdWF+iP6gxGzuWltqshI0GT4FNS3h/LSvqXKpzPe+qDPXoG080bsa7u4cXrFBil8x2cSoYK0SZsC2zdYDj0yjI6MGxwgeryr36bp6ZzPUjf+qg5teXjC8hyqGsRkTzvtEQp4sA4STXgpDDPV/QAv2s/d7lh5y3HJQpuAY8cqdUvJp1KGYYlgmq+YTaFfWJ+rcy7tDGRjiD7HfBRG6eeVK55YZxCJEIjV+GFMNxVHiAhgxV7UpwW7swDrSBzU1UGtjy3LyzHVV7M+UziSvFzPktXkKXBuA/XvvuQeO3qZQ2tiSVZwqDrpqyL0d4yilGkUy8FW8WbIeaOPNKFZGPZnM+l7FuPQBzwyAKz0KlsVMeNFxcMDwezLrB4Be6kMr9nSz3kAOuSlnmQcoi7iZcizW9xXLLZ11q+2/0XqvPqO9dtb1KQThD2fY43IUGitRx2qMLb4uCRWOPmk+MULQn6gL2moZ3M81xHWRa3HplG+3YRmnhfvygt9jun2AzXy6ScC5ybS2LsWIxsCSTj5JqjlhWP19zKCEMspDC5FOvY/AgyX3aJqVr7/NRJd4IZ0bO0syc7j8s6I0Qbn2oe2q5t5UIM2WWA6zvCmEgKbe2v6W1M45HfvopxXcLULjMYsjvYnr5qhulicvhpoPIOYlH8aGWNhJRbF9dCk+hpWNhy/dBREFpDZzQKVKGf59NagP02vodPyCZujksBqmIL6fDjgM4jzFrlqWs8KvisFhHq61V2MXpn9UOXlL4vqgr/md/4b/jYSKNYgzd9UFKxakdffko15w+1uwO3/BlXKW3ohypjbzqq56rtcn0hL4R1LgDPNYPnc8xM/HPgfUOs4CCYStJxecLcifudqqYxhc1z1J4zukAlJtekhbBR+E1uuEKd0qDbsSxrpuGCTzBHQOoArdng8ujoptby1h3ZuCeymnm4IHB4uSVpviC66MkTOIQ5VhybtainM8PRiSemhF/UbU2EsOvdOkLfFRxkEcnLtb+wQGeRKXv+aOA0EXcRqycOW44Khevlfhhx1bF2K+7XfoDCP1HzZRcNf0NylH0wk89q71ibKrGZTIQijhE1gKxOuiPARbVpT991VPY53JrrmXY3F5a4x137SYJVlRyLOTv/lkluTvx/sO1DUtwSwjAq0NYuUSFJg2Avno1V/FEOzDZz/GrKbAwTs1j88UBQmv4u8Z3nW7IH+7Ut9ff8ABGpp8FSd8jcSIm+YATDL7fZRrTpPzjrZToklYLL8mfFYXJuLtYc5mmcNY+mskH1Vx4pT1ema2U3LcMoLf5LUfEB4o45PMzIlOfyx+K9/KPtx7OIJ00xn7sGgsXRANTrHoFSSzbPuU2PhwUniLMKSCRQ/8jEMXAUwY7aPa2WZOt+GMruNzff/IgZ8PnZbj3IDwcknbzijh4tlBbiBsKMEBp1sX66uJljEmHEFo868JG55skbiFZkNcNKecqyZ3uyVflv/+rS0QMvA3f14vOq0eQmPzsetAJrdjG68Wc12UyqnoAsP2+XE+gQm39Zu6tbsOl4gwG++89vJ16rRp9BCIvhTQ7mhC4UXq2y9T2pYWFLggg5upHZzY64T4sgPvwuegbKj5uuIKr/fTwt2+eJRc/TCkEGlZ9J0GWZlWTxWuvbSz3oX6S/hL/eeucVfpH27naPzmGIDkceTUMC35TAWnAIrndTt8TUk4Eg3fF7G8FxM4NF+/Zi0M/auqwhAP4M1wccmcQXEIw91UJNyO738rc2Oezg/rJgL9ztIqP6TMyuF3y3EGsGm7UfJM5IBEJkyQskVni6GEE3oyuXeWQw+UGp6jnrqBvU7Q0idZQ9zzKEVoA8QviQeATeGEsv0Hn08RlNvcOtK+dMt//Ryujm4lnuFtNhZEgW+4kxHxu4+OJCIBh+zrTunEjgVJbfmNCm5pgV7UWvt2YpfmSgwD/LnIiEKU8+7iYOK4VNogW7KtZpTZu6GMu8LCqzhxMJH2QQNxXOD7vY/cjVh1NLdsco8Bunk/y+XgtR3sB+ZMLzBuZgJnqr43i5tELzOkR/tY493V6A5aaRq+8YW8a9JQINs5Dr0EGsh7Jx057YgDc4yaJCXI8Eb6ZaRVGvFqGXyJtmoT/+ZtfgwZT0PQCt+gnXx+HyD/+qaWyzqteMF0euZow5fa/yjTWvTOz4d0QqKaaT5QNum2d9Yw0KylqK5QX80BJlF6sCbbscceHVTPyxHH9bqM8HCDwejYY6B93EzKwXzR68TvHXxuRCamdE9C8LAbdc7tM5YUn1p4ftWrn07BO1OL2R2EtYz6+1RJs1VCK3yMBMzeyT+VTxsF9YqMSGjpYGt4k6s3fWfCpsqSuCeQkFDpQ7chowNVQUY4NViR4O2zL+tJ0TyYtV1QVn5Lg0BwY6y5vPJnNiyCaiqR7AAUC/CtGEMsOKsAmHOigH7HeBXlFrQPhylShcH+4Wjvze5uFJ8MdGJjwUipO9pdWCOPxr3DAIsQvWfKp39YdilSqmXtRQheRxOg5riO1XWIkeYBWVZU1mYsgAXSwimQOZgDewal61OyZPtQbOOcjQDAdEp/oh4svPr1KiJJ/sORJp/4PSIaYdRhlwj90bNoOZzR3+Z7NByJIrR3IRbR0W/tDwvqxDBd5fAkphrqDK+pDwrIdwGMJ+s+Gw1Urojh8AX0kEr63zwT2Qbsl+6kE11yyWtENrVb/6zaH+2iz8+KFbPa+dc+cp8tIbRYsM/waYIwG49/FmrHKSQGVeGxEvYIM/gLaukgy+0bWVvGdpFXu/3aOnyYvJ8MO7I14lC+N43HOk4sVS8fH9woA7kOTIw8mdG6VROdjPPzKsdeCoNkTJOwYP5hf9/7fE1O2qEOuuikn/29j+g+DIM0xXeNA4JpzFADBSLjqz1YW9Wtak3nqshWnzh1LXeJhux1XOmnsleeqy7LAaSivSh7ZMIlWloQqyuYhxc9KOYSXpDp3Lv/aETxgvWP4BWgZPBb4Uu8GGCdcTf1HTzhO9RgGSwyKaHfy5rtHfTtDOJRbTA/UU3Y1fVQ6RVYxXv8eZCcB8rbXhBnOBcCZNxwGKsPcn/o/GsDQ8lo7bcASqgxSF2Ukwp4OKSlUQIXmqS8sW2JYtIJMmq2eXutHUL+vjycJyr/SparMNILY9p9tDb715YuHBSr2rSFyCHs0sW0RdMN42fQTpSdrSkwvsqnJVVhBpZVZldnNk7BoNcksIRHbMuf4Y3WywSbwTZy5Ja/aRF7YMvcuC32v/G3fctV8Mf/NZWXQQ4AaSIatVcvPPxSUo1AP8sK4qO3K2JwVTFDpZQevn3E7OmSbeKR8XikjAALJSULRc69fSwj5DDIOxiSFwm7nJ+cW/lJEU6dGx0t6K5Ouvn1tawBpb1B7VpMZfKvHOvPbE4H/ou+ldssFjKVzrlC5KHaF7bJsPryB2Z6fvseMZENruiMVA3gJ2a4lyr+KFeXO8NzttWSGSZ/1B7wQECRrejcc+tomiAVSoje6VtrHTsgSEkhcjiyGqjVGXrm1D30plXIdl76QUI5kMjPJ0H/MEiz1Zm+iCtsE0tMhJqvXeX1G1Cr26uaawsiksnunV5P1YLC5MdBlmw+rlxdU9gzfkb53hl0kthXjzMBUd7NdSGlRNhZjJ/A2rJIwjyqjgZW4Ga/m2Z7xWMT3XnYuClkdD9s33YkBr1FMnuG+m2f9IlDKDzQL0Z1JO4EmngjCBLM6mNy4SE2O6rEpKK/E+k+cRttAabvImRvFlnCMsekvAa66i9u+gE7Bbkp60E8LbkE1w68lRykBWtLk1qqan/C+Jh5CxuLg0tcSzk4Aj91pcVjoAiN5ouD5UxnIw1Jd3zcYFqrZSvYQenDw1JUGmBZ9rh1kkFZM4QodQHCzSIeAwFGK7+iFcXW+PBl2OYHpCU/AS/R+CZez6n+LWXblzH1Rlg2NTUEykUd5gvXsIF5sbW/Z69wZmQlWtMh4A1Gz4cX3gOUL6s4pS4igOSHXuNC0aiK3VnNhQsoKI2edkQeT0HK6Gv5xK7gFnFRiXvtlnQSosDBYxslaOO6PkHESgjYI+BO23B/thOywxTP0GZx/u5AEiUKOJ9zx0c8QuTmbtiAda6DmoTt1q1y0Kt3yGcZDMqbJ4ELPS6ie0j3wJkb5s/9eshkdRP25R4i/xjf8ikUgZzCzNVJVtaDJWvmI29xCzOGtk0iCZdYNnriGTRVAMEDwcNpV83UeRKn+xIMy+FzLcDhJkct7qyvZvG/ahfLT9zEJiCJPzGYewwvNr3GEx/94RXep5z+q8XvNrocHZshX3+XiGPalwN28joBPb7P6jrOsPIuFKrBkHuSBxpSuOejd1SSVGnFHjrU2Cw4iZo8SGwUNWZjTjpgF/J1Wc1ulM5fWukiINp8dSbBwn9SKD4sj23kIwp128A8FHbuZGsTx6slutVJ11SiPa0q9ly5etA8MgbLXggNrJJ7OANcrrDSL6ZE/GJOEzOzKgvZPQy4xk5jE+98ydiVBPX5BS/pjug/yxvyuiklDo635jhFI6YDsPr6robNEgDpM1p/CKVS+aM8aQEvmIOmZX9aTtCsSOxViMFVgLqRsWEmm4rxuwTjD13J4JXobC8SeeIe2+Qyio1KWPmw3kxUFEV4aCW2PWXGqJLine truncated
U0VOQwEw0ns8YDG0jTWYQ1y0Hg0RIor5A8hnRTDbcQ+YqcVsLf+9TkxJ+IsTX+Kr6cOanzwn1m6z3bZgAOURfifURlMcUgSskVHUq41QobVGUOjXbcCTWiBTAF3k4FUsFEk80AZCAh8de/Yv7AlmrnfXUUt1bpxBfqi3zYjO8jT4V4HLzhdA1hdNHiazuc6LCajSThzM6GR9fLS+cv9H5bsRuxH/0UfNa+4Fki4BA1xtO1xi0DJGh+DkxLwnZ8hhgvCSH77f+3Fr/3R7rdXBvuPWAAh5Tq305tg9peD3KI44VHCXJPOySW4ruDN+XbsA8BX4OnA6x1FgT0wfHJ7gb+vfYVO5CZ37Z+vr/GjBRanLwPf62ASbb7zNk4pz15W2448GYlV5oJ2WyN7Ai7kadyr9FVquwGvvMucxeVtCP2rjh8TypQAee35pJISQMHPNs0+FABA0OyQwwmKW3nK0B2Xckfdv+xX3f0wbMB9pPJnmEBl0l35XUE1RJG45mDV5K7Mnni8G8XU4PKfcnlhugypo0N9HXjPr1zriI741Msj7m5CMDxks6HtTd+8hNjbcKFUIs/IzT45Xnq7ZvLXgVW1u+Fxz9dtG17GL7sjNndg1aRmUVH35BcihvqNCZmZiVWSmxUCAwSGq/AZLWXsqlj024qY/phZ8WkuuH6KmRMORhK698ybJKi+Cgnf1hzmeqFXLy9lZMQAC+CHecmWg5icNIVe+zKckkdRTazU8lj+/RTYCJjsqdYm5zJXPu8VugSkDv1KUNiTRZT5bjwRTZwHHWhLAY8IomD4nSzb8ak4ugs4d60tqCML4FqPaUmH2D+6u9dt2B4Txb2yojG/xhyZENHuep0lT9GUOrT6Yh0TB6O/bC2Wd1cKoa1zjD48+v08FZlncqWzn4zs8eQwN/X+r5pD2JqbwhC2ts/kL6LIMFBSmHVgPCD5Tq+gxihWqbi3/szjB1YejV68N+v0ALhsJVnW5AgtqXqNcdmdx+M1WfUEHBe6F6cKd1kEeDpxaQbH04DE9RiSpO+Ed2n5d+yhXrcibBpJi9nNTvQWAtoR09P6IOAyLlaFNxrb+VDaDhFS/L+KuV8nHJpa3eNNpRf+GlgogOQuNYUJb/oOnSNlEAYWq9By/hdNOJuJVGwJPUqd8cc2+JTe9qslwQPACiPz5I31I6z8aoMWCK4gi/WlZQk+Hew3hBMRLbDI3ucVx1x/io1YvVvMyL8PLEPHWHpYesnRw6X6zw3a4TnRwvvwpf8Q2n8stfpPLme1IQX0veOyDvn1IVIv8uOPmm3BDe6WfDd+jvoCFVTB9Q0B5z8/2WlpZIwfyBK+jAHPzrXuFGZThOTRU1rxT4uf3s+SxRMEi4NCwOH7aGkDLYYu83XdAIt9uuNjmHLqnTup1l16RSO03+L2GMvciwcHkH79oj5zK4jTkifAW2FFOijPIkJChXlDkU1fEtyIzYkOn/TqyaarUZ+O95UpoZEV37pwRrCLvftGhdM/rRuPwyw6lkbr1kWNx2ExswbIezICAxeW7ICPsVgrQJ2URlH++RBL/s030mciYyyo8Uc+Eo3jaGsXbt5g+JvrQUWiUn8/alGxyo4N/IjhkMsWjNkxEfpBwxhjQ1CLk3p70v4xYYeoHI0v/VGt94IvFO5VE2VOBpmZPMpezJeOnbCzFa2N61zMfCPm/sMCFASl4Ssh/AAZTbtEmf99M9WIuvxTg11Q+bvv3QnJF5gSbVQxQmJU3eju4fEinj/hRNK7qHVWg3IfDaN+LvoxWu3nHOzOLnueo06PI0NyibS8tX3LJ/SbS34zvHfBLd2AI78aLG5V+olXeMvNIhtndaBs/6FmxkqoaZR2SHESTl5exaMIzekF5Hv+O1Cuapv7SO2QaB15LX770bP8TuY2G1uTLCtjEvqBV5QiIGiSCxv1vYFYLEpp1wxvfM06ZsbfUXw7pPs306yxe8mQp3smh5YZrV31cBYJFNLToK5Et/Y+wToTuVYSlzhLEjOOhvBfueyXkIQawEwaly5LeH9fNe+M1pM4E7duP2/UEGr8UR9pVLsR99nwclMehVZ1bts7Wf1WRSwaiEJJVVysMdMXp82VIriAyhQmU9TQzBaIhN1Ktmrns3O76JZwgodG/N+e0jU3cc7CcsGyGU/NR+8I01HKCSus6bn8kyoWa1iCIA2QriqzlipMcxJ6qVgWgX59KtgUB0CZD5tXYX1rfABkigw3p8pKPJJVoCDoIpoxLub7EJcX80JH0Ky7C41htOUQGbzININtHvCZ4+plWY/IyM2ski3A73DMmwR6x7ljCYx20HonX7LrbxvonazNQuB2mIo6JGQ4dmu7uAOx+3rgQSYoT6r6Rrd8VnggoT+8wY8J61yoIgMY4MZZmTHAa+w0e2glQPPYrpszzyrm+5eTk6TiC85FA4MpdtmqUYd4z4mpRhQDRgJTLdjDK0e3c3eX1t01eGh/OSPLqqXz+wuaFvcOjxxnB6F4Wa1/+iQVdXPoW2oX5fgmgR/DyipBkKIG5zwDoCCzkdSmyM6GJ6h6jjP92D3nN1yx+EKBqF6c5g9DDWJ+reoSR1F1ij/qwZDxjJpulKmy+928l+fRZHOXT8iVqX7vy6nMvuuT24q/IUhKPonTwoSDH2pe/kCCn4uGhi/ccMQ5rQCGQWYKl3JuY3xZhPLNEtvSj/9rJwiwPpLNYlG7MVsePdxMZLmcrML7AUhNOeUJs+Niqg3uCmixvm5V+Ef8y7USxCJa0m998nTKWvu/1pDivs3U1Puo5bOOm3VZR+8Q9Iyfme9LUJ4iURJIHVlc4hksrmJgt7ZARTU72EELZVdnfDV4W81V8qiBDOxh/JBwxeZl+eMw4RRprxTmLflNTemnXmjacCOvhlj/oY6RrKOR2MbTTE9vaevwiCD4AxQYe/6b3FBk3wwoD2leuKMVv0z4eo7UFgj8iSMqAbYziD6ekrRZOrwYPFCrQ+8kP27Tw4FUcG2pOxlBDesRQy++wtY6VdzKhPclI91SeM6GN7wOExG3nyc2oIs8vhEHDU5hh7tlWmRuRlA4MRcZShfTIp6j9RSvjVxn8hvpzmv7EmjAglhe6wz3aCmuSxUIj8XYhmfJ1qvFifir/Jg7/dPsEZWoSEwC8fIk9+nrPz/LAH975H8YSk8RsRoe5q7TAr/0cu1nWyjLIiwA2HIfNQYUupLLSVrrEzfzVEcKBxyTIkGZI2fb6SYqcDp2kaYoycD/MTSz7D5vbDnfG7cWD0nf50AymwLRzlL/YNWEwXunPGO9wsP2wdNxxrOCxMGe2t9iCQPtOESMTmHi5g/P1uuJXUqWjA/D+7Wi0zRWLQ+g41tMThtABP2wi58/wi5y6XLLY1DSoe7e329C1RLF/JglZM7LEHBI+dx+s/V0pj3prCDLmSy0o+fVt+Qt9kHtpWi4yNZFFIyG+kL+leyrCdn12+SIUzynYPi5Aflbu1PHk6wZlNlAWPNlCA9CiiEVPl35+qRteV4xlhvU7uVELvSXaYWE+jR1tImdaTG4zrI9mEGBkg/ybG+VgrYv9JtohcmY/KBXdPtf0wsfpuSTqp98J5qy5SeihjmfInLQufmFa327h92lreMRVwnA11Ml0NmqnMzsGgUnQp76OxiJq3SGkp2vN5C8heJ28Exi4rKwWwXPwgQpBGgjKOUlZ1EdvAzuSikckpo7xB5LDXp+jh2ubYpqko+tDXtnbI4fpNDZe/YarWhR0nqH5rypv77XPygi4h+XIvQ0FD+q2dMzluiSf72+SR9Kb6bWtsDc3grI23znMrc303THdcJTPTgdV0eHSKlIykIW0gh9Ih8MsK7il5EA/BpO9R8vEmY4iV4GbNuPQqxukrnHbze33xqxGircMDefVAbixikqWQQtjqqIPN/HSnK7WluXIQ12JzQw1xYtyjL2nvZZdr8OH8LDxi+TdkIXHNyky2Z1Jf5xHXsN38GqvBvghiZU5nFHelo51LdV6OSXUsnG/KBOnVokIWyNWASAKRGHlcDcJm005Miim+PQjavii5d029AqRQ8M+no7bR57k4JiJMtGk+rutmEn8MFLveWwgAigqb48PagfBsCRXMVrJXwY9k+KbRSbEqZc8IeJHeXx9l5mby0nnPiwMXYpjnBricwSygmhn9nc9RTB5diwFbGvgVKCfhulXM5SSsAqQBNfISpGbUglja2/ue7UY73Xb0Dp5EPUYHm70I7nXxWM1W9X9ZU3JRRt+Lm93syXG58Y7FPoda+Yd8hPzbDQkUTuB3uCUJUAUB+VCIIIuJIP+ul2rHFe6BKFF8KizAFfYuR9J9X1HEqB5/kBzA4WMKns4aHmf+FcFWcUs1vUDj4wulAYA2YpcOrRKkrEnxl7AAwRdmerfBcpaSFu1sgP8+iMRUww0H4yNMuCenf65hrgBgapvAZjFXF7vNFhzbWg6cs7b+QNIjs41m4N33MzWYuspqYeZBP4Dgzse23XVkBFfqDl8obwJtU+2940Ad+IukVPOAh+7RCwOL++txhaXQm+EspVwN7hvEfnofRgoHQyZvH4lb+ksaYsmv5RUTNrjLeBBLmEzfeMdhIHKmantMVk/A50q11ci0ACoWiwkpICadwgkCwG/vUZ93z3E4mXTEJb2Vi1g5x1QHzVKsc11s54VSdwVZPJrcG83VAhl8s5/XXY9WRtPevzEOlgtbto7M42U3wgqndRnCaogcCL3kocSOoRtotZoGoF2vf1vk1fDXxS3rXEGL6AMM4/NW6F/84+a9z7LExC15GeZUj7NQM7rUIS3/38Sp9f6yILZJ3zM59Twr6BevjsmajNlCMSq64PXo0IcjmWyzKtvhmUhYdiyg4bSl8CgxcZ9E+KRhIL6Cptpd9ERu8WFzYADUs+oB/yd78QHjvtYQbPEt19ce4D7mJpYSqFdz/8gxoRQ4jh8qRhbiyoU3C2p/a/LrXMIRQgzuuxvscA4GEmEJvE2udg25i9c3YECrGzDfJCrQQGn1RHNaSDLine truncated
+26
View File
@@ -178,6 +178,32 @@ jobs:
echo "plan2code-app exited within 5s (exit code $?); smoke test failed"
exit 1
fi
- name: Smoke-test the dashboard frame connects (macOS)
if: runner.os == 'macOS'
shell: bash
# A window whose dashboard frame never signs in still passes the alive check above
# (WebKit gives the frame no cookie, so macOS signs it in by a path prefix:
# takeFramePrefix in routes.mjs). Here the app autostarts
# scripts/smoke-agent.mjs, which opens a real console as an agent would, and
# scripts/smoke-frame.mjs waits up to 60s for that console's /health to count the
# frame as a browser. Runs only where the matrix has macOS: manual runs and pull
# requests labeled `full-matrix`.
run: |
project="$(mktemp -d)"
export PLAN2CODE_CONSOLE_HOME="$(mktemp -d)"
export PLAN2CODE_CONSOLE_DIR="$GITHUB_WORKSPACE/src/web-console"
export PLAN2CODE_APP_AGENT_BIN="$(pwd)/scripts/smoke-agent.mjs"
# No browser of the console's own, so only the app's frame can count as one.
export PLAN2CODE_NO_BROWSER=1
target/release/plan2code-app --project "$project" --agent claude &
pid=$!
status=0
node scripts/smoke-frame.mjs "$PLAN2CODE_CONSOLE_HOME" || status=$?
kill "$pid" 2>/dev/null || true
# The console is detached from the agent, so it outlives the app: stop it from the
# project folder it was opened in, under the same console home.
(cd "$project" && node "$PLAN2CODE_CONSOLE_DIR/console.mjs" stop --all) || true
exit "$status"
node-tests:
name: npm test (${{ matrix.os }})
+40 -9
View File
@@ -137,6 +137,8 @@ jobs:
GH_TOKEN: ${{ github.token }}
steps:
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- uses: actions/download-artifact@v8.0.2
with:
path: dist
@@ -187,18 +189,47 @@ jobs:
if [ "$state" = "true" ]; then
gh release edit "$TAG" --draft=false
fi
- name: Move the release branch to this tag
- name: Publish the slim install refs
# The README's first install is `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release`, so new users
# get the newest release and never a half-finished main. Last step, after the release is
# public: a failure earlier leaves the branch on the previous release. Fast-forward only
# (no --force), so a tag that is not ahead of the branch fails loudly instead of
# rewinding what people install.
# get the newest release and never a half-finished main, and exact updates fetch the
# immutable `install-vX.Y.Z` tag. scripts/publish-install-refs.mjs builds one synthetic
# commit holding only the runtime payload (install.js, package.json, version.json, LICENSE, NOTICE, src/)
# and a manifest binding it to this tag, then pushes it to both refs in one atomic push.
# Last step, after the release is public: a failure earlier leaves both refs on the
# previous release. Fast-forward only (no --force), and an existing install tag is never
# overwritten, so a bad run fails loudly instead of rewinding what people install.
env:
GIT_AUTHOR_NAME: github-actions[bot]
GIT_AUTHOR_EMAIL: 41898099+github-actions[bot]@users.noreply.github.com
GIT_COMMITTER_NAME: github-actions[bot]
GIT_COMMITTER_EMAIL: 41898099+github-actions[bot]@users.noreply.github.com
run: |
# The checkout is shallow, and git decides "fast-forward" locally: without the full
# history the branch's old tip is unknown here and the push is refused as "fetch first".
# The push authenticates with the workflow token through an askpass helper: the helper
# script contains no secret, the token itself stays only in this step's process
# environment, and actions/checkout does not persist it into .git/config.
cat > "$RUNNER_TEMP/p2c-git-askpass.sh" <<'EOF'
#!/bin/sh
case "$1" in
*Username*) printf '%s\n' x-access-token ;;
*) printf '%s\n' "$GH_TOKEN" ;;
esac
EOF
chmod +x "$RUNNER_TEMP/p2c-git-askpass.sh"
export GIT_ASKPASS="$RUNNER_TEMP/p2c-git-askpass.sh"
export GIT_TERMINAL_PROMPT=0
export GCM_INTERACTIVE=never
git config credential.helper ""
git config credential.username x-access-token
# The checkout is shallow, and the publisher needs the release branch's old tip as the
# new commit's parent and to check the move is a fast-forward.
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
git fetch --no-tags --unshallow origin
fi
git fetch --no-tags origin "refs/tags/${TAG}:refs/tags/${TAG}"
sha="$(git rev-parse "refs/tags/${TAG}^{commit}")"
git push origin "${sha}:refs/heads/release"
if git ls-remote --exit-code --heads origin release > /dev/null; then
git fetch --no-tags origin "+refs/heads/release:refs/remotes/origin/release"
fi
# The release branch already exists. A fork or first migration without one
# intentionally fails here rather than guessing; bootstrap it locally with the
# publisher's explicit --allow-missing-release-branch.
node scripts/publish-install-refs.mjs --tag "$TAG" --repo "$GITHUB_WORKSPACE"
+1
View File
@@ -1,3 +1,4 @@
.env
specs/
specs--completed/
dist/
+48 -22
View File
@@ -14,18 +14,42 @@
### 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 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
- About: install.js
- 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
### 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
### 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
@@ -33,16 +57,21 @@
- Why: The new tools fold-out reused git-tools and the Branches row's flex rule laid it out side by side.
- Noted: 2026-11-17, quick-task
### Each recordInstalled() in install.js stamps the version being installed into install.json, so a failed update must restore the old one with setRecordVersion(), or a retry says Already on.
- Kind: how-it-works
- About: install.js
- Noted: 2026-11-17, implement-review
### Before test-app-meter.mjs on a fresh checkout, run npm ci and node scripts/vendor.mjs in plan2code-app/: without ui/vendor/, app.js stops at its top-level await.
- Kind: command
- About: scripts/test-app-meter.mjs, plan2code-app/scripts/vendor.mjs
- Noted: 2026-12-03, 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
### From a desktop app terminal, run console tests with its PLAN2CODE_* vars unset (env -u PLAN2CODE_IN_APP ...): test-web-console-server.mjs and the loop tests read process.env directly.
- Kind: command
- About: scripts/web-console-test-helpers.mjs
- Noted: 2026-12-04, implement-review
### 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
@@ -64,25 +93,22 @@
- About: src/web-console/public/screens/agents
- Noted: 2026-11-17, implement-review
### The app's webview data sits outside ~/.plan2code, in Tauri's app_local_data_dir() on Windows and Linux (%LOCALAPPDATA%/com.plan2code.desktop); appWebviewDirs() in install.js lists it per OS.
- Kind: how-it-works
- About: install.js
- Noted: 2026-11-17, implement-review
### The desktop app's CSP allows no inline script, so anything that must run before the first paint (the saved theme and accent) goes in the classic head script ui/theme-early.js, not in app.js.
- Kind: convention
- About: plan2code-app/ui/theme-early.js
- Noted: 2026-11-17, implement-review
### The launcher's prompts each open a new readline on stdin, so a test piping several answers at once loses all but the first; drive a multi-prompt flow by writing each answer after a short delay.
### To drive several launcher prompts in scripts/test-launcher.mjs, use runAtTerminal(): each prompt opens a new readline on stdin, so piping all answers at once loses every one after the first.
- Kind: how-it-works
- About: src/launcher/plan2code.js
- About: src/launcher/plan2code.js, scripts/test-launcher.mjs
- Why: Each launcher prompt opens a new readline, so piping all answers at once loses every answer after the first.
- Noted: 2026-11-15, implement-review
### 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
### 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
+50
View File
@@ -0,0 +1,50 @@
# Installer
Paths: install.js, src/installer/**, scripts/bench-install-update.mjs, scripts/publish-install-refs.mjs, scripts/test-install-*.mjs, scripts/install-*.mjs
### A new src/installer/ module that install.js requires must join the file list npxCopy() copies in scripts/test-install-update.mjs, or every release redirect test fails.
- Kind: convention
- About: scripts/test-install-update.mjs, install.js
- Why: Adding skills-cli.js and canonical-skills.js failed five release redirect tests until npxCopy() copied them too.
- Noted: 2026-12-03, 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
- About: install.js
- 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
### A test that calls install() must point APPDATA and LOCALAPPDATA at the temp HOME first: its cleanLegacyPaths() sweep reads the VS Code prompts and Crush skills folders from them, outside HOME.
- Kind: how-it-works
- About: install.js, scripts/test-install-update.mjs
- Noted: 2026-12-03, implement-review
### An install-ref fixture test checks each fixture's own root for cleanup, never a count of p2c-install-refs-* in the temp dir: other test files build fixtures in parallel.
- Kind: correction
- About: scripts/test-install-refs.mjs, scripts/install-ref-fixtures.mjs
- Why: The cleanup test counted the temp dir and failed once other test files built fixtures alongside it.
- Noted: 2026-12-03, implement-review
### Each recordInstalled() in install.js stamps the version being installed into install.json, so a failed update must restore the old one with setRecordVersion(), or a retry says Already on.
- Kind: how-it-works
- About: install.js
- Noted: 2026-11-17, implement-review
### Give bench-install-update.mjs no --workdir whose path holds a UUID, since npm 12 redacts UUIDs in paths to *** and every isolated path breaks; the default temp workdir is safe.
- Kind: how-it-works
- About: scripts/bench-install-update.mjs
- Noted: 2026-12-03, implement-review
### skills@1.5.x skips every agent link when skills add gets the canonical store as its source, so agentLinkSource() gives that pin the built skills/ folder.
- Kind: how-it-works
- About: src/installer/skills-cli.js, install.js
- Noted: 2026-12-03, implement-review
### The app's webview data sits outside ~/.plan2code, in Tauri's app_local_data_dir() on Windows and Linux (%LOCALAPPDATA%/com.plan2code.desktop); appWebviewDirs() in install.js lists it per OS.
- Kind: how-it-works
- About: install.js
- Noted: 2026-11-17, implement-review
### update() says Already on from the record, command, skills and console; the app file is judged only by install.json's appVersion, so a piece that can stay old needs its own recorded version.
- Kind: how-it-works
- About: install.js
- Noted: 2026-12-04, quick-task
+1 -1
View File
@@ -3,7 +3,7 @@
The small games behind the die in the web console's top bar. This is the full guide to each game and to the rules they share; the console guide has the short version. Back to [the web console guide](web-console.md#activities).
The **die** in the top bar, right of the megaphone, opens **Activities**: small
The **die** in the top bar, right of the text size buttons, opens **Activities**: small
games to play while you wait, say through a long build. Thirteen ship today,
**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**. The window opens on a
**picker**: a row per game, in two columns on a wide window, with a small cover
+3 -2
View File
@@ -171,8 +171,9 @@ The same journey is four commands, each in a new conversation:
3. `/plan2code-3-implement specs/task-api/overview.md`, once per phase. It finds the next open phase itself.
4. `/plan2code-4-finalize specs/task-api/overview.md`. Verifies, updates docs, and archives the spec.
Add `--web` to any of them (for example `/plan2code-1-plan --web`) to open that step straight on the
web console without being asked. Every command and argument is in the README's
Typed on their own they start in your saved default (say "make the terminal my default" once to
set it; until then they ask). Add `--web` to any of them (for example `/plan2code-1-plan --web`) to
open that step straight on the web console for one session. Every command and argument is in the README's
[Prefer the terminal?](../README.md#prefer-the-terminal) section. You can switch between terminal and
console at any point, because the files under `specs/` are the only state.
+1 -1
View File
@@ -161,7 +161,7 @@ Security, six controls, about 60 lines:
1. Bind `127.0.0.1`.
2. **`Host` header allowlist.** This is the DNS-rebinding defense and the highest-value line in the server. Vite shipped GHSA-vg6x-rcgg-rjx6 for exactly this omission.
3. 128-bit token **in the URL path**, not the query string. Path placement also kills the Windows `cmd /c start` `&`-injection hazard, because the URL then contains no `&`.
4. First `GET /s/<token>/` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free.
4. First `GET /s/<token>/` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free. The macOS desktop app's frame is the exception: WebKit gives a cross-site frame no cookie, so there the 302 goes to `/f/<sha256(token)[0:32]>/` on the same `127.0.0.1` address, the router takes that exact prefix off the raw request line once, and a request under it passes the token gate. The page uses only page-relative URLs, so it works at `/` and under the prefix alike. Not a `<key>.localhost` host name: macOS tries it on `[::1]` first, where another process can take the port.
5. `Origin` check on every mutating request.
6. Strict CSP with no `unsafe-inline`, which is why JS and CSS are separate files rather than one inlined HTML.
+21 -2
View File
@@ -133,6 +133,11 @@ this:
visiting from talking to it through a DNS rebinding trick.
- A 128-bit token in the link, swapped for an `HttpOnly; SameSite=Strict` cookie
on first load so it leaves your address bar, your history and any screenshot.
In the macOS desktop app the page's frame gets no cookie (WebKit blocks
cookies for a frame from another site), so the link sends that frame to
`/f/<key>/` on the same `127.0.0.1` address instead, where the key is a hash
of the token, and the server lets in only requests under that exact prefix.
The frame has no address bar, and a browser tab still gets the cookie.
- A strict Content Security Policy with no inline script allowed.
- Markdown written by the agent is turned into page elements directly and never
into an HTML string, so a document that quotes a hostile README cannot run
@@ -169,8 +174,9 @@ 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`. |
| `POST /learning/tidy-quiet` | Tidy-up quiet: an empty JSON object (origin-checked; 409 `not-on` unless Learning is On). Stores a fingerprint of the saved lessons in `tidy-quiet.json` beside `pause.json`, so `scan.learning.nearCap` stays false until a lesson file changes. Sent by the banner's Not now and by a Tidy up that proposed nothing; repaints with no agent. |
| `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`. |
@@ -282,8 +288,21 @@ button, a different color.
```bash
node scripts/capture-screenshots.mjs # every screen
node scripts/capture-screenshots.mjs --only dashboard # one screen
node scripts/capture-screenshots.mjs --app # the desktop app's five pictures
```
`--app` takes the desktop app's pictures (`app-launch`, `app-terminal`,
`loop-setup`, `loop-banner`, `loop-stop`, dark only). It runs the app's own
page from `plan2code-app/ui` in Chrome with a stand-in for its Rust side, so the
bar, the launch card, the loop banner and the terminal panel are the real ones,
and frames a real staged console with the app's settings on. No agent runs: the
terminal text is written by `scripts/capture-app-shots.mjs`. It needs the app's
vendor files (`npm install` and `node scripts/vendor.mjs` in `plan2code-app`).
The README banner, `docs/banner.jpg`, is drawn by `node scripts/make-banner.mjs`
from the console's own step poses. Rerun it when the tagline, the license or a
step pose changes.
Each screen is staged with no agent, from the payloads in
`scripts/screenshots/` (its README names the file behind each screen), in a
throwaway sample project and console home that the script removes when it is
+18 -6
View File
@@ -30,7 +30,8 @@ inside it, or add `--web` to a skill (`/plan2code-1-plan --web plan a lunch voti
**Where next.** [walkthrough.md](walkthrough.md) follows one feature from the first idea to the
last phase. The rest of this file is the reference: every card, button and rule. Prefer the terminal?
Run the same commands without `--web` and answer there; the files under `specs/` are identical.
Answer **terminal** the one time a skill asks (or add `--terminal`); the
files under `specs/` are identical.
---
@@ -89,7 +90,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,10 +114,10 @@ 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.
Or start any step by its command (the full list is in the README's [Prefer the terminal?](../README.md#prefer-the-terminal) section). Until you save a default, it asks "In your browser (suggested)" or "Here in the terminal" each time; say "make the terminal (or web console) my default" and every skill in every project starts there (saved in `~/.plan2code/console/interface.json`). Add `--web` or `--terminal` to use the other one for one session (`/plan2code-1-plan --web plan a lunch voting app`), or just ask for it in your request; say "make the web console my default" to change it, or "ask me again" to clear it. One-session choices never change your default, and a task that is only *about* web code is not a request for the console. 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.
While the page is open, the agent's messages in the terminal end with `→ Look at the web console` and, while it waits on you, say *Waiting on your answer in the web console*.
@@ -474,11 +475,22 @@ the `/plan2code` command instead. That command is on both of these screens
anyway, for starting the dashboard in a fresh conversation — the better choice
after a long skill, since a fresh conversation starts with a clean context.
The Implementation Loop's own end screen works the same way: finished or
stopped, its actions sit beside a **Back to the dashboard** button that opens
The Implementation Loop is app only: with a spec picked, open **Implement** on the dashboard, tick its
**Loop** checkbox, and press **Set up Implementation Loop**. Its setup asks how many review rounds
per phase to allow (default 2): when a phase's own review leaves Critical or Warning, fresh reviewers
run up to that many more rounds before the phase is committed. Its own end screen works the same way:
finished or 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.
The **Review Loop** is app only too: open **Review** on the dashboard, tick its **Loop** checkbox, and
press **Set up Review Loop**. 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
+5 -3
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`. Whether a skill starts in the terminal or the console is asked each run until the person saves a default (`console.mjs interface`, saved in `~/.plan2code/console/interface.json`); `--web` / `--terminal` or plain words override it for one session. 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 **Loop** checkbox on Implement's confirm pane, disabled outside the app, 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 **Loop** checkbox on Review's confirm pane, disabled outside the app, `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 `publicLine 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 writes for it are the personal pause (`POST /learning/pause`) and the tidy-up quiet (`POST /learning/tidy-quiet`: a Tidy up that proposed nothing, or the banner's Not now, hides the nudge until the saved lessons change), both on this machine only, 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.
@@ -57,6 +57,8 @@ Build commands, installer menu options, non-interactive skill-build verification
Run the targeted suites for the part you changed, not the full `npm test`, when a change stays inside one area (a game, one console page, the launcher, one skill script); the full run is for changes to shared code, sync merges, version bumps and before a PR. The area-to-suite table is in "Targeted tests first".
Never run the Activities game tests as part of the full suite: `npm test` leaves them out, and they run only on request with `npm run test:games` (the owner runs them by hand when a game changes).
Details: [Development Commands](./.agents-docs/AGENTS-development-commands.md)
## Test map
@@ -118,5 +120,5 @@ When you make a mistake, get corrected, or discover something about this codebas
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → System → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
- When a test checks how `cmd.exe` finds a `.cmd`/`.bat` (current folder before PATH), clear `NoDefaultCurrentDirectoryInExePath` for the run under test (`env_remove` in Rust, `undefined` in a `test-launcher.mjs` `box.run` env): some shells (Claude Code's among them) already set it, and the decoy `.cmd` test for custom agents passed without its fix until it did.
- Never set a `Secure` cookie for the app's `tauri://localhost` frame (Linux and macOS): WebKit drops a Secure cookie sent over plain `http://127.0.0.1`, so every request after the sign-in got a 403 and the Linux app showed "its page did not show in this window" while working on Windows, where WebView2 counts loopback as secure. `cookieSameSite()` in `src/web-console/routes.mjs` sends Lax there and None; Secure only to `tauri.localhost`; check an embed change in a WebKit view, not only Chrome.
- Never set a `Secure` cookie for the app's `tauri://localhost` frame (Linux and macOS): WebKit drops a Secure cookie sent over plain `http://127.0.0.1`, so every request after the sign-in got a 403 and the Linux app showed "its page did not show in this window" while working on Windows, where WebView2 counts loopback as secure. `cookieSameSite()` in `src/web-console/routes.mjs` sends Lax there and None; Secure only to `tauri.localhost`; check an embed change in a WebKit view, not only Chrome. On macOS WebKit gives the frame no cookie even with Lax, so it signs in by the path prefix `/f/<key>/` (`takeFramePrefix()` in `routes.mjs`), and every URL the page uses must be page-relative (`scripts/test-web-console-relative-urls.mjs`).
- On Windows, treat a console the agent opened as dying with the agent: the app ends the agent's whole Job Object, so a `detached` server goes too, with no `exit` event. A `console.mjs post` still succeeds because it writes the session's files, so it proves nothing about the server; only the window's reconnect brings the page back. Every loop phase ends this way, and a reconnect budget that never refilled once lost the loop's stop card after Phase 3.
+143
View File
@@ -4,6 +4,149 @@ 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.7 (2026-12-05)
### 🐛 Fixed
- **Desktop app**: on macOS the dashboard now shows in the app's window. Before, WebKit gave that part of the window no sign-in cookie, so every request was refused.
- **Desktop app**: on macOS and Linux, quitting now stops the running agent together with what it started, and the dashboards it opened, however you quit: the close button, the menu, the Dock, Ctrl+C, a closed terminal or a plain `kill`. An agent that ends by itself still leaves a dev server it was asked to keep running.
- **Desktop app**: on macOS, Cmd+Q and the menu's Quit ask first while an agent is running, as the close button does, and one click answers the question even when the window was in the background.
- **Desktop app**: on macOS and Linux, starting from the Dock, Finder or a desktop entry now finds Node and agents set up only in your shell's interactive config, such as nvm in `~/.zshrc`. A slow or hung shell profile holds up the start by about 5 seconds at most; before, there was no limit.
- **Desktop app**: on macOS, Ctrl+V in the terminal reaches the agent, so Claude Code can take a pasted picture, and Cmd+V pastes without a Paste menu first.
- **Desktop app**: on macOS, the Dock shows Planny's icon while the app runs, and the window opens in front of the terminal that started it.
- **Desktop app**: after Change project, "The console stopped" no longer covers the new project, and Stop now in either loop no longer holds up the window while the agent ends.
- **Web console and launcher**: on macOS, a folder picker that fails no longer acts like Cancel: Workspace says Browse is not available, and `plan2code` asks you to type the folder. On every system, Browse opens at the nearest folder still there when the last one is gone.
- **Web console**: the Card width choices in User Preferences no longer run into each other at the Narrow width, and the page's closing signal is no longer refused in Safari and the macOS app.
- **Quick Task**: the See it running card, shown after a build, no longer says that nothing has been changed yet.
- **For contributors**: every URL the console page uses must be page-relative (`fetch("state")`, never `fetch("/state")`), because one that starts with a slash fails in the macOS app and nowhere else. `scripts/test-web-console-relative-urls.mjs` names any that does.
- **For contributors**: on macOS, the `app` workflow now fails when the dashboard never connects inside the app (manual runs and pull requests labeled `full-matrix`), and the release checklist covers the macOS fixes above.
## v3.2.6 (2026-12-04)
### ✨ Added
- **Web console**: when the Notes panel is stacked under the question (window 1080px wide or narrower), a drag handle on its top edge makes it taller or shorter; arrow keys nudge it, a double-click gives back the automatic height, and the size is kept between sessions.
### 🔧 Changed
- **Web console**: the dashboard's Implementation Loop and Review Loop cards are gone; Implement's and Review's confirm panes carry a Loop checkbox instead (app only, disabled outside the app and while a loop runs), whose Start opens the matching loop setup screen.
- **Skills**: every skill prompt, the console card and the Ask chat contract now say to reply in US English unless the person asks for another language, so replies and question cards stay in English when the person's messages or the project's files are not.
- **Desktop app**: when the skills are newer than the app, the bar now reads "Update to latest: vX.Y.Z" with an Update and restart button, instead of "Skills vX.Y.Z are newer than this app" with no way forward.
- **Launcher**: Devin's Balanced choice maps to Sonnet 5.5 Medium instead of SWE-2.1 High.
### 🐛 Fixed
- **Installer**: `plan2code update` and the app's Update and restart now fetch the desktop app again when `install.json` does not record it at this version, instead of stopping at Already on while the app file stays on an older release; the record keeps the app's version as `appVersion`, so a machine already on the app gets one app reinstall on its next update.
- **Web console**: after you press Finalize, Continue building, Fix together or Back to the dashboard on the Implementation Loop end screen, the button now shows a spinner and a working label and stays disabled until the page moves on; the Review Loop end screen's pressed button shows the same spinner.
## v3.2.5 (2026-12-03)
### 🔧 Changed
- **Installer**: the slim install refs also carry `LICENSE` and `NOTICE`.
- **For contributors**: run `npm run setup:hooks` once after `npm install` to turn on the pre-commit hooks; the `prepare` script that did it is gone.
### 🐛 Fixed
- **Installer**: the slim install refs announced in v3.2.4 were not published with it, because the release step refuses a `package.json` with a `prepare` script, so first installs kept getting v3.2.3. `npm test` now checks the real `package.json` for such scripts.
## v3.2.4 (2026-12-03)
### ✨ Added
- **Installer**: first installs and updates fetch a slim, runtime-only `release` branch and immutable `install-vX.Y.Z` tags instead of the whole repository, which the release workflow now publishes after each release. `--main`, branches and plain `vX.Y.Z` tags still work as before.
### 🔧 Changed
- **Installer**: each skill is copied into the shared skills store once, with a journal and rollback, and agents are linked by a single `skills add`; before, every agent's copy was rewritten, which made installs and updates slow.
- **Installer**: the shared console is staged in a checksummed folder and switched in only when complete, so an interrupted install or update no longer leaves a half-written console; the pinned `skills` CLI is now an exact version chosen by your Node version.
- **Update check**: `plan2code update` picks the newest release and fetches its slim ref when one exists, and falls back to the full tag when it does not.
- **For contributors**: `npm test` leaves out the Activities game suites; run them with `npm run test:games` when a game changes.
### 🐛 Fixed
- **Desktop app**: Change project, and picking a recent folder, now starts the same agent again in the new folder, on the same model, effort and permission mode; before, the new folder showed the launch card and an empty terminal until you pressed Start.
## v3.2.3 (2026-12-02)
### 🔧 Changed
- **Docs**: the README banner carries the tagline "Plan it. Approve it. Let it build." and the Apache 2.0 license.
### 🐛 Fixed
- **Docs**: the desktop app pictures in the README, the desktop app guide and the landing page (the launch card, the app with its terminal docked, and the Implementation Loop's setup, banner and stop screen) are real captures instead of labeled placeholders.
- **For contributors**: `node scripts/capture-screenshots.mjs --app` captures the five desktop app pictures from the app's own page with a stand-in for its Rust side, `node scripts/make-banner.mjs` draws the banner from the console's step poses, and `make-app-placeholders` is gone.
## v3.2.2 (2026-11-30)
### ✨ Added
- **Remembered interface**: a skill started on its own opens in your saved default, terminal or web console, instead of asking every run. With no default saved it asks as before, and saves nothing until you say "make the terminal (or web console) my default" (`console.mjs interface --set`, saved in `~/.plan2code/console/interface.json` for every project). `--web`, `--terminal` or plain words override it for one session, and a session can switch either way mid-run. The desktop app and the dashboard always use the web console. Next-step commands are printed bare, with a note that `--web` opens the web console; the console's own finish card still adds `--web`.
- **launcher**: Devin's model menu offers SWE-2.1, Gemini 4 Carbon and Gemini 3.8 Flash at Medium and High, and a Fusion model (Claude Opus 5.5 Medium with SWE-2.1 Medium as its sidekick).
### 🔧 Changed
- **launcher**: the model menus are sorted by vendor, lighter models before stronger ones, Medium before High.
- **launcher**: Devin's menu no longer lists Low-effort models, to stay within its 30 entries. If you chose one for Thrifty, Balanced or Best, the loop now uses the shipped choice; add the model under User Preferences, Agents & models, Add a model to keep using it.
- **Implementation Loop**: Devin's Balanced strength uses SWE-2.1 High (was SWE-2 High), at the same price.
## v3.2.1 (2026-11-29)
### ✨ Added
- **Web console**: text size buttons in the top bar, between the megaphone and the die: [-], the current size and [+] scale all the console's text in seven steps from 80% to 150%, the size returns to 100% when you click it, your choice is kept with your other looks, and Back to default on the Appearance tab resets it.
- **Learning**: the Tidy up banner has a Not now button that hides it until your saved lessons change (remembered on this machine only).
### 🔧 Changed
- **Git**: committing from the board takes one card, the commit subject and a choice of Commit only or Commit and push, answered in one send; choosing push is the yes, so the Commit this? and Push confirms are gone.
### 🐛 Fixed
- **Learning**: the Tidy up banner stays hidden once a Tidy up finds nothing to do, until your saved lessons change; before, it came straight back and Tidy up only said there was nothing to tidy.
## 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
+4 -4
View File
@@ -17,9 +17,9 @@ The web console is the main way in: a local page where questions, documents, bui
| From your project (shell) | `plan2code` | Opens Claude Code, Devin or Codex on the dashboard (`--cli claude` / `devin` / `codex` to choose) |
| Inside any agent | `/plan2code` (`$plan2code` in Codex) | Opens the dashboard: a card for every skill, launched on the same page |
| Install | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release` | Installs the skills and the `plan2code` command (to update, run `plan2code update`; re-running the install command also works, and removes nothing) |
| Update | `plan2code update` | Updates the skills, command, app and status line, with no menu (metrics and the bot only from a git checkout: `node install.js`); never uninstalls anything |
| Update | `plan2code update` | Updates the skills, command, app and status line from the newest slim install ref, with no menu (metrics and the bot only from a git checkout: `node install.js`); never uninstalls anything. Roll back with `plan2code update --tag vX.Y.Z`; use `--main` only for full-source development |
| Uninstall | `plan2code uninstall` | Removes the skills, command, app and dev tools after a Y/N; then asks whether `~/.plan2code/` (your notebooks, handoffs, settings) goes too. `--yes` skips the questions and keeps your data, `--purge` deletes it |
| Straight into a skill | `/plan2code-1-plan --web` (any step) | Skips the "web console or terminal?" question and opens the page |
| Straight into a skill | `/plan2code-1-plan --web` (any step) | Opens the page for this session, whatever your saved default |
The install command always opens a menu. Back at your prompt with no output at all? npm could not reach the repository and hid the reason: run `git ls-remote https://github.com/jparkerweb/plan2code.git` to see it (usually the network, a proxy or the VPN).
@@ -33,7 +33,7 @@ The **Implementation Loop** (app only) builds every remaining phase of a spec un
## Commands
Every command below is what a dashboard card runs. Typed on its own, each one asks "web console or terminal?" first.
Every command below is what a dashboard card runs. Typed on its own, each one starts in your saved default (terminal or web console); with none saved, it asks each time.
| Step | Command | Input | Output |
| ---------- | ----------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------- |
@@ -60,7 +60,7 @@ Every command below is what a dashboard card runs. Typed on its own, each one as
| changelog | /plan2code-changelog | Your branch | `CHANGELOG.md` entries and the `package.json` version, from the default branch's latest version |
| git | /plan2code-git | Your repo | Commits (`<subject>` / `AI Assisted`), branches, pull with conflict help, push, publish |
**Terminal instead:** run any command without `--web` and answer the interface question with **terminal**. Nothing is lost: same questions, same gates, same files under `specs/`. You can switch between the two mid-feature.
**Terminal or console, remembered:** until you save a default, each skill asks whether you want the web console or the terminal; say "make the terminal (or web console) my default" and every skill in every project starts there. Add `--web` or `--terminal` to override it for one session, or say "web console" or "terminal" to switch mid-session. Nothing is lost either way: same questions, same gates, same files under `specs/`.
## File Structure
+8 -5
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.4 · Apache 2.0 · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
Version 3.2.7 · Apache 2.0 · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
---
@@ -128,7 +128,7 @@ cd plan2code
node install.js
# Only if you plan to modify or contribute to Plan2Code itself
npm install && npx husky
npm install && npm run setup:hooks
```
</details>
@@ -277,9 +277,10 @@ Each one is a card on the dashboard and a command in your agent. Which cards lig
### Prefer the terminal?
Every skill also runs right in the terminal. Each one asks at the start whether you want the web
console or the terminal; add `--web` to skip the question and go straight to the web console:
`/plan2code-1-plan --web plan a REST API for tasks`.
Every skill also runs right in the terminal. Typed on its own, a skill starts in your saved default;
with none saved it asks "web console or terminal?" each time, until you say "make the terminal (or
web console) my default". Add `--web` (`/plan2code-1-plan --web plan a REST API for tasks`) or
`--terminal` to override that for one session.
---
@@ -308,6 +309,8 @@ the requirements.
**Too many or too few phases.** Fix it in Step 2 — a phase should be a logical grouping of work, not
a fixed size.
**An update seems stuck on old content.** `plan2code update` normally fetches the newest release's slim `install-vX.Y.Z` ref. Name the release you want, or roll back, with `plan2code update --tag vX.Y.Z`; a release without a slim ref is fetched by its plain tag on purpose. `plan2code update --main` installs the full source for development. `--force` fetches nothing newer: it only skips the `Already on` stop and reinstalls the version already fetched.
**The agent runs on another machine, or over SSH.** The page is served on `127.0.0.1` of the machine
the agent runs on, so your browser can only reach it there. A forwarded port often works; otherwise
work in the terminal, which loses nothing.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

After

Width:  |  Height:  |  Size: 79 KiB

+59 -7
View File
@@ -127,7 +127,7 @@ separate context-window meter of its own, so there is only ever one gauge to rea
threshold is tuned. The terminal panel has its own toolbar: dock it to the bottom or the right, collapse
it to a thin strip, or maximize it; its size is remembered. An "agent may need you" badge appears on a
collapsed or small panel once the agent has sat quiet for a while. **Change project** (in the project
menu) asks first if an agent is running, then stops it and the console before opening the new folder. It shows the same folder picker, with **Choose a folder** first and the recent folders under it (the one already open is left out); Cancel or Escape keeps the project as it is.
menu) asks first if an agent is running, then stops it and the console before opening the new folder, where the same agent starts again on the same model, effort and permission mode (with no agent in use, the launch card shows instead). It shows the same folder picker, with **Choose a folder** first and the recent folders under it (the one already open is left out); Cancel or Escape keeps the project as it is.
If the console itself ever needs reconnecting (it stopped, or the skills were just updated), every path
to that offers the same **Reconnect the console** button — never "Restart the console" in one place and
@@ -146,9 +146,9 @@ agent CLI.
## Implementation Loop
The Implementation Loop builds every remaining phase of a documented spec for you, one after another,
while you do something else. It is in the app only: the dashboard shows an **Implementation Loop**
card there, and nowhere else. Pick a spec, answer a short setup, press **Start the loop**, and the app
confirms it once in its own window before anything runs.
while you do something else. It is in the app only: with a spec picked, open **Implement** on the
dashboard, tick its **Loop** checkbox, and press **Set up Implementation Loop**. Answer a short setup,
press **Start the loop**, and the app confirms it once in its own window before anything runs.
![The Implementation Loop setup screen.](screenshots/loop-setup-dark.webp)
@@ -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).
@@ -266,7 +267,58 @@ the quick check and the commits are the app's own. The finish screen counts each
the full report** opens it, saved as `specs/<feature>/LOOP-SUMMARY-<date>.md` (`-2` and so on for another
the same day). After a stop, **Read why, and the report so far** shows it on the stop screen. While a build
is unfinished it lives in `~/.plan2code/console/loop-reports.json`, not the project, because 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".
clean tree. The in-app **Help** has a matching topic, **Implementation Loop**, linked as **How the loop works** on the loop setup screen.
## 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: open **Review** on the dashboard and tick its
**Loop** checkbox to reach the setup screen. The checkbox is disabled 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
@@ -274,11 +326,11 @@ clean tree. The in-app **Help** has a matching topic, **Implementation Loop**, w
When a newer release is out, the app's top bar shows **Update available** with **Update and restart**
and a **What's new** link to the release page. **Update and restart** installs the newest release (the
same installer `plan2code update` runs, with its progress in the bar) and then reopens the app on the
same installer `plan2code update` runs; the bar shows its compact progress lines, ending in the installer summary) and then reopens the app on the
same project; no terminal is needed. A running file cannot be overwritten on Windows, but the installer
renames it aside and the app then restarts into the new one. If an agent or a loop is running, the app
asks first (the same check as closing the window, with Stay as the default); answer Stay and the bar
offers **Restart Plan2Code** for when you are ready. If the update fails, the app you have keeps running
offers **Restart Plan2Code** for when you are ready. If the update fails or runs past its five-minute limit, the child installer is stopped, the app you have keeps running
and the bar says why; you can press the button again or run `plan2code update` in a terminal. After the
restart the bar says **Updated to vX** once. The app asks again every few hours while it stays open, and
says so when it cannot check (git missing, or no answer from GitHub). The dashboard's own **Update
Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 131 KiB

+674 -156
View File
File diff suppressed because it is too large. Load diff
+5 -3
View File
@@ -1,6 +1,6 @@
{
"name": "plan2code",
"version": "3.1.4",
"version": "3.2.7",
"private": true,
"license": "Apache-2.0",
"engines": {
@@ -10,14 +10,16 @@
"plan2code-install": "./install.js"
},
"scripts": {
"prepare": "husky",
"setup:hooks": "husky",
"build:skills": "node install.js --build-skills",
"fix:eol": "node scripts/fix-line-endings.mjs",
"set-version": "node scripts/set-version.mjs",
"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-agent-lookup.mjs scripts/test-agents-file.mjs scripts/test-app-meter.mjs scripts/test-app-smoke-agent.mjs scripts/test-app-smoke-frame.mjs scripts/test-browser-helper.mjs scripts/test-check-console-openings.mjs scripts/test-check-doc-size.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-test-lanes.mjs scripts/test-check-versions.mjs scripts/test-console-stub.mjs scripts/test-console-wire-budgets.mjs scripts/test-getting-started.mjs scripts/test-git-repo.mjs scripts/test-install-bench.mjs scripts/test-install-e2e.mjs scripts/test-install-refs.mjs scripts/test-install-update.mjs scripts/test-launcher.mjs scripts/test-line-endings.mjs scripts/test-publish-install-refs.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-script-coverage.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-finalize.mjs scripts/test-script-git.mjs scripts/test-script-lessons.mjs scripts/test-script-pathfinder.mjs scripts/test-script-pr-prep.mjs scripts/test-script-run-check.mjs scripts/test-script-test-commands.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-xray.mjs scripts/test-set-version.mjs scripts/test-skill-scripts.mjs scripts/test-skill-test-runs.mjs scripts/test-spec-carry-page.mjs scripts/test-spec-carry.mjs scripts/test-standalone-check.mjs scripts/test-ui-prototype-page.mjs scripts/test-us-english.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-card-rows.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-git.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-notepad.mjs scripts/test-web-console-page-ask.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-frame.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-review-loop.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-setup.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-relative-urls.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-shape.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-source.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-workspace.mjs",
"test:games": "node scripts/node-test.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-intro.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-mine.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-page-activities.mjs"
},
"devDependencies": {
"gpt-tokenizer": "2.9.0",
+5 -2
View File
@@ -957,7 +957,7 @@ dependencies = [
[[package]]
name = "fake-agent"
version = "3.1.4"
version = "3.2.7"
dependencies = [
"serde_json",
"terminal_size",
@@ -2647,10 +2647,13 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "plan2code-app"
version = "3.1.4"
version = "3.2.7"
dependencies = [
"chrono",
"libc",
"objc2",
"objc2-app-kit",
"objc2-foundation",
"portable-pty",
"reqwest",
"serde",
+1
View File
@@ -33,6 +33,7 @@ There is no dot while busy or once a finished step has nothing left to press; a
| `src-tauri/` | The Rust app |
| `ui/` | The app page (plain HTML, CSS and JavaScript, no framework) |
| `fake-agent/` | A stand-in agent program the tests run in a real pseudo-terminal |
| `scripts/` | `vendor.mjs` (copies the xterm files into `ui/vendor/`), and CI's macOS frame check: `smoke-agent.mjs`, a stand-in agent that opens a real console, and `smoke-frame.mjs`, which waits for the console's `/health` to count the app's frame |
| `package.json` | The app's own npm packages (xterm, the Tauri CLI). Separate from the repo root so the root and the console stay dependency-free |
## Build and run
+36 -4
View File
@@ -37,11 +37,26 @@ file directly after checking it against the release's checksum list.
- [ ] `plan2code --classic` runs the agent in the terminal with the app installed
- [ ] Linux only: with `DISPLAY` and `WAYLAND_DISPLAY` unset, `plan2code` runs the terminal flow
- [ ] The desktop shortcut opens the folder menu (Choose a folder first, recent folders under it) and then the app
- [ ] macOS: started from the desktop shortcut or `plan2code` in Terminal, the app's window opens in
front of Terminal, as the active app
- [ ] macOS: the first start is stopped by Gatekeeper, **Open Anyway** in System Settings (Privacy &
Security) lets it through, and `docs/desktop-app.md` describes what you saw
- [ ] macOS and Linux: start the app from the Dock, Finder or a `.desktop` file (not a terminal) on
a machine where Node is only on PATH through nvm, Homebrew or Volta: the first-run checklist
still finds Node and the installed CLIs, and the console and an agent still start
- [ ] macOS: the same from Finder with Node set up by nvm in `~/.zshrc` only (not `~/.zprofile`):
Node and the agent are still found. With Node and an agent on the login PATH instead
(Homebrew, or nvm in `~/.zprofile`), `~/.zshrc` is not read at start, only on Check again;
with Homebrew's Node there but the agent installed by npm under nvm in `~/.zshrc`, the agent
is still found at start. A hung `~/.zprofile`
delays the start by 3 s at most and a hung `~/.zshrc` by 2 s; only a slow `~/.zprofile`
followed by a hung `~/.zshrc` reaches 5 s
- [ ] macOS and Linux: when the installer puts the `plan2code` command in a folder that is not on
PATH, its closing steps say so and name the line to add and the startup file to add it to;
done as written, `plan2code` runs in a new terminal
- [ ] macOS: canceling the folder picker (the `plan2code` launcher's, or Workspace's add folder)
reads as a cancel; a picker that fails instead (an `osascript` error other than -128) shows
an error in the console, and makes the launcher ask for the folder path to be typed
- [ ] Windows: SmartScreen's **More info**, then **Run anyway**, lets it through, and
`docs/desktop-app.md` describes what you saw
- [ ] `plan2code update` updates the skills, the command and the app, including while the app is
@@ -55,6 +70,8 @@ file directly after checking it against the release's checksum list.
## The window (each system)
- [ ] The dashboard shows in the frame and the terminal panel is visible beneath it
- [ ] macOS: the frame signs in by itself (WebKit gives it no cookie, so the console moves it under
its own `/f/<key>/` path on `127.0.0.1`); a blank frame or a sign-in page in it is a failure
- [ ] Resizing the window keeps both usable; dragging the handle resizes the panel
- [ ] The bar shows the project folder; the permission note appears only while an agent started
with checks off is running, never otherwise
@@ -92,8 +109,9 @@ file directly after checking it against the release's checksum list.
- [ ] **Change project** in the top bar's project menu, with an agent running: it asks first, then the folder
picker (Choose a folder, then recent folders) opens; canceling the picker leaves the running agent and its project untouched
- [ ] Start the app with no arguments: it shows the folder picker, not the last project; a recent folder opens in one click
- [ ] Change project, pick a different folder: the old agent and console stop, the new folder opens
on the launch card (or the checklist, if its own first run has not passed yet)
- [ ] Change project, pick a different folder: the old agent and console stop, and the same agent starts in the new folder
on the same model and mode, with its dashboard showing (the launch card, or the checklist if its own
first run has not passed yet, only when no agent was in use)
- [ ] Reload the window (or navigate away and back) while an agent is running: the terminal redraws
from where it was, not blank, and the dashboard reconnects to the same session
- [ ] When the app and the installed skills differ in version, the bar's right end offers **Update
@@ -111,7 +129,9 @@ Do each of Claude Code, Devin and Codex for a few minutes:
- [ ] Pasting several lines
- [ ] A line with Unicode and emoji
- [ ] Select text in the terminal: it copies on its own; Ctrl+Shift+C (Windows, Linux) or Cmd+C
(macOS) copies the selection too; Ctrl+V / Cmd+V pastes
(macOS) copies the selection too; Ctrl+V (Windows, Linux) or Cmd+V (macOS) pastes
- [ ] macOS: Cmd+V pastes the text once, at once, with no **Paste** menu popping up first
- [ ] macOS: Ctrl+V reaches the agent instead of pasting (Claude Code pastes a copied image with it)
- [ ] Exiting the agent: the agent menu reads "ended" with the reason beside it, and New Session stays
just left of it
@@ -120,10 +140,22 @@ Do each of Claude Code, Devin and Codex for a few minutes:
- [ ] Start, then **New Session**: it confirms once, with Planny on a coffee break and no claim about unsaved
work, then a fresh agent starts on the same agent, model, effort and permission mode, and the
dashboard shows the pick-up chip with a brief that matches the session
- [ ] macOS and Linux: once New Session's dashboard shows, `ps -Ao pid,command | grep server.mjs` lists
the new console only; the old one stopped when the window moved on from it
- [ ] An agent that ends by itself leaves the app asking nothing until New Session or **Change agent**
(in the agent menu) is pressed; Change agent reopens the launch card with a real choice to make again
- [ ] Closing the window while an agent runs asks first, and "no" keeps the window open
- [ ] Cmd+Q on macOS asks the same
- [ ] macOS: Cmd+Q and the app menu's Quit ask the same while an agent works, in the window; Quit
from the Dock's menu quits at once with no question, and its cleanup still runs
- [ ] macOS: with another app in front, the window's close button asks in front of it, and one
click on Quit quits; Cmd+Q with the window minimized brings the window back with the question
- [ ] macOS and Linux: after each way of quitting (Cmd+Q, the app menu's Quit, closing the window,
a plain `kill` of the app, Ctrl+C or closing the terminal when the app's program was run from
one, and on macOS Quit from the Dock), with an agent running, nothing is left:
`ps -Ao pid,pgid,command | grep -E 'plan2code-app|server.mjs'` shows no app, no agent or
process of its group, and no console the agent opened. After an agent that ended by itself,
the same shows no app and no console it opened, while a process it left running in its
group on purpose (a backgrounded dev server) is still there
- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then New Session; check Task
Manager and confirm no leftover `node.exe` (or the CLI's own process) is left running
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "fake-agent"
version = "3.1.4"
version = "3.2.7"
description = "A stand-in agent program for the Plan2Code app's tests"
edition = "2021"
publish = false
+212 -1
View File
@@ -10,8 +10,18 @@
//! 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)
//! STRAY (macOS and Linux) start a child that ignores hangup and is never
//! waited for, and print its process id as `STRAY <n>`; elsewhere
//! say `STRAY unavailable`
//! <other> echoed back as `echo: <line>`
//!
//! A change in terminal size is reported on its own as `SIZE <cols>x<rows>`.
@@ -43,8 +53,14 @@ 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,
/// `STRAY`: leave a hangup-ignoring child behind in the agent's process group.
Stray,
Echo(String),
}
@@ -65,6 +81,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 +130,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 {
@@ -82,6 +139,24 @@ fn write_report_to(home: &std::path::Path, sid: &str, json: &str) -> bool {
std::fs::write(&temp, text).is_ok() && std::fs::rename(&temp, &file).is_ok()
}
/// A child that ignores hangup, in this process's group, never waited for.
#[cfg(unix)]
fn start_stray() -> Option<u32> {
std::process::Command::new("/bin/sh")
.args(["-c", "trap '' HUP; exec sleep 300"])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.ok()
.map(|child| child.id())
}
#[cfg(not(unix))]
fn start_stray() -> Option<u32> {
None
}
pub fn parse(line: &str) -> Command {
let line = line.trim();
if let Some(rest) = line.strip_prefix("STEP ") {
@@ -109,12 +184,48 @@ 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;
}
if line == "STRAY" {
return Command::Stray;
}
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,12 +280,30 @@ 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 {
thread::sleep(Duration::from_secs(3600));
}
}
Command::Stray => match start_stray() {
Some(pid) => say(&format!("STRAY {pid}")),
None => say("STRAY unavailable"),
},
Command::Echo(text) => say(&format!("echo: {text}")),
}
}
@@ -204,6 +333,7 @@ mod tests {
Command::Report("{\"phase\":2}".into())
);
assert_eq!(parse("HANG\r\n"), Command::Hang);
assert_eq!(parse("STRAY"), Command::Stray);
}
#[test]
@@ -230,6 +360,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.4",
"version": "3.2.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "plan2code-app",
"version": "3.1.4",
"version": "3.2.7",
"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.4",
"version": "3.2.7",
"private": true,
"description": "Plan2Code desktop app (Tauri). Separate from the repo root so the root and the web console stay dependency-free.",
"scripts": {
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env node
// A stand-in agent for CI's smoke run of the built app (.github/workflows/app.yml).
// Point PLAN2CODE_APP_AGENT_BIN at this file. Like a real agent, it opens a web
// console dashboard, with the environment the app gave it, so the console
// announces itself to the window and the dashboard frame has something to
// connect to (smoke-frame.mjs then checks it did). The repo's fake-agent opens
// no console, so it cannot stand in for this.
//
// It needs PLAN2CODE_CONSOLE_DIR (the folder holding console.mjs), ignores the
// arguments the app passes a real agent, and then waits on its input until it
// closes. It starts nothing else: the console server is detached, and the
// smoke run stops it with `console.mjs stop --all`.
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
const consoleDir = process.env.PLAN2CODE_CONSOLE_DIR;
if (!consoleDir) {
console.error('smoke-agent: PLAN2CODE_CONSOLE_DIR is not set; it names the folder holding console.mjs');
process.exit(2);
}
const open = spawnSync(process.execPath, [join(consoleDir, 'console.mjs'), 'open', '--workflow', 'dashboard'], {
stdio: ['ignore', 'inherit', 'inherit'],
});
if (open.error || open.status !== 0) {
console.error(`smoke-agent: console.mjs open failed (${open.error ? open.error.message : `exit ${open.status}`})`);
process.exit(1);
}
console.log('smoke-agent: dashboard open; waiting on input');
process.stdin.resume();
process.stdin.on('end', () => process.exit(0));
+100
View File
@@ -0,0 +1,100 @@
// Checks the app's dashboard frame connected to its console, for CI's macOS smoke
// run (.github/workflows/app.yml). A window that comes up but never signs its
// frame in looks alive to a process check; the console's own browser count
// does not lie.
//
// node smoke-frame.mjs [<console home>] [--timeout-ms N]
//
// The console home defaults to PLAN2CODE_CONSOLE_HOME. Waits for a session
// handle there (runtime/<project hash>/<sid>.json), then polls that session's
// open GET /health until it counts a browser. Exit 0 once one connects; exit 1
// when the time (60 s by default, for both waits together) runs out, with the
// last answer printed; exit 2 for a usage error.
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { parseArgs } from 'node:util';
const POLL_MS = 500;
const REQUEST_MS = 2000;
let parsed;
try {
parsed = parseArgs({ allowPositionals: true, options: { 'timeout-ms': { type: 'string' } } });
} catch (err) {
usage(err.message);
}
const home = parsed.positionals[0] || process.env.PLAN2CODE_CONSOLE_HOME;
if (!home) usage('no console home: pass one, or set PLAN2CODE_CONSOLE_HOME');
const timeoutMs = Number(parsed.values['timeout-ms'] ?? 60000);
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) usage('--timeout-ms takes a positive number');
const deadline = Date.now() + timeoutMs;
let last = null;
while (Date.now() < deadline) {
// Read again each round: a reconnect can resume the session on a new port.
const handle = newestHandle(home);
if (handle) {
last = await health(handle);
if (last.body && last.body.sid === handle.sid && last.body.browsers >= 1) {
console.log(`smoke-frame: the dashboard frame connected (browsers ${last.body.browsers}, port ${handle.port})`);
process.exit(0);
}
}
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
}
if (!last) {
console.error(`smoke-frame: no session appeared under ${home} within ${timeoutMs} ms`);
} else {
console.error(`smoke-frame: no browser connected within ${timeoutMs} ms; last /health answer from port ${last.port}: ${last.text}`);
}
process.exit(1);
function usage(message) {
console.error(`smoke-frame: ${message}\nusage: node smoke-frame.mjs [<console home>] [--timeout-ms N]`);
process.exit(2);
}
// The most recently written session handle under the home, or null.
function newestHandle(consoleHome) {
const runtime = join(consoleHome, 'runtime');
let newest = null;
for (const hash of safeList(runtime)) {
for (const name of safeList(join(runtime, hash))) {
if (!name.endsWith('.json')) continue;
const file = join(runtime, hash, name);
try {
const handle = JSON.parse(readFileSync(file, 'utf8'));
const mtime = statSync(file).mtimeMs;
if (Number.isInteger(handle.port) && handle.sid && (!newest || mtime > newest.mtime)) newest = { ...handle, mtime };
} catch {
// Half written or removed between the listing and the read: the next round sees it whole.
}
}
}
return newest;
}
function safeList(dir) {
try {
return readdirSync(dir);
} catch {
return [];
}
}
// One /health answer: the raw text for the failure message, and the body when it parsed.
async function health(handle) {
try {
const res = await fetch(`http://127.0.0.1:${handle.port}/health`, { signal: AbortSignal.timeout(REQUEST_MS) });
const text = await res.text();
let body = null;
try {
body = JSON.parse(text);
} catch {
// Not JSON: kept as text for the message.
}
return { port: handle.port, text: `${res.status} ${text}`, body };
} catch (err) {
return { port: handle.port, text: `no answer (${err.message})`, body: null };
}
}
+8 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "plan2code-app"
version = "3.1.4"
version = "3.2.7"
description = "Plan2Code desktop app"
edition = "2021"
publish = false
@@ -28,6 +28,13 @@ reqwest = { version = "0.13", default-features = false, features = ["blocking",
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(target_os = "macos")'.dependencies]
# Already pulled in by tauri itself; named directly here only to set the Dock
# icon (`set_app_icon` in main.rs), which tauri does for dev builds alone.
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSImage", "NSResponder"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSData", "NSGeometry"] }
[target.'cfg(windows)'.dependencies]
# Already pulled in by portable-pty itself; named directly here only for the
# Job Object APIs it does not expose (ending a `cmd /c` npm shim's whole
+130 -8
View File
@@ -11,6 +11,7 @@ use std::thread;
use serde::Serialize;
use crate::agents::{agent_launch_spec, Agent, PermissionMode};
use crate::log;
use crate::pty_host::{PtyHost, StartOptions};
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
@@ -35,6 +36,12 @@ pub type BeforeFresh = Arc<dyn Fn() -> Option<String> + Send + Sync>;
/// the manager.
pub type ForgetSession = Arc<dyn Fn() + Send + Sync>;
/// Runs once for each agent that ends, however it ends: by itself, by a stop,
/// or replaced by Restart or a loop phase's fresh start. It can run with the
/// manager's state locked, so it must return quickly and must not call back
/// into the manager.
pub type Ended = Arc<dyn Fn() + Send + Sync>;
/// What the page needs to draw the bar. `generation` counts the agents started
/// so far: a new number means a fresh agent, so the terminal clears.
#[derive(Clone, Debug, Serialize)]
@@ -116,12 +123,17 @@ struct Shared {
sink: Sink,
before_fresh: Mutex<Option<BeforeFresh>>,
forget_session: Mutex<Option<ForgetSession>>,
ended: Mutex<Option<Ended>>,
/// Environment every agent this manager starts gets, on top of its own:
/// the in-app signal that sends the agent's console pages to this window.
extra_env: Mutex<Vec<(String, String)>>,
/// Bumped for every agent started. Output and exits from an older agent
/// compare against it and are dropped.
generation: AtomicU64,
/// The threads that wait for each agent's end and finish the process group
/// of one the app replaced, so a stop can wait for them.
#[cfg(unix)]
ends: Mutex<Vec<thread::JoinHandle<()>>>,
inner: Mutex<Inner>,
}
@@ -144,8 +156,11 @@ impl AgentManager {
sink,
before_fresh: Mutex::new(None),
forget_session: Mutex::new(None),
ended: Mutex::new(None),
extra_env: Mutex::new(Vec::new()),
generation: AtomicU64::new(0),
#[cfg(unix)]
ends: Mutex::new(Vec::new()),
inner: Mutex::new(Inner {
state: AgentState::Idle,
running: None,
@@ -177,6 +192,13 @@ impl AgentManager {
}
}
/// Run `hook` once for every agent that ends (see `Ended`).
pub fn set_ended(&self, hook: Ended) {
if let Ok(mut slot) = self.shared.ended.lock() {
*slot = Some(hook);
}
}
/// Make the app forget the console session it follows, so the next agent's
/// `open` starts a new one.
pub fn forget_session(&self) {
@@ -366,6 +388,7 @@ impl AgentManager {
self.shared.generation.fetch_add(1, Ordering::SeqCst);
if let Some(old) = inner.running.take() {
let _ = old.host.kill();
self.shared.ended();
}
}
match self.shared.spawn(&mut inner, prompt, choice, extra_env) {
@@ -455,7 +478,9 @@ impl AgentManager {
}
/// End the agent for good (quitting). Nothing starts afterwards, and the
/// agent's process is gone when this returns.
/// agent's process, with what is left of its process group on macOS and
/// Linux, is gone when this returns. So is the group of an agent replaced
/// a moment before, whose grace may still be running.
pub fn stop(&self) {
let host = {
let mut inner = lock(&self.shared.inner);
@@ -470,7 +495,12 @@ impl AgentManager {
if let Some(host) = host {
let _ = host.kill();
let _ = host.wait();
// The app may exit right after, before `kill`'s own grace runs out.
host.end_group();
self.shared.ended();
}
#[cfg(unix)]
self.shared.finish_ends();
}
}
@@ -513,6 +543,42 @@ impl Shared {
}
}
/// An agent ended: run the `ended` hook, if one is set.
fn ended(&self) {
let hook = self.ended.lock().ok().and_then(|slot| slot.clone());
if let Some(run) = hook {
run();
}
}
/// Keep an agent's end thread, so `finish_ends` can wait for it; threads
/// already done are let go.
#[cfg(unix)]
fn keep_end(&self, end: thread::JoinHandle<()>) {
let mut ends = self
.ends
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
ends.retain(|kept| !kept.is_finished());
ends.push(end);
}
/// Wait until every agent started here has ended and the process group of
/// each one the app stopped or replaced is gone: the app may exit straight
/// after, which would cut a replaced agent's grace short.
#[cfg(unix)]
fn finish_ends(&self) {
let ends = std::mem::take(
&mut *self
.ends
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()),
);
for end in ends {
let _ = end.join();
}
}
fn emit(&self, inner: &Inner) {
(self.sink)(AgentEvent::State(self.snapshot(inner)));
}
@@ -602,14 +668,25 @@ impl Shared {
self.emit(inner);
let shared = Arc::clone(self);
thread::spawn(move || {
let end = thread::spawn(move || {
let reason = match host.wait_described() {
Ok((_, Some(signal))) => format!("was ended by a signal ({signal})"),
Ok((_, Some(signal))) => format!("{SIGNAL_REASON} ({signal})"),
Ok((code, None)) => format!("exited with code {code}"),
Err(e) => format!("stopped: {e}"),
};
shared.on_exit(generation, reason);
// Only an agent the app stopped or replaced takes its process
// group with it: after a Restart or New Session this finishes
// what `kill`'s grace thread started (after a stop it finds the
// group gone). An agent that ended by itself leaves its group
// alone, so work the person asked it to leave running survives.
if !shared.on_exit(generation, reason) {
host.end_group();
}
});
#[cfg(unix)]
self.keep_end(end);
#[cfg(not(unix))]
drop(end);
Ok(())
}
@@ -620,6 +697,7 @@ impl Shared {
self.generation.fetch_add(1, Ordering::SeqCst);
if let Some(old) = inner.running.take() {
let _ = old.host.kill();
self.ended();
}
let hook = self.before_fresh.lock().ok().and_then(|slot| slot.clone());
inner.brief_note = hook.and_then(|run| run());
@@ -644,19 +722,42 @@ impl Shared {
}
}
/// The agent's process ended. Stale if a newer agent has replaced it.
fn on_exit(self: &Arc<Self>, generation: u64, reason: String) {
/// The agent's process ended. Stale if a newer agent has replaced it, or
/// the app stopped it. True when it ended by itself (not stale).
fn on_exit(self: &Arc<Self>, generation: u64, reason: String) -> bool {
let mut inner = lock(&self.inner);
if self.generation.load(Ordering::SeqCst) != generation {
return;
return false;
}
inner.running = None;
// Ended on its own: say why and start nothing.
// Ended on its own: say why and start nothing. A signal nobody here
// sent (stop and Restart move the generation on first) also goes to
// the log, since the bar's reason is gone once a new agent starts.
if let Some((choice, _)) = &inner.last_start {
if let Some(line) = exit_log_line(choice.kind.id(), &reason) {
log::line(&line);
}
}
inner.state = AgentState::Ended { reason };
self.emit(&inner);
// Still locked: no fresh agent can start, and announce, before the
// hook has taken what this one left.
self.ended();
true
}
}
/// How the bar's reason starts for an agent a signal ended.
const SIGNAL_REASON: &str = "was ended by a signal";
/// The log line for an agent's end, from its id and the bar's reason: only
/// an end by a signal gets one, since an exit code is the agent's own word.
fn exit_log_line(agent: &str, reason: &str) -> Option<String> {
reason
.starts_with(SIGNAL_REASON)
.then(|| format!("plan2code: the agent {agent} {reason}"))
}
#[cfg(test)]
mod replay_tests {
use super::*;
@@ -684,3 +785,24 @@ mod replay_tests {
assert_eq!(replay, b"6789");
}
}
#[cfg(test)]
mod exit_log_tests {
use super::*;
#[test]
fn a_signal_gives_a_line_naming_the_agent_and_the_signal() {
let reason = format!("{SIGNAL_REASON} (Killed: 9)");
let line = exit_log_line("claude", &reason).expect("a signal is logged");
assert!(line.contains("claude"), "{line}");
assert!(line.contains("Killed: 9"), "{line}");
assert!(line.starts_with("plan2code: "), "{line}");
}
#[test]
fn an_exit_code_or_a_failed_wait_gives_no_line() {
assert_eq!(exit_log_line("claude", "exited with code 0"), None);
assert_eq!(exit_log_line("claude", "exited with code 1"), None);
assert_eq!(exit_log_line("claude", "stopped: wait failed"), None);
}
}
+78 -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")]
@@ -1146,6 +1150,34 @@ pub fn custom_agents() -> (Vec<CustomAgent>, Vec<String>) {
.unwrap_or_default()
}
/// The command of every built-in and custom agent that the lookup searches
/// PATH for by name, each once, in list order. A command with a folder in it
/// runs from there, whatever PATH holds, so it is left out. The PATH lookup at
/// start (`node_check::login_shell_path`) reads the shell's interactive config
/// when none of these is on the login PATH.
#[cfg(unix)]
pub fn path_agent_commands() -> Vec<String> {
let (custom, _) = custom_agents();
path_commands(
builtin_entries()
.iter()
.map(|entry| entry.command.as_str())
.chain(custom.iter().map(|agent| agent.command.as_str())),
)
}
/// `path_agent_commands` over the given commands.
#[cfg(unix)]
fn path_commands<'a>(commands: impl Iterator<Item = &'a str>) -> Vec<String> {
let mut seen = HashSet::new();
commands
.map(clean_command)
.filter(|command| !command.is_empty() && !has_separator(command, false))
.filter(|command| seen.insert(*command))
.map(str::to_string)
.collect()
}
fn clean_command(command: &str) -> &str {
let command = command.trim();
command
@@ -1652,6 +1684,31 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn the_path_agent_commands_are_the_bare_names_each_once() {
// The baked built-ins, then a custom list with a repeat, a quoted
// name, a command with a folder in it and an empty one.
let builtins = parse_agent_list(BAKED_AGENTS).expect("the baked list parses");
let custom = [
"codex",
"\"opencode\"",
"/opt/tools/bin/gemini",
"./agent",
" ",
];
assert_eq!(
path_commands(
builtins
.builtins
.iter()
.map(|entry| entry.command.as_str())
.chain(custom)
),
["claude", "devin", "codex", "opencode"]
);
}
#[test]
fn the_baked_list_matches_the_shipped_agents_json() {
// include_str! means the baked copy IS src/launcher/agents.json; this
@@ -1678,6 +1735,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 +1881,7 @@ mod tests {
prompt: String::new(),
args: vec![],
bypass_args: vec![],
helpers: false,
model_args: vec![],
install_url: None,
install: PerOs::default(),
@@ -1985,10 +2058,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!(
(
+470 -12
View File
@@ -6,6 +6,7 @@ use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use serde::Serialize;
@@ -119,6 +120,13 @@ fn node_command(console_dir: &Path) -> Command {
use std::os::windows::process::CommandExt;
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
}
// Ctrl+C and a closing terminal signal the app's whole process group: a stop running there
// would end before it stopped its console.
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
command
}
@@ -403,22 +411,237 @@ impl ConsoleSupervisor {
if self.stopped {
return Ok(());
}
let output = node_command(&self.console_dir)
.args(stop_args(&self.session.sid))
.current_dir(&self.project_dir)
.output()
.map_err(err)?;
self.stopped = true;
if !output.status.success() {
return Err(format!(
"console stop failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
));
let result = run_stop(&self.console_dir, &self.project_dir, &self.session.sid);
// Only a stop that could not run at all leaves the flag clear, as before.
if !matches!(result, Err(StopError::NotRun(_))) {
self.stopped = true;
}
Ok(())
result.map_err(StopError::into_message)
}
}
/// `console.mjs stop --session <sid> --force` for any session, run in the
/// project folder: the same stop `ConsoleSupervisor::stop` runs, for a console
/// this app does not supervise (one an agent announced and the window has
/// since moved on from).
pub fn stop_console_session(
console_dir: &Path,
project_dir: &Path,
sid: &str,
) -> Result<(), String> {
run_stop(console_dir, project_dir, sid).map_err(StopError::into_message)
}
/// One console an agent announced. `left` once that agent has ended while the
/// window still showed the console: nothing needs it after the window moves on.
struct Announced {
sid: String,
left: bool,
}
/// The console sessions this app's agents announced on macOS and Linux, by
/// sid, in the order they came: the ones to stop when the agent that opened
/// them ends, when the window moves on from one an ended agent left, or when
/// the app quits. Consoles the app started itself are never recorded here, and
/// one the app stopped for good is forgotten; the bar's stop, which keeps the
/// session to start it again, leaves it recorded. Also holds the threads still
/// stopping consoles after an agent's end or a new page, so a quit can wait for
/// them.
#[derive(Default)]
pub struct AnnouncedConsoles {
consoles: Mutex<Vec<Announced>>,
stops: Mutex<Vec<std::thread::JoinHandle<()>>>,
}
impl AnnouncedConsoles {
fn lock(&self) -> MutexGuard<'_, Vec<Announced>> {
self.consoles
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
/// Remember `sid`, announced by a running agent; one already recorded is
/// kept once, and is no longer left: the new agent joined it.
pub fn record(&self, sid: &str) {
let mut consoles = self.lock();
match consoles.iter_mut().find(|known| known.sid == sid) {
Some(known) => known.left = false,
None => consoles.push(Announced {
sid: sid.to_string(),
left: false,
}),
}
}
/// Remember `sid` as left by an agent that has ended; one a new agent
/// announced in the meantime stays that agent's.
fn leave(&self, sid: &str) {
let mut consoles = self.lock();
if !consoles.iter().any(|known| known.sid == sid) {
consoles.push(Announced {
sid: sid.to_string(),
left: true,
});
}
}
/// Drop `sid` from the record: the app stopped that console itself.
pub fn forget(&self, sid: &str) {
self.lock().retain(|known| known.sid != sid);
}
/// Every recorded sid, in record order, and an empty record after.
pub fn take_all(&self) -> Vec<String> {
std::mem::take(&mut *self.lock())
.into_iter()
.map(|known| known.sid)
.collect()
}
/// Every console left by an agent that has ended, but for the one the
/// window follows, no longer recorded after.
fn take_left(&self, followed: Option<&str>) -> Vec<String> {
let mut consoles = self.lock();
let (left, kept) = std::mem::take(&mut *consoles)
.into_iter()
.partition(|known| known.left && followed != Some(known.sid.as_str()));
*consoles = kept;
left.into_iter().map(|known| known.sid).collect()
}
/// The window follows `followed` now: stop each console an agent that has
/// ended left under it, with `stop` on a thread of its own, since a stop
/// runs `node`. A console of an agent still running is never touched.
pub fn stop_left<F>(&self, followed: &str, stop: F)
where
F: Fn(&str) + Send + 'static,
{
let sids = self.take_left(Some(followed));
if sids.is_empty() {
return;
}
self.keep_stop(std::thread::spawn(move || {
for sid in sids {
stop(&sid);
}
}));
}
/// Keep a thread that is stopping consoles, so `finish_stops` can wait
/// for it; threads already done are let go.
fn keep_stop(&self, stop: std::thread::JoinHandle<()>) {
let mut stops = self
.stops
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
stops.retain(|kept| !kept.is_finished());
stops.push(stop);
}
/// Wait for every console stop still running on a thread, after an agent's
/// end or a new page: the app may exit straight after, which would cut it
/// short.
pub fn finish_stops(&self) {
let stops = std::mem::take(
&mut *self
.stops
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()),
);
for stop in stops {
let _ = stop.join();
}
}
}
/// The hook an agent manager runs when an agent ends (`AgentManager::set_ended`):
/// it takes every console `announced` holds at once, inside the hook, so a
/// console the next agent announces later is never taken by mistake, then
/// stops each with `stop` on a thread of its own, since a stop runs `node` and
/// the hook must return quickly. The console the window follows (`followed`)
/// is left to the supervisor and recorded again, as left: stopped under the
/// window, the bar's health poll would only start it again as a server no one
/// tracks. It is stopped once the window moves on (`stop_left`), here if that
/// happened while this thread was deciding, or at the quit. `followed` is asked
/// on that thread too: it takes the console lock, held across `node` runs,
/// while the hook runs with the agent manager locked. A caller about to stop
/// the followed console waits for the thread first (`finish_stops`), so it is
/// never recorded again after that stop.
/// The macOS and Linux stand-in for Windows' Job Object, which ends every
/// console an agent opened along with it.
pub fn stop_announced_on_end<K, F>(
announced: Arc<AnnouncedConsoles>,
followed: K,
stop: F,
) -> Arc<dyn Fn() + Send + Sync>
where
K: Fn() -> Option<String> + Send + Sync + 'static,
F: Fn(&str) + Send + Sync + 'static,
{
let followed = Arc::new(followed);
let stop = Arc::new(stop);
Arc::new(move || {
let sids = announced.take_all();
if sids.is_empty() {
return;
}
let (followed, stop, record) = (
Arc::clone(&followed),
Arc::clone(&stop),
Arc::clone(&announced),
);
announced.keep_stop(std::thread::spawn(move || {
let shown = followed();
let mut left = false;
for sid in sids {
if shown.as_deref() == Some(sid.as_str()) {
record.leave(&sid);
left = true;
} else {
stop(&sid);
}
}
if left {
// A page that took the window since the question above found
// nothing left to stop yet.
for sid in record.take_left(followed().as_deref()) {
stop(&sid);
}
}
}));
})
}
/// Why a stop failed: it never ran (`node` could not be started), or it ran
/// and the console said no.
enum StopError {
NotRun(String),
Failed(String),
}
impl StopError {
fn into_message(self) -> String {
match self {
StopError::NotRun(message) | StopError::Failed(message) => message,
}
}
}
fn run_stop(console_dir: &Path, project_dir: &Path, sid: &str) -> Result<(), StopError> {
let output = node_command(console_dir)
.args(stop_args(sid))
.current_dir(project_dir)
.output()
.map_err(|e| StopError::NotRun(err(e)))?;
if !output.status.success() {
return Err(StopError::Failed(format!(
"console stop failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
)));
}
Ok(())
}
/// Is the session's folder still in the console's home. Unknown (no home
/// directory) counts as there, so the answer never throws a session away. A
/// sid that is not a plain folder name (empty, `..`, a path) is never there.
@@ -463,6 +686,241 @@ fn stop_args(sid: &str) -> [&str; 4] {
mod tests {
use super::*;
#[test]
fn announced_consoles_are_taken_once_in_order_without_duplicates() {
let announced = AnnouncedConsoles::default();
announced.record("s1");
announced.record("s2");
announced.record("s1");
assert_eq!(announced.take_all(), vec!["s1", "s2"]);
assert!(announced.take_all().is_empty(), "taking clears the record");
}
#[test]
fn forget_drops_one_console_and_keeps_the_rest() {
let announced = AnnouncedConsoles::default();
announced.record("s1");
announced.record("s2");
announced.forget("s1");
announced.forget("never-recorded");
assert_eq!(announced.take_all(), vec!["s2"]);
}
#[test]
fn an_agents_end_asks_which_console_the_window_follows_off_its_own_thread() {
// The hook runs with the agent manager locked, and the followed check
// takes the console lock, which is held across `node` runs: asked
// there, typing into the terminal stalled behind a console stop.
let announced = Arc::new(AnnouncedConsoles::default());
let asked_on = Arc::new(Mutex::new(Vec::new()));
let log = Arc::clone(&asked_on);
let hook = stop_announced_on_end(
Arc::clone(&announced),
move || {
log.lock().unwrap().push(std::thread::current().id());
None
},
|_| {},
);
announced.record("s1");
hook();
announced.finish_stops();
let asked_on = asked_on.lock().unwrap();
assert_eq!(asked_on.len(), 1, "asked once");
assert_ne!(asked_on[0], std::thread::current().id());
}
#[test]
fn an_agents_end_leaves_the_console_the_window_follows_and_keeps_it_recorded() {
// New Session ends the old agent while the window still shows its
// console: stopping it there only had the bar's poll bring it back as
// a server nobody tracked, which then outlived the quit.
let announced = Arc::new(AnnouncedConsoles::default());
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&stopped);
let hook = stop_announced_on_end(
Arc::clone(&announced),
|| Some("followed".to_string()),
move |sid| log.lock().unwrap().push(sid.to_string()),
);
announced.record("followed");
announced.record("other");
hook();
announced.finish_stops();
assert_eq!(*stopped.lock().unwrap(), vec!["other"]);
assert_eq!(
announced.take_all(),
vec!["followed"],
"kept for the quit, or until the window moves on"
);
}
/// An agent that ended while the window showed its console `sid`.
fn left_under_the_window(sid: &'static str) -> Arc<AnnouncedConsoles> {
let announced = Arc::new(AnnouncedConsoles::default());
announced.record(sid);
let hook = stop_announced_on_end(
Arc::clone(&announced),
move || Some(sid.to_string()),
|sid| panic!("{sid} was stopped under the window"),
);
hook();
announced.finish_stops();
announced
}
/// What `stop_left` stops once the window follows `followed`.
fn stopped_by_moving_to(announced: &AnnouncedConsoles, followed: &str) -> Vec<String> {
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&stopped);
announced.stop_left(followed, move |sid| log.lock().unwrap().push(sid.into()));
announced.finish_stops();
let stopped = stopped.lock().unwrap().clone();
stopped
}
#[test]
fn the_window_moving_on_stops_the_console_an_ended_agent_left_once() {
let announced = left_under_the_window("old");
announced.record("new");
assert!(stopped_by_moving_to(&announced, "old").is_empty(), "shown");
assert_eq!(stopped_by_moving_to(&announced, "new"), vec!["old"]);
assert!(stopped_by_moving_to(&announced, "new").is_empty(), "once");
assert_eq!(announced.take_all(), vec!["new"]);
}
#[test]
fn the_window_moving_on_never_stops_a_running_agents_console() {
// One agent may open a second session and still use the first.
let announced = AnnouncedConsoles::default();
announced.record("first");
announced.record("second");
assert!(stopped_by_moving_to(&announced, "second").is_empty());
// A new agent that joins the console an ended one left makes it its own.
let announced = left_under_the_window("joined");
announced.record("joined");
announced.record("second");
assert!(stopped_by_moving_to(&announced, "second").is_empty());
assert_eq!(announced.take_all(), vec!["joined", "second"]);
}
/// An agent's end whose console `old` the window shows, where `meanwhile`
/// runs right after the hook asked which console that is: what it stopped.
fn stopped_by_an_end_while<M>(meanwhile: M) -> (Vec<String>, Vec<String>)
where
M: Fn(&AnnouncedConsoles) -> &'static str + Send + Sync + 'static,
{
let announced = Arc::new(AnnouncedConsoles::default());
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
let (log, record) = (Arc::clone(&stopped), Arc::clone(&announced));
let shown = Mutex::new("old");
let hook = stop_announced_on_end(
Arc::clone(&announced),
move || {
let mut shown = shown.lock().unwrap();
let answer = shown.to_string();
if answer == "old" {
*shown = meanwhile(&record);
}
Some(answer)
},
move |sid| log.lock().unwrap().push(sid.to_string()),
);
announced.record("old");
hook();
announced.finish_stops();
let stopped = stopped.lock().unwrap().clone();
(stopped, announced.take_all())
}
#[test]
fn a_page_that_takes_the_window_while_an_agents_end_decides_still_stops_the_old_console() {
let (stopped, recorded) = stopped_by_an_end_while(|announced| {
announced.record("new");
announced.stop_left("new", |sid| panic!("{sid} is not left yet"));
"new"
});
assert_eq!(stopped, vec!["old"]);
assert_eq!(recorded, vec!["new"]);
}
#[test]
fn a_new_agent_that_joins_the_console_while_an_agents_end_decides_keeps_it() {
let (stopped, recorded) = stopped_by_an_end_while(|announced| {
announced.record("old");
announced.record("new");
"new"
});
assert!(stopped.is_empty(), "{stopped:?}");
assert_eq!(recorded, vec!["old", "new"]);
}
#[test]
fn finish_stops_waits_for_the_stop_a_new_page_started() {
// Quitting right after New Session: the exit must not cut it short.
let announced = left_under_the_window("old");
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&stopped);
announced.stop_left("new", move |sid| {
std::thread::sleep(Duration::from_millis(300));
log.lock().unwrap().push(sid.to_string());
});
assert!(stopped.lock().unwrap().is_empty(), "it runs on a thread");
announced.finish_stops();
assert_eq!(*stopped.lock().unwrap(), vec!["old"]);
}
#[test]
fn finish_stops_waits_for_the_stops_an_agents_end_still_has_running() {
// Quitting right after an agent ended: the exit must not cut its
// consoles' stops short.
let announced = Arc::new(AnnouncedConsoles::default());
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&stopped);
let hook = stop_announced_on_end(
Arc::clone(&announced),
|| None,
move |sid| {
std::thread::sleep(Duration::from_millis(300));
log.lock().unwrap().push(sid.to_string());
},
);
announced.record("s1");
hook();
assert!(
stopped.lock().unwrap().is_empty(),
"the stop runs on a thread"
);
announced.finish_stops();
assert_eq!(*stopped.lock().unwrap(), vec!["s1"]);
}
#[cfg(unix)]
#[test]
fn a_console_call_runs_in_a_process_group_of_its_own() {
// Ctrl+C and a closing terminal signal the app's whole group: a stop
// already running there ended before it stopped its console.
let console = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console");
let mut child = node_command(&console)
.arg("help")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.expect("node starts");
let pid = child.id() as i32;
// SAFETY: getpgid only reads; the child is not waited for yet, so its id is its own.
let group = unsafe { libc::getpgid(pid) };
let _ = child.wait();
assert_eq!(group, pid);
}
#[test]
fn the_apps_stop_calls_pass_force() {
let args = stop_args("20261101-120000-abcdef");
+9
View File
@@ -7,20 +7,29 @@ pub mod attention;
pub mod brief;
pub mod console_supervisor;
pub mod handoff;
pub mod log;
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)]
pub mod task_dialog;
#[cfg(unix)]
pub mod term_signal;
pub mod ui_confirm;
pub mod versions;
+10
View File
@@ -0,0 +1,10 @@
//! Lines for the app's log, its stderr, on the paths a quit takes. `eprintln!` panics when the
//! write fails, as it does once the terminal the app was started from has closed: the quit's
//! cleanup would end at its first line, with the app still open.
use std::io::Write;
/// Writes one line, or nothing when the log cannot be written to.
pub fn line(text: &str) {
let _ = writeln!(std::io::stderr(), "{text}");
}
+536 -126
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 text: String = one_line(&text).chars().take(200).collect();
let cause = StopCause::WatcherFailed(text);
let line = stop_line(&cause, 0, "", false);
stop_loop(&ctx, cause, line, &["resume", "fix"]);
return;
}
let panicked = watch_loop(ctx.limits.watch_every, || {
if step(&ctx) {
WatchStep::Continue
} else {
WatchStep::Stop
}
});
if let Some(text) = panicked {
let text: String = one_line(&text).chars().take(200).collect();
let cause = StopCause::WatcherFailed(text);
let line = stop_line(&cause, 0, "", false);
stop_loop(&ctx, cause, line, &["resume", "fix"]);
}
}
@@ -2289,7 +2353,7 @@ fn observe(ctx: &Ctx, stage: Option<&str>, asked: bool) {
/// A file time is never later than now: a file dated in the future (a clock
/// that was wrong, a copied file) must not hold the last sign of work ahead of
/// the clock, or silence would never fire.
fn clamp_to_now(time: SystemTime) -> SystemTime {
pub(crate) fn clamp_to_now(time: SystemTime) -> SystemTime {
time.min(SystemTime::now())
}
@@ -2303,7 +2367,7 @@ fn modified(path: &Path) -> Option<SystemTime> {
/// The newest sign of work: the session's own files, or a file `git status`
/// lists (ignored folders never appear, so they never count).
fn newest_work(session_dir: &Path, project: &Path) -> Option<SystemTime> {
pub(crate) fn newest_work(session_dir: &Path, project: &Path) -> Option<SystemTime> {
let mut newest = ["state.json", "events.ndjson"]
.iter()
.filter_map(|name| modified(&session_dir.join(name)))
@@ -2409,12 +2473,91 @@ fn stop_before_mark(ctx: &Ctx, snap: &Snapshot, staged: bool) -> bool {
false
}
fn stop_requested(ctx: &Ctx) -> bool {
pub(crate) fn stop_requested(ctx: &Ctx) -> bool {
lock(&ctx.slot)
.as_ref()
.is_some_and(|r| r.run_id == ctx.run_id && r.stop_now)
}
/// The extra review rounds a phase's own review calls for (FR-28): with Review
/// on, `review_rounds` above zero and a Critical or Warning left in a report
/// that otherwise could pass, fresh round sessions review the phase's diff
/// before it is judged. Returns the report to judge (the phase agent's own when
/// no round ran, else with the last round's counts in its place), or `None`
/// when the loop was stopped here and the stop is already recorded.
fn extra_rounds(ctx: &Ctx, snap: &Snapshot, outcome: Outcome) -> Option<Outcome> {
let review = outcome.review.clone().unwrap_or_default();
let left = leftover(&review, FixLevel::Critical) + leftover(&review, FixLevel::Warning);
// A phase that reports failed only for its findings has no other failure:
// its tests, tasks and conflicts are still checked by the judge afterwards.
let findings_only = outcome.result == "failed"
&& outcome.reason.as_deref() == Some("findings")
&& outcome.conflicts.is_empty();
let tests_hold = outcome
.tests
.as_ref()
.is_none_or(|t| !t.ran || t.passed || excused_failures(t));
if snap.setup.extra_rounds() == 0
|| !review.ran
|| left == 0
|| !(outcome.result == "passed" || findings_only)
|| !tests_hold
{
return Some(outcome);
}
let n = snap.phase_n;
let stop_with = |cause: StopCause, line: String| {
stop_loop(ctx, cause, line, &["resume", "fix"]);
None
};
let start = {
let guard = lock(&ctx.slot);
let rec = guard.as_ref().filter(|r| r.run_id == ctx.run_id)?;
rec.phase_start.clone()
};
let Some(start) = start else {
keep_output(
ctx,
"The extra review rounds were skipped: the tree as the phase began could not be recorded.",
);
return Some(outcome);
};
let input = phase_rounds::RoundsInput {
project: snap.project.clone(),
phase: n,
setup: snap.setup.clone(),
cap: snap.setup.extra_rounds(),
helpers: phase_rounds::helpers_for(ctx),
start,
unfixed: review.unfixed.clone(),
dir: ctx
.home
.join("loop-phase-rounds")
.join(format!("{}-phase-{n}", ctx.run_id)),
};
let end = phase_rounds::run_rounds(ctx, &input);
match end {
phase_rounds::RoundsEnd::Done(done) => {
keep_rounds(ctx, &done.rounds);
Some(phase_rounds::judged_after(outcome, &done))
}
phase_rounds::RoundsEnd::Person { rounds } => {
keep_rounds(ctx, &rounds);
stop_by_person(ctx, snap);
None
}
phase_rounds::RoundsEnd::Failed { reason, rounds } => {
keep_rounds(ctx, &rounds);
let cause = StopCause::Refused(format!(
"an extra review round failed ({})",
one_line(&reason)
));
let line = stop_line(&cause, n, "", false);
stop_with(cause, line)
}
}
}
/// Judge a phase's report and, when it holds, record it: quick check, mark,
/// approval line, commit, stop the agent, then the next phase, a stop the
/// person asked for, or the finish. Returns whether the loop goes on.
@@ -2436,6 +2579,11 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
if outcome.phase != n {
return refused(format!("the report names Phase {}", outcome.phase));
}
// A phase whose own review left a Critical or a Warning gets fresh review
// rounds before it is judged (the hook; nothing else about the phase changes).
let Some(outcome) = extra_rounds(ctx, snap, outcome) else {
return false;
};
let status = match loop_tools::specs_status(&snap.project, &snap.spec) {
Ok(status) => status,
Err(e) => return refused(format!("the spec could not be read ({})", one_line(&e))),
@@ -2595,6 +2743,11 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
retries: snap.phase_retries,
assumed: phase_assumptions(&snap.project, &snap.spec, n, Some(&entry)),
warnings,
rounds: lock(&ctx.slot)
.as_ref()
.filter(|r| r.run_id == ctx.run_id)
.map(|r| r.phase_rounds.clone())
.unwrap_or_default(),
..ReportEntry::default()
}
.with_outcome(&outcome);
@@ -2798,7 +2951,7 @@ fn add_entry(ctx: &Ctx, entry: ReportEntry) {
rec.report.entries.push(entry);
(rec.project.clone(), rec.report.clone())
};
let result = loop_report::save(&ctx.home, &saved.0, &saved.1);
let result = save_report(&ctx.home, &saved.0, &saved.1);
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
rec.report_failure = result.err();
}
@@ -2809,8 +2962,9 @@ fn set_step(ctx: &Ctx, step: Step) {
let mut guard = lock(&ctx.slot);
match guard.as_mut().filter(|r| r.run_id == ctx.run_id) {
Some(rec) => {
let changed = rec.step != step;
let changed = rec.step != step || rec.step_text.is_some();
rec.step = step;
rec.step_text = None;
changed
}
None => false,
@@ -2827,6 +2981,13 @@ fn keep_output(ctx: &Ctx, output: &str) {
}
}
/// Keep the extra rounds the phase has run, for its report entry.
pub(crate) fn keep_rounds(ctx: &Ctx, rounds: &[loop_report::RoundEntry]) {
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
rec.phase_rounds = rounds.to_vec();
}
}
fn keep_report(ctx: &Ctx, outcome: &Outcome, entry: &Value) {
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
rec.last_outcome = Some(outcome.clone());
@@ -3297,6 +3458,7 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) {
if let Some(outcome) = &rec.last_outcome {
entry = entry.with_outcome(outcome);
}
entry.rounds.clone_from(&rec.phase_rounds);
}
// What the phase ran on, as `add_entry` does for every other entry.
if let Some(run) = rec.phase_run(at) {
@@ -3304,7 +3466,7 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) {
entry.model = run.model_text();
}
rec.report.entries.push(entry);
rec.report_failure = loop_report::save(&ctx.home, &rec.project, &rec.report).err();
rec.report_failure = save_report(&ctx.home, &rec.project, &rec.report).err();
let mut evidence = evidence_with_report(&evidence_markdown(&cause, &line, &rec), &rec);
let sent = stop_message(&cause, &Where::of(&rec, at), &line)
.and_then(|message| notify(&rec.setup, &message));
@@ -3681,6 +3843,12 @@ pub fn summary_markdown(rec: &RunningRecord, date: &str, finalize: &FinalizeNote
if setup.review {
md.push_str(&format!("- Fixes: {}\n", levels_text(setup)));
}
if setup.review {
md.push_str(&format!(
"- Review rounds per phase: {}\n",
setup.extra_rounds()
));
}
md.push_str(&format!("- Commit each phase: {}\n", yes(setup.commit)));
let on_question = match setup.on_question {
OnQuestion::Pause => "pause and wait for you",
@@ -3726,7 +3894,7 @@ pub fn summary_markdown(rec: &RunningRecord, date: &str, finalize: &FinalizeNote
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
fn setup() -> LoopSetup {
@@ -4837,31 +5005,6 @@ second line"
// ----------------------------------------------- failures, stops, the strip
fn at(minutes: u64) -> SystemTime {
UNIX_EPOCH + Duration::from_secs(minutes * 60)
}
#[test]
fn silence_waits_past_the_limit_and_never_while_a_question_waits() {
let s = setup(); // 20 minutes
assert!(!silence_expired(at(120), at(100), &s, None, false));
assert!(silence_expired(at(121), at(100), &s, None, false));
// A waiting question has no time limit.
assert!(!silence_expired(at(1000), at(0), &s, None, true));
// The skill's own quiet minutes stretch the limit, never shrink it.
assert!(!silence_expired(at(140), at(100), &s, Some(45), false));
assert!(silence_expired(at(146), at(100), &s, Some(45), false));
assert!(silence_expired(at(121), at(100), &s, Some(5), false));
// Capped at 60 minutes whatever either side asks for.
assert!(silence_expired(at(161), at(100), &s, Some(500), false));
let mut long = setup();
long.silence_minutes = 60;
assert!(!silence_expired(at(160), at(100), &long, Some(90), false));
assert!(silence_expired(at(161), at(100), &long, Some(90), false));
// A clock that went backwards is not silence.
assert!(!silence_expired(at(100), at(200), &s, None, false));
}
#[test]
fn only_a_crash_silence_or_a_missing_console_retries_and_only_once() {
let s = setup();
@@ -5268,7 +5411,7 @@ second line"
/// Whether `program` runs; a test that needs it says so and skips when not.
/// On CI (`CI` is set) a missing program fails the test instead, so a
/// runner without git or node cannot turn the tests into silent passes.
fn program_ready(test: &str, program: &str) -> bool {
pub(crate) fn program_ready(test: &str, program: &str) -> bool {
let found = std::process::Command::new(program)
.arg("--version")
.output()
@@ -5283,13 +5426,13 @@ second line"
found
}
fn git_ready(test: &str) -> bool {
pub(crate) fn git_ready(test: &str) -> bool {
program_ready(test, "git")
}
/// Git, node and the skill scripts (`specs.mjs`, `commit-msg.mjs`) the tick
/// runs. The scripts are the repository's own (see `loop_tools::skill_script`).
fn harness_ready(test: &str) -> bool {
pub(crate) fn harness_ready(test: &str) -> bool {
let scripts = loop_tools::skill_script("specs.mjs").is_some()
&& loop_tools::skill_script("commit-msg.mjs").is_some();
assert!(
@@ -5299,7 +5442,7 @@ second line"
git_ready(test) && program_ready(test, "node")
}
fn git_in(repo: &Path, args: &[&str]) -> String {
pub(crate) fn git_in(repo: &Path, args: &[&str]) -> String {
let out = std::process::Command::new("git")
.args(args)
.current_dir(repo)
@@ -5383,7 +5526,7 @@ second line"
}
/// Where `cargo build -p fake-agent` leaves the fake agent, built on first use.
fn fake_agent_path() -> PathBuf {
pub(crate) fn fake_agent_path() -> PathBuf {
static BUILD: std::sync::Once = std::sync::Once::new();
BUILD.call_once(|| {
let status = std::process::Command::new(env!("CARGO"))
@@ -5406,7 +5549,7 @@ second line"
/// The fake agent as a custom agent. The loop's tests start it this way, not
/// through `PLAN2CODE_APP_AGENT_BIN`: that variable is process-wide, and
/// other tests in this process read it.
fn fake_agent_launch() -> Launch {
pub(crate) fn fake_agent_launch() -> Launch {
let agent = crate::agents::CustomAgent {
id: "fake".into(),
name: "Fake agent".into(),
@@ -5422,7 +5565,7 @@ second line"
/// An agent manager for the fake agent, and everything the agents printed. The pump answers the pseudo-terminal's cursor question,
/// as a terminal does, or Windows holds the output back.
fn fake_agent_manager(folder: &Path) -> (Arc<AgentManager>, Arc<Mutex<String>>) {
pub(crate) fn fake_agent_manager(folder: &Path) -> (Arc<AgentManager>, Arc<Mutex<String>>) {
use crate::agent_manager::AgentEvent;
let (tx, rx) = std::sync::mpsc::channel();
let tx = Mutex::new(tx);
@@ -5449,7 +5592,7 @@ second line"
}
/// Poll until `ready`; the wait ends on state, not on a fixed sleep.
fn wait_until(what: &str, mut ready: impl FnMut() -> bool) {
pub(crate) fn wait_until(what: &str, mut ready: impl FnMut() -> bool) {
let deadline = Instant::now() + Duration::from_secs(30);
while Instant::now() < deadline {
if ready() {
@@ -7858,4 +8001,271 @@ second line"
);
agent.stop();
}
// ------------------------------------------------ extra review rounds in a phase
fn quick_limits() -> Limits {
Limits {
watch_every: Duration::from_millis(20),
notice_wait: Duration::from_secs(20),
..Limits::default()
}
}
/// A `roundOutcome` the way a round agent posts it; the reviewer lists the
/// Warning it found as unfixed, the fixer says what its round left.
fn round_json(round: u32, role: &str, critical: u32, warning: u32) -> Value {
let mut value = json!({
"round": round, "role": role, "result": "passed", "reason": null,
"summary": "Round done",
"review": { "critical": critical, "warning": warning, "suggestion": 0,
"fixed": [], "unfixed": [], "suggestions": [] },
"tests": { "ran": true, "passed": true, "summary": "ok" },
});
if role != "fixer" {
value["report"] = json!("report");
}
if role == "reviewer" {
value.as_object_mut().unwrap().remove("tests");
if warning > 0 {
value["review"]["unfixed"] =
json!([{ "title": "Close the handle", "file": "work.txt" }]);
}
}
value
}
/// What the player saw of a round session before it answered.
struct Seen {
scope: String,
banner: String,
}
/// Answer the phase's extra round sessions in order: wait for each one the
/// driver starts, read its scope file and the banner, hand the driver its
/// page (as the app's notice does) and post its `roundOutcome`.
fn play_rounds(
ctx: &Ctx,
script: Vec<(u32, &'static str, Value)>,
) -> thread::JoinHandle<Vec<Seen>> {
let ctx = ctx.clone();
thread::spawn(move || {
let mut seen = Vec::new();
for (round, role, outcome) in script {
let want = match role {
"reviewer" => Role::Reviewer,
"fixer" => Role::Fixer,
_ => Role::Both,
};
wait_until("a round session to wait for", || {
lock(&ctx.slot)
.as_ref()
.and_then(|rec| rec.round_wait.as_ref())
.is_some_and(|w| w.round == round && w.role == want && w.sid.is_none())
});
let (phase, banner) = {
let guard = lock(&ctx.slot);
let rec = guard.as_ref().unwrap();
(rec.phases[rec.current].n, state_event(rec).step)
};
let dir = ctx
.home
.join("loop-phase-rounds")
.join(format!("{}-phase-{phase}", ctx.run_id))
.join(format!("round-{round}-{role}-t0"));
let scope = std::fs::read_to_string(dir.join("scope.md")).expect("a scope file");
let sid = format!("r{round}{role}");
let folder = ctx.home.join("sessions").join(&sid);
std::fs::create_dir_all(&folder).unwrap();
let post = |state: &Value| {
let mut state = state.clone();
state["schema"] = json!(crate::session_reader::SCHEMA);
std::fs::write(folder.join("state.json.tmp"), state.to_string()).unwrap();
std::fs::rename(folder.join("state.json.tmp"), folder.join("state.json"))
.unwrap();
state
};
let locked =
post(&json!({ "loop": { "driving": true, "round": round, "role": role } }));
note_page(&ctx.slot, "review", &sid, &locked);
let mut done = locked.clone();
done["roundOutcome"] = outcome;
done["docs"] = json!([{ "id": "report", "kind": "report", "title": "Review round",
"blocks": [{ "id": "r", "md": "Found things to fix." }] }]);
post(&done);
seen.push(Seen { scope, banner });
}
seen
})
}
/// A phase report whose own review left one Warning, the way a phase agent
/// that could not fix it reports it.
fn findings_report(phase: u32) -> Value {
let mut report = good_report(phase);
report["result"] = json!("failed");
report["reason"] = json!("findings");
report["review"] = json!({
"ran": true, "recheck": true,
"left": { "critical": 0, "warning": 1, "suggestion": 0 },
"unfixed": [{ "level": "warning", "title": "Close the handle", "file": "work.txt" }],
});
report
}
/// A running loop on a throwaway repo whose Phase 2 is built (tasks ticked,
/// one file written) after the start snapshot the rounds measure from.
fn built_phase(name: &str) -> (Ctx, PathBuf, PathBuf) {
let repo = throwaway_repo(name);
let (ctx, home) = running_loop(&repo, quick_limits());
lock(&ctx.slot).as_mut().unwrap().phase_start =
Some(round_boundary::snapshot(&repo).unwrap());
finish_phase_tasks(&repo, 2);
std::fs::write(repo.join("work.txt"), "phase work\n").unwrap();
(ctx, repo, home)
}
#[test]
fn a_phase_with_a_warning_left_runs_fresh_rounds_then_commits_once() {
if !harness_ready("extra rounds") {
return;
}
let (ctx, repo, home) = built_phase("extra-rounds");
let before = git_in(&repo, &["rev-list", "--count", "HEAD"]);
write_session(&home, json!({ "loopOutcome": findings_report(2) }));
let player = play_rounds(
&ctx,
vec![
(1, "reviewer", round_json(1, "reviewer", 0, 1)),
(1, "fixer", round_json(1, "fixer", 0, 1)),
(2, "reviewer", round_json(2, "reviewer", 0, 0)),
],
);
assert!(tick(&ctx), "the clean round 2 lets the phase pass");
let seen = player.join().unwrap();
assert_eq!(seen[0].banner, "Review round 1 of 2");
assert_eq!(seen[2].banner, "Review round 2 of 2");
assert!(
seen[0].scope.contains("everything the phase changed"),
"{}",
seen[0].scope
);
let diff = seen[0]
.scope
.lines()
.find_map(|l| l.strip_prefix("- "))
.unwrap();
let diff = std::fs::read_to_string(diff).unwrap();
assert!(diff.contains("work.txt"), "the whole phase diff: {diff}");
assert!(
seen[1].scope.contains("Close the handle")
&& seen[1].scope.contains("reviewer-report.md"),
"the fixer is briefed with the unfixed list: {}",
seen[1].scope
);
assert!(
!seen[0].scope.contains("Close the handle"),
"the reviewer sees no brief"
);
assert!(
seen[2].scope.contains("previous round's changes"),
"{}",
seen[2].scope
);
let after = git_in(&repo, &["rev-list", "--count", "HEAD"]);
assert_eq!(
after.parse::<u32>().unwrap(),
before.parse::<u32>().unwrap() + 1,
"one commit for the phase"
);
assert_eq!(
git_in(&repo, &["log", "-1", "--format=%s"]),
"Add the driver"
);
assert!(git_in(&repo, &["show", "--name-only", "--format=", "HEAD"]).contains("work.txt"));
let entry = last_entry_saved(&home, &repo);
assert_eq!(entry.result, EntryResult::Passed);
assert_eq!(entry.rounds.len(), 2);
assert_eq!((entry.rounds[0].warning, entry.rounds[1].warning), (1, 0));
let md = loop_report::body_markdown(&lock(&ctx.slot).as_ref().unwrap().report);
assert!(
md.contains("Extra review rounds: 2 (left after: 0 Critical, 0 Warning)"),
"{md}"
);
end_the_test(&ctx);
}
#[test]
fn findings_left_after_the_rounds_judge_the_phase_with_those_counts() {
if !harness_ready("extra rounds cap") {
return;
}
let (ctx, repo, home) = built_phase("extra-rounds-cap");
lock(&ctx.slot).as_mut().unwrap().setup.review_rounds = 1;
// The phase agent leaves two Warnings; the one round leaves one, so only
// the last round's count can make the stop line say "1 Warning".
let mut report = findings_report(2);
report["review"]["left"]["warning"] = json!(2);
report["review"]["unfixed"]
.as_array_mut()
.unwrap()
.push(json!({ "level": "warning", "title": "Name the timer", "file": "work.txt" }));
write_session(&home, json!({ "loopOutcome": report }));
let player = play_rounds(
&ctx,
vec![
(1, "reviewer", round_json(1, "reviewer", 0, 1)),
(1, "fixer", round_json(1, "fixer", 0, 1)),
],
);
assert!(
!tick(&ctx),
"a Warning left after the only round stops the phase"
);
player.join().unwrap();
let entry = last_entry_saved(&home, &repo);
assert_eq!(entry.result, EntryResult::Stopped);
assert!(
entry.line.contains("1 Warning left after the re-check"),
"{}",
entry.line
);
assert_eq!(entry.rounds.len(), 1);
assert_eq!(
git_in(&repo, &["rev-list", "--count", "HEAD"]),
"1",
"nothing was committed"
);
end_the_test(&ctx);
}
#[test]
fn no_rounds_run_when_nothing_is_left_when_they_are_zero_or_when_review_is_off() {
if !harness_ready("extra rounds skipped") {
return;
}
// Nothing left: the phase commits as before and no round folder appears.
let (ctx, repo, home) = built_phase("extra-none");
write_session(&home, json!({ "loopOutcome": good_report(2) }));
assert!(tick(&ctx));
assert!(last_entry_saved(&home, &repo).rounds.is_empty());
assert!(!home.join("loop-phase-rounds").exists());
end_the_test(&ctx);
// Zero rounds: the Warning stops the phase as it always did.
let (ctx, repo, home) = built_phase("extra-zero");
lock(&ctx.slot).as_mut().unwrap().setup.review_rounds = 0;
write_session(&home, json!({ "loopOutcome": findings_report(2) }));
assert!(!tick(&ctx));
assert!(last_entry_saved(&home, &repo).rounds.is_empty());
assert!(!home.join("loop-phase-rounds").exists());
end_the_test(&ctx);
// Review off: the setting means nothing, and the report judges as before.
let (ctx, repo, home) = built_phase("extra-off");
lock(&ctx.slot).as_mut().unwrap().setup.review = false;
write_session(&home, json!({ "loopOutcome": findings_report(2) }));
let _ = tick(&ctx);
assert!(last_entry_saved(&home, &repo).rounds.is_empty());
assert!(!home.join("loop-phase-rounds").exists());
end_the_test(&ctx);
}
}
@@ -32,10 +32,42 @@ pub struct Assumption {
pub note: String,
}
/// Which loop wrote an entry. Entries saved before the Review Loop existed
/// carry no kind and read as `Implementation`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EntryKind {
#[default]
Implementation,
Review,
}
/// One round of a Review Loop, as its entry keeps it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct RoundEntry {
pub n: u32,
pub critical: u32,
pub warning: u32,
pub suggestion: u32,
pub fixed: Vec<String>,
pub left_open: Vec<String>,
pub commit: Option<String>,
pub tests: String,
pub started: String,
pub ended: String,
/// "Balanced" and so on, or empty for an agent run as launched.
pub strength: String,
pub retried: bool,
}
/// One thing that happened to a phase, in the order it happened.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ReportEntry {
pub kind: EntryKind,
/// A Review Loop's rounds, in order; empty for an Implementation Loop phase.
pub rounds: Vec<RoundEntry>,
pub at: String,
pub phase: u32,
pub name: String,
@@ -298,6 +330,23 @@ fn entry_markdown(md: &mut String, e: &ReportEntry) {
if e.retries > 0 {
md.push_str(&format!("- Retries: {}\n", e.retries));
}
if let Some(last) = e.rounds.last() {
md.push_str(&format!(
"- Extra review rounds: {} (left after: {} Critical, {} Warning)\n",
e.rounds.len(),
last.critical,
last.warning
));
for round in &e.rounds {
md.push_str(&format!(
" - Round {}: {} Critical, {} Warning found, {} fixed\n",
round.n,
round.critical,
round.warning,
round.fixed.len()
));
}
}
if !e.warnings.is_empty() {
let notes: Vec<String> = e.warnings.iter().map(|w| cell(w)).collect();
md.push_str(&format!("- Warnings: {}\n", notes.join("; ")));
@@ -0,0 +1,16 @@
//! Loop machinery both the Implementation Loop (`loop_driver`) and the Review
//! Loop call: starting an agent session, the watcher, the retry rule, the
//! saved report list and the notification.
pub mod report_list;
pub mod retry;
pub mod rounds;
pub mod session;
pub mod watch;
use crate::loop_notify::{self, NotifyKind};
/// Send a notification of `kind` to `url`; the reason it failed, if it did.
pub fn notify(kind: NotifyKind, url: &str, param: &str, message: &str) -> Result<(), String> {
loop_notify::send(kind, url, param, message)
}
@@ -0,0 +1,16 @@
//! The saved report list (`loop-reports.json`): one entry point for both the
//! Implementation Loop and the Review Loop.
use std::path::Path;
use crate::loop_report::{self, LoopReport};
/// The saved report for `spec` in `project`, when there is one.
pub fn load_reports(home: &Path, project: &Path, spec: &str) -> Option<LoopReport> {
loop_report::load(home, project, spec)
}
/// Save `report` for `project`.
pub fn save_report(home: &Path, project: &Path, report: &LoopReport) -> Result<(), String> {
loop_report::save(home, project, report)
}
@@ -0,0 +1,28 @@
//! The retry rule and the strength step-up, called by both the Implementation
//! Loop and the Review Loop.
use std::collections::BTreeMap;
use crate::loop_driver::{LoopSetup, StopCause};
use crate::models::{self, StrengthRow};
/// One fresh retry for a crash, silence or an announce notice that never came
/// (a crash), when the setup allows it and the phase has not used it yet. A
/// failed watcher is never retried.
pub fn should_retry(cause: &StopCause, setup: &LoopSetup, retries_used_this_phase: u32) -> bool {
matches!(
cause,
StopCause::Crash | StopCause::Silence | StopCause::NoSession
) && setup.retry_once
&& retries_used_this_phase == 0
}
/// The strength word one step above `current`, or `None` when there is none
/// (Best stays, an unmapped word stays). A thin wrapper over
/// `models::next_strength`, so a caller without a `RunningRecord` can step up.
pub fn next_strength_word(
resolved: &BTreeMap<String, StrengthRow>,
current: &str,
) -> Option<String> {
models::next_strength(resolved, current)
}
@@ -0,0 +1,110 @@
//! The pieces of a review round both loops read the same way: whether an
//! announced page is a round's session, the round's `roundOutcome` in a session
//! state, the report text it names, the proofs the app checks for itself, and
//! the reviewer's findings as the fixer's brief. The Review Loop and the
//! Implementation Loop's extra review rounds (a phase's hook) both call them.
use serde_json::Value;
use crate::round_logic::{Finding, Role, RoundOutcome, RoundProofs};
/// The word a role goes by in a console state and a prompt.
pub fn role_word(role: Role) -> &'static str {
match role {
Role::Both => "both",
Role::Reviewer => "reviewer",
Role::Fixer => "fixer",
}
}
/// Whether an announced page is this round's session: the agent locked it with
/// `open --loop` for this round and role, and it holds no report yet.
pub fn page_is_this_round(state: &Value, round: u32, role: Role) -> bool {
state["loop"]["driving"].as_bool().unwrap_or(false)
&& state["loop"]["round"].as_u64() == Some(u64::from(round))
&& state["loop"]["role"].as_str() == Some(role_word(role))
&& state.get("roundOutcome").is_none_or(Value::is_null)
}
/// The round's outcome in `state`, when it is this round's and this role's.
pub fn round_outcome_in(
state: &Value,
round: u32,
role: Role,
) -> Option<Result<RoundOutcome, String>> {
let raw = state
.get("roundOutcome")
.filter(|value| value.is_object())?;
match serde_json::from_value::<RoundOutcome>(raw.clone()) {
Ok(outcome) => (outcome.round == round && outcome.role == role).then_some(Ok(outcome)),
Err(err) => Some(Err(format!("the round's report could not be read ({err})"))),
}
}
/// The text of the report doc the outcome names, from the session's `docs`.
pub fn report_text(state: &Value, id: &str) -> Option<String> {
let doc = state["docs"]
.as_array()?
.iter()
.find(|doc| doc["id"].as_str() == Some(id))?;
let mut text = String::new();
if let Some(blocks) = doc["blocks"].as_array() {
for block in blocks {
if let Some(md) = block["md"].as_str() {
text.push_str(md);
text.push_str("\n\n");
}
}
}
Some(text)
}
pub fn proofs_for(state: &Value, outcome: &RoundOutcome, role: Role) -> RoundProofs {
let report_doc_present = match role {
Role::Fixer => true,
_ => outcome
.report
.as_deref()
.is_some_and(|id| report_text(state, id).is_some()),
};
let (tests_ran, tests_passed) = match role {
// A reviewer changes nothing and is not asked for tests.
Role::Reviewer => (true, true),
_ => outcome
.tests
.as_ref()
.map_or((false, false), |t| (t.ran, t.passed)),
};
RoundProofs {
report_doc_present,
tests_ran,
tests_passed,
}
}
pub fn finding_line(finding: &Finding) -> String {
match finding.line {
Some(line) => format!("- {} ({}:{line})", finding.title, finding.file),
None => format!("- {} ({})", finding.title, finding.file),
}
}
/// The reviewer's findings, as the fixer's brief: the report's text and the
/// Critical and Warning findings the reviewer left unfixed.
pub fn reviewer_brief(text: &str, outcome: &RoundOutcome) -> String {
let mut brief = format!(
"# Reviewer report\n\n{}\n\nFound: {} Critical, {} Warning, {} Suggestion.\n\n",
text.trim(),
outcome.review.critical,
outcome.review.warning,
outcome.review.suggestion
);
if !outcome.review.unfixed.is_empty() {
brief.push_str("## Fix these\n\n");
for finding in &outcome.review.unfixed {
brief.push_str(&finding_line(finding));
brief.push('\n');
}
}
brief
}
@@ -0,0 +1,62 @@
//! What a loop needs to start an agent session and read its console state: the
//! shared context, `start_session` and `read_session_state`. Both the
//! Implementation Loop and the Review Loop call it.
use std::path::PathBuf;
use std::sync::Arc;
use crate::agent_manager::AgentManager;
use crate::loop_driver::{self, Hooks, Launch, Limits, LoopSlot, Strength};
use crate::models::StrengthRow;
use crate::session_reader;
/// What the watch thread needs, shared by every step of one loop.
#[derive(Clone)]
pub struct Ctx {
pub slot: LoopSlot,
pub agent: Arc<AgentManager>,
pub console_dir: PathBuf,
pub home: PathBuf,
pub launch: Launch,
pub run_id: u64,
pub hooks: Arc<Hooks>,
pub limits: Limits,
}
/// What a started session reports: the agent's generation and the model and
/// effort it started on.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SessionStart {
pub generation: u64,
pub model: Option<String>,
pub effort: Option<String>,
}
/// Start a fresh agent on `prompt`. With `strength` (the word and its row) the
/// agent starts on that row's model and effort with `PLAN2CODE_LOOP_STRENGTH`
/// set; without it, on the agent's launch choice.
pub fn start_session(
ctx: &Ctx,
prompt: &str,
strength: Option<(Strength, &StrengthRow)>,
) -> Result<SessionStart, String> {
match strength {
Some((word, row)) => {
loop_driver::start_phase_with(&ctx.agent, &ctx.launch, prompt.to_string(), row, word)?
}
None => loop_driver::start_with(&ctx.agent, &ctx.launch, prompt.to_string())?,
}
let snapshot = ctx.agent.snapshot();
Ok(SessionStart {
generation: snapshot.generation,
model: snapshot.model,
effort: snapshot.effort,
})
}
/// The console state of session `sid`, or `None` when it cannot be read now.
pub fn read_session_state(ctx: &Ctx, sid: &str) -> Option<serde_json::Value> {
session_reader::load(&ctx.home, sid)
.ok()
.map(|session| session.state)
}
@@ -0,0 +1,129 @@
//! The watcher's timing, the silence rule and the generic watch loop, called by
//! both the Implementation Loop and the Review Loop.
use std::time::{Duration, SystemTime};
use crate::loop_driver::LoopSetup;
/// How often the watcher looks at the running loop.
pub const WATCH_EVERY: Duration = Duration::from_secs(2);
/// How often silence looks at the session's files and the tree.
pub const ACTIVITY_EVERY: Duration = Duration::from_secs(30);
/// What a step of the watch loop says to do next.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WatchStep {
Continue,
Stop,
}
/// Look every `every` until `step` says `Stop`. A panic in `step` ends the
/// watch and comes back as its text (`Some`), so the caller can end its loop
/// with the "watcher failed" stop instead of leaving a loop running with
/// nothing watching it; a normal stop returns `None`.
pub fn watch_loop<F: FnMut() -> WatchStep>(every: Duration, mut step: F) -> Option<String> {
loop {
std::thread::sleep(every);
let seen = std::panic::catch_unwind(std::panic::AssertUnwindSafe(&mut step));
match seen {
Ok(WatchStep::Continue) => {}
Ok(WatchStep::Stop) => return None,
Err(payload) => {
return Some(
payload
.downcast_ref::<&str>()
.map(|s| (*s).to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "an unknown error".to_string()),
);
}
}
}
}
/// Whether the agent has been quiet too long. A waiting question never counts
/// (the person may take all night). The limit is the setup's silence minutes
/// or the skill's own `quietMinutes`, whichever is longer, at most 60.
pub fn silence_expired(
now: SystemTime,
last_activity: SystemTime,
setup: &LoopSetup,
quiet_minutes: Option<u32>,
waiting: bool,
) -> bool {
if waiting {
return false;
}
let minutes = setup
.silence_minutes
.max(quiet_minutes.unwrap_or(0))
.min(60);
let limit = Duration::from_secs(u64::from(minutes) * 60);
now.duration_since(last_activity)
.is_ok_and(|quiet| quiet > limit)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::loop_driver::{FixMode, OnQuestion};
use std::time::UNIX_EPOCH;
fn setup() -> LoopSetup {
LoopSetup {
fix_mode: FixMode::Levels,
on_question: OnQuestion::Pause,
..LoopSetup::default()
}
}
fn at(minutes: u64) -> SystemTime {
UNIX_EPOCH + Duration::from_secs(minutes * 60)
}
#[test]
fn the_watch_loop_stops_on_stop_and_returns_the_text_of_a_panic() {
let none = Duration::ZERO;
let mut calls = 0;
let stopped = watch_loop(none, || {
calls += 1;
if calls < 3 {
WatchStep::Continue
} else {
WatchStep::Stop
}
});
assert_eq!((stopped, calls), (None, 3));
let quiet = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let literal = watch_loop(none, || panic!("literal"));
let text = "formatted".to_string();
let owned = watch_loop(none, || panic!("{text}"));
let other = watch_loop(none, || std::panic::panic_any(1_u8));
std::panic::set_hook(quiet);
assert_eq!(literal.as_deref(), Some("literal"));
assert_eq!(owned.as_deref(), Some("formatted"));
assert_eq!(other.as_deref(), Some("an unknown error"));
}
#[test]
fn silence_waits_past_the_limit_and_never_while_a_question_waits() {
let s = setup(); // 20 minutes
assert!(!silence_expired(at(120), at(100), &s, None, false));
assert!(silence_expired(at(121), at(100), &s, None, false));
// A waiting question has no time limit.
assert!(!silence_expired(at(1000), at(0), &s, None, true));
// The skill's own quiet minutes stretch the limit, never shrink it.
assert!(!silence_expired(at(140), at(100), &s, Some(45), false));
assert!(silence_expired(at(146), at(100), &s, Some(45), false));
assert!(silence_expired(at(121), at(100), &s, Some(5), false));
// Capped at 60 minutes whatever either side asks for.
assert!(silence_expired(at(161), at(100), &s, Some(500), false));
let mut long = setup();
long.silence_minutes = 60;
assert!(!silence_expired(at(160), at(100), &long, Some(90), false));
assert!(silence_expired(at(161), at(100), &long, Some(90), false));
// A clock that went backwards is not silence.
assert!(!silence_expired(at(100), at(200), &s, None, false));
}
}
+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"}"#;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+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
}
+51 -4
View File
@@ -19,7 +19,7 @@ pub const BATCH_INTERVAL: Duration = Duration::from_millis(16);
/// On macOS and Linux the kill is a hang-up signal, which a program can ignore.
/// This long after it, a command that is still running is killed outright.
#[cfg(unix)]
const HANGUP_GRACE: Duration = Duration::from_secs(2);
pub const HANGUP_GRACE: Duration = Duration::from_secs(2);
/// What to run, where, and how big the terminal starts.
pub struct StartOptions {
@@ -43,6 +43,11 @@ pub struct PtyHost {
/// a process id that may have been given to something else.
#[cfg(unix)]
exited: Arc<AtomicBool>,
/// Set once `end_group` has seen the process group empty (or killed what
/// was left of it), so `kill`'s late group kill never signals a group id
/// that may since have been given to something else.
#[cfg(unix)]
group_done: Arc<AtomicBool>,
/// A Windows Job Object the spawned process was assigned to, so ending
/// it (`kill`, or this host simply being dropped) ends every process
/// still in it, not just the one directly spawned: a `cmd /c` npm shim's
@@ -150,6 +155,8 @@ impl PtyHost {
pid,
#[cfg(unix)]
exited: Arc::new(AtomicBool::new(false)),
#[cfg(unix)]
group_done: Arc::new(AtomicBool::new(false)),
#[cfg(windows)]
job,
})
@@ -171,7 +178,9 @@ impl PtyHost {
.map_err(err)
}
/// End the command. Safe to call while `wait` is blocked in another thread.
/// End the command and everything it started that is still in its process
/// group (on Windows, its Job Object). Safe to call while `wait` is
/// blocked in another thread.
pub fn kill(&self) -> Result<(), String> {
let result = self.killer.lock().map_err(err)?.kill().map_err(err);
// The job object, when there is one, ends the whole process tree:
@@ -187,22 +196,60 @@ impl PtyHost {
if cfg!(windows) {
return Ok(());
}
// portable-pty only sends SIGHUP on macOS and Linux; follow it with
// SIGKILL if the command is still there after the grace period.
// portable-pty only sends SIGHUP on macOS and Linux, and only to the
// command itself. It starts the command under `setsid`, so the
// command's pid is also its process group's id: hang up the whole
// group too, then, after the grace period, kill whatever of the group
// is still there. A process that left the group (`setsid`, a detached
// child) is out of reach here.
#[cfg(unix)]
if let Some(pid) = self.pid {
// SAFETY: plain signal to the command's own process group.
unsafe { libc::kill(-(pid as i32), libc::SIGHUP) };
let exited = Arc::clone(&self.exited);
let group_done = Arc::clone(&self.group_done);
thread::spawn(move || {
thread::sleep(HANGUP_GRACE);
if !exited.load(Ordering::SeqCst) {
// SAFETY: plain signal to a process id the command still holds.
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
}
// The group outlives its leader while any member is left; signal 0
// only asks whether one is. Once `end_group` saw it gone, its id
// may belong to another group by now: leave it alone.
// SAFETY: plain signals to the command's own process group.
if !group_done.load(Ordering::SeqCst)
&& unsafe { libc::kill(-(pid as i32), 0) } == 0
{
unsafe { libc::kill(-(pid as i32), libc::SIGKILL) };
}
});
}
result
}
/// For after `kill` and `wait` when the app is about to exit: `kill`'s
/// grace thread dies with the app, so this blocks until nothing of the
/// command's process group is left, killing what is still there after
/// `HANGUP_GRACE`. A no-op on Windows, where `kill` ended the Job Object.
pub fn end_group(&self) {
#[cfg(unix)]
if let Some(pid) = self.pid {
let group = -(pid as i32);
let deadline = Instant::now() + HANGUP_GRACE;
// SAFETY: signal 0 only asks whether the group still has members.
while unsafe { libc::kill(group, 0) } == 0 {
if Instant::now() >= deadline {
// SAFETY: plain signal to the command's own process group.
unsafe { libc::kill(group, libc::SIGKILL) };
break;
}
thread::sleep(Duration::from_millis(20));
}
self.group_done.store(true, Ordering::SeqCst);
}
}
/// Block until the command ends and return its exit code. A command ended by
/// a signal reports 1.
pub fn wait(&self) -> Result<u32, String> {
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"
);
}
}
+134
View File
@@ -0,0 +1,134 @@
//! SIGTERM (a plain `kill`), SIGINT (Ctrl+C) and SIGHUP (the terminal closed) end a process at
//! once by default, so the app's quit cleanup never ran and the consoles its agents had opened
//! kept running. Here they are caught instead and handed to a thread of its own, which runs the
//! cleanup it was given, once. The handler only writes one byte to a pipe, which a signal handler
//! may safely do; the thread does the work.
//! A second SIGTERM or SIGINT ends the process at once, so a cleanup that stalls never leaves a
//! plain `kill` unable to end the app. A repeated SIGHUP does not: closing a terminal can send it
//! twice at once, from the shell and from the terminal itself, and the commands the cleanup runs
//! ignore it too.
//! Unix only: Windows has none of these to catch.
use std::io;
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
/// The signals that run the cleanup.
const SIGNALS: [libc::c_int; 3] = [libc::SIGTERM, libc::SIGINT, libc::SIGHUP];
static INSTALLED: AtomicBool = AtomicBool::new(false);
static CAUGHT: AtomicBool = AtomicBool::new(false);
static WRITE_END: AtomicI32 = AtomicI32::new(-1);
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
unsafe fn errno() -> *mut libc::c_int {
libc::__error()
}
#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe fn errno() -> *mut libc::c_int {
libc::__errno_location()
}
extern "C" fn on_signal(signal: libc::c_int) {
if CAUGHT.swap(true, Ordering::SeqCst) {
if signal != libc::SIGHUP {
// SAFETY: raise is async-signal-safe. SA_RESETHAND has put this signal's default
// action back, so it ends the process as the handler returns.
unsafe { libc::raise(signal) };
}
return;
}
let fd = WRITE_END.load(Ordering::Relaxed);
if fd < 0 {
return;
}
let byte = 1u8;
// SAFETY: write is async-signal-safe, and the end is non-blocking, so it never hangs the
// handler. errno is put back, since the code the signal interrupted may be about to read it.
unsafe {
let saved = *errno();
libc::write(fd, (&byte as *const u8).cast(), 1);
*errno() = saved;
}
}
fn last_error(what: &str) -> io::Error {
let error = io::Error::last_os_error();
io::Error::new(error.kind(), format!("{what}: {error}"))
}
/// Runs `cleanup` on a thread of its own the first time the process gets SIGTERM, SIGINT or
/// SIGHUP, instead of the process ending there; a second SIGTERM or SIGINT ends it. A signal the
/// process was started with ignored (`nohup` ignores SIGHUP) stays ignored. Once per process: a
/// second call is an error and changes nothing.
pub fn on_terminate(cleanup: impl FnOnce() + Send + 'static) -> io::Result<()> {
if INSTALLED.swap(true, Ordering::SeqCst) {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"the signal handler is already installed",
));
}
let mut ends = [0; 2];
// SAFETY: pipe fills the two-element array it is given.
if unsafe { libc::pipe(ends.as_mut_ptr()) } != 0 {
return Err(last_error("pipe"));
}
let [read_end, write_end] = ends;
// SAFETY: fcntl on the two descriptors just made. Close-on-exec keeps them out of the
// agents and consoles the app starts.
unsafe {
libc::fcntl(read_end, libc::F_SETFD, libc::FD_CLOEXEC);
libc::fcntl(write_end, libc::F_SETFD, libc::FD_CLOEXEC);
let flags = libc::fcntl(write_end, libc::F_GETFL);
libc::fcntl(write_end, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
WRITE_END.store(write_end, Ordering::SeqCst);
std::thread::Builder::new()
.name("quit-signal".into())
.spawn(move || {
let mut byte = 0u8;
loop {
// SAFETY: a one-byte read into a local; it blocks until the handler writes.
let read = unsafe { libc::read(read_end, (&mut byte as *mut u8).cast(), 1) };
if read == 1 {
break;
}
if read < 0 && io::Error::last_os_error().kind() == io::ErrorKind::Interrupted {
continue;
}
// The pipe failed: no cleanup can be signalled any more, so none runs.
return;
}
// For the commands the cleanup runs, which start with this process's ignored signals:
// a repeated SIGHUP would end one before it has done its work.
// SAFETY: ignoring a signal installs no handler.
unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) };
cleanup();
})?;
for signal in SIGNALS {
// SAFETY: a zeroed sigaction is a valid one to read the current action into, and, with the
// handler set and an empty mask, to install. SA_RESTART resumes the calls the signal
// interrupts elsewhere in the app, and SA_RESETHAND puts the default action back once the
// handler has run, so a second one ends the app; SIGHUP goes without it.
unsafe {
let mut action: libc::sigaction = std::mem::zeroed();
if libc::sigaction(signal, std::ptr::null(), &mut action) != 0 {
return Err(last_error("sigaction"));
}
if action.sa_sigaction == libc::SIG_IGN {
continue;
}
action = std::mem::zeroed();
action.sa_sigaction = on_signal as extern "C" fn(libc::c_int) as libc::sighandler_t;
action.sa_flags = libc::SA_RESTART;
if signal != libc::SIGHUP {
action.sa_flags |= libc::SA_RESETHAND;
}
libc::sigemptyset(&mut action.sa_mask);
if libc::sigaction(signal, &action, std::ptr::null_mut()) != 0 {
return Err(last_error("sigaction"));
}
}
}
Ok(())
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Plan2Code",
"version": "3.1.4",
"version": "3.2.7",
"identifier": "com.plan2code.desktop",
"build": {
"frontendDist": "../ui",
@@ -521,6 +521,197 @@ fn a_phase_start_runs_on_its_model_and_env_and_leaves_the_launch_choice_alone()
h.manager.stop();
}
/// Counts the manager's `ended` calls.
fn count_ends(h: &Harness) -> Arc<Mutex<usize>> {
let ends = Arc::new(Mutex::new(0));
let counter = Arc::clone(&ends);
h.manager.set_ended(Arc::new(move || {
*counter.lock().unwrap() += 1;
}));
ends
}
/// Wait (briefly) for `ends` to reach `want`, then make sure it stays there.
fn expect_ends(h: &mut Harness, ends: &Arc<Mutex<usize>>, want: usize, what: &str) {
let deadline = Instant::now() + Duration::from_secs(5);
while *ends.lock().unwrap() < want && Instant::now() < deadline {
h.pump_for(Duration::from_millis(50));
}
// A late exit of an agent already counted must not count again.
h.pump_for(Duration::from_millis(500));
assert_eq!(*ends.lock().unwrap(), want, "{what}");
}
#[test]
fn ended_runs_once_for_an_agent_that_exits_by_itself() {
let mut h = Harness::new();
let ends = count_ends(&h);
h.start_and_wait_ready();
h.type_line("EXIT 7");
h.wait_state("Ended", |s| matches!(s.state, AgentState::Ended { .. }));
expect_ends(&mut h, &ends, 1, "one natural end");
// Nothing is running now: a stop ends nothing more.
h.manager.stop();
expect_ends(&mut h, &ends, 1, "a stop with no running agent");
}
#[test]
fn ended_runs_once_for_a_stopped_agent_and_never_for_a_stop_of_none() {
let mut h = Harness::new();
let ends = count_ends(&h);
h.manager.stop();
expect_ends(&mut h, &ends, 0, "a stop before any start");
h.start_and_wait_ready();
h.manager.stop();
expect_ends(&mut h, &ends, 1, "one stop of a running agent");
}
#[test]
fn ended_runs_once_for_the_old_agent_on_restart_and_on_a_fresh_start() {
let mut h = Harness::new();
let ends = count_ends(&h);
h.start_and_wait_ready();
h.manager.restart().unwrap();
h.wait_for_output(READY, 2);
expect_ends(&mut h, &ends, 1, "the restarted agent's old one");
h.manager
.start_fresh("/plan2code next".to_string())
.unwrap();
h.wait_for_output(READY, 3);
expect_ends(&mut h, &ends, 2, "the old agent a fresh start replaced");
h.manager.stop();
expect_ends(&mut h, &ends, 3, "the last agent, stopped");
}
#[test]
fn an_ended_agent_takes_the_consoles_it_announced_and_only_those() {
use plan2code_app_lib::console_supervisor::{stop_announced_on_end, AnnouncedConsoles};
let mut h = Harness::new();
let announced = Arc::new(AnnouncedConsoles::default());
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&stopped);
h.manager.set_ended(stop_announced_on_end(
Arc::clone(&announced),
|| None,
move |sid| {
log.lock().unwrap().push(sid.to_string());
},
));
h.start_and_wait_ready();
announced.record("s1");
h.manager.stop();
let deadline = Instant::now() + Duration::from_secs(5);
while stopped.lock().unwrap().is_empty() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
// Recorded after the end: it belongs to whatever comes next.
announced.record("s2");
std::thread::sleep(Duration::from_millis(300));
assert_eq!(*stopped.lock().unwrap(), vec!["s1"]);
assert_eq!(announced.take_all(), vec!["s2"], "s2 was never taken");
}
/// Starts the harness's agent, has it leave a child that ignores the
/// terminal's hangup in its process group, and returns that child's pid.
#[cfg(unix)]
fn start_with_stray(h: &mut Harness) -> u32 {
h.start_and_wait_ready();
h.type_line("STRAY");
h.wait_for_output("STRAY ", 1);
let stray: u32 = h
.seen
.rsplit("STRAY ")
.next()
.unwrap()
.split(|c: char| !c.is_ascii_digit())
.next()
.unwrap()
.parse()
.expect("the stray child's pid");
assert!(process_alive(stray), "the stray child should be running");
stray
}
/// Waits out the hangup grace for `stray` to go, then kills it if it is
/// still there, so a failing test leaves nothing running. True if it went.
#[cfg(unix)]
fn stray_gone(stray: u32) -> bool {
use plan2code_app_lib::pty_host::HANGUP_GRACE;
let deadline = Instant::now() + HANGUP_GRACE + Duration::from_secs(2);
while process_alive(stray) && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(50));
}
let gone = !process_alive(stray);
if !gone {
let _ = std::process::Command::new("kill")
.args(["-9", &stray.to_string()])
.status();
}
gone
}
/// An agent that ends by itself leaves its process group alone: work the
/// person asked it to leave running (a dev server it backgrounded) stays up,
/// as it did before the app ended process groups at all.
#[cfg(unix)]
#[test]
fn an_agent_that_exits_by_itself_leaves_its_process_group_running() {
let mut h = Harness::new();
let stray = start_with_stray(&mut h);
h.type_line("EXIT 0");
h.wait_state("Ended", |s| matches!(s.state, AgentState::Ended { .. }));
assert!(
!stray_gone(stray),
"the stray child was ended with an agent that exited by itself"
);
}
/// An agent the app stops (quit, a project switch) takes its process group
/// with it, a child that ignores the terminal's hangup included.
#[cfg(unix)]
#[test]
fn a_stopped_agent_takes_its_process_group_with_it() {
let mut h = Harness::new();
let stray = start_with_stray(&mut h);
h.manager.stop();
assert!(
stray_gone(stray),
"the stray child outlived its stopped agent"
);
}
/// A Restart or New Session replaces the agent, and its process group goes
/// with the old one.
#[cfg(unix)]
#[test]
fn a_replaced_agent_takes_its_process_group_with_it() {
let mut h = Harness::new();
let stray = start_with_stray(&mut h);
h.manager.restart().unwrap();
assert!(
stray_gone(stray),
"the stray child outlived its replaced agent"
);
h.manager.stop();
}
/// Quitting right after New Session: the replaced agent's grace is still
/// running on a thread that would end with the app.
#[cfg(unix)]
#[test]
fn a_stop_right_after_a_restart_waits_for_the_replaced_agents_process_group() {
let mut h = Harness::new();
let stray = start_with_stray(&mut h);
h.manager.restart().expect("restart");
h.manager.stop();
let left = process_alive(stray);
assert!(stray_gone(stray), "the stray child outlived its grace");
assert!(!left, "the stray child was still there when stop returned");
}
#[test]
fn a_phase_start_with_no_launch_choice_is_refused() {
let h = Harness::new();
@@ -7,7 +7,7 @@ use std::path::PathBuf;
use std::process::Command;
use std::time::{Duration, Instant};
use plan2code_app_lib::console_supervisor::{app_origin, ConsoleSupervisor};
use plan2code_app_lib::console_supervisor::{app_origin, stop_console_session, ConsoleSupervisor};
fn have_node() -> bool {
Command::new("node")
@@ -120,6 +120,38 @@ fn a_killed_console_is_dead_and_restarts() {
sup.stop().expect("stop");
}
#[test]
fn stopping_a_session_by_id_never_panics() {
let Some(project) = setup() else { return };
// The console has nothing to stop for a session it does not know: that is
// not a failure.
assert_eq!(
stop_console_session(&repo_console_dir(), &project, "no-such-session"),
Ok(())
);
// A folder with no console in it is.
let empty = temp_dir("no-console");
let error = stop_console_session(&empty, &project, "no-such-session")
.expect_err("no console.mjs to run");
assert!(error.starts_with("console stop failed"), "{error}");
}
#[test]
fn a_session_stopped_by_id_stops_answering() {
let Some(project) = setup() else { return };
let mut sup =
ConsoleSupervisor::start(project.clone(), app_origin().to_string()).expect("start");
assert!(until_health(&sup, true), "the console URL never answered");
let sid = sup.session().sid.clone();
stop_console_session(&repo_console_dir(), &project, &sid).expect("stop by id");
assert!(
until_health(&sup, false),
"the console still answered after stop_console_session()"
);
sup.stop().expect("a second stop is harmless");
}
#[test]
fn a_live_console_is_not_restarted() {
let Some(project) = setup() else { return };
+96
View File
@@ -103,6 +103,102 @@ fn kill_ends_a_running_step() {
);
}
/// A grandchild that ignores hangup is still in the agent's process group
/// (portable-pty starts the agent under `setsid`), so `kill` must reach it
/// through the group once the grace is up. An ordinary grandchild already dies
/// with its shell, when the kernel hangs up the terminal, so it cannot show this.
#[cfg(unix)]
#[test]
fn kill_ends_a_hangup_ignoring_grandchild_after_the_grace() {
use plan2code_app_lib::pty_host::HANGUP_GRACE;
let (host, pid) =
start_sh_with_grandchild("trap '' HUP; sleep 300 & echo GRANDCHILD=$! END; wait");
assert!(alive(pid), "the grandchild should be running before kill");
host.kill().unwrap();
host.wait().unwrap();
assert!(
gone_within(pid, HANGUP_GRACE + Duration::from_secs(2)),
"the hangup-ignoring grandchild outlived kill()"
);
}
/// An agent that ended by itself was never killed, so no grace thread of
/// `kill`'s is there to finish its group: only `end_group` can end the
/// grandchild that ignored the terminal's hangup.
#[cfg(unix)]
#[test]
fn end_group_ends_what_a_command_that_exited_by_itself_left() {
let (host, pid) = start_sh_with_grandchild(
"(trap '' HUP; exec sleep 300) & echo GRANDCHILD=$! END; sleep 0.2; exit 0",
);
host.wait().unwrap();
assert!(alive(pid), "the grandchild outlived its shell, as set up");
host.end_group();
// Only the moment it takes the reaper to collect it.
assert!(
gone_within(pid, Duration::from_secs(1)),
"the grandchild outlived end_group()"
);
}
/// `script` under `/bin/sh -c` on a pty; it must print `GRANDCHILD=<pid> END`.
/// Returns the host and that pid.
#[cfg(unix)]
fn start_sh_with_grandchild(script: &str) -> (PtyHost, i32) {
let (tx, rx) = channel();
let host = PtyHost::start(
StartOptions {
program: "/bin/sh".to_string(),
args: vec!["-c".to_string(), script.to_string()],
env: vec![],
cwd: None,
cols: 80,
rows: 24,
},
move |bytes| {
let _ = tx.send(bytes);
},
)
.expect("start the shell");
let mut seen = String::new();
wait_for(&host, &rx, &mut seen, " END");
let pid = seen
.rsplit("GRANDCHILD=")
.next()
.unwrap()
.split(|c: char| !c.is_ascii_digit())
.next()
.unwrap()
.parse()
.expect("the grandchild's pid");
(host, pid)
}
#[cfg(unix)]
fn alive(pid: i32) -> bool {
// SAFETY: signal 0 only asks whether the process exists.
unsafe { libc::kill(pid, 0) == 0 }
}
/// Whether `pid` is gone within `within`; killed on the way out either way,
/// so a failing test leaves nothing behind.
#[cfg(unix)]
fn gone_within(pid: i32, within: Duration) -> bool {
let deadline = Instant::now() + within;
while alive(pid) && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
let gone = !alive(pid);
if !gone {
// SAFETY: a process this test started.
unsafe { libc::kill(pid, libc::SIGKILL) };
}
gone
}
/// An npm `.cmd` shim: `cmd.exe` is the directly spawned process, the real
/// program (here, the fake agent) its grandchild. `kill` must end both, not
/// just `cmd.exe` (Task 9.8).
@@ -0,0 +1,263 @@
//! The signals that end the app against the handler that turns them into its quit cleanup. A
//! file of its own, so the handler lives in a test process of its own: without it, a signal below
//! ends the whole process and the run fails. The handler installs once per process, so every
//! other case runs in a child: this test binary again, running only `signal_child`.
#![cfg(unix)]
use std::io::{BufRead, BufReader, IsTerminal, Write};
use std::os::fd::{FromRawFd, OwnedFd};
use std::os::unix::process::ExitStatusExt;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::mpsc::channel;
use std::time::{Duration, Instant};
use plan2code_app_lib::{log, term_signal};
/// Names the case, and is set only in the child process a test starts.
const CHILD: &str = "P2C_TERM_SIGNAL_CHILD";
/// The child's exit codes: its cleanup ran to the end, or it did not when it should have.
const CLEANED: i32 = 0;
const NOT_CLEANED: i32 = 3;
#[test]
fn a_sigterm_runs_the_cleanup_instead_of_ending_the_process() {
let (tx, rx) = channel();
term_signal::on_terminate(move || {
let _ = tx.send(());
})
.expect("the handler installs");
raise(libc::SIGTERM);
rx.recv_timeout(Duration::from_secs(5))
.expect("the cleanup ran after SIGTERM");
// A second install is refused: one signal, one cleanup.
assert!(term_signal::on_terminate(|| {}).is_err());
}
#[test]
fn ctrl_c_and_a_closed_terminal_run_the_cleanup_too() {
for case in ["sigint", "sighup"] {
let status = outcome(child(case).spawn().expect("the child starts"));
assert_eq!(status.code(), Some(CLEANED), "{case}: {status:?}");
}
}
#[test]
fn a_second_signal_ends_the_app_while_its_cleanup_still_runs() {
// A cleanup that stalls must not leave a plain `kill` or Ctrl+C unable to
// end the app, whichever signal started it.
for (case, ends_by) in [
("sigterm twice", libc::SIGTERM),
("sigint twice", libc::SIGINT),
("sighup then sigterm", libc::SIGTERM),
] {
let status = outcome(child(case).spawn().expect("the child starts"));
assert_eq!(status.signal(), Some(ends_by), "{case}: {status:?}");
}
}
#[test]
fn a_repeated_sighup_lets_the_cleanup_finish() {
// Closing a terminal can send it twice at once: zsh passes it on to the
// program in front, and the terminal's own hangup sends it again.
let status = outcome(child("sighup twice").spawn().expect("the child starts"));
assert_eq!(status.code(), Some(CLEANED), "{status:?}");
}
#[test]
fn a_signal_the_app_was_started_with_ignored_stays_ignored() {
// `nohup` starts a program with SIGHUP ignored, to outlive its terminal.
let status = outcome(child("ignored sighup").spawn().expect("the child starts"));
assert_eq!(status.code(), Some(CLEANED), "{status:?}");
}
#[test]
fn a_command_the_cleanup_runs_outlives_a_repeated_sighup() {
// The cleanup stops consoles by running `node`, which the second SIGHUP of
// a closed terminal would end before it stopped anything.
let status = outcome(child("command").spawn().expect("the child starts"));
assert_eq!(status.code(), Some(CLEANED), "{status:?}");
}
#[test]
fn a_cleanup_that_logs_after_its_terminal_is_gone_still_finishes() {
for case in ["sighup, closed terminal", "sigterm, closed terminal"] {
logs_to_a_closed_terminal(case);
}
}
/// Runs the child on a terminal of its own, and closes that terminal once the
/// child has its handler.
fn logs_to_a_closed_terminal(case: &str) {
let (mut master, mut slave) = (-1, -1);
// SAFETY: openpty fills the two descriptors; the name and settings are optional.
let opened = unsafe {
libc::openpty(
&mut master,
&mut slave,
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
)
};
assert_eq!(opened, 0, "openpty: {}", std::io::Error::last_os_error());
// SAFETY: both descriptors were just opened, and nothing else owns them. Close-on-exec keeps
// the terminal's other end out of the child, which would hold it open.
let (master, slave) = unsafe {
libc::fcntl(master, libc::F_SETFD, libc::FD_CLOEXEC);
(OwnedFd::from_raw_fd(master), OwnedFd::from_raw_fd(slave))
};
let mut child = child(case)
.stdout(Stdio::piped())
.stderr(Stdio::from(slave))
.spawn()
.expect("the child starts");
let stdout = child.stdout.take().expect("the child's stdout is piped");
let ready = BufReader::new(stdout)
.lines()
.map_while(Result::ok)
.any(|line| line.ends_with("ready"));
assert!(ready, "the child installed the handler");
drop(master);
let status = outcome(child);
assert_eq!(status.code(), Some(CLEANED), "{case}: {status:?}");
}
fn raise(signal: libc::c_int) {
// SAFETY: raise only sends this process a signal.
assert_eq!(unsafe { libc::raise(signal) }, 0);
}
/// This test binary again, running only `signal_child` on `case`.
fn child(case: &str) -> Command {
let mut command = Command::new(std::env::current_exe().expect("the test binary"));
command
.args(["--exact", "signal_child", "--test-threads=1", "--nocapture"])
.env(CHILD, case)
.stdout(Stdio::null())
.stderr(Stdio::null());
command
}
/// How the child ended, within 30 s.
fn outcome(mut child: Child) -> ExitStatus {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
if let Some(status) = child.try_wait().expect("the child can be waited on") {
return status;
}
if Instant::now() > deadline {
let _ = child.kill();
let _ = child.wait();
panic!("the child neither ended nor exited within 30 s");
}
std::thread::sleep(Duration::from_millis(50));
}
}
/// Not a check on its own: the child process of the tests above. Run any other
/// way, it returns at once.
#[test]
fn signal_child() {
let Some(case) = std::env::var_os(CHILD) else {
return;
};
// A signal this run was started with ignored (`nohup`, a script's `&`)
// would stay ignored, and no case below means that one.
for signal in [libc::SIGTERM, libc::SIGINT, libc::SIGHUP] {
// SAFETY: putting a signal's default action back installs no handler.
unsafe { libc::signal(signal, libc::SIG_DFL) };
}
match case.to_str().expect("a case name") {
"sigint" => cleans_up_after(&[libc::SIGINT]),
"sighup" => cleans_up_after(&[libc::SIGHUP]),
"sighup twice" => cleans_up_after(&[libc::SIGHUP, libc::SIGHUP]),
"sigterm twice" => ends_during_the_cleanup(libc::SIGTERM, libc::SIGTERM),
"sigint twice" => ends_during_the_cleanup(libc::SIGINT, libc::SIGINT),
"sighup then sigterm" => ends_during_the_cleanup(libc::SIGHUP, libc::SIGTERM),
"ignored sighup" => ignores_sighup(),
"command" => runs_a_command_through_a_sighup(),
"sighup, closed terminal" => logs_after_its_terminal_closed(libc::SIGHUP),
"sigterm, closed terminal" => logs_after_its_terminal_closed(libc::SIGTERM),
other => panic!("no such case: {other}"),
}
}
/// The cleanup takes a moment, so a signal that ends the app would cut it short.
fn cleans_up_after(signals: &[libc::c_int]) {
term_signal::on_terminate(|| {
std::thread::sleep(Duration::from_millis(300));
std::process::exit(CLEANED);
})
.expect("the handler installs");
for signal in signals {
raise(*signal);
}
std::thread::sleep(Duration::from_secs(5));
std::process::exit(NOT_CLEANED);
}
fn ends_during_the_cleanup(first: libc::c_int, second: libc::c_int) {
let (tx, rx) = channel();
term_signal::on_terminate(move || {
let _ = tx.send(());
// A cleanup that never finishes.
loop {
std::thread::sleep(Duration::from_secs(60));
}
})
.expect("the handler installs");
raise(first);
rx.recv_timeout(Duration::from_secs(5))
.expect("the first signal started the cleanup");
raise(second);
// Still running: the second signal was swallowed.
std::thread::sleep(Duration::from_secs(2));
std::process::exit(NOT_CLEANED);
}
fn ignores_sighup() {
// SAFETY: ignoring a signal installs no handler.
unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) };
term_signal::on_terminate(|| std::process::exit(NOT_CLEANED)).expect("the handler installs");
raise(libc::SIGHUP);
std::thread::sleep(Duration::from_secs(1));
std::process::exit(CLEANED);
}
fn runs_a_command_through_a_sighup() {
term_signal::on_terminate(|| {
let status = Command::new("/bin/sh")
.args(["-c", "kill -HUP $$; exit 0"])
.status()
.expect("sh runs");
std::process::exit(if status.success() {
CLEANED
} else {
NOT_CLEANED
});
})
.expect("the handler installs");
raise(libc::SIGHUP);
std::thread::sleep(Duration::from_secs(5));
std::process::exit(NOT_CLEANED);
}
fn logs_after_its_terminal_closed(signal: libc::c_int) {
assert!(std::io::stderr().is_terminal(), "stderr is a terminal");
term_signal::on_terminate(|| {
log::line("a line from the cleanup");
std::process::exit(CLEANED);
})
.expect("the handler installs");
println!("ready");
// Closed once a write fails: macOS reports neither a hangup nor a lost terminal here.
let deadline = Instant::now() + Duration::from_secs(10);
while std::io::stderr().write_all(b".").is_ok() {
assert!(Instant::now() < deadline, "the terminal never closed");
std::thread::sleep(Duration::from_millis(10));
}
raise(signal);
std::thread::sleep(Duration::from_secs(5));
std::process::exit(NOT_CLEANED);
}
+170 -12
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);
@@ -969,6 +972,29 @@ let helloTimer = null;
// Nothing has shown here yet: no agent has opened the dashboard. No polling,
// no "reconnect" button makes sense until that first page lands.
let consoleKnown = false;
// Which console the checks below ask about. A project switch moves it on, so
// an answer that comes back afterward is about a console that is gone.
let consoleEpoch = 0;
// The project moved on, and its console was stopped on purpose: nothing is
// known here again until the new agent opens a page. Left known, the next
// poll found no console and put "The console stopped" over the new agent's
// start, or the launch card; left in the frame, the old page showed its "Lost
// contact" around it.
function forgetConsole() {
consoleEpoch += 1;
consoleKnown = false;
clearInterval(pollTimer);
pollTimer = null;
clearTimeout(helloTimer);
currentUrl = null;
frameReady = false;
// As for any page going away (loadFrame): its taskbar dot and its game go too.
clearAttention();
setGameFull(false);
frame.src = 'about:blank';
markConsoleAlive();
}
function loadFrame(url) {
currentUrl = url;
@@ -1038,6 +1064,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;
@@ -1170,6 +1275,7 @@ setWindowTheme(document.documentElement.getAttribute('data-theme') === 'light' ?
// No hello in time: ask the console why, and say so with a way forward.
async function onNoHello() {
if (frameReady || !consoleKnown || restarting) return;
const epoch = consoleEpoch;
// A page that does not answer cannot say it is done needing the person.
clearAttention();
// The next phase's console is on its way; the poll says so instead. Look
@@ -1185,6 +1291,7 @@ async function onNoHello() {
} catch {
// The status check itself failed; treat it as a console that is not answering.
}
if (epoch !== consoleEpoch) return;
if (!status || status.state !== 'running') {
showState('The console stopped, so the page could not show.', 'Reconnect the console', reconnectConsole);
} else {
@@ -1352,12 +1459,15 @@ let pollTimer = null;
// on its own session. The app never opens a dashboard on its own (the agent
// does, by running the skill), so there is nothing to start before that.
async function reconnectConsole() {
const epoch = consoleEpoch;
markConsoleAlive();
showState('Reconnecting to the console...');
try {
const info = await invoke('console_start');
if (epoch !== consoleEpoch) return;
loadFrame(info.url);
} catch (error) {
if (epoch !== consoleEpoch) return;
showErrorState(error, 'reach the console', 'Retry', reconnectConsole);
// An old console cannot be framed: the fix is the skills update, so offer it.
if (String(error).includes('too old')) setVersionState({ kind: 'too-old' });
@@ -1371,8 +1481,10 @@ const RECONNECT_LIMIT = 3;
let reconnects = 0;
async function pollConsole() {
const epoch = consoleEpoch;
try {
const status = await invoke('console_status');
if (epoch !== consoleEpoch) return;
if (status.state === 'running') {
markConsoleAlive();
return;
@@ -1628,6 +1740,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 +1789,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 +1856,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
@@ -2004,7 +2131,7 @@ function afterProjectKnown() {
// tears the old project's agent and console down before the new one is
// remembered, so nothing from it carries over. Cancel (or Escape) leaves
// the current project as it was; the folder already open is not listed.
async function doChangeProject() {
async function doChangeProject(prior = null) {
try {
const dir = await showFolderPicker({ dialog: true });
if (!dir) {
@@ -2018,15 +2145,46 @@ async function doChangeProject() {
setProjectDir(dir);
if (appState) appState.projectDir = dir;
restarting = false;
currentUrl = null;
frameReady = false;
afterProjectKnown();
forgetConsole();
// An agent was in use: start the same one (agent, model, effort and
// permission mode) in the new folder, rather than leaving the launch card
// and an empty terminal. Nothing to carry over: the launch card as before.
if (prior) await startPriorAgent(prior);
else afterProjectKnown();
} catch (error) {
showErrorState(error, 'switch project', 'Try again', doChangeProject);
showErrorState(error, 'switch project', 'Try again', () => doChangeProject(prior));
}
}
// What the agent in use was started with, kept before a project switch tears
// it down: null when none was started (a bare start), or its kind is unknown.
function priorAgentSettings() {
if (!agent.kind || (agent.state !== 'running' && agent.state !== 'ended')) return null;
return {
kind: agent.kind,
model: agent.model || null,
effort: agent.effort || null,
mode: agent.mode === 'bypass' ? 'bypass' : 'checked',
};
}
async function startPriorAgent({ kind, model, effort, mode }) {
launchAgentEl.value = kind;
setAgentStatus('');
beginWait('Starting the agent in the new project...');
const { cols, rows } = terminal.size();
try {
await invoke('agent_start', { kind, model, effort, mode, cols, rows });
terminal.focus();
} catch (error) {
endWait();
setAgentError(error, 'start the agent');
showLaunchCard();
}
}
async function changeProject() {
const prior = priorAgentSettings();
if (agentActive()) {
const yes = await confirmModal({
title: 'Stop the running agent and switch to a different project?',
@@ -2036,7 +2194,7 @@ async function changeProject() {
});
if (!yes) return;
}
doChangeProject();
doChangeProject(prior);
}
changeProjectBtn.onclick = () => {
+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); }
+65 -8
View File
@@ -110,6 +110,12 @@ export function lastAgentNotice(list, remembered) {
export function barNextSteps({ consoleDead = false, version = null, newRelease = null, updatedTo = null, notReplaced = null } = {}) {
const v = version || {};
const steps = [];
const rel = newRelease || {};
const notes = rel.latest ? { label: "What's new", url: releaseNotesUrl(rel.latest) } : null;
// A release that is merely out, with no update under way: while skills are ahead of the app,
// the lead step below offers it, so the same button is not shown twice.
const releasePlain = Boolean(rel.latest) && !rel.restartNeeded && rel.updating === undefined && !rel.failed;
let aheadOffersUpdate = false;
if (v.kind === 'updated') {
steps.push({ id: 'updated', text: 'Skills updated', title: 'Updated. Reconnect the console to use the new version.', tone: 'ok', action: 'restart-console' });
} else if (consoleDead) {
@@ -134,7 +140,15 @@ export function barNextSteps({ consoleDead = false, version = null, newRelease =
steps.push({ id: 'failed', text: 'Update failed', title: String(v.error || 'The update did not finish.'), tone: 'err', action: 'update' });
break;
case 'ahead':
steps.push({ id: 'ahead', text: `Skills v${v.skills} are newer than this app`, title: `The installed skills are v${v.skills}, newer than this app (v${v.app}). Get the new app.`, tone: 'warn', action: null });
// The skills are ahead of the app, so another Update skills run cannot help: the release's
// Update and restart replaces the app file. While that is under way, failed or waiting for
// a restart, its own step below says so instead.
if (releasePlain) {
steps.push({ id: 'ahead', text: `Update to latest: v${rel.latest}`, title: `The installed skills are v${v.skills}, newer than this app (v${v.app}). Update and restart installs v${rel.latest}; nothing needs a terminal.`, tone: 'warn', action: 'update-restart', link: notes });
aheadOffersUpdate = true;
} else if (!rel.latest) {
steps.push({ id: 'ahead', text: `App v${v.app} is older than the skills (v${v.skills})`, title: `The installed skills are v${v.skills}, newer than this app (v${v.app}). Get the new app.`, tone: 'warn', action: null });
}
break;
default:
break;
@@ -144,8 +158,6 @@ export function barNextSteps({ consoleDead = false, version = null, newRelease =
// `{ latest, failed: reason }`, `{ latest, restartNeeded: true }` (installed, waiting for the
// restart) or `{ problem }` (the check could not run); `updatedTo` is the version the app
// restarted into, shown once.
const rel = newRelease || {};
const notes = rel.latest ? { label: "What's new", url: releaseNotesUrl(rel.latest) } : null;
if (rel.latest) {
const latest = rel.latest;
if (rel.restartNeeded) {
@@ -155,7 +167,7 @@ export function barNextSteps({ consoleDead = false, version = null, newRelease =
steps.push({ id: 'new-release', text: line, title: line, tone: 'warn', busy: true, action: null });
} else if (rel.failed) {
steps.push({ id: 'new-release', text: 'Update failed', title: `${rel.failed} Plan2Code is still running as it was. You can try again, or run \`${NEW_RELEASE_COMMAND}\` in a terminal.`, tone: 'err', action: 'update-restart', link: notes });
} else {
} else if (!aheadOffersUpdate) {
steps.push({ id: 'new-release', text: `Update available: v${latest}`, title: `Plan2Code v${latest} is out. Update and restart installs it; nothing needs a terminal.`, tone: 'warn', action: 'update-restart', link: notes });
}
} else if (rel.problem) {
@@ -210,6 +222,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 +238,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 +265,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 +319,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,
};
@@ -720,7 +774,10 @@ export function shortcutFromMessage(data) {
* What a key press does in the terminal's clipboard handling: "copy" (Ctrl+Shift+C, Cmd+C, and
* Ctrl+C while text is selected, the Windows Terminal rule: with nothing selected Ctrl+C is the
* interrupt and returns null), "paste" (Ctrl+V, Ctrl+Shift+V, Cmd+V), or null. With `mac`, a plain
* Ctrl+C is always the interrupt, as in every macOS terminal: copy there is Cmd+C.
* Ctrl+C is always the interrupt, as in every macOS terminal: copy there is Cmd+C. Ctrl+V belongs to
* the agent there too (Claude Code pastes an image with it), and Cmd+V returns null as well: it is
* left to the webview's own paste event, which xterm takes as one paste, because reading the
* clipboard from script makes WebKit ask with a Paste menu before the text arrives.
*/
export function clipboardAction(event, hasSelection, { mac = false } = {}) {
if (!event || event.altKey) return null;
@@ -730,7 +787,7 @@ export function clipboardAction(event, hasSelection, { mac = false } = {}) {
if (event.ctrlKey && !event.metaKey) return event.shiftKey || (hasSelection && !mac) ? 'copy' : null;
return null;
}
if (key === 'v' && (event.ctrlKey || event.metaKey)) return 'paste';
if (key === 'v' && !mac && (event.ctrlKey || event.metaKey)) return 'paste';
return null;
}
+1 -1
View File
@@ -139,7 +139,7 @@ export async function mountTerminal(container, { onInput, onResize, onFontSize,
// Ctrl+C copies while text is selected and is the interrupt otherwise (the Windows Terminal
// rule; on a Mac it is always the interrupt); Ctrl+Shift+C and Cmd+C always copy.
// preventDefault on the paste keys: the browser's own paste event would otherwise reach the
// terminal a second time.
// terminal a second time. On a Mac no key is a paste key here: Cmd+V is that own paste event.
const action = clipboardAction(event, term.hasSelection(), { mac: IS_MAC });
if (action === 'copy') {
copySelection();
+837
View File
@@ -0,0 +1,837 @@
#!/usr/bin/env node
// Install/update benchmark for Plan2Code. Dev-only: lives in scripts/ so it
// never ships inside a skill or the runtime install payload.
//
// node scripts/bench-install-update.mjs --mode cold-npx --baseline v3.2.1 --candidate main
//
// Every timed run is given throwaway home, npm, console and application-data
// locations. The measured installer never sees the developer's real HOME,
// npm prefix or npm cache. warm-npx deliberately separates cache warmth from
// installer-state warmth: one untimed warm-up per ref primes the npm cache
// shared by that ref's timed runs, but uses a sibling warm-up HOME, so every
// timed run still starts with a fresh HOME. warm-canonical is the mode that
// reuses HOME, because its purpose is to measure repeated updates against
// already-installed state.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const { readTimingEvents } = require("../src/installer/timing.js");
export const MODES = ["cold-npx", "warm-npx", "warm-canonical"];
// The desktop app kills an update after this long; the benchmark reports each ref's headroom
// against it so a healthy run that approaches it is visible. The timeout itself lives in the app.
export const DESKTOP_APP_TIMEOUT_MS = 300000;
export function desktopTimeoutHeadroom(totalMs, limitMs = DESKTOP_APP_TIMEOUT_MS) {
const max = totalMs && typeof totalMs.max === "number" ? totalMs.max : null;
if (max === null) return { limitMs, maxTotalMs: null, headroomMs: null, exceeded: null };
return { limitMs, maxTotalMs: max, headroomMs: Math.round(limitMs - max), exceeded: max >= limitMs };
}
export const PHASES = ["bootstrap", "skills", "console", "canonical", "link-refresh", "pieces"];
export const MODE_BEHAVIOR = {
"cold-npx": "fresh isolated HOME and npm cache per timed run; the cache is cleared immediately before timing",
"warm-npx": "one untimed warm-up per ref primes the npm cache shared by that ref's timed runs, but uses a separate warm-up HOME; every timed HOME is fresh",
"warm-canonical": "one untimed warm-up per ref reuses the same isolated HOME and npm cache; every timed run is a repeated update against that HOME",
};
const VALUE_FLAGS = new Set(["baseline", "candidate", "mode", "runs", "json", "workdir", "repo-url"]);
const BOOLEAN_FLAGS = new Set(["keep-workdirs", "help"]);
const EXPECTED_EVENTS = [
"bootstrap-start",
"installer-start",
"installer-end",
"skills-built",
"console-staged",
"console-committed",
"canonical-staged",
"canonical-committed",
"retired-removed",
"links-refreshed",
"piece-installed",
];
const CONTROLLED_ENV = [
"HOME",
"USERPROFILE",
"npm_config_prefix",
"npm_config_cache",
"PLAN2CODE_CONSOLE_HOME",
"PLAN2CODE_BENCH_JSON",
"PLAN2CODE_BENCH_MODE",
"PLAN2CODE_INSTALL_REF",
"APPDATA",
"LOCALAPPDATA",
"XDG_CONFIG_HOME",
// Repo-local git state and inline git config must never leak into a child
// benchmark. Credential helpers and SSH agent variables stay inherited on
// purpose: a benchmark of a private fork needs the person's normal auth.
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_CONFIG",
"GIT_CONFIG_COUNT",
"GIT_CONFIG_PARAMETERS",
"npm_config_userconfig",
"NPM_CONFIG_USERCONFIG",
];
export function usage() {
return `Usage: node scripts/bench-install-update.mjs --mode cold-npx|warm-npx|warm-canonical \\
[--baseline <ref>] [--candidate <ref>] [--runs <n>] [--json <path>] [--workdir <path>] [--repo-url <url>] [--keep-workdirs]
Dev-only benchmark. At least one of --baseline or --candidate is required.
--runs defaults to 3. Refs use letters, digits, slash, dot, dash and underscore only.
Modes:
cold-npx ${MODE_BEHAVIOR["cold-npx"]}
warm-npx ${MODE_BEHAVIOR["warm-npx"]}
warm-canonical ${MODE_BEHAVIOR["warm-canonical"]}`;
}
function fail(message) {
return { ok: false, error: message };
}
function validRef(ref) {
// Windows runs npx through the shell. This intentionally accepts the normal
// branch/tag/sha alphabet and excludes shell metacharacters, whitespace and
// '#' rather than trying to make cmd.exe quoting safe for every byte git
// might theoretically permit in a ref.
return typeof ref === "string" && /^[A-Za-z0-9_][A-Za-z0-9._/-]{0,199}$/.test(ref) && !ref.includes("..") && !ref.includes("//");
}
export function parseArgs(argv) {
const options = { runs: 3, keepWorkdirs: false };
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (!arg.startsWith("--")) return fail(`Unexpected argument: ${arg}`);
const name = arg.slice(2);
if (BOOLEAN_FLAGS.has(name)) {
options[toCamel(name)] = true;
continue;
}
if (!VALUE_FLAGS.has(name)) return fail(`Unknown flag: --${name}`);
const value = argv[i + 1];
if (value === undefined || value.startsWith("--")) return fail(`Missing value for --${name}`);
options[toCamel(name)] = value;
i++;
}
if (options.help) return { ok: true, help: true, options };
if (!options.mode) return fail("Missing required --mode cold-npx|warm-npx|warm-canonical");
if (!MODES.includes(options.mode)) return fail(`Unknown mode: ${options.mode}`);
if (!options.baseline && !options.candidate) return fail("At least one of --baseline or --candidate is required");
for (const [label, ref] of [
["baseline", options.baseline],
["candidate", options.candidate],
]) {
if (ref && !validRef(ref)) return fail(`Unsafe or unsupported ${label} ref: ${ref}`);
}
const runs = Number(options.runs);
if (!Number.isInteger(runs) || runs < 1) return fail("--runs must be a positive integer");
options.runs = runs;
options.refs = [];
if (options.baseline) options.refs.push({ label: "baseline", ref: options.baseline });
if (options.candidate) options.refs.push({ label: "candidate", ref: options.candidate });
return { ok: true, options };
}
function toCamel(flag) {
return flag.replace(/-([a-z])/g, (_, ch) => ch.toUpperCase());
}
function normalizeForCompare(value) {
let normalized = path.resolve(String(value));
while (normalized.length > path.parse(normalized).root.length && /[\\/]$/.test(normalized)) normalized = normalized.slice(0, -1);
return process.platform === "win32" ? normalized.toLowerCase() : normalized;
}
function samePath(a, b) {
return normalizeForCompare(a) === normalizeForCompare(b);
}
function uniquePaths(values) {
const seen = new Set();
const out = [];
for (const value of values.flat()) {
if (!value || typeof value !== "string") continue;
const key = normalizeForCompare(value);
if (!seen.has(key)) {
seen.add(key);
out.push(value);
}
}
return out;
}
export function realInstallPaths(env = process.env) {
const home = env.HOME || env.USERPROFILE || os.homedir();
const appData = env.APPDATA || (home ? path.join(home, "AppData", "Roaming") : null);
const localAppData = env.LOCALAPPDATA || (home ? path.join(home, "AppData", "Local") : null);
return {
home: uniquePaths([os.homedir(), env.HOME, env.USERPROFILE]),
npmPrefix: uniquePaths([
env.npm_config_prefix,
env.NPM_CONFIG_PREFIX,
process.platform === "win32" && appData ? path.join(appData, "npm") : "/usr/local",
]),
npmCache: uniquePaths([
env.npm_config_cache,
env.NPM_CONFIG_CACHE,
process.platform === "win32" && localAppData ? path.join(localAppData, "npm-cache") : home ? path.join(home, ".npm") : null,
]),
consoleHome: uniquePaths([env.PLAN2CODE_CONSOLE_HOME, home ? path.join(home, ".plan2code", "console") : null]),
appData: uniquePaths([env.APPDATA, env.LOCALAPPDATA, env.XDG_CONFIG_HOME]),
};
}
export function isolationErrors(env, real = realInstallPaths(), { boundaryRoot = null } = {}) {
const errors = [];
const required = [
"HOME",
"USERPROFILE",
"npm_config_prefix",
"npm_config_cache",
"PLAN2CODE_CONSOLE_HOME",
"PLAN2CODE_BENCH_JSON",
"APPDATA",
"LOCALAPPDATA",
"XDG_CONFIG_HOME",
];
for (const key of required) {
if (!env[key]) errors.push(`${key} is missing`);
else if (!path.isAbsolute(env[key])) errors.push(`${key} is not absolute: ${env[key]}`);
}
if (errors.length) return errors;
const sensitive = [
...(real.home || []).map((p) => ["real home", p]),
...(real.npmPrefix || []).map((p) => ["real npm prefix", p]),
...(real.npmCache || []).map((p) => ["real npm cache", p]),
...(real.consoleHome || []).map((p) => ["real console home", p]),
...(real.appData || []).map((p) => ["real application-data path", p]),
];
for (const key of required) {
for (const [label, realPath] of sensitive) {
if (samePath(env[key], realPath)) errors.push(`${key} equals the ${label}: ${env[key]}`);
}
}
if (boundaryRoot) {
const root = normalizeForCompare(boundaryRoot);
for (const key of required) {
const value = normalizeForCompare(env[key]);
const relative = path.relative(root, value);
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) errors.push(`${key} is outside the benchmark work root: ${env[key]}`);
}
}
return [...new Set(errors)];
}
export function assertIsolatedEnvironment(env, real, options) {
const errors = isolationErrors(env, real, options);
if (errors.length) {
const error = new Error(`Refusing to benchmark outside an isolated environment:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
error.isolationFailure = true;
throw error;
}
}
function mkdirs(paths) {
for (const dir of paths) fs.mkdirSync(dir, { recursive: true });
}
export function createIsolatedEnvironment({ root, cachePath = null, cacheDescription = "<shared with the timed run>", benchJsonName = path.join("timing", "events.jsonl"), stdoutName = path.join("logs", "stdout.log"), stderrName = path.join("logs", "stderr.log") }) {
const home = path.join(root, "home");
const npmPrefix = path.join(root, "npm-prefix");
const npmCache = cachePath || path.join(root, "npm-cache");
const consoleHome = path.join(root, "console-home");
const appData = path.join(root, "app-data", "roaming");
const localAppData = path.join(root, "app-data", "local");
const xdgConfigHome = path.join(root, "xdg-config");
const benchJson = path.join(root, benchJsonName);
const stdoutLog = path.join(root, stdoutName);
const stderrLog = path.join(root, stderrName);
mkdirs([home, npmPrefix, npmCache, consoleHome, appData, localAppData, xdgConfigHome, path.dirname(benchJson), path.dirname(stdoutLog), path.dirname(stderrLog)]);
const paths = { root, home, npmPrefix, npmCache, consoleHome, appData, localAppData, xdgConfigHome, benchJson, stdoutLog, stderrLog };
const env = {
HOME: home,
USERPROFILE: home,
npm_config_prefix: npmPrefix,
npm_config_cache: npmCache,
PLAN2CODE_CONSOLE_HOME: consoleHome,
PLAN2CODE_BENCH_JSON: benchJson,
// Set all three on every platform. Windows installers read the first two,
// Linux tools read the XDG path, and cross-platform tools may read either;
// keeping all of them inside the temp tree is stronger isolation.
APPDATA: appData,
LOCALAPPDATA: localAppData,
XDG_CONFIG_HOME: xdgConfigHome,
};
const layout = {
home: "home/",
npmPrefix: "npm-prefix/",
npmCache: cachePath ? cacheDescription : "npm-cache/",
consoleHome: "console-home/",
appData: "app-data/roaming/",
localAppData: "app-data/local/",
xdgConfigHome: "xdg-config/",
benchJson: benchJsonName.split(path.sep).join("/"),
stdoutLog: stdoutName.split(path.sep).join("/"),
stderrLog: stderrName.split(path.sep).join("/"),
};
return { root, paths, env, layout };
}
export function childProcessEnvironment(overrides, base = process.env) {
const controlled = new Set(CONTROLLED_ENV.map((key) => key.toLowerCase()));
const env = {};
for (const [key, value] of Object.entries(base)) {
const upper = key.toUpperCase();
if (!controlled.has(key.toLowerCase()) && !/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(upper)) env[key] = value;
}
return { ...env, ...overrides };
}
function safePart(text) {
return String(text).replace(/[^A-Za-z0-9._-]+/g, "_").slice(0, 60) || "ref";
}
export function createWorkspace(workdir = null) {
if (workdir) {
const parent = path.resolve(workdir);
fs.mkdirSync(parent, { recursive: true });
return { parent, root: fs.mkdtempSync(path.join(parent, "install-bench-")) };
}
return { parent: os.tmpdir(), root: fs.mkdtempSync(path.join(os.tmpdir(), "p2c-install-bench-")) };
}
export function buildNpxInvocation(ref, repoUrl = "https://github.com/jparkerweb/plan2code.git") {
if (!validRef(ref)) throw new Error(`Unsafe or unsupported ref: ${ref}`);
const args = ["--yes", "--allow-git=all", `git+${repoUrl}#${ref}`, "--update", "--force"];
const windows = process.platform === "win32";
// Modern Node refuses to spawn a .cmd directly without a shell, while
// shell:true concatenates arguments and warns. executeNpx invokes cmd.exe
// explicitly on Windows; the invocation shape here remains the logical npx
// command the benchmark is measuring. The strict ref alphabet above keeps
// the fixed command line free of cmd metacharacters.
return {
command: windows ? "npx.cmd" : "npx",
args,
shell: false,
argv: [windows ? "npx.cmd" : "npx", ...args],
};
}
const SECRET_ENV_NAME = /(?:TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|\bKEY\b)/i;
function secretValues(env) {
return Object.entries(env)
.filter(([key, value]) => SECRET_ENV_NAME.test(key) && typeof value === "string" && value.length >= 1)
.map(([, value]) => value)
.sort((a, b) => b.length - a.length)
.slice(0, 100);
}
export function redactSecrets(text, secrets = []) {
let out = String(text ?? "");
out = out.replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{8,}\b/g, "<redacted-token>");
out = out.replace(/\bgithub_pat_[A-Za-z0-9_]{8,}\b/g, "<redacted-token>");
out = out.replace(/\b(x-access-token:)[^\s/@]+@/gi, "$1<redacted>@");
out = out.replace(/\b(https?:\/\/[^\s/@:]+:)[^\s/@]+@/gi, "$1<redacted>@");
out = out.replace(/^(\s*(?:username|user|password|pass|token|secret)\s*[=:]\s*)\S+.*$/gim, "$1<redacted>");
out = out.replace(/\b((?:access_token|token|password|secret)=)[^\s&]+/gi, "$1<redacted>");
out = out.replace(/\b(authorization:\s*(?:basic|bearer)\s+)\S+/gi, "$1<redacted>");
for (const secret of secrets) {
if (secret) out = out.split(secret).join("<redacted>");
}
return out;
}
export function sanitizeArgv(argv, env = process.env) {
const secrets = secretValues(env);
return argv.map((arg) => redactSecrets(arg, secrets));
}
function writeSanitizedLog(file, text, env) {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, redactSecrets(text, secretValues(env)), "utf8");
}
export async function executeNpx({ command, args, shell, cwd, env, stdoutLog, stderrLog }, spawnImpl = spawn) {
return new Promise((resolve) => {
let child;
try {
const windowsNpx = process.platform === "win32" && command.toLowerCase() === "npx.cmd";
const spawnCommand = windowsNpx ? process.env.ComSpec || "cmd.exe" : command;
const spawnArgs = windowsNpx ? ["/d", "/s", "/c", command, ...args] : args;
child = spawnImpl(spawnCommand, spawnArgs, { cwd, env, shell, stdio: ["ignore", "pipe", "pipe"] });
} catch (error) {
writeSanitizedLog(stdoutLog, "", env);
writeSanitizedLog(stderrLog, error.stack || error.message, env);
resolve({ exitCode: null, signal: null, error: error.message, endedMs: Date.now() });
return;
}
let stdout = "";
let stderr = "";
let settled = false;
const finish = (result) => {
if (settled) return;
settled = true;
// The clock stops when npx closes; sanitizing and writing the logs is
// harness overhead, not installer time.
const endedMs = Date.now();
writeSanitizedLog(stdoutLog, stdout, env);
writeSanitizedLog(stderrLog, stderr + (result.error ? `${stderr ? "\n" : ""}${result.error}\n` : ""), env);
resolve({ ...result, endedMs });
};
child.stdout?.on("data", (chunk) => (stdout += chunk));
child.stderr?.on("data", (chunk) => (stderr += chunk));
child.once("error", (error) => finish({ exitCode: null, signal: null, error: error.message }));
child.once("close", (exitCode, signal) => finish({ exitCode, signal, error: null }));
});
}
function eventAt(event) {
const ms = Date.parse(event?.at || "");
return Number.isFinite(ms) ? ms : null;
}
function eventsNamed(events, name) {
return events.filter((event) => event && event.event === name);
}
function firstEvent(events, name) {
return eventsNamed(events, name)[0] || null;
}
function lastEvent(events, name) {
const matches = eventsNamed(events, name);
return matches[matches.length - 1] || null;
}
function numericDuration(event) {
return event && typeof event.durationMs === "number" && Number.isFinite(event.durationMs) ? event.durationMs : null;
}
function roundMs(value) {
return typeof value === "number" && Number.isFinite(value) ? Math.round(value * 1000) / 1000 : null;
}
function spanMs(startEvent, endEvent) {
const start = eventAt(startEvent);
const end = eventAt(endEvent);
if (start === null || end === null) return null;
return Math.max(0, end - start);
}
function directOrSpan(events, durationName, startName, endName) {
const direct = numericDuration(lastEvent(events, durationName));
if (direct !== null) return direct;
return spanMs(firstEvent(events, startName), lastEvent(events, endName));
}
export function summarizeEvents(events, { startedAt = null } = {}) {
// Prefer the durationMs stamped by the installer at a phase's completion
// boundary. For older refs whose events are point-in-time only, fall back
// to the closest timestamp span. Missing data stays null; it is evidence
// about that ref, not a benchmark failure.
const valid = (events || []).filter((event) => event && typeof event === "object" && typeof event.event === "string");
const counts = {};
for (const event of valid) counts[event.event] = (counts[event.event] || 0) + 1;
const childStart = typeof startedAt === "number" ? startedAt : Date.parse(startedAt || "");
const bootstrapEnd = firstEvent(valid, "bootstrap-start") || firstEvent(valid, "installer-start");
const bootstrap = Number.isFinite(childStart) && eventAt(bootstrapEnd) !== null ? Math.max(0, eventAt(bootstrapEnd) - childStart) : null;
const pieceEvents = eventsNamed(valid, "piece-installed");
const pieceTotals = {};
let piecesTotal = 0;
let anyPieceDuration = false;
for (const event of pieceEvents) {
const piece = event.piece || "<unknown>";
const duration = numericDuration(event);
if (!pieceTotals[piece]) pieceTotals[piece] = { totalMs: 0, count: 0, results: [] };
pieceTotals[piece].count++;
if (event.result !== undefined) pieceTotals[piece].results.push(event.result);
if (duration !== null) {
pieceTotals[piece].totalMs += duration;
piecesTotal += duration;
anyPieceDuration = true;
}
}
for (const piece of Object.values(pieceTotals)) piece.totalMs = roundMs(piece.totalMs);
const piecesFallback = spanMs(lastEvent(valid, "links-refreshed"), lastEvent(valid, "installer-end"));
const redirectDuration = numericDuration(lastEvent(valid, "redirect-end"));
const retiredDuration = numericDuration(lastEvent(valid, "retired-removed"));
const installerDuration = numericDuration(lastEvent(valid, "installer-end"));
const firstAt = valid.map(eventAt).filter((v) => v !== null).sort((a, b) => a - b)[0] ?? null;
const lastAt = valid.map(eventAt).filter((v) => v !== null).sort((a, b) => a - b).at(-1) ?? null;
const phases = {
bootstrap: roundMs(bootstrap),
skills: roundMs(directOrSpan(valid, "skills-built", "installer-start", "skills-built")),
console: roundMs(directOrSpan(valid, "console-committed", "console-staged", "console-committed")),
canonical: roundMs(directOrSpan(valid, "canonical-committed", "canonical-staged", "canonical-committed")),
"link-refresh": roundMs(directOrSpan(valid, "links-refreshed", "retired-removed", "links-refreshed")),
pieces: roundMs(anyPieceDuration ? piecesTotal : piecesFallback),
};
return {
phases,
pieces: pieceTotals,
eventCount: valid.length,
eventCounts: Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b))),
missingEvents: EXPECTED_EVENTS.filter((name) => !counts[name]),
firstEventAt: firstAt === null ? null : new Date(firstAt).toISOString(),
lastEventAt: lastAt === null ? null : new Date(lastAt).toISOString(),
eventSpanMs: firstAt === null || lastAt === null ? null : roundMs(Math.max(0, lastAt - firstAt)),
installerMs: roundMs(installerDuration),
extraPhases: {
redirect: roundMs(redirectDuration),
"retired-removal": roundMs(retiredDuration),
},
};
}
export function stats(values) {
const nums = (values || []).filter((value) => typeof value === "number" && Number.isFinite(value)).sort((a, b) => a - b);
if (!nums.length) return null;
const middle = Math.floor(nums.length / 2);
const median = nums.length % 2 ? nums[middle] : (nums[middle - 1] + nums[middle]) / 2;
return { median: roundMs(median), min: roundMs(nums[0]), max: roundMs(nums[nums.length - 1]), count: nums.length };
}
export function summarizeRuns(runs) {
const groups = new Map();
for (const run of runs || []) {
const key = `${run.ref}\u0000${run.mode}`;
if (!groups.has(key)) groups.set(key, { ref: run.ref, mode: run.mode, labels: new Set(), runs: [] });
const group = groups.get(key);
group.labels.add(run.label);
group.runs.push(run);
}
return [...groups.values()].map((group) => {
const rows = group.runs;
const pieceNames = [...new Set(rows.flatMap((run) => Object.keys(run.pieceTotals || {})))].sort();
const exitCodes = {};
for (const run of rows) exitCodes[String(run.exitCode)] = (exitCodes[String(run.exitCode)] || 0) + 1;
return {
ref: group.ref,
mode: group.mode,
labels: [...group.labels].sort(),
runs: rows.length,
exitCodes,
nonZeroExitRuns: rows.filter((run) => run.exitCode !== 0).length,
missingJsonlRuns: rows.filter((run) => !run.hasTimingJson).length,
totalMs: stats(rows.map((run) => run.totalMs)),
desktopTimeout: desktopTimeoutHeadroom(stats(rows.map((run) => run.totalMs))),
installerMs: stats(rows.map((run) => run.installerMs)),
eventCount: stats(rows.map((run) => run.eventCount)),
phases: Object.fromEntries(PHASES.map((phase) => [phase, stats(rows.map((run) => run.phases?.[phase]))])),
pieces: Object.fromEntries(pieceNames.map((piece) => [piece, stats(rows.map((run) => run.pieceTotals?.[piece]?.totalMs))])),
};
});
}
function environmentRecord({ kind, runId, label, ref, mode, runIndex, isolated, reuse }) {
return {
kind,
runId,
label,
ref,
mode,
runIndex,
tempRoot: isolated.root,
layout: isolated.layout,
variables: { ...isolated.env, PLAN2CODE_BENCH_MODE: mode, PLAN2CODE_INSTALL_REF: ref },
paths: isolated.paths,
reuse,
};
}
function canonicalWarmupEnvironment(timed) {
const benchJson = path.join(timed.root, "timing", "warmup-events.jsonl");
const stdoutLog = path.join(timed.root, "logs", "warmup.stdout.log");
const stderrLog = path.join(timed.root, "logs", "warmup.stderr.log");
mkdirs([path.dirname(benchJson), path.dirname(stdoutLog)]);
return {
root: timed.root,
paths: { ...timed.paths, benchJson, stdoutLog, stderrLog },
env: { ...timed.env, PLAN2CODE_BENCH_JSON: benchJson },
layout: { ...timed.layout, benchJson: "timing/warmup-events.jsonl", stdoutLog: "logs/warmup.stdout.log", stderrLog: "logs/warmup.stderr.log" },
};
}
function canonicalTimedEnvironment(shared, runIndex) {
const benchJson = path.join(shared.root, "timing", `run-${runIndex}-events.jsonl`);
const stdoutLog = path.join(shared.root, "logs", `run-${runIndex}.stdout.log`);
const stderrLog = path.join(shared.root, "logs", `run-${runIndex}.stderr.log`);
mkdirs([path.dirname(benchJson), path.dirname(stdoutLog)]);
return {
root: shared.root,
paths: { ...shared.paths, benchJson, stdoutLog, stderrLog },
env: { ...shared.env, PLAN2CODE_BENCH_JSON: benchJson },
layout: {
...shared.layout,
benchJson: `timing/run-${runIndex}-events.jsonl`,
stdoutLog: `logs/run-${runIndex}.stdout.log`,
stderrLog: `logs/run-${runIndex}.stderr.log`,
},
};
}
async function executeIsolated({ execute, target, mode, isolated, boundaryRoot, realPaths, repoUrl }) {
const invocation = buildNpxInvocation(target.ref, repoUrl);
const env = childProcessEnvironment({
...isolated.env,
PLAN2CODE_BENCH_MODE: mode,
// The ref is intentional: exact benchmark refs must not be silently
// redirected to another release, and the installer timing seam uses this
// variable to stamp the ref onto every JSONL event.
PLAN2CODE_INSTALL_REF: target.ref,
});
assertIsolatedEnvironment(env, realPaths, { boundaryRoot });
const startedMs = Date.now();
const startedAt = new Date(startedMs).toISOString();
let outcome;
try {
outcome = await execute({
command: invocation.command,
args: invocation.args,
shell: invocation.shell,
cwd: isolated.paths.home,
env,
stdoutLog: isolated.paths.stdoutLog,
stderrLog: isolated.paths.stderrLog,
timingPath: isolated.paths.benchJson,
});
} catch (error) {
outcome = { exitCode: null, signal: null, error: error.message };
}
const measuredEndMs = typeof outcome?.endedMs === "number" && Number.isFinite(outcome.endedMs) ? outcome.endedMs : Date.now();
return {
argv: sanitizeArgv(invocation.argv, env),
cwd: isolated.paths.home,
startedAt,
endedAt: new Date(measuredEndMs).toISOString(),
startedMs,
totalMs: roundMs(measuredEndMs - startedMs),
exitCode: outcome?.exitCode ?? outcome?.code ?? outcome?.status ?? null,
signal: outcome?.signal ?? null,
spawnError: redactSecrets(outcome?.error || "", secretValues(env)) || null,
};
}
function normalizeRunOptions(options) {
const refs = options.refs || [
...(options.baseline ? [{ label: "baseline", ref: options.baseline }] : []),
...(options.candidate ? [{ label: "candidate", ref: options.candidate }] : []),
];
return {
refs,
mode: options.mode,
runs: options.runs ?? 3,
workdir: options.workdir || null,
repoUrl: options.repoUrl || undefined,
keepWorkdirs: Boolean(options.keepWorkdirs),
};
}
export async function runBenchmark(rawOptions, { execute = executeNpx, realPaths = realInstallPaths(), workspace = null } = {}) {
const options = normalizeRunOptions(rawOptions);
if (!MODES.includes(options.mode)) throw new Error(`Unknown mode: ${options.mode}`);
if (!options.refs.length) throw new Error("At least one ref is required");
if (!Number.isInteger(options.runs) || options.runs < 1) throw new Error("runs must be a positive integer");
const space = workspace || createWorkspace(options.workdir);
const report = {
generatedAt: new Date().toISOString(),
mode: options.mode,
modeBehavior: MODE_BEHAVIOR[options.mode],
repoUrl: options.repoUrl || "https://github.com/jparkerweb/plan2code.git",
runs: [],
warmups: [],
summary: [],
environments: [],
};
for (const [targetIndex, target] of options.refs.entries()) {
const targetId = `${targetIndex + 1}-${target.label}-${safePart(target.ref)}`;
let sharedCachePath = null;
let sharedCanonical = null;
// Warm modes get exactly one untimed warm-up per ref, before that ref's
// timed repetitions. warm-npx shares only the npm cache with timed runs;
// warm-canonical shares the whole isolated install state.
if (options.mode !== "cold-npx") {
const warmupId = `${targetId}-warmup`;
let warmup;
if (options.mode === "warm-npx") {
sharedCachePath = path.join(space.root, `${targetId}-shared-npm-cache`);
fs.mkdirSync(sharedCachePath, { recursive: true });
// Deliberate measurement choice: cache warmth yes, HOME/canonical
// state no. This keeps warm-npx distinct from warm-canonical.
warmup = createIsolatedEnvironment({
root: path.join(space.root, warmupId),
cachePath: sharedCachePath,
cacheDescription: "<shared warm-npx cache for this ref>",
});
} else {
sharedCanonical = createIsolatedEnvironment({ root: path.join(space.root, `${targetId}-canonical-home`) });
sharedCachePath = sharedCanonical.paths.npmCache;
warmup = canonicalWarmupEnvironment(sharedCanonical);
}
const warmReuse = {
warmsCacheForTimedRuns: true,
warmupHomeReusedByTimedRuns: options.mode === "warm-canonical",
oneWarmupPerRef: true,
};
report.environments.push(environmentRecord({ kind: "warmup", runId: warmupId, label: target.label, ref: target.ref, mode: options.mode, runIndex: null, isolated: warmup, reuse: warmReuse }));
const warmResult = await executeIsolated({ execute, target, mode: options.mode, isolated: warmup, boundaryRoot: space.root, realPaths, repoUrl: options.repoUrl });
report.warmups.push({
runId: warmupId,
label: target.label,
ref: target.ref,
mode: options.mode,
runIndex: null,
...warmResult,
stdoutLog: warmup.paths.stdoutLog,
stderrLog: warmup.paths.stderrLog,
timingJsonl: warmup.paths.benchJson,
timed: false,
});
}
for (let runIndex = 1; runIndex <= options.runs; runIndex++) {
const runId = `${targetId}-run-${runIndex}`;
let timed;
const reuse = {
npmCacheFromWarmup: options.mode !== "cold-npx",
homeFromWarmup: options.mode === "warm-canonical",
cacheSharedAcrossTimedRuns: options.mode !== "cold-npx",
homeSharedAcrossTimedRuns: options.mode === "warm-canonical",
};
if (options.mode === "cold-npx") {
timed = createIsolatedEnvironment({ root: path.join(space.root, runId) });
fs.rmSync(timed.paths.npmCache, { recursive: true, force: true });
fs.mkdirSync(timed.paths.npmCache, { recursive: true });
} else if (options.mode === "warm-npx") {
timed = createIsolatedEnvironment({
root: path.join(space.root, runId),
cachePath: sharedCachePath,
cacheDescription: "<shared warm-npx cache for this ref>",
});
} else {
timed = canonicalTimedEnvironment(sharedCanonical, runIndex);
}
report.environments.push(environmentRecord({ kind: "timed", runId, label: target.label, ref: target.ref, mode: options.mode, runIndex, isolated: timed, reuse }));
const outcome = await executeIsolated({ execute, target, mode: options.mode, isolated: timed, boundaryRoot: space.root, realPaths, repoUrl: options.repoUrl });
const events = readTimingEvents(timed.paths.benchJson);
const eventSummary = summarizeEvents(events, { startedAt: outcome.startedMs });
const modeCounts = {
matching: events.filter((event) => event.mode === options.mode).length,
missing: events.filter((event) => event.mode === undefined).length,
mismatched: events.filter((event) => event.mode !== undefined && event.mode !== options.mode).length,
};
report.runs.push({
runId,
label: target.label,
ref: target.ref,
mode: options.mode,
runIndex,
...outcome,
stdoutLog: timed.paths.stdoutLog,
stderrLog: timed.paths.stderrLog,
timingJsonl: timed.paths.benchJson,
hasTimingJson: fs.existsSync(timed.paths.benchJson),
...eventSummary,
pieceTotals: eventSummary.pieces,
modeCounts,
});
}
}
report.summary = summarizeRuns(report.runs);
return { report, workspace: space };
}
function formatStat(stat, unit = " ms") {
if (!stat) return "-";
return `${stat.median}${unit} median (min ${stat.min}${unit}, max ${stat.max}${unit})`;
}
export function printReport(report, log = console.log) {
log(`install/update benchmark, mode=${report.mode}`);
log(`mode behavior: ${report.modeBehavior}`);
for (const row of report.summary) {
log("");
log(`${row.labels.join("+")} ${row.ref}: ${row.runs} timed run${row.runs === 1 ? "" : "s"}, exits ${JSON.stringify(row.exitCodes)}, missing JSONL ${row.missingJsonlRuns}`);
log(` total`.padEnd(24) + formatStat(row.totalMs));
const timeout = row.desktopTimeout;
if (timeout && timeout.maxTotalMs !== null) {
log(` desktop-app timeout`.padEnd(24) + `slowest run ${timeout.maxTotalMs} ms of ${timeout.limitMs} ms: ${timeout.exceeded ? "EXCEEDED" : `${timeout.headroomMs} ms headroom`}`);
}
log(` installer`.padEnd(24) + formatStat(row.installerMs));
for (const phase of PHASES) log(` ${phase}`.padEnd(24) + formatStat(row.phases[phase]));
const pieces = Object.keys(row.pieces || {});
if (pieces.length) {
log(" pieces:");
for (const piece of pieces) log(` ${piece}`.padEnd(24) + formatStat(row.pieces[piece]));
}
}
}
export function writeJsonReport(file, report) {
const target = path.resolve(file);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, `${JSON.stringify(report, null, 2)}\n`, "utf8");
return target;
}
async function main() {
const parsed = parseArgs(process.argv.slice(2));
if (!parsed.ok) {
console.error(usage());
console.error(`\nerror: ${parsed.error}`);
process.exit(2);
}
if (parsed.help) {
console.log(usage());
return;
}
let workspace = null;
try {
workspace = createWorkspace(parsed.options.workdir);
const result = await runBenchmark(parsed.options, { workspace });
printReport(result.report);
if (parsed.options.json) {
const written = writeJsonReport(parsed.options.json, result.report);
console.log(`\nJSON report: ${written}`);
}
if (parsed.options.keepWorkdirs) console.log(`workdirs kept under: ${workspace.root}`);
} catch (error) {
console.error(error.stack || error.message || error);
process.exitCode = 1;
} finally {
if (workspace && !parsed.options.keepWorkdirs) fs.rmSync(workspace.root, { recursive: true, force: true });
}
}
const invokedAs = process.argv[1] ? path.resolve(process.argv[1]) : null;
if (invokedAs && invokedAs === path.resolve(fileURLToPath(import.meta.url))) {
main();
}
+322
View File
@@ -0,0 +1,322 @@
// The desktop app's five pictures for the docs, taken by
// `node scripts/capture-screenshots.mjs --app`. Dev-only.
//
// The app's own page (plan2code-app/ui: the bar, the launch card, the loop
// banner, the terminal panel) runs in Chrome from a small static server, with
// a stand-in for the Rust side of window.__TAURI__: `invoke` answers from a
// fixed table, `listen` keeps the handlers so a scene can fire `console-page`
// and the agent's output channel. The dashboard in its frame is a real console
// session staged the same way as every other shot (capture-screenshots.mjs),
// with PLAN2CODE_IN_APP and PLAN2CODE_EMBED_ORIGIN set so it may be framed and
// draws its app-only parts (the loop cards, the loop setup, the stop screen).
// The terminal text is written by the scene: no agent runs.
//
// Each shot is dark only, 1280x800 at twice the pixel density, Ocean highlight.
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
export const APP_SHOTS = ["app-launch", "app-terminal", "loop-setup", "loop-banner", "loop-stop"];
const TYPES = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png", ".woff2": "font/woff2" };
/** Serves plan2code-app/ui on 127.0.0.1. Resolves { origin, close }. */
export function serveAppUi(root) {
const dir = path.join(root, "plan2code-app", "ui");
for (const f of ["xterm.js", "addon-fit.js", "xterm.css", "tokens.css"]) {
if (!fs.existsSync(path.join(dir, "vendor", f))) {
throw new Error(`plan2code-app/ui/vendor/${f} is missing: run \`npm install\` and \`node scripts/vendor.mjs\` in plan2code-app first.`);
}
}
const server = http.createServer((req, res) => {
const rel = decodeURIComponent(new URL(req.url, "http://x").pathname).replace(/^\/+/, "") || "index.html";
const abs = path.join(dir, rel);
if (!abs.startsWith(dir + path.sep) || !fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
res.writeHead(404);
return res.end();
}
res.writeHead(200, { "content-type": TYPES[path.extname(abs)] || "application/octet-stream", "cache-control": "no-store" });
fs.createReadStream(abs).pipe(res);
});
return new Promise((resolve) => {
server.listen(0, "127.0.0.1", () => {
resolve({ origin: `http://127.0.0.1:${server.address().port}`, close: () => new Promise((r) => server.close(r)) });
});
});
}
// The launch card's agents, the way the Rust side lists them: the three
// built-ins, installed, with the shipped model menu.
function availability(root) {
const models = JSON.parse(fs.readFileSync(path.join(root, "src", "launcher", "models.json"), "utf8"));
const entry = (id, label) => ({ id, label, installed: true, state: "found", path: null, folder: null, installHint: "", installUrl: null, hasEffort: id !== "devin", custom: false, models: models[id] || [] });
return { agents: [entry("claude", "Claude Code"), entry("codex", "Codex"), entry("devin", "Devin")], warnings: [] };
}
// Runs in the app page only (the console's frame gets nothing): the stand-in
// for the Tauri globals. `config` comes from the scene.
function tauriStub(config) {
if (window.top !== window) return;
const hub = { listeners: {}, channel: null, config };
window.__p2c = hub;
class Channel {
constructor() {
this.onmessage = null;
}
}
const answers = {
app_state: () => ({
projectDir: config.projectDir,
firstRunDone: true,
nodeChecked: true,
nodeVersion: "22.11.0",
// Nothing saved: the app's own default split for this window width.
termPanel: null,
// One step under the default, so the scenes' lines fit the default pane.
terminalFontSize: 12,
copyOnSelect: false,
lastAgent: "claude",
launchModel: "",
}),
agent_availability: () => config.availability,
platform_info: () => ({ os: "windows", windowsBuild: 26100 }),
agent_reattach: (args) => {
hub.channel = args.onOutput;
return { state: "idle", generation: 0 };
},
loop_state: () => config.loopState,
loop_facts: () => config.loopFacts,
console_status: () => ({ state: "running" }),
console_start: () => ({ url: hub.consoleUrl }),
version_status: () => ({ mismatch: false }),
check_new_release: () => ({ latest: null, problem: null }),
recent_folders: () => [],
};
const windowApi = new Proxy({}, { get: (_, name) => (name === "setTitle" ? async (t) => { document.title = t; } : async () => {}) });
window.__TAURI__ = {
core: {
Channel,
invoke: async (cmd, args) => (answers[cmd] ? answers[cmd](args || {}) : null),
},
event: {
listen: async (name, cb) => {
(hub.listeners[name] ||= []).push(cb);
return () => {};
},
},
window: { getCurrentWindow: () => windowApi },
};
hub.emit = (name, payload) => (hub.listeners[name] || []).forEach((cb) => cb({ payload }));
hub.agent = (state) => hub.channel && hub.channel.onmessage(state);
hub.write = (text) => hub.channel && hub.channel.onmessage(new TextEncoder().encode(text).buffer);
}
// What the terminal shows in each scene. Plain words in the shape of an agent's
// session, not any agent's real screen.
const DIM = "\x1b[2m";
const OFF = "\x1b[0m";
const BLUE = "\x1b[38;5;75m";
const GREEN = "\x1b[32m";
const RED = "\x1b[31m";
const lines = (...rows) => rows.join("\r\n") + "\r\n";
const TERM_DASHBOARD = lines(
`${DIM}~/code/task-api${OFF}`,
"",
`${BLUE}>${OFF} /plan2code`,
"",
"● Opening the dashboard.",
"",
"● Bash(console.mjs open)",
` ${DIM}⎿ → See the dashboard${OFF}`,
` ${DIM}beside this terminal.${OFF}`,
"",
"● The dashboard is open.",
" Phases 1 and 2 are done.",
" Implement is next, for",
" Phase 3. Pick a card",
" when you are ready.",
"",
`${DIM} Waiting for your pick...${OFF}`,
);
const TERM_BUILDING = lines(
`${DIM}Phase 3 of 4, by the loop${OFF}`,
"",
"● Read(phase-3.md)",
"",
"● Update(routes.js)",
` ${DIM}⎿ GET /tasks, paged${OFF}`,
"",
"● Update(tasks.test.js)",
` ${DIM}⎿ 6 tests for paging${OFF}`,
"",
"● Bash(npm test)",
` ${DIM}⎿${OFF} ${GREEN}✔ 41 passed${OFF} ${DIM}(1.8s)${OFF}`,
"",
"● Task 3.1 done.",
" Next: POST /tasks.",
"",
"● Update(routes.js)",
` ${DIM}⎿ POST /tasks with Zod${OFF}`,
);
const TERM_STOPPED = lines(
`${DIM}Phase 3 of 4, by the loop${OFF}`,
"",
"● Update(routes.js)",
` ${DIM}⎿ PATCH, DELETE /tasks/:id${OFF}`,
"",
"● Bash(npm test)",
` ${DIM}⎿${OFF} ${RED}✖ 2 failed${OFF}, 46 passed`,
"",
"● Still failing after a fix",
" round. Reporting to the",
" loop.",
);
const LOOP_FACTS = { agent: "claude", agentLabel: "Claude Code", model: "opus", effort: "high", permissionMode: "bypass", promptSupport: true, running: false };
const LOOP_RUNNING = {
running: true,
kind: "phases",
phase: 3,
phases: 4,
phaseName: "API endpoints",
step: "Building",
specName: "task-api",
strength: "balanced",
model: "sonnet",
effort: "high",
retriesUsed: 0,
canStopAfter: true,
};
const LOOP_STOPPED = {
kind: "stopped",
reason: "Phase 3 stopped: its tests still failed after a fix round.",
line: "npm test failed twice in Phase 3: PATCH /tasks/:id answers 200 for a deleted task, and a second DELETE answers 204 (test/tasks.test.js)",
advice: "Decide whether a deleted task should answer 404 or 410, then fix it together with an agent.",
recommend: "fix",
phase: 3,
phases: [
{ n: 3, name: "API endpoints", commit: null, unfixed: 0, retries: 1 },
{ n: 4, name: "Authentication", commit: null, unfixed: 0, retries: 0 },
],
uncommitted: ["src/tasks/routes.js", "test/tasks.test.js"],
can: ["ask", "resume", "fix", "dashboard"],
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
/**
* Takes one app shot. `h` carries what capture-screenshots.mjs owns: the
* browser, the app page's origin, the sample project, `cli`, `post`, `stage`
* and the output folder.
*/
export async function captureAppShot(name, h) {
const { browser, origin, project, cli, post, stage, root, out } = h;
const config = { projectDir: project, availability: availability(root), loopFacts: LOOP_FACTS, loopState: null };
let sid = null;
let url = null;
if (name === "app-terminal" || name === "loop-setup") {
({ sid, url } = stage(project, { workflow: "dashboard", posts: ["dashboard"] }));
} else if (name === "loop-banner" || name === "loop-stop") {
// A loop phase's page: opened with --loop, which only works under the app.
const r = cli(project, "open", "--workflow", "implement", "--spec", "specs/task-api", "--loop", "--no-open");
if (r.code !== 0 || !r.out || !r.out.url) throw new Error(`open --loop failed (${r.code}): ${r.err.trim()}`);
({ sid, url } = { sid: r.out.sid, url: r.out.url });
post(project, sid, "build");
if (name === "loop-banner") config.loopState = { ...LOOP_RUNNING, startedAtMs: 0 };
else {
const file = path.join(path.dirname(r.out.session), `loop-end-${sid}.json`);
fs.writeFileSync(file, JSON.stringify({ loopEnd: LOOP_STOPPED, agent: { status: "waiting" } }));
const p = cli(project, "post", "--session", sid, "--file", file);
if (p.code !== 0) throw new Error(`posting the loop's end failed (${p.code}): ${p.err.trim()}`);
}
}
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2, colorScheme: "dark" });
try {
await ctx.addInitScript(tauriStub, config);
const page = await ctx.newPage();
page.on("pageerror", (e) => console.log(` page error: ${e.message}`));
await page.goto(origin + "/index.html", { waitUntil: "domcontentloaded" });
await page.waitForFunction(() => window.__p2c && window.__p2c.channel, null, { timeout: 15000 });
// The banner's clock: started 23 minutes ago, set once the page is up.
if (config.loopState) {
await page.evaluate(() => {
const s = { ...window.__p2c.config.loopState, startedAtMs: Date.now() - 23 * 60 * 1000 - 12000 };
window.__p2c.emit("loop-state", s);
});
}
if (name === "app-launch") {
await page.locator("#launch-card:not([hidden])").waitFor({ timeout: 10000 });
await page.selectOption("#launch-model", "opus");
await page.selectOption("#launch-effort", "high");
await sleep(800);
} else {
const ended = name === "loop-stop";
await page.evaluate(
({ text, ended, loop }) => {
const p = window.__p2c;
p.agent({ state: "running", kind: "claude", generation: 1, mode: "bypass", model: loop ? "sonnet" : "opus", effort: "high" });
p.write(text);
if (ended) p.agent({ state: "ended", kind: "claude", generation: 1, mode: "bypass", model: "sonnet", effort: "high", reason: "exited with code 0" });
},
{ text: name === "loop-banner" ? TERM_BUILDING : name === "loop-stop" ? TERM_STOPPED : TERM_DASHBOARD, ended, loop: name.startsWith("loop-") && name !== "loop-setup" },
);
await page.evaluate((u) => {
window.__p2c.consoleUrl = u;
window.__p2c.emit("console-page", { url: u, sid: "", workflow: "" });
}, url);
const frame = page.frameLocator("iframe");
// The dashboard in the app opens on Planny asleep: wake him the way a
// person would, past the intro.
if (name === "app-terminal" || name === "loop-setup") {
const skip = frame.getByRole("button", { name: "Skip the intro" });
await skip.waitFor({ timeout: 20000 });
await skip.click();
await skip.waitFor({ state: "hidden" });
}
// Anything drawn in the main column: cards, the loop's end, or a phase's
// build-in-progress heading.
const drawn = frame.locator(".dash-card, .card, .handoff, .loop-end, #main h1, #main h2").first();
await drawn.waitFor({ timeout: 20000 }).catch(async () => {
const text = await frame.locator("body").innerText().catch(() => "");
console.log(` warning: ${name}: nothing known drew in the frame; it reads: ${text.slice(0, 300).replace(/\s+/g, " ")}`);
});
// The cards' entrance.
await sleep(3500);
// The dashboard: the suggested card in view, as in the console's own shot.
if (name === "app-terminal") {
await frame.locator(".dash-toggle").evaluate((n) => n.scrollIntoView({ block: "start", behavior: "instant" }));
await sleep(400);
}
if (name === "loop-setup") {
// The card is the button itself.
await frame.locator(".dash-card", { hasText: "Implementation Loop" }).first().click();
await frame.locator("#loop-start").waitFor({ timeout: 10000 });
await sleep(1500);
// From its top: the spec, the phases left and the strength.
await frame.locator(".loop-setup, #main").first().evaluate((n) => n.scrollIntoView({ block: "start", behavior: "instant" }));
await sleep(400);
}
if (name === "loop-stop") await frame.locator(".loop-end-actions").waitFor({ timeout: 10000 });
}
const cdp = await ctx.newCDPSession(page);
const clip = { x: 0, y: 0, width: 1280, height: 800, scale: 2 };
const { data } = await cdp.send("Page.captureScreenshot", { format: "webp", quality: 85, captureBeyondViewport: false, clip });
await cdp.detach();
const file = path.join(out, `${name}-dark.webp`);
fs.writeFileSync(file, Buffer.from(data, "base64"));
console.log(`${path.basename(file)} ${Math.round(fs.statSync(file).size / 1024)} KB`);
return file;
} finally {
await ctx.close();
if (sid) cli(project, "stop", "--session", sid);
}
}
+21 -4
View File
@@ -16,6 +16,10 @@
//
// Shots: dashboard, dashboard-plan, dashboard-utilities, question, doc, build, signoff, signoff-changes, finish, ask, git,
// notebook, learning, lessons, deps, activities and prototypes.
// --app takes the desktop app's five pictures instead (app-launch, app-terminal,
// loop-setup, loop-banner, loop-stop; dark only): the app's own page with a
// stand-in for its Rust side, framing a real staged console. See
// scripts/capture-app-shots.mjs. --only picks one of them.
// --compare adds workspace, stop, delete, help, prefs and cleanup: screens the
// docs never show, for checking a change by eye against a "before" set. Its
// --out must be outside docs/screenshots/, so the set is never published.
@@ -37,6 +41,7 @@ import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { launchBrowser } from "./browser.mjs";
import { APP_SHOTS, captureAppShot, serveAppUi } from "./capture-app-shots.mjs";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
@@ -351,7 +356,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");
@@ -659,8 +664,12 @@ async function main() {
fail(`--compare never writes into ${path.relative(ROOT, docs)}: pass --out with a folder outside it.`);
}
const table = args.compare ? { ...SHOTS, ...COMPARE_SHOTS } : SHOTS;
const names = args.only ? [args.only] : Object.keys(table);
for (const n of names) if (!table[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(table).join(", ")}`);
const known = args.app ? APP_SHOTS : Object.keys(table);
const names = args.only ? [args.only] : known;
for (const n of names) if (!known.includes(n)) fail(`Unknown shot "${n}". Shots: ${known.join(", ")}`);
// The app's page is served before any console starts: the console is told
// its origin is allowed to frame it.
const appUi = args.app ? await serveAppUi(ROOT) : null;
SCRATCH = fs.mkdtempSync(path.join(SCRATCH_ROOT, "p2c-shots-"));
HOME = path.join(SCRATCH, "console-home");
@@ -672,7 +681,11 @@ async function main() {
PLAN2CODE_NOTEPADS_DIR: path.join(SCRATCH, "notepads"),
PLAN2CODE_LEARNING_DIR: path.join(SCRATCH, "learning"),
PLAN2CODE_NO_BROWSER: "1",
...(appUi ? { PLAN2CODE_IN_APP: "1", PLAN2CODE_EMBED_ORIGIN: appUi.origin } : {}),
};
// Never announce to a real app window this shell may have inherited.
for (const k of ["PLAN2CODE_APP_TOKEN", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_CONSOLE_SID", "PLAN2CODE_APP_VERSION"]) delete ENV[k];
if (!appUi) delete ENV.PLAN2CODE_IN_APP;
fs.mkdirSync(HOME, { recursive: true });
fs.mkdirSync(OUT, { recursive: true });
let browser = null;
@@ -687,7 +700,10 @@ async function main() {
...(typeof args.browser === "string" ? { executablePath: args.browser } : {}),
args: ["--no-first-run", "--no-default-browser-check", "--mute-audio"],
});
for (const name of names) {
if (appUi) {
for (const name of names) await captureAppShot(name, { browser, origin: appUi.origin, project, cli, post, stage, root: ROOT, out: OUT });
}
for (const name of appUi ? [] : names) {
const spec = table[name];
const where = spec.repo
? makeGitProject()
@@ -709,6 +725,7 @@ async function main() {
if (args.snapshot) fs.writeFileSync(path.resolve(String(args.snapshot)), JSON.stringify(SNAP));
} finally {
if (browser) await browser.close();
if (appUi) await appUi.close();
if (project) cli(project, "stop", "--all");
removeScratch();
}
+3 -6
View File
@@ -1,6 +1,6 @@
// Fails when the console opening paragraph of a skill drifts from the shared one.
//
// Eighteen skills open with the same "web console or terminal?" paragraph. Only
// Twenty-one skills open with the same "terminal or web console?" paragraph. Only
// the workflow name, the notes file and a few skill-specific clauses may differ;
// the shared sentences below must read the same in every one, so a fix to one
// skill's opening cannot silently skip the others. Matching ignores case and
@@ -15,19 +15,16 @@ import { fileURLToPath } from "node:url";
// own words on purpose is listed in EXEMPT with the reason.
export const SHARED = [
{ id: "first", text: "The FIRST thing you do, before anything else in this file" },
{ id: "ask", text: "**web console** (browser page, suggested) or **terminal**?" },
{ id: "ask", text: '**terminal** or **web console**? Run `node "<D>/console.mjs" interface`' },
{ id: "rule", text: "and follow its rule: the request or the saved default decides; ask only if it says so or the command fails." },
{ id: "run", text: 'run `node "<D>/console.mjs" open --workflow {w}` before reading' },
{ id: "dir", text: "<D>: references/web-console/ beside this SKILL.md" },
{ id: "dirfile", text: "or the dir in ~/.plan2code/console/console-dir" },
{ id: "read", text: "then read <D>/console.md" },
{ id: "switch", text: "Switchable anytime." },
{ id: "web", text: "If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag." },
{ id: "dash", text: "Launched by the dashboard? Its session is already open: resume it (console-launches.md)" },
];
export const EXEMPT = {
// Implement + Review defers to Implementation Mode's own Interface question.
"plan2code-3-implement-review": { ask: "defers to Implementation Mode's Interface question", run: "the question is Implementation Mode's" , switch: "Implementation Mode's Interface section says it" },
// Git runs an instruction in the argument in the terminal at once and has its own hand-off lines.
"plan2code-git": { dash: "also resumes from Commit it now and the Changelog hand-off", first: "opens with the run-at-once rule for an argument" },
};
+32 -6
View File
@@ -1,10 +1,12 @@
// Fails when a built prompt names an agent product's tool by its product name.
// Fails when a built prompt names an agent product's tool by its product name,
// or bakes --web into a skill command.
//
// Prompts are read by many agents, and each one calls the same tool something
// else. Prompt text says what to do ("ask with the question tool", "list the
// folder") and never what one product's tool is called. This reads every
// Markdown file in the built skills/ tree, so run it after
// `node install.js --build-skills`.
// folder") and never what one product's tool is called. Skill commands are
// printed bare so the person's saved terminal or web console default decides;
// a baked --web overrides it. This reads every Markdown file in the built
// skills/ tree, so run it after `node install.js --build-skills`.
// Usage: node scripts/check-prompt-wording.mjs [skillsDir] (defaults to ./skills)
import fs from "node:fs";
@@ -29,6 +31,7 @@ export const BANNED = [
];
const PATTERN = new RegExp(`(?<![A-Za-z0-9_])(${BANNED.join("|")})(?![A-Za-z0-9_])`);
const BAKED_WEB_PATTERN = /`[^`\n]*\/plan2code[\w-]*[^`\n]*--web\b[^`\n]*`/g;
function* markdownFiles(dir) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
@@ -52,6 +55,21 @@ export function findBanned(dir) {
return hits;
}
// Returns [{ file, line, text }] for every skill command with --web baked in.
export function findBakedWeb(dir) {
const hits = [];
for (const file of markdownFiles(dir)) {
fs.readFileSync(file, "utf8")
.split("\n")
.forEach((lineText, i) => {
for (const m of lineText.matchAll(BAKED_WEB_PATTERN)) {
hits.push({ file: path.relative(dir, file).split(path.sep).join("/"), line: i + 1, text: m[0] });
}
});
}
return hits;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const dir = process.argv[2] ? path.resolve(process.argv[2]) : path.join(root, "skills");
@@ -60,10 +78,18 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
process.exit(1);
}
const hits = findBanned(dir);
const baked = findBakedWeb(dir);
if (hits.length) {
for (const h of hits) console.error(` FAIL ${h.file}:${h.line} names a product tool: ${h.name}`);
console.error(" Say what to do in neutral words (\"the question tool\", \"list the folder\").");
process.exit(1);
} else {
console.log("Built prompts name no product tool.");
}
console.log("Built prompts name no product tool.");
if (baked.length) {
for (const h of baked) console.error(` FAIL ${h.file}:${h.line} bakes --web into a skill command: ${h.text}`);
console.error(" Write the command bare and add \"(add `--web` for the web console)\" after it: a baked flag overrides the person's saved terminal or web console default.");
} else {
console.log("Built prompts bake no --web into skill commands.");
}
if (hits.length || baked.length) process.exit(1);
}
+306
View File
@@ -0,0 +1,306 @@
// Compact installable end-to-end fixtures: real installer code in a local
// git-ref fixture, but a deliberately small stand-in web console so automated
// tests do not clone and copy tens of megabytes of media for every case. The
// installer/build inputs outside src/web-console are the repository's real
// files, including binary runtime files. Everything here is dev-only.
//
// Limit: the slim payload is assembled here by hand, not by
// scripts/publish-install-refs.mjs, so a file the real publisher's allowlist
// leaves out would not show up in these tests. The publisher's own required-file
// validation is covered in scripts/test-publish-install-refs.mjs.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import crypto from "node:crypto";
import { spawnSync } from "node:child_process";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { createInstallRefFixture } from "./install-ref-fixtures.mjs";
import { assertIsolatedEnvironment, childProcessEnvironment, createIsolatedEnvironment } from "./bench-install-update.mjs";
const require = createRequire(import.meta.url);
const { selectSkillsCliVersion } = require("../src/installer/skills-cli.js");
export const INSTALL_E2E_VERSIONS = Object.freeze(["1.0.0", "2.0.0", "3.1.2"]);
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
function readRepo(rel, buffer = false) {
const data = fs.readFileSync(path.join(ROOT, ...rel.split("/")));
return buffer ? data : data.toString("utf8");
}
function walkFiles(dir, base = dir, out = []) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) walkFiles(full, base, out);
else if (entry.isFile()) out.push(path.relative(base, full).split(path.sep).join("/"));
}
return out;
}
/**
* The runtime payload of one fixture release. Everything under src/ except the
* web console is the real repository tree. The web console is reduced to the
* files the installer and launcher directly require plus the contract docs the
* skills copy; end-to-end installer tests validate staging and completion
* markers, not the console UI's media bundle.
*/
export function compactRuntimeFiles(version) {
const pkg = JSON.parse(readRepo("package.json"));
pkg.version = version;
const versionJson = JSON.parse(readRepo("version.json"));
versionJson.version = version;
const files = {
"install.js": readRepo("install.js"),
"package.json": `${JSON.stringify(pkg, null, 2)}\n`,
"version.json": `${JSON.stringify(versionJson, null, 2)}\n`,
"LICENSE": readRepo("LICENSE"),
"NOTICE": readRepo("NOTICE"),
};
for (const rel of walkFiles(path.join(ROOT, "src"), path.join(ROOT, "src"))) {
if (rel.startsWith("web-console/")) continue;
files[`src/${rel}`] = fs.readFileSync(path.join(ROOT, "src", ...rel.split("/")));
}
for (const rel of [
"console.mjs",
"console.md",
"building.md",
"console-docs.md",
"update-check.mjs",
"agent-lookup.mjs",
]) {
files[`src/web-console/${rel}`] = fs.readFileSync(path.join(ROOT, "src", "web-console", rel));
}
files["src/web-console/public/favicon.png"] = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "favicon.png"));
return files;
}
/**
* The full local repository shape with installable plain release trees and
* slim synthetic trees. Plain tags carry `docs/promo.md`; install tags do not,
* and carry the binding manifest the publisher writes.
*/
export function createInstallE2EFixture(options = {}) {
const releases = INSTALL_E2E_VERSIONS.map((version) => {
const runtime = compactRuntimeFiles(version);
const installFiles = {
...runtime,
".plan2code-install-ref.json": `${JSON.stringify({ kind: "install-ref", version, sourceTag: `v${version}`, sourceCommit: `fixture-v${version}`, files: Object.fromEntries(Object.entries(runtime).map(([name, content]) => [name, crypto.createHash("sha256").update(content).digest("hex")])) }, null, 2)}\n`,
};
return {
version,
annotated: version === "3.1.2",
installTag: version !== "1.0.0",
files: { ...runtime, "docs/promo.md": `# heavy fixture docs for v${version}\n` },
installFiles,
};
});
return createInstallRefFixture({ releases, ...options });
}
/** A temp root for one or more installer runs against one logical machine. */
export function makeInstallE2ERunRoot() {
return fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), "p2c-install-e2e-run-"));
}
/**
* Seed the exact pinned skills CLI in npm's private cache shape. The tiny CLI
* records each invocation as JSONL and exits successfully, so installs exercise
* resolveSkillsCli's cached path and never touch the npm registry.
*/
export function seedCachedSkillsCli(npmCache) {
const pin = selectSkillsCliVersion(process.versions.node);
const packageDir = path.join(npmCache, "_npx", "install-e2e-fixture", "node_modules", "skills");
fs.mkdirSync(path.join(packageDir, "bin"), { recursive: true });
fs.writeFileSync(
path.join(packageDir, "package.json"),
`${JSON.stringify({ name: "skills", version: pin, type: "module", bin: { skills: "bin/cli.mjs" }, dependencies: {} }, null, 2)}\n`
);
fs.writeFileSync(
path.join(packageDir, "bin", "cli.mjs"),
[
'import fs from "node:fs";',
'import path from "node:path";',
"const log = process.env.PLAN2CODE_SKILLS_CLI_LOG;",
"const argv = process.argv.slice(2);",
"if (log) {",
" fs.mkdirSync(path.dirname(log), { recursive: true });",
" fs.appendFileSync(log, JSON.stringify({ argv, cwd: process.cwd() }) + '\\n');",
"}",
"if (argv[0] === 'remove') {",
" const store = path.join(process.env.HOME || '', '.agents', 'skills');",
" for (const name of argv.slice(1).filter((arg) => !arg.startsWith('-'))) {",
" if (name === 'plan2code' || name.startsWith('plan2code-')) fs.rmSync(path.join(store, name), { recursive: true, force: true });",
" }",
"}",
"process.exit(0);",
"",
].join("\n")
);
return { pin };
}
/** JSONL records written by the seeded skills CLI, or [] when it never ran. */
export function readSkillsCliLog(file) {
try {
return fs
.readFileSync(file, "utf8")
.split(/\r?\n/)
.filter(Boolean)
.map((line) => JSON.parse(line));
} catch {
return [];
}
}
/**
* Fetch `ref` from the fixture with real git and run its install.js as a child
* inside one fully isolated machine image. Pass the same `root` again to model
* an update or uninstall on the same machine; omit it for a fresh machine.
* `planted` variables are set after the credential scrub, so a test can plant
* a sentinel secret and check that it never reaches an artifact.
*/
export function runFixtureInstaller(
fixture,
{
ref,
releaseRef = null,
root = makeInstallE2ERunRoot(),
planted = {},
} = {}
) {
const isolated = createIsolatedEnvironment({ root: path.join(root, "isolated") });
assertIsolatedEnvironment(isolated.env, undefined, { boundaryRoot: root });
seedCachedSkillsCli(isolated.paths.npmCache);
const cliLog = path.join(root, "skills-cli.jsonl");
const checkout = path.join(root, "payload");
fixture.checkout(ref, checkout);
const env = childProcessEnvironment({
...isolated.env,
PLAN2CODE_INSTALL_REF: ref,
PLAN2CODE_SKILLS_CLI_LOG: cliLog,
PLAN2CODE_RELEASE_BASE: "http://127.0.0.1:9/",
GIT_TERMINAL_PROMPT: "0",
GCM_INTERACTIVE: "never",
});
if (releaseRef) env.PLAN2CODE_RELEASE_REF = releaseRef;
else delete env.PLAN2CODE_RELEASE_REF;
// Automated end-to-end runs must not inherit app-loop state, user git
// credential configuration or hosted credentials. They use local-path git
// only; sensitive inherited variables are removed too so a typo can never
// turn into a credential-backed network fetch.
const emptyGitConfig = path.join(root, "empty-gitconfig");
fs.writeFileSync(emptyGitConfig, "");
env.GIT_CONFIG_NOSYSTEM = "1";
env.GIT_CONFIG_GLOBAL = emptyGitConfig;
for (const key of Object.keys(env)) {
if (/(?:TOKEN|SECRET|PASSWORD|CREDENTIAL|ASKPASS|^SSH_AUTH_SOCK$|^SSH_AGENT_PID$|^GIT_SSH|^PLAN2CODE_LS_REMOTE_FILE$)/i.test(key)) delete env[key];
if (/^PLAN2CODE_(?:IN_APP|EMBED_ORIGIN|CONSOLE_SID|LOOP_STRENGTH)/i.test(key)) delete env[key];
}
Object.assign(env, planted);
const result = spawnSync(process.execPath, [path.join(checkout, "install.js"), "--update", "--force"], {
cwd: checkout,
env,
encoding: "utf8",
input: "",
timeout: 180000,
windowsHide: true,
});
return {
root,
ref,
releaseRef,
checkout,
isolated,
cliLog,
env,
result,
stdout: result.stdout || "",
stderr: result.stderr || "",
cleanup: () => fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }),
};
}
/**
* A local npx stand-in for launcher-driven end-to-end runs. It accepts the real
* launcher's `git+https://github.com/...#ref` argument, but fetches that ref
* from the bare local fixture and runs its install.js. This keeps the launcher's
* production argument shape under test without any network use.
*/
export function installLocalNpxShim(root, fixture) {
const bin = path.join(root, "local-npx-bin");
fs.mkdirSync(bin, { recursive: true });
const driver = path.join(bin, "local-npx.mjs");
fs.writeFileSync(
driver,
[
'import fs from "node:fs";',
'import os from "node:os";',
'import path from "node:path";',
'import { execFileSync, spawnSync } from "node:child_process";',
`const origin = ${JSON.stringify(fixture.dir)};`,
'const args = process.argv.slice(2);',
'const at = args.findIndex((arg) => arg.startsWith("git+"));',
'if (at === -1) { console.error("local npx fixture: no git package spec"); process.exit(2); }',
'const spec = args[at];',
'const ref = spec.includes("#") ? spec.slice(spec.indexOf("#") + 1) : "main";',
'const rest = args.slice(at + 1);',
'const checkout = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-local-npx-payload-"));',
'try {',
' execFileSync("git", ["clone", "--quiet", "--depth", "1", "--branch", ref, origin, checkout], { stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" } });',
' fs.rmSync(path.join(checkout, ".git"), { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });',
' if (process.env.PLAN2CODE_LOCAL_NPX_LOG) {',
' fs.mkdirSync(path.dirname(process.env.PLAN2CODE_LOCAL_NPX_LOG), { recursive: true });',
' fs.appendFileSync(process.env.PLAN2CODE_LOCAL_NPX_LOG, JSON.stringify({ spec, ref, rest, synthetic: fs.existsSync(path.join(checkout, ".plan2code-install-ref.json")), docs: fs.existsSync(path.join(checkout, "docs", "promo.md")) }) + "\\n");',
' }',
' const run = spawnSync(process.execPath, [path.join(checkout, "install.js"), ...rest], { stdio: "inherit", env: process.env });',
' process.exitCode = run.status ?? 1;',
'} finally {',
' fs.rmSync(checkout, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });',
'}',
"",
].join("\n")
);
if (process.platform === "win32") {
fs.writeFileSync(path.join(bin, "npx.cmd"), `@echo off\r\n"${process.execPath}" "${driver}" %*\r\nexit /b %errorlevel%\r\n`);
} else {
fs.writeFileSync(path.join(bin, "npx"), `#!/bin/sh\nexec "${process.execPath}" "${driver}" "$@"\n`);
fs.chmodSync(path.join(bin, "npx"), 0o755);
}
return { bin, driver };
}
/** The fixture snapshot as a file for PLAN2CODE_LS_REMOTE_FILE. */
export function writeFixtureSnapshot(fixture, root) {
const file = path.join(root, "ls-remote.txt");
fs.writeFileSync(file, fixture.lsRemote(), "utf8");
return file;
}
/** Environment for invoking the installed launcher inside one isolated run image. */
export function launcherRunEnvironment(run, { bin, lsRemoteFile }) {
const env = { ...run.env, PLAN2CODE_LS_REMOTE_FILE: lsRemoteFile };
const pathKey = Object.keys(env).find((key) => key.toUpperCase() === "PATH") || "PATH";
env[pathKey] = bin + path.delimiter + (env[pathKey] || "");
return env;
}
/** Convenience readers for the isolated machine image returned above. */
export function installE2EJson(run, ...parts) {
try {
return JSON.parse(fs.readFileSync(path.join(run.isolated.paths.home, ...parts), "utf8"));
} catch {
return null;
}
}
export function installE2EExists(run, ...parts) {
return fs.existsSync(path.join(run.isolated.paths.home, ...parts));
}
+234
View File
@@ -0,0 +1,234 @@
// Local git-ref fixtures for the install/update tests: bare repositories in
// temp dirs, built with one `git fast-import` stream each, so no network, no
// working tree and no dozens of slow per-object git spawns are ever involved.
// A fixture carries the ref shape the installer and launcher reason about:
//
// - lightweight and annotated `vX.Y.Z` release tags on `main` commits
// (annotated ones produce peeled `^{}` lines in ls-remote output),
// - synthetic `install-vX.Y.Z` tags on slim payload commits, the shape the
// release workflow publishes (phase 5 builds the real publisher),
// - a `release` branch at the newest synthetic tip, or absent,
// - feature branches and a non-release tag the parsers must ignore,
// - older rollback versions, with and without a synthetic ref.
//
// Everything runs under the scrubbed git environment of
// scripts/skill-script-helpers.mjs (importing it here is what the failure log
// requires of fixture-building tests), and Node built-ins only.
//
// import { createInstallRefFixture } from "./install-ref-fixtures.mjs";
// const fx = createInstallRefFixture();
// fx.snapshotText(); // `git ls-remote --tags --heads`-style text
// fx.refs.tags["v3.1.2"]; // shas, per ref name
// fx.cleanup(); // idempotent
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { scrubbedEnv } from "./skill-script-helpers.mjs";
import { compareVersions } from "../src/web-console/update-check.mjs";
/**
* The default release ladder: a lightweight rollback with no synthetic ref, a
* rollback with one, and an annotated newest release with one. Exactly the
* matrix the rollback and fallback tests need; pass `releases` to vary it.
* Per release: `annotated` makes the v* tag annotated, `installTag` adds a
* synthetic `install-v*` ref, `files` replaces the full-source tree, and
* `installFiles` replaces the slim synthetic tree.
*/
export const DEFAULT_RELEASES = [
{ version: "1.0.0" },
{ version: "2.0.0", installTag: true },
{ version: "3.1.2", annotated: true, installTag: true },
];
/** The files of one full-source commit on main for `version` (docs/ included: the heavy tree). */
function fullTreeFiles(version) {
return {
"install.js": `// install.js for v${version}\n`,
"package.json": `${JSON.stringify({ name: "plan2code", version }, null, 2)}\n`,
"version.json": `${JSON.stringify({ version, releaseDate: "2026-01-01" }, null, 2)}\n`,
"src/web-console/update-check.mjs": `// update-check for v${version}\n`,
"docs/promo.md": `# heavy docs for v${version}\n`,
};
}
/** The slim runtime payload of a synthetic install commit: the full tree minus what the spec excludes. */
function slimTreeFiles(version, sourceCommitMark) {
const files = fullTreeFiles(version);
delete files["docs/promo.md"];
files[".plan2code-install-ref.json"] = `${JSON.stringify({ releaseRef: `v${version}`, sourceCommit: `mark-${sourceCommitMark}` }, null, 2)}\n`;
return files;
}
// fast-import streams are length-delimited: `data <n>` plus exactly n bytes.
// Strings are UTF-8; Buffers stay byte-exact, so a real binary runtime file can
// ride in a fixture without being corrupted.
function dataBlock(content) {
const body = Buffer.isBuffer(content) ? content : Buffer.from(String(content), "utf8");
return Buffer.concat([Buffer.from(`data ${body.length}\n`, "utf8"), body]);
}
const textBlock = (text) => Buffer.from(String(text), "utf8");
const person = (who, ts) => `${who} Fixture <fixture@example.com> ${ts} +0000`;
/** One commit command with its whole tree inline (`M ... inline` needs no blob commands or index), as byte parts. */
function commitCommand(ref, mark, message, files, ts, fromMark) {
const parts = [textBlock(`commit ${ref}\nmark :${mark}\n${person("author", ts)}\n${person("committer", ts)}\n`), dataBlock(message)];
if (fromMark) parts.push(textBlock(`from :${fromMark}\n`));
for (const [name, content] of Object.entries(files)) parts.push(textBlock(`M 100644 inline ${name}\n`), dataBlock(content));
return parts;
}
export function createInstallRefFixture({
releases = DEFAULT_RELEASES,
releaseBranch = true,
releaseVersion = null,
featureBranches = ["feature/demo"],
extraTags = ["nightly"],
mainBranch = "main",
} = {}) {
if (!Array.isArray(releases) || releases.length === 0) throw new Error("createInstallRefFixture: releases must be a non-empty array");
const root = fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), "p2c-install-refs-"));
const dir = path.join(root, "origin.git");
const env = scrubbedEnv();
const git = (args, options = {}) => execFileSync("git", ["--git-dir", dir, ...args], { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], env, ...options }).trim();
execFileSync("git", ["init", "-q", "--bare", "-b", mainBranch, dir], { env, stdio: "pipe" });
// Newest-first ordering is derived numerically, never lexically: 3.10.0
// must outrank 3.9.0 for the release branch and `newest` to be right.
const ordered = [...releases].sort((a, b) => compareVersions(a.version, b.version) ?? 0);
// The whole repository as one stream: main commits auto-parent per ref, the
// synthetic chain rides on refs/heads/release for the same reason, and
// resets pin the lightweight tags, feature branches and extra tags. Three
// git processes build a fixture (init, fast-import, for-each-ref) where the
// plumbing equivalent needs dozens — on Windows that is seconds each.
const stream = [];
const push = (text) => stream.push(textBlock(text));
const pushCommit = (...args) => stream.push(...commitCommand(...args));
let mark = 0;
let ts = 1700000000;
const versions = [];
let mainMark = null;
let syntheticMark = null;
for (const release of ordered) {
const { version, annotated = false, installTag = false } = release;
mainMark = ++mark;
ts += 60;
const fullFiles = release.files || fullTreeFiles(version);
pushCommit(`refs/heads/${mainBranch}`, mainMark, `release ${version}\n`, fullFiles, ts);
const entry = { version, annotated, install: null, mainMark };
if (annotated) {
push(`tag v${version}\nfrom :${mainMark}\n${person("tagger", ts)}\n`);
stream.push(dataBlock(`release ${version}\n`));
} else {
push(`reset refs/tags/v${version}\nfrom :${mainMark}\n`);
}
if (installTag) {
syntheticMark = ++mark;
entry.install = { mark: syntheticMark };
pushCommit("refs/heads/release", syntheticMark, `install payload ${version}\n`, release.installFiles || slimTreeFiles(version, mainMark), ts);
push(`reset refs/tags/install-v${version}\nfrom :${syntheticMark}\n`);
}
versions.push(entry);
}
const newest = ordered[ordered.length - 1].version;
for (const branch of featureBranches) push(`reset refs/heads/${branch}\nfrom :${mainMark}\n`);
for (const name of extraTags) push(`reset refs/tags/${name}\nfrom :${mainMark}\n`);
// The published shape: the release branch tip is a synthetic slim commit.
// It already is (the chain built it there) unless the fixture pins a stale
// tip or no synthetic ref exists at all, where it is a legacy full-source
// tip on main instead.
let releaseTipMark = null;
if (releaseBranch) {
const pinned = releaseVersion ? versions.find((v) => v.version === releaseVersion) : null;
if (releaseVersion && !pinned) throw new Error(`createInstallRefFixture: releaseVersion ${releaseVersion} is not one of the releases`);
if (pinned) releaseTipMark = pinned.install ? pinned.install.mark : pinned.mainMark;
else if (!syntheticMark) releaseTipMark = mainMark;
if (releaseTipMark) push(`reset refs/heads/release\nfrom :${releaseTipMark}\n`);
}
git(["fast-import", "--quiet"], { input: Buffer.concat(stream) });
if (!releaseBranch) git(["update-ref", "-d", "refs/heads/release"]);
// The shas fast-import wrote, in one process: objecttype names the annotated
// tag objects, and %(*objectname) peels them to their commits.
const listing = git(["for-each-ref", "--format", "%(refname) %(objectname) %(objecttype) %(*objectname)"]);
const refs = { heads: {}, tags: {}, peeled: {} };
for (const line of listing.split("\n")) {
if (!line) continue;
const [ref, sha, type, peeled] = line.split(" ");
if (ref.startsWith("refs/heads/")) refs.heads[ref.slice("refs/heads/".length)] = sha;
else if (ref.startsWith("refs/tags/")) {
refs.tags[ref.slice("refs/tags/".length)] = sha;
if (type === "tag" && peeled) refs.peeled[ref.slice("refs/tags/".length)] = peeled;
}
}
for (const entry of versions) {
// The commit a release tag names: its peeled target when annotated, the ref target otherwise.
entry.commit = refs.peeled[`v${entry.version}`] || refs.tags[`v${entry.version}`];
if (entry.install) entry.install.commit = refs.tags[`install-v${entry.version}`];
}
/**
* `git ls-remote`-style snapshot text, derived from the refs recorded at
* build time: one `<sha>\t<ref>` line per ref, sorted by ref name the way
* git sorts them, with a peeled `^{}` line immediately after each annotated
* tag. Matches real ls-remote output byte for byte for these fixtures (the
* test file asserts exactly that), so it can seed PLAN2CODE_LS_REMOTE_FILE
* without spawning anything.
*/
function snapshotText({ tags = true, heads = true } = {}) {
const entries = [];
if (heads) for (const [name, sha] of Object.entries(refs.heads)) entries.push([`refs/heads/${name}`, sha, null]);
if (tags) {
for (const [name, sha] of Object.entries(refs.tags)) entries.push([`refs/tags/${name}`, sha, refs.peeled[name] || null]);
}
entries.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
let out = "";
for (const [ref, sha, peel] of entries) {
out += `${sha}\t${ref}\n`;
if (peel) out += `${peel}\t${ref}^{}\n`;
}
return out;
}
/** The real thing: `git ls-remote` against the bare repo on disk. Local-path transport, so offline. */
function lsRemote({ tags = true, heads = true } = {}) {
const args = ["ls-remote"];
if (tags) args.push("--tags");
if (heads) args.push("--heads");
return execFileSync("git", [...args, dir], { encoding: "utf8", env });
}
/**
* A real local fetch of one ref into `dest`, laid out like an npx package
* rather than a working clone: the payload is complete, and `.git` is gone.
* The transport is the fixture's local path, so no network or credentials.
*/
function checkout(ref, dest) {
fs.rmSync(dest, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(path.dirname(dest), { recursive: true });
execFileSync("git", ["clone", "--quiet", "--depth", "1", "--branch", ref, dir, dest], { encoding: "utf8", env, stdio: ["ignore", "pipe", "pipe"] });
fs.rmSync(path.join(dest, ".git"), { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
return dest;
}
let cleaned = false;
function cleanup() {
if (cleaned) return;
cleaned = true;
// maxRetries for Windows, where a just-exited git can hold a pack file
// for a beat; read-only object files are chmodded away by rm itself.
fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
return { dir, root, refs, versions, newest, mainBranch, snapshotText, lsRemote, checkout, cleanup };
}
-70
View File
@@ -1,70 +0,0 @@
#!/usr/bin/env node
// Writes labeled placeholder pictures for the desktop app and the Implementation
// Loop (docs/screenshots/app-*.webp, loop-*.webp) so the docs and the landing page
// carry their final markup before the owner has captured the real window.
// Replace each file with the real capture (same name, same 2560x1600 size);
// nothing else needs editing. The shot list (state, window size, theme) is in
// specs/polish-3-2/phase-11.md's completion summary. Dev-only.
//
// node scripts/make-app-placeholders.mjs [--browser <path>] [--force]
//
// Never overwrites a file that exists unless --force: a real capture stays.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { launchBrowser } from "./browser.mjs";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const DIR = path.join(ROOT, "docs", "screenshots");
const SHOTS = [
["app-launch-dark", "The launch card", "Which agent, model and effort to start on"],
["app-terminal-dark", "The app with the terminal docked", "The dashboard beside the agent's terminal"],
["loop-setup-dark", "Implementation Loop setup", "The setup screen before a run"],
["loop-banner-dark", "The Loop mid-run", "The banner while a phase builds"],
["loop-stop-dark", "The Loop's stop screen", "Why it stopped, with the evidence"],
];
const force = process.argv.includes("--force");
const flag = process.argv.indexOf("--browser");
const browser = await launchBrowser(flag > 0 ? { executablePath: process.argv[flag + 1] } : {});
try {
const page = await browser.newPage();
for (const [name, title, line] of SHOTS) {
const out = path.join(DIR, `${name}.webp`);
if (fs.existsSync(out) && !force) {
console.log(`${name}.webp exists, kept`);
continue;
}
const data = await page.evaluate(
([t, l]) => {
const c = document.createElement("canvas");
c.width = 2560;
c.height = 1600;
const g = c.getContext("2d");
g.fillStyle = "#171513";
g.fillRect(0, 0, 2560, 1600);
g.strokeStyle = "#46403a";
g.setLineDash([24, 16]);
g.lineWidth = 4;
g.strokeRect(60, 60, 2440, 1480);
g.fillStyle = "#f0ece5";
g.textAlign = "center";
g.font = "700 96px sans-serif";
g.fillText(t, 1280, 740);
g.fillStyle = "#b6afa3";
g.font = "400 56px sans-serif";
g.fillText(l, 1280, 840);
g.fillStyle = "#e0a24a";
g.font = "600 44px sans-serif";
g.fillText("Placeholder: the real capture goes here", 1280, 960);
return c.toDataURL("image/webp", 0.85).split(",")[1];
},
[title, line],
);
fs.writeFileSync(out, Buffer.from(data, "base64"));
console.log(`${name}.webp ${Math.round(fs.statSync(out).size / 1024)} KB`);
}
} finally {
await browser.close();
}
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env node
// Renders the README banner, docs/banner.jpg (2048x600: 1024x300 at twice the
// pixel density). Dev-only.
//
// node scripts/make-banner.mjs [--browser <path>]
//
// The five Plannys are the console's own step poses (the <svg data-pose> in
// src/web-console/public/index.html), drawn with its tokens.css and poses.css
// in the dark theme, held still. Rerun it when the tagline, the license or a
// step pose changes. Needs playwright-core (a root devDependency) and a local
// Chrome or Edge.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { launchBrowser } from "./browser.mjs";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const PUBLIC = path.join(ROOT, "src", "web-console", "public");
const STEPS = [
["pathfinder", "Pathfinder"],
["plan", "Plan"],
["document", "Document"],
["implement", "Implement"],
["finalize", "Finalize"],
];
const TAGLINE = "Plan it. Approve it. Let it build.";
const FOOT = "plan2code.jparkerweb.com · Apache 2.0";
// One pose's <svg> from the console page, by its data-pose.
function pose(html, name) {
const m = new RegExp(`<svg class="pose[^"]*" data-pose="${name}"[\\s\\S]*?</svg>`).exec(html);
if (!m) throw new Error(`no data-pose="${name}" in index.html`);
return m[0];
}
// A fixed sky, so two runs draw the same picture.
function stars() {
let seed = 7;
const rand = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
const out = [];
// Kept off the words and the step labels, where a dot reads as punctuation.
const onText = (x, y) => (x < 40 && y > 15 && y < 82) || (x > 43 && y > 58 && y < 76);
while (out.length < 34) {
const blue = rand() < 0.35;
const x = rand() * 100;
const y = rand() * 100;
if (onText(x, y)) continue;
out.push(`<i style="left:${x.toFixed(2)}%;top:${y.toFixed(2)}%;width:${blue ? 3 : 2 + Math.round(rand())}px;height:${blue ? 3 : 2 + Math.round(rand())}px;background:${blue ? "var(--accent)" : "var(--ink-3)"};opacity:${(0.35 + rand() * 0.5).toFixed(2)}"></i>`);
}
return out.join("");
}
const index = fs.readFileSync(path.join(PUBLIC, "index.html"), "utf8");
const css = (f) => pathToFileURL(path.join(PUBLIC, "styles", f)).href;
const page = `<!doctype html>
<html data-theme="dark"><head><meta charset="utf-8">
<link rel="stylesheet" href="${css("tokens.css")}">
<link rel="stylesheet" href="${css("poses.css")}">
<style>
*, *::before, *::after { animation: none !important; transition: none !important; }
html, body { margin: 0; background: var(--bg); }
.banner { position: relative; width: 1024px; height: 300px; overflow: hidden; background: var(--bg); color: var(--ink); font-family: var(--sans); }
.sky i { position: absolute; border-radius: 50%; }
.words { position: absolute; left: 44px; top: 62px; }
h1 { margin: 0; font: 700 74px/1 var(--serif); letter-spacing: -1px; color: var(--ink); }
h1 b { color: var(--accent); font-weight: 700; }
.tag { margin: 22px 0 0; font-size: 23px; color: var(--ink-2); }
.tag em { font-style: normal; color: var(--accent); }
.foot { margin: 22px 0 0; font-size: 12px; font-weight: 600; letter-spacing: 2.4px; text-transform: uppercase; color: var(--ink-3); }
.steps { position: absolute; left: 462px; right: 40px; top: 86px; display: flex; justify-content: space-between; }
.path { position: absolute; left: 470px; right: 52px; top: 176px; border-top: 2px dashed var(--rule-2); }
.step { width: 104px; text-align: center; position: relative; }
.step .pose { height: 92px; width: auto; margin: 0 auto; display: block; }
.step span { display: block; margin-top: 14px; font-size: 12px; font-weight: 700; letter-spacing: 1.6px; text-transform: uppercase; color: var(--ink-2); }
</style></head><body>
<div class="banner">
<div class="sky">${stars()}</div>
<div class="words">
<h1>Plan<b>2</b>Code</h1>
<p class="tag">Plan it. Approve it. <em>Let it build.</em></p>
<p class="foot">${FOOT}</p>
</div>
<div class="path"></div>
<div class="steps">${STEPS.map(([id, label]) => `<div class="step">${pose(index, id)}<span>${label}</span></div>`).join("")}</div>
</div>
</body></html>`;
if (!page.includes(TAGLINE.split(" Let")[0])) throw new Error("tagline drifted");
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-banner-"));
const file = path.join(tmp, "banner.html");
fs.writeFileSync(file, page);
const flag = process.argv.indexOf("--browser");
const browser = await launchBrowser(flag > 0 ? { executablePath: process.argv[flag + 1] } : {});
try {
const tab = await browser.newPage({ viewport: { width: 1024, height: 300 }, deviceScaleFactor: 2, colorScheme: "dark" });
await tab.goto(pathToFileURL(file).href);
await tab.evaluate(() => document.fonts.ready);
const out = path.join(ROOT, "docs", "banner.jpg");
await tab.screenshot({ path: out, type: "jpeg", quality: 90, clip: { x: 0, y: 0, width: 1024, height: 300 } });
console.log(`wrote ${path.relative(ROOT, out)} (${Math.round(fs.statSync(out).size / 1024)} KB)`);
} finally {
await browser.close();
fs.rmSync(tmp, { recursive: true, force: true });
}
+19
View File
@@ -124,6 +124,25 @@ export async function openSession(browser, { t, workflow, payload: first, projec
return s;
}
// Stands a real window in for the desktop app that frames the page, listening
// to what the page tells it (kept in window.__told); the returned function
// replies the way the app's window does.
export 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);
}
// Waits until the document has not changed for `quietMs`, or `maxMs` at most (a page that never
// goes quiet must not block a test). Counts mutations in the page and polls the count from
// here, so it needs no timer in the page.
+640
View File
@@ -0,0 +1,640 @@
#!/usr/bin/env node
// Publishes the slim install refs of one release: a synthetic commit whose tree
// holds only the runtime payload (install.js, package.json, version.json, LICENSE,
// NOTICE and src/) plus a binding manifest, pushed once as the immutable
// `refs/tags/install-vX.Y.Z` and as the new fast-forward tip of
// `refs/heads/release`. Dev-only: lives in scripts/ so it never ships inside a
// skill or the runtime payload it assembles.
//
// node scripts/publish-install-refs.mjs --tag v3.2.3 --repo "$GITHUB_WORKSPACE"
//
// Runs in the full release checkout of .github/workflows/release-app.yml,
// after the GitHub release is public. The payload is read from the source
// tag's own git tree, never from the working tree, and the commit is built
// with a temporary index, so the checkout and its normal index are never
// touched. Zero dependencies: Node built-ins and the git on PATH.
//
// Exit codes: 0 published (or a dry run that would publish), 1 refused or
// failed (nothing pushed), 2 bad arguments.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import crypto from "node:crypto";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
export const INSTALL_REF_MANIFEST = ".plan2code-install-ref.json";
// The package scripts that make npm prepare a git dependency with a full dev install (pacote).
export const GIT_DEP_LIFECYCLE = new Set(["prepare", "build", "install", "preinstall", "postinstall", "prepack"]);
export const RELEASE_BRANCH_REF = "refs/heads/release";
export const REMOTE = "origin";
const TAG_SHAPE = /^v(\d+\.\d+\.\d+)$/;
/**
* The runtime payload, as data: exactly these top-level files plus the
* recursive trees under `prefixes`, minus any path with an `excludedSegments`
* folder in it. `forbiddenTopLevel` names what must never appear (reported on
* its own when it does), and `required` the files an install cannot run
* without; the workflow skill sources install.js's SOURCE_PROMPTS names are
* required on top of these (`workflowSkillSources()`).
*/
export const RUNTIME_PAYLOAD = Object.freeze({
files: Object.freeze(["install.js", "package.json", "version.json", "LICENSE", "NOTICE"]),
prefixes: Object.freeze(["src/"]),
excludedSegments: Object.freeze(["node_modules", ".git", "fixtures", "__fixtures__"]),
forbiddenTopLevel: Object.freeze([
".git",
".github",
"docs",
"scripts",
"specs",
"skills",
"plan2code-app",
"plan2code-metrics",
"plan2code-bot",
]),
required: Object.freeze([
"install.js",
"package.json",
"version.json",
"LICENSE",
"NOTICE",
"src/launcher/plan2code.js",
"src/web-console/update-check.mjs",
"src/web-console/console.mjs",
"src/installer/timing.js",
"src/installer/skills-cli.js",
"src/installer/canonical-skills.js",
"src/installer/console-stage.js",
// Read by install.js at runtime too: the skills' forwarding stub, the status line, the
// launcher's model menu, agent list and lookup, and the desktop shortcut's icons.
"src/web-console-stub/console.mjs",
"src/statusline-claude/statusline.js",
"src/launcher/models.json",
"src/launcher/agents.json",
"src/web-console/agent-lookup.mjs",
"src/launcher/plan2code.ico",
"src/web-console/public/favicon.png",
]),
});
/** The allowlist the payload is assembled and validated against. */
export function runtimePayloadAllowlist() {
return RUNTIME_PAYLOAD;
}
/** Whether a `/`-separated path relative to the payload root belongs in the payload. */
export function isAllowedPayloadPath(rel, allowlist = RUNTIME_PAYLOAD) {
if (typeof rel !== "string" || rel === "" || rel.startsWith("/") || rel.includes("\\")) return false;
const parts = rel.split("/");
if (parts.some((p) => p === "" || p === "." || p === "..")) return false;
if (allowlist.forbiddenTopLevel.includes(parts[0])) return false;
if (allowlist.files.includes(rel)) return true;
if (!allowlist.prefixes.some((prefix) => rel.startsWith(prefix) && rel.length > prefix.length)) return false;
return !parts.slice(0, -1).some((p) => allowlist.excludedSegments.includes(p));
}
/**
* What install.js builds the skills from, read from its SOURCE_PROMPTS array:
* each top-level `source: '<name>.md'` as `src/<name>.md`, each shared script
* a `scripts: [...]` list names (plus SHARED_SCRIPTS_ALWAYS) as
* `src/skill-scripts/<name>`, and each `additionalReferences` `{ source: ... }`
* as `src/<source>` (a file or a folder). An empty list means the array could
* not be read, which validation reports.
*/
export function workflowSkillSources(installJsText) {
const start = installJsText.indexOf("const SOURCE_PROMPTS = [");
if (start === -1) return [];
const end = installJsText.indexOf("\n];", start);
const block = installJsText.slice(start, end === -1 ? undefined : end);
const names = (list) => [...list.matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1]);
const sources = [...block.matchAll(/^ {4}source: ['"]([^'"]+\.md)['"]/gm)].map((m) => `src/${m[1]}`);
if (!sources.length) return [];
const shared = [...block.matchAll(/^ {4}scripts: \[([^\]]*)\]/gm)].flatMap((m) => names(m[1]));
const always = /^const SHARED_SCRIPTS_ALWAYS = \[([^\]]*)\]/m.exec(installJsText);
if (shared.length && always) shared.push(...names(always[1]));
const references = [...block.matchAll(/\{ source: ['"]([^'"]+)['"]/g)].map((m) => `src/${m[1]}`);
return [...new Set([...sources, ...shared.map((name) => `src/skill-scripts/${name}`), ...references])];
}
export class PublishError extends Error {
constructor(message, details = null) {
super(message);
this.name = "PublishError";
this.details = details;
}
}
// Credentials can ride in a remote URL (https://user:token@host); git echoes
// URLs in its errors, so every message that leaves this script goes through this.
const redact = (text) => String(text).replace(/(\/\/)[^/\s@]+@/g, "$1***@");
function git(repo, args, { input, env, allowFail = false, encoding = "utf8" } = {}) {
const r = spawnSync("git", ["-C", repo, ...args], {
input,
env: env || process.env,
encoding: encoding === "buffer" ? undefined : encoding,
maxBuffer: 1024 * 1024 * 1024,
windowsHide: true,
});
if (r.error) throw new PublishError(`git ${args[0]} could not run: ${redact(r.error.message)}`);
if (r.status !== 0 && !allowFail) {
const stderr = Buffer.isBuffer(r.stderr) ? r.stderr.toString("utf8") : r.stderr || "";
throw new PublishError(`git ${args[0]} failed: ${redact(stderr.trim() || `exit ${r.status}`)}`);
}
return r;
}
const gitText = (repo, args, options) => git(repo, args, options).stdout.trim();
/** The commit a ref names, or null when it does not exist (annotated tags peel to their commit). */
function commitOf(repo, ref) {
const r = git(repo, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { allowFail: true });
return r.status === 0 ? r.stdout.trim() : null;
}
function readJsonAt(repo, commit, file) {
const r = git(repo, ["show", `${commit}:${file}`], { allowFail: true });
if (r.status !== 0) throw new PublishError(`${file} is missing from the source commit ${commit}`);
try {
return JSON.parse(r.stdout);
} catch (err) {
throw new PublishError(`${file} in the source commit is not valid JSON: ${err.message}`);
}
}
/**
* Resolves the source tag and checks that the tag, its version.json, its root
* package.json and the checkout agree before anything is written. The tag may
* be annotated or lightweight. `sourceCommit`, when given, stands in for HEAD.
*/
export function verifySource({ repo, tag, sourceCommit = null }) {
const shape = TAG_SHAPE.exec(tag || "");
if (!shape) throw new PublishError(`the source tag must be an exact vX.Y.Z release tag, not "${tag}"`);
const version = shape[1];
const tagCommit = commitOf(repo, `refs/tags/${tag}`);
if (!tagCommit) throw new PublishError(`the tag ${tag} does not exist in ${repo}; fetch it first`);
const checkout = sourceCommit ? commitOf(repo, sourceCommit) : commitOf(repo, "HEAD");
if (!checkout) throw new PublishError(`the source commit ${sourceCommit || "HEAD"} cannot be resolved`);
if (checkout !== tagCommit) {
throw new PublishError(`${sourceCommit ? "the supplied source commit" : "the checkout's HEAD"} ${checkout} is not the commit ${tag} names (${tagCommit})`);
}
const versionJson = readJsonAt(repo, tagCommit, "version.json");
const packageJson = readJsonAt(repo, tagCommit, "package.json");
const mismatches = [];
if (versionJson.version !== version) mismatches.push(`version.json says ${versionJson.version}`);
if (packageJson.version !== version) mismatches.push(`package.json says ${packageJson.version}`);
if (mismatches.length) throw new PublishError(`the versions do not match the tag ${tag}: ${mismatches.join(", ")}`);
// npm runs a full dev-dependency install for a git package that has one of these scripts, so
// every user's npx would download the dev tools (Playwright and the rest) before installing.
const lifecycle = Object.keys(packageJson.scripts || {}).filter((name) => GIT_DEP_LIFECYCLE.has(name));
if (lifecycle.length) {
throw new PublishError(`package.json has ${lifecycle.join(", ")}: npm would install every dev dependency on each user's machine before the installer runs; remove the script or rename it`);
}
return { version, sourceTag: tag, sourceCommit: tagCommit };
}
/** Every `{ mode, type, sha, path }` in a commit's tree, recursively. */
function treeEntries(repo, commit) {
const out = gitText(repo, ["ls-tree", "-r", "-z", "--full-tree", commit]).split("\0");
const entries = [];
for (const line of out) {
if (!line) continue;
const tab = line.indexOf("\t");
const [mode, type, sha] = line.slice(0, tab).split(" ");
entries.push({ mode, type, sha, path: line.slice(tab + 1) });
}
return entries;
}
/** The contents of many blobs from one `git cat-file --batch`, in order. */
function readBlobs(repo, shas) {
if (!shas.length) return [];
const out = git(repo, ["cat-file", "--batch"], { input: `${shas.join("\n")}\n`, encoding: "buffer" }).stdout;
const blobs = [];
let at = 0;
for (const sha of shas) {
const nl = out.indexOf(0x0a, at);
const header = out.subarray(at, nl).toString("utf8").split(" ");
if (header[0] !== sha || header[1] !== "blob") throw new PublishError(`git cat-file could not read blob ${sha}`);
const size = Number(header[2]);
blobs.push(out.subarray(nl + 1, nl + 1 + size));
at = nl + 1 + size + 1;
}
return blobs;
}
function ensureEmptyDir(dir) {
if (fs.existsSync(dir)) {
if (!fs.statSync(dir).isDirectory()) throw new PublishError(`the output ${dir} is not a folder`);
if (fs.readdirSync(dir).length) throw new PublishError(`the output folder ${dir} is not empty`);
} else {
fs.mkdirSync(dir, { recursive: true });
}
}
/**
* Copies the allowlisted files of `commit`'s tree into the clean folder
* `output`, keeping each file's git mode (an executable 100755 stays one).
* Returns `{ output, modes, excluded }`: `modes` maps each payload path to its
* mode, `excluded` counts the tree's files left out.
*/
export function assemblePayload({ repo, commit, output, allowlist = RUNTIME_PAYLOAD }) {
ensureEmptyDir(output);
const picked = [];
let excluded = 0;
for (const entry of treeEntries(repo, commit)) {
if (!isAllowedPayloadPath(entry.path, allowlist)) {
excluded++;
continue;
}
if (entry.type !== "blob" || (entry.mode !== "100644" && entry.mode !== "100755")) {
throw new PublishError(`${entry.path} is a ${entry.mode === "120000" ? "symlink" : entry.type} (mode ${entry.mode}); the payload holds regular files only`);
}
picked.push(entry);
}
const blobs = readBlobs(
repo,
picked.map((e) => e.sha),
);
const modes = {};
picked.forEach((entry, i) => {
const dest = path.join(output, ...entry.path.split("/"));
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.writeFileSync(dest, blobs[i]);
if (entry.mode === "100755") fs.chmodSync(dest, 0o755);
modes[entry.path] = entry.mode;
});
return { output, modes, excluded };
}
/** Every file under `dir`, as sorted `/`-separated relative paths; symlinks are listed in `links`. */
function walk(dir) {
const files = [];
const links = [];
const visit = (abs, rel) => {
for (const name of fs.readdirSync(abs)) {
const childAbs = path.join(abs, name);
const childRel = rel ? `${rel}/${name}` : name;
const st = fs.lstatSync(childAbs);
if (st.isSymbolicLink()) links.push(childRel);
else if (st.isDirectory()) visit(childAbs, childRel);
else files.push(childRel);
}
};
visit(dir, "");
return { files: files.sort(), links: links.sort() };
}
/**
* Checks an assembled payload folder: every required file present (including
* every skill build input its install.js names), nothing outside the
* allowlist and no forbidden top-level entry. `report` is a diff-like list:
* `- path` missing, `+ path` unexpected.
*/
export function validatePayload(dir, { allowlist = RUNTIME_PAYLOAD } = {}) {
const { files, links } = walk(dir);
const present = new Set(files);
const required = [...allowlist.required];
if (present.has("install.js")) {
const sources = workflowSkillSources(fs.readFileSync(path.join(dir, "install.js"), "utf8"));
if (!sources.length) required.push("install.js SOURCE_PROMPTS (no workflow skill sources found)");
required.push(...sources);
}
// A required folder (a reference such as src/web-console) is present when it holds a file.
const has = (rel) => present.has(rel) || files.some((f) => f.startsWith(`${rel}/`));
const missing = [...new Set(required)].filter((rel) => !has(rel)).sort();
const unexpected = [...files.filter((rel) => rel !== INSTALL_REF_MANIFEST && !isAllowedPayloadPath(rel, allowlist)), ...links.map((rel) => `${rel} (symlink)`)].sort();
const topLevel = new Set([...files, ...links].map((rel) => rel.split("/")[0]));
const forbidden = allowlist.forbiddenTopLevel.filter((name) => topLevel.has(name));
const bytes = files.reduce((sum, rel) => sum + fs.statSync(path.join(dir, ...rel.split("/"))).size, 0);
const report = [...missing.map((rel) => `- ${rel}`), ...unexpected.map((rel) => `+ ${rel}`), ...forbidden.map((name) => `+ ${name}/ (forbidden top-level entry)`)];
return {
ok: !missing.length && !unexpected.length && !forbidden.length,
files: files.length,
bytes,
manifest: present.has(INSTALL_REF_MANIFEST),
missing,
unexpected,
forbidden,
report,
};
}
const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("hex");
/**
* Writes `.plan2code-install-ref.json` at the payload root, binding it to
* its release: `{ kind, version, sourceTag, sourceCommit, files }`, `files`
* mapping every other payload path to its sha256. Hashed first, written last.
*/
export function writeInstallRefManifest(dir, { version, sourceTag, sourceCommit }) {
const files = {};
for (const rel of walk(dir).files) {
if (rel === INSTALL_REF_MANIFEST) continue;
files[rel] = sha256(fs.readFileSync(path.join(dir, ...rel.split("/"))));
}
const manifest = { kind: "install-ref", version, sourceTag, sourceCommit, files };
fs.writeFileSync(path.join(dir, INSTALL_REF_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
return manifest;
}
// commit-tree needs an author and committer. A release runner has none
// configured, so the GitHub Actions bot stands in unless git or the
// environment already names one.
const BOT = { name: "github-actions[bot]", email: "41898099+github-actions[bot]@users.noreply.github.com" };
function identityEnv(repo, base) {
const env = { ...base };
const configured = (key) => git(repo, ["config", "--get", key], { allowFail: true }).stdout.trim();
const name = configured("user.name");
const email = configured("user.email");
for (const role of ["AUTHOR", "COMMITTER"]) {
if (!env[`GIT_${role}_NAME`] && !name) env[`GIT_${role}_NAME`] = BOT.name;
if (!env[`GIT_${role}_EMAIL`] && !email) env[`GIT_${role}_EMAIL`] = BOT.email;
}
return env;
}
// Windows caps a command line near 32K characters; stay far below it.
const MAX_ARGS_CHARS = 8000;
/**
* Builds the synthetic commit from the payload folder with a temporary
* GIT_INDEX_FILE inside the repository's git dir: an empty index, blobs
* written with `hash-object -w`, entries added with `update-index --cacheinfo`,
* `write-tree`, then `commit-tree` on `parent`. The checkout's working tree
* and normal index are never touched. Returns `{ tree, commit }`.
*/
export function createSyntheticCommit({ repo, dir, modes, parent, message }) {
const gitDir = gitText(repo, ["rev-parse", "--absolute-git-dir"]);
const indexFile = path.join(gitDir, `p2c-install-index-${process.pid}-${crypto.randomBytes(4).toString("hex")}`);
const env = { ...process.env, GIT_INDEX_FILE: indexFile };
const removeIndex = () => {
fs.rmSync(indexFile, { force: true });
fs.rmSync(`${indexFile}.lock`, { force: true });
};
removeIndex();
try {
const files = walk(dir).files;
const abs = files.map((rel) => path.join(dir, ...rel.split("/")));
const shas = gitText(repo, ["hash-object", "-w", "--no-filters", "--stdin-paths"], { input: `${abs.join("\n")}\n`, env }).split(/\r?\n/);
if (shas.length !== files.length) throw new PublishError(`git hash-object returned ${shas.length} ids for ${files.length} files`);
let batch = [];
let chars = 0;
const flush = () => {
if (!batch.length) return;
git(repo, ["update-index", "--add", ...batch], { env });
batch = [];
chars = 0;
};
files.forEach((rel, i) => {
const info = `${modes[rel] || "100644"},${shas[i]},${rel}`;
if (chars + info.length > MAX_ARGS_CHARS) flush();
batch.push("--cacheinfo", info);
chars += info.length + 13;
});
flush();
const tree = gitText(repo, ["write-tree"], { env });
const commit = gitText(repo, ["commit-tree", tree, "-p", parent, "-F", "-"], { input: message, env: identityEnv(repo, env) });
return { tree, commit };
} finally {
removeIndex();
}
}
/** The remote's sha for each ref asked about, from one `git ls-remote`; absent refs are left out. */
function remoteRefs(repo, remote, refs) {
const r = git(repo, ["ls-remote", remote, ...refs], { allowFail: true });
if (r.status !== 0) throw new PublishError(`git ls-remote ${remote} failed: ${redact(r.stderr.trim() || `exit ${r.status}`)}`);
const found = {};
for (const line of r.stdout.split(/\r?\n/)) {
const [sha, ref] = line.split("\t");
if (sha && ref && refs.includes(ref)) found[ref] = sha;
}
return found;
}
/**
* The parent of the new synthetic commit: the remote release branch's tip when
* it exists (the first migration parents the legacy full-source tip only so
* the push stays a fast-forward); with no release branch, the source tag's
* commit, but only when `allowMissingReleaseBranch` says so.
*/
export function selectParent({ repo, releaseTip, sourceCommit, allowMissingReleaseBranch }) {
if (releaseTip) {
if (!commitOf(repo, releaseTip)) {
throw new PublishError(`the release branch tip ${releaseTip} is not in this checkout; fetch ${RELEASE_BRANCH_REF} first`);
}
return { parent: releaseTip, parentKind: "release" };
}
if (allowMissingReleaseBranch) return { parent: sourceCommit, parentKind: "source-tag" };
throw new PublishError(`${RELEASE_BRANCH_REF} does not exist on ${REMOTE}; pass --allow-missing-release-branch for a first publication`);
}
/** Refuses an install tag that already exists here or on the remote: install tags are never overwritten. */
export function checkInstallTagFree({ repo, installTagRef, remoteHas }) {
const local = git(repo, ["rev-parse", "--verify", "--quiet", installTagRef], { allowFail: true }).status === 0;
if (local || remoteHas) {
throw new PublishError(`${installTagRef} already exists ${local && remoteHas ? "here and on the remote" : local ? "in this checkout" : "on the remote"}; install tags are immutable and are never overwritten`);
}
}
/** Negative, zero or positive as `a` (X.Y.Z) is below, equal to or above `b`. */
function compareReleaseVersions(a, b) {
const pa = a.split(".").map(Number);
const pb = b.split(".").map(Number);
for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] - pb[i];
return 0;
}
/** readJsonAt, or null when the file is not in that commit or does not parse. */
function readJsonAtOrNull(repo, commit, file) {
try {
return readJsonAt(repo, commit, file);
} catch {
return null;
}
}
/**
* The version the release branch tip installs: its install-ref manifest's, else its version.json
* (a legacy full-source tip), else null when neither can be read.
*/
export function releaseTipVersion(repo, releaseTip) {
if (!releaseTip) return null;
const manifest = readJsonAtOrNull(repo, releaseTip, INSTALL_REF_MANIFEST);
if (manifest && typeof manifest.version === "string") return manifest.version;
const versionJson = readJsonAtOrNull(repo, releaseTip, "version.json");
return versionJson && typeof versionJson.version === "string" ? versionJson.version : null;
}
/**
* Refuses to point the release branch at a version that is not newer than the one it installs
* now: a hotfix tagged from a maintenance branch, or two publications finishing out of order,
* would otherwise send every README install back to an older release. `allowOlder` is the
* explicit override for a deliberate rollback.
*/
export function checkNewerThanRelease({ repo, releaseTip, version, allowOlder = false }) {
if (allowOlder || !releaseTip) return;
const current = releaseTipVersion(repo, releaseTip);
if (current && compareReleaseVersions(version, current) <= 0) {
throw new PublishError(`the release branch already installs ${current}; refusing to move it to ${version}, which is not newer (pass --allow-older for a deliberate rollback)`);
}
}
/**
* True when this release is already fully published: the install tag exists on the remote, the
* release branch points at it, and its manifest names this release's source commit. A second run
* for the same tag (the workflow has more than one trigger) then has nothing to do.
*/
export function alreadyPublished({ repo, remoteTag, releaseTip, sourceCommit }) {
if (!remoteTag || remoteTag !== releaseTip) return false;
const manifest = readJsonAtOrNull(repo, remoteTag, INSTALL_REF_MANIFEST);
return Boolean(manifest && manifest.sourceCommit === sourceCommit);
}
/** Refuses a release branch move that would not be a fast-forward. */
export function checkFastForward({ repo, priorTip, commit }) {
if (!priorTip) return;
const r = git(repo, ["merge-base", "--is-ancestor", priorTip, commit], { allowFail: true });
if (r.status !== 0) throw new PublishError(`the release branch tip ${priorTip} is not an ancestor of ${commit}; refusing a non-fast-forward move`);
}
/**
* Publishes one release's slim install refs: verify the source, assemble and
* validate the payload, write the manifest, build one synthetic commit, check
* collision and fast-forward, then push that commit to both refs in one
* command (unless `dryRun`). Returns the summary the CLI prints as JSON.
*/
export function publishInstallRefs({ tag, version = null, repo, dryRun = false, output = null, allowMissingReleaseBranch = false, sourceCommit = null, allowOlder = false }) {
repo = path.resolve(repo || process.cwd());
const source = verifySource({ repo, tag, sourceCommit });
if (version && version !== source.version) throw new PublishError(`the version ${version} does not match the tag ${tag}`);
const installTagRef = `refs/tags/install-${tag}`;
const remote = remoteRefs(repo, REMOTE, [installTagRef, RELEASE_BRANCH_REF]);
const releaseTip = remote[RELEASE_BRANCH_REF] || null;
if (alreadyPublished({ repo, remoteTag: remote[installTagRef] || null, releaseTip, sourceCommit: source.sourceCommit })) {
return { ok: true, dryRun, pushed: false, alreadyPublished: true, tag, version: source.version, sourceCommit: source.sourceCommit, commit: releaseTip, refs: { tag: installTagRef, branch: RELEASE_BRANCH_REF } };
}
checkInstallTagFree({ repo, installTagRef, remoteHas: Boolean(remote[installTagRef]) });
checkNewerThanRelease({ repo, releaseTip, version: source.version, allowOlder });
const { parent, parentKind } = selectParent({ repo, releaseTip, sourceCommit: source.sourceCommit, allowMissingReleaseBranch });
const keep = Boolean(output);
const dir = keep ? path.resolve(output) : fs.mkdtempSync(path.join(os.tmpdir(), "p2c-install-payload-"));
try {
const { modes, excluded } = assemblePayload({ repo, commit: source.sourceCommit, output: dir });
const before = validatePayload(dir);
if (!before.ok) throw new PublishError(`the runtime payload of ${tag} is not valid`, before.report);
writeInstallRefManifest(dir, source);
const validation = validatePayload(dir);
if (!validation.ok || !validation.manifest) throw new PublishError(`the runtime payload of ${tag} is not valid after the manifest was written`, validation.report);
const message = `Install payload for ${tag}\n\nSource commit: ${source.sourceCommit}\n`;
const { tree, commit } = createSyntheticCommit({ repo, dir, modes, parent, message });
checkFastForward({ repo, priorTip: releaseTip, commit });
if (!dryRun) git(repo, ["push", "--atomic", REMOTE, `${commit}:${installTagRef}`, `${commit}:${RELEASE_BRANCH_REF}`]);
return {
ok: true,
dryRun,
pushed: !dryRun,
tag,
version: source.version,
sourceCommit: source.sourceCommit,
commit,
tree,
parent,
parentKind,
files: validation.files,
bytes: validation.bytes,
excluded,
manifest: INSTALL_REF_MANIFEST,
refs: { tag: installTagRef, branch: RELEASE_BRANCH_REF },
payload: keep ? dir : null,
validation: { missing: validation.missing, unexpected: validation.unexpected, forbidden: validation.forbidden },
};
} finally {
if (!keep) fs.rmSync(dir, { recursive: true, force: true });
}
}
export const USAGE = `Usage: node scripts/publish-install-refs.mjs --tag vX.Y.Z [options]
Publishes the slim runtime payload of a release as refs/tags/install-vX.Y.Z and
the new fast-forward tip of refs/heads/release, in one push to origin.
--tag <vX.Y.Z> the release tag (required, exact vX.Y.Z)
--repo <checkout> the full release checkout (default: the current folder)
--output <dir> assemble the payload into this empty folder and keep it
--dry-run build and check everything, push nothing
--json <path> also write the result as JSON to this file
--allow-missing-release-branch first publication: parent the source tag's commit
when refs/heads/release does not exist yet
--allow-older move refs/heads/release even when it already installs
this version or a newer one (a deliberate rollback)
`;
/** `{ options }` from argv, or `{ error }` for anything unknown, missing or malformed. */
export function parseArgs(argv) {
const options = { tag: null, repo: null, output: null, dryRun: false, json: null, allowMissingReleaseBranch: false, allowOlder: false };
const valued = { "--tag": "tag", "--repo": "repo", "--output": "output", "--json": "json" };
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg in valued) {
const value = argv[++i];
if (value === undefined || value.startsWith("--")) return { error: `${arg} needs a value` };
options[valued[arg]] = value;
} else if (arg === "--dry-run") options.dryRun = true;
else if (arg === "--allow-missing-release-branch") options.allowMissingReleaseBranch = true;
else if (arg === "--allow-older") options.allowOlder = true;
else return { error: `unknown argument: ${arg}` };
}
if (!options.tag) return { error: "--tag is required" };
if (!TAG_SHAPE.test(options.tag)) return { error: `--tag must be an exact vX.Y.Z release tag, not "${options.tag}"` };
return { options };
}
function main(argv) {
const parsed = parseArgs(argv);
if (parsed.error) {
process.stderr.write(`${parsed.error}\n\n${USAGE}`);
return 2;
}
const { options } = parsed;
const writeJson = (value) => {
if (options.json) fs.writeFileSync(options.json, `${JSON.stringify(value, null, 2)}\n`);
};
try {
const result = publishInstallRefs({
tag: options.tag,
repo: options.repo || process.cwd(),
dryRun: options.dryRun,
output: options.output,
allowMissingReleaseBranch: options.allowMissingReleaseBranch,
allowOlder: options.allowOlder,
});
writeJson(result);
if (result.alreadyPublished) {
process.stdout.write(`${result.tag} is already published: ${result.refs.tag} and ${result.refs.branch} point at ${result.commit}\n`);
return 0;
}
const verb = result.dryRun ? "Would publish" : "Published";
process.stdout.write(
`${verb} ${result.commit} (tree ${result.tree}) to ${result.refs.tag} and ${result.refs.branch}\n` +
` parent ${result.parent} (${result.parentKind}), ${result.files} files, ${result.bytes} bytes, ${result.excluded} source files left out\n`,
);
return 0;
} catch (err) {
if (!(err instanceof PublishError)) throw err;
writeJson({ ok: false, error: err.message, details: err.details });
process.stderr.write(`publish-install-refs: ${err.message}\n${err.details ? `${err.details.join("\n")}\n` : ""}Nothing was pushed.\n`);
return 1;
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
process.exitCode = main(process.argv.slice(2));
}
+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 }));
+156 -3
View File
@@ -119,6 +119,16 @@ test("each version state reads and acts as the old version bar did", () => {
const [ahead] = barNextSteps({ version: { kind: "ahead", skills: "3.2.0", app: "3.1.0" } });
assert.equal(ahead.action, null, "another Update skills run cannot help when the skills are ahead");
assert.match(ahead.title, /newer than this app \(v3\.1\.0\)\. Get the new app\./);
assert.equal(ahead.text, "App v3.1.0 is older than the skills (v3.2.0)", "no release known: the plain facts, never 'Skills ... are newer'");
// A release is out: the same step offers Update and restart, and the release step is not shown twice.
const leadSteps = barNextSteps({ version: { kind: "ahead", skills: "3.2.5", app: "3.2.4" }, newRelease: { latest: "3.2.5" } });
assert.deepEqual(leadSteps.map((step) => [step.id, step.text, step.action]), [["ahead", "Update to latest: v3.2.5", "update-restart"]]);
assert.match(leadSteps[0].title, /Update and restart installs v3\.2\.5/);
assert.equal(leadSteps[0].link.label, "What's new");
// While it runs, fails or waits for the restart, the release's own step says so, with no second button.
for (const newRelease of [{ latest: "3.2.5", updating: "Downloading" }, { latest: "3.2.5", failed: "No." }, { latest: "3.2.5", restartNeeded: true }]) {
assert.deepEqual(barNextSteps({ version: { kind: "ahead", skills: "3.2.5", app: "3.2.4" }, newRelease }).map((step) => step.id), ["new-release"]);
}
const [updating] = barNextSteps({ version: { kind: "updating", line: "Installing skills (4 of 9)" } });
assert.deepEqual([updating.text, updating.busy, updating.action], ["Installing skills (4 of 9)", true, null], "no button while it runs");
const [remains] = barNextSteps({ version: { kind: "remains", skills: "3.0.0", app: "3.1.0" } });
@@ -471,8 +481,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/);
@@ -529,6 +540,31 @@ test("app.js refills the reconnect budget on a new page and brings the page back
assert.match(app.slice(app.indexOf("async function showLoopEnd"), app.indexOf("function applyLoopState")), /reconnectConsole\(\)/);
});
test("app.js forgets the old project's console on a project switch, so no check of it covers the new agent's start or the launch card", () => {
const app = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "app.js"), "utf8");
const at = app.indexOf("function forgetConsole");
assert.ok(at > 0, "left known, the old console's poll put \"The console stopped\" over the new agent's start, or the launch card, five seconds after a switch");
const forget = app.slice(at, app.indexOf("\n}\n", at));
assert.match(forget, /consoleKnown = false/, "nothing is known again until the new agent opens a page");
assert.match(forget, /clearInterval\(pollTimer\);\s*pollTimer = null/, "the poll stops, and showAnnounced can start it again");
assert.match(forget, /clearTimeout\(helloTimer\)/, "a hello still awaited from the old page is not waited for");
assert.match(forget, /markConsoleAlive\(\)/, "the bar drops a Console stopped it was showing");
assert.match(forget, /frame\.src = 'about:blank'/, "the stopped console's page leaves the frame, or its Lost contact shows around the launch card");
assert.match(forget, /clearAttention\(\);\s*setGameFull\(false\)/, "and takes its taskbar dot and its full-screen game with it, as loadFrame does");
assert.match(forget, /consoleEpoch \+= 1/, "a check already under way can tell the project moved on");
const change = app.slice(app.indexOf("async function doChangeProject"), app.indexOf("function changeProject"));
assert.match(change, /forgetConsole\(\);[^}]*if \(prior\) await startPriorAgent\(prior\);\s*else afterProjectKnown\(\)/s, "forgotten before the new agent starts or the launch card shows");
// Each check that waits on the app answers for the console it asked about.
for (const name of ["onNoHello", "reconnectConsole", "pollConsole"]) {
const from = app.indexOf(`async function ${name}`);
const body = app.slice(from, app.indexOf("\n}\n", from));
assert.match(body, /const epoch = consoleEpoch;/, `${name} notes which console it asks about`);
const awaits = body.split("await invoke(").length - 1;
const guards = body.split("if (epoch !== consoleEpoch) return;").length - 1;
assert.ok(guards >= awaits, `${name} drops an answer that comes back after a switch (${guards} checks for ${awaits} waits)`);
}
});
test("the window title says a loop is running, and when it needs the person", () => {
assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Build" }), "Loop: Phase 2 of 7 - lunch");
assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Waiting on you" }), "Loop needs you: Phase 2 - lunch");
@@ -570,6 +606,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");
@@ -1051,7 +1174,7 @@ test("the top bar collapses instead of scrolling, and +N more is a button that l
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>/);
@@ -1285,6 +1408,36 @@ test("clipboardAction: Ctrl+C copies only with a selection (else it is the inter
assert.equal(clipboardAction(null, true), null);
});
test("clipboardAction on a Mac: Ctrl+V goes to the agent, Cmd+V is left to the webview's own paste", () => {
const ev = (key, mods = {}) => ({ key, ctrlKey: false, metaKey: false, shiftKey: false, altKey: false, ...mods });
assert.equal(clipboardAction(ev("v", { ctrlKey: true }), false, { mac: true }), null, "xterm sends \\x16 to the agent (Claude Code's image paste)");
assert.equal(clipboardAction(ev("V", { ctrlKey: true, shiftKey: true }), false, { mac: true }), null);
assert.equal(clipboardAction(ev("v", { metaKey: true }), false, { mac: true }), null, "a script clipboard read makes WebKit ask with a Paste menu first");
});
test("clipboardAction off a Mac: every key decides exactly as before the Mac rule", () => {
// The rule as it was before Ctrl+V was left to the agent on a Mac.
const before = (event, hasSelection) => {
if (event.altKey) return null;
const key = event.key.toLowerCase();
if (key === "c") {
if (event.metaKey && !event.ctrlKey) return "copy";
if (event.ctrlKey && !event.metaKey) return event.shiftKey || hasSelection ? "copy" : null;
return null;
}
if (key === "v" && (event.ctrlKey || event.metaKey)) return "paste";
return null;
};
for (const key of ["c", "C", "v", "V", "x"]) {
for (let bits = 0; bits < 16; bits++) {
const event = { key, ctrlKey: Boolean(bits & 1), metaKey: Boolean(bits & 2), shiftKey: Boolean(bits & 4), altKey: Boolean(bits & 8) };
for (const sel of [true, false]) {
assert.equal(clipboardAction(event, sel), before(event, sel), `${key} ${JSON.stringify(event)} selection ${sel}`);
}
}
}
});
test("the terminal pastes once and in brackets, copies on select only by preference, and has a Copy / Paste / Clear menu", () => {
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
assert.match(term, /term\.paste\(text\)/, "bracketed paste, not onInput(text)");
+109
View File
@@ -0,0 +1,109 @@
// Tests for plan2code-app/scripts/smoke-agent.mjs, the stand-in agent CI's
// macOS smoke run starts in place of a real agent CLI. Run with:
// node --test scripts/test-app-smoke-agent.mjs
//
// The stand-in has one job: open a real web console the way an agent would,
// so the app's dashboard frame has something to connect to. This runs it
// outside the app, under a throwaway console home, and checks a live session
// appears and the stand-in ends when its input closes.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const AGENT = path.join(HERE, "../plan2code-app/scripts/smoke-agent.mjs");
const CONSOLE_DIR = path.join(HERE, "../src/web-console");
// The desktop app's own variables would have the console announce itself to
// a live window. Deleted from the spawned environment, never inherited.
const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_APP_VERSION", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_CONSOLE_SID"];
function outsideAppEnv(extra) {
const env = { ...process.env, ...extra };
for (const name of APP_VARS) delete env[name];
return env;
}
// Every session handle under a console home: runtime/<project hash>/<sid>.json.
function handles(consoleHome) {
const runtime = path.join(consoleHome, "runtime");
if (!fs.existsSync(runtime)) return [];
return fs.readdirSync(runtime).flatMap((hash) =>
fs
.readdirSync(path.join(runtime, hash))
.filter((name) => name.endsWith(".json"))
.map((name) => JSON.parse(fs.readFileSync(path.join(runtime, hash, name), "utf8")))
);
}
async function waitFor(check, ms) {
const end = Date.now() + ms;
while (Date.now() < end) {
const value = check();
if (value) return value;
await new Promise((resolve) => setTimeout(resolve, 100));
}
return check();
}
function pidAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (err) {
return err.code === "EPERM";
}
}
test("smoke agent: is an executable Node script with no dependencies", { skip: process.platform === "win32" }, () => {
const source = fs.readFileSync(AGENT, "utf8");
assert.ok(source.startsWith("#!/usr/bin/env node\n"), "starts with a node shebang");
assert.ok((fs.statSync(AGENT).mode & 0o111) !== 0, "has its executable bits set");
for (const [, name] of source.matchAll(/from\s+["']([^"']+)["']/g)) {
assert.ok(name.startsWith("node:"), `imports only Node built-ins, not ${name}`);
}
});
test("smoke agent: opens a live dashboard session, then ends when its input closes", async (t) => {
const consoleHome = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-agent-home-"));
const project = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-agent-project-"));
const env = outsideAppEnv({ PLAN2CODE_CONSOLE_HOME: consoleHome, PLAN2CODE_NO_BROWSER: "1", PLAN2CODE_CONSOLE_DIR: CONSOLE_DIR });
let agent;
t.after(() => {
if (agent && agent.exitCode === null) agent.kill("SIGKILL");
// --all stops this folder's sessions, so it runs from the project, under the same home.
spawnSync(process.execPath, [path.join(CONSOLE_DIR, "console.mjs"), "stop", "--all"], { cwd: project, env, timeout: 15000 });
fs.rmSync(consoleHome, { recursive: true, force: true });
fs.rmSync(project, { recursive: true, force: true });
});
agent = spawn(process.execPath, [AGENT, "--some-agent-flag"], { cwd: project, env, stdio: ["pipe", "pipe", "pipe"] });
let output = "";
agent.stdout.on("data", (chunk) => (output += chunk));
agent.stderr.on("data", (chunk) => (output += chunk));
const exited = new Promise((resolve) => agent.on("exit", (code) => resolve(code)));
const handle = await waitFor(() => handles(consoleHome)[0], 20000);
assert.ok(handle, `a session appeared under the console home; agent said: ${output}`);
const health = await (await fetch(`http://127.0.0.1:${handle.port}/health`)).json();
assert.equal(health.ok, true);
assert.equal(health.sid, handle.sid, "the port answers for this session");
const state = JSON.parse(fs.readFileSync(path.join(consoleHome, "sessions", handle.sid, "state.json"), "utf8"));
assert.equal(state.workflow, "dashboard");
// Still running until its input closes, like an agent waiting for the person.
assert.equal(agent.exitCode, null, "the stand-in waits on its input");
agent.stdin.end();
const code = await Promise.race([exited, new Promise((resolve) => setTimeout(() => resolve("timeout"), 10000))]);
assert.equal(code, 0, `the stand-in exits cleanly once its input closes; agent said: ${output}`);
// The console outlives the agent (it is detached), so the stop below is what ends it.
const stop = spawnSync(process.execPath, [path.join(CONSOLE_DIR, "console.mjs"), "stop", "--all"], { cwd: project, env, encoding: "utf8", timeout: 15000 });
assert.equal(stop.status, 0, stop.stderr);
assert.equal(await waitFor(() => !pidAlive(handle.pid), 10000), true, "the console server is gone after stop --all");
});
+113
View File
@@ -0,0 +1,113 @@
// Tests for plan2code-app/scripts/smoke-frame.mjs, the check CI's macOS smoke
// run uses to prove the app's dashboard frame connected to the console. Run with:
// node --test scripts/test-app-smoke-frame.mjs
//
// No app and no real console: a session handle under a throwaway console home
// points at a tiny local server whose /health answers with a browser count the
// test controls.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const SCRIPT = path.join(HERE, "../plan2code-app/scripts/smoke-frame.mjs");
const SID = "20261108-000000-abcdef";
// A /health server answering with `browsers()` for this session.
async function healthServer(browsers) {
const server = http.createServer((req, res) => {
if (req.url !== "/health") return res.writeHead(404).end();
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ ok: true, sid: SID, browsers: browsers(), rev: 1, phase: "unknown" }));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
return server;
}
// A console home holding one session handle, the way server.mjs writes it.
function consoleHomeFor(port) {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-frame-home-"));
const dir = path.join(home, "runtime", "0123456789abcdef");
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, `${SID}.json`), JSON.stringify({ v: 1, sid: SID, pid: process.pid, port, url: `http://127.0.0.1:${port}/` }));
return home;
}
function run(args, env = {}) {
return new Promise((resolve) => {
const child = spawn(process.execPath, [SCRIPT, ...args], { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] });
let output = "";
child.stdout.on("data", (chunk) => (output += chunk));
child.stderr.on("data", (chunk) => (output += chunk));
child.on("exit", (code) => resolve({ code, output }));
});
}
test("smoke frame: passes once /health counts a browser", async (t) => {
let asked = 0;
const server = await healthServer(() => (++asked < 3 ? 0 : 1));
const home = consoleHomeFor(server.address().port);
t.after(() => {
server.close();
fs.rmSync(home, { recursive: true, force: true });
});
const { code, output } = await run([home, "--timeout-ms", "10000"]);
assert.equal(code, 0, output);
assert.ok(asked >= 3, "it kept polling while no browser was connected");
assert.match(output, /connected/);
});
test("smoke frame: fails with the last answer printed when no browser ever connects", async (t) => {
const server = await healthServer(() => 0);
const home = consoleHomeFor(server.address().port);
t.after(() => {
server.close();
fs.rmSync(home, { recursive: true, force: true });
});
const { code, output } = await run([home, "--timeout-ms", "1500"]);
assert.equal(code, 1, output);
assert.match(output, /"browsers":0/, "the last /health answer is printed");
});
test("smoke frame: fails when no session ever appears, and reads the home from PLAN2CODE_CONSOLE_HOME", async (t) => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-frame-empty-"));
t.after(() => fs.rmSync(home, { recursive: true, force: true }));
const { code, output } = await run(["--timeout-ms", "1000"], { PLAN2CODE_CONSOLE_HOME: home });
assert.equal(code, 1, output);
assert.match(output, /no session/i);
});
test("smoke frame: refuses to run with no console home", async () => {
const env = { ...process.env };
delete env.PLAN2CODE_CONSOLE_HOME;
const result = await new Promise((resolve) => {
const child = spawn(process.execPath, [SCRIPT], { env, stdio: ["ignore", "pipe", "pipe"] });
let output = "";
child.stderr.on("data", (chunk) => (output += chunk));
child.on("exit", (code) => resolve({ code, output }));
});
assert.equal(result.code, 2, result.output);
});
test("smoke frame: the CI step keeps the console from opening a browser, so only the frame can count", () => {
// Inside the app the console opens no browser of its own. If the app's signal
// to it were lost, `open` would start the runner's browser, which signs in by
// cookie and would pass this check with the frame dead.
const workflow = fs.readFileSync(path.join(HERE, "../.github/workflows/app.yml"), "utf8");
const start = workflow.indexOf("- name: Smoke-test the dashboard frame connects (macOS)");
assert.ok(start >= 0, "the frame step is there");
// The step runs to the blank line that ends it.
const end = workflow.indexOf("\n\n", start);
const step = workflow.slice(start, end === -1 ? undefined : end);
assert.match(step, /\n\s+export PLAN2CODE_NO_BROWSER=1\n/, step);
assert.ok(step.indexOf("PLAN2CODE_NO_BROWSER") < step.indexOf("target/release/plan2code-app"), "set before the app starts");
});
+4 -4
View File
@@ -32,15 +32,15 @@ test("the real prompts pass", () => {
test("a drifted shared sentence is named with its skill", () => {
const dir = copySrc();
edit(dir, "plan2code-review.md", "Switchable anytime.", "You can switch whenever.");
edit(dir, "plan2code-review.md", "and follow its rule", "and follow its nose");
const problems = check(dir);
assert.equal(problems.length, 1);
assert.match(problems[0], /plan2code-review\.md: shared sentence "switch"/);
assert.match(problems[0], /plan2code-review\.md: shared sentence "rule"/);
});
test("punctuation and case alone do not count as drift", () => {
const dir = copySrc();
edit(dir, "plan2code-test.md", "Switchable anytime.", "switchable anytime.");
edit(dir, "plan2code-test.md", "and follow its rule:", "AND FOLLOW ITS RULE;");
edit(dir, "plan2code-test.md", "Its session is already open: resume it", "Its session is already open \u2014 resume it");
assert.deepEqual(check(dir), []);
});
@@ -73,7 +73,7 @@ test("helpers", () => {
test("the CLI exits 1 on drift", () => {
const dir = copySrc();
edit(dir, "plan2code-git.md", "Switchable anytime.", "Whenever.");
edit(dir, "plan2code-git.md", "ask only if it says so", "ask only if it wants");
const r = spawnSync(process.execPath, [path.join(HERE, "check-console-openings.mjs"), dir], { encoding: "utf8" });
assert.equal(r.status, 1);
assert.match(r.stderr, /plan2code-git\.md/);
+15 -1
View File
@@ -5,7 +5,7 @@ import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { BANNED, findBanned } from "./check-prompt-wording.mjs";
import { BANNED, findBanned, findBakedWeb } from "./check-prompt-wording.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.dirname(HERE);
@@ -37,6 +37,16 @@ test("a longer word that contains a banned name is not a hit", () => {
assert.deepEqual(findBanned(dir), []);
});
test("a baked --web in a skill command is found, with its file and line", () => {
const dir = fixture({ "x/SKILL.md": "fine\n`NEXT STEP: /plan2code-1-plan --web`\n" });
assert.deepEqual(findBakedWeb(dir), [{ file: "x/SKILL.md", line: 2, text: "`NEXT STEP: /plan2code-1-plan --web`" }]);
});
test("a bare command with the web-console note is not a hit", () => {
const dir = fixture({ "a.md": "Run `/plan2code-1-plan` (add `--web` for the web console)\n`--web` is the console flag\n" });
assert.deepEqual(findBakedWeb(dir), []);
});
test("the CLI exits 1 on a hit and 0 on a clean tree", () => {
const bad = fixture({ "a.md": "never use Glob\n" });
const r = spawnSync(process.execPath, [path.join(HERE, "check-prompt-wording.mjs"), bad], { encoding: "utf8" });
@@ -49,3 +59,7 @@ test("the CLI exits 1 on a hit and 0 on a clean tree", () => {
test("the built skills tree names no product tool", { skip: !fs.existsSync(path.join(ROOT, "skills")) }, () => {
assert.deepEqual(findBanned(path.join(ROOT, "skills")), []);
});
test("the built skills tree bakes no --web into skill commands", { skip: !fs.existsSync(path.join(ROOT, "skills")) }, () => {
assert.deepEqual(findBakedWeb(path.join(ROOT, "skills")), []);
});
+4 -3
View File
@@ -25,7 +25,7 @@ const OUTSIDE_APP = Object.fromEntries(
export const BUDGETS = {
// The card an agent reads once per session.
card: { "console.md": 9700 },
card: { "console.md": 9800 },
// Each topic file under notes/, read when its workflow starts.
notes: {
"changelog.md": 1400,
@@ -42,8 +42,9 @@ export const BUDGETS = {
"pathfinder.md": 2622, // raised by the UI prototype line's bytes only
"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
"quick-task.md": 5238, // raised by the UI prototype line's, the prototype recap line's, the prototype archive wording's, the lessons card line's, the Changes tab lines' and the post-build cards' nothingYet 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,
+534
View File
@@ -0,0 +1,534 @@
// Tests for src/installer/timing.js and the install/update benchmark harness.
// Run with: node --test scripts/test-install-bench.mjs
//
// timing.js is tested directly here; install.js does not need to be required
// for this seam. The benchmark execution tests inject the child-process
// executor, so they never reach the network, npx or a real installer.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { EventEmitter } from "node:events";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import {
assertIsolatedEnvironment,
childProcessEnvironment,
createIsolatedEnvironment,
createWorkspace,
executeNpx,
isolationErrors,
parseArgs,
redactSecrets,
runBenchmark,
stats,
summarizeEvents,
summarizeRuns,
desktopTimeoutHeadroom,
DESKTOP_APP_TIMEOUT_MS,
usage,
writeJsonReport,
} from "./bench-install-update.mjs";
const require = createRequire(import.meta.url);
const timing = require("../src/installer/timing.js");
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const BENCH = path.join(ROOT, "scripts", "bench-install-update.mjs");
const INSTALL = path.join(ROOT, "install.js");
// install.js reads HOME once at load. Point it at a throwaway directory before
// requiring it, matching scripts/test-install-update.mjs; no installer command runs here.
const INSTALL_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-install-bench-home-"));
process.env.HOME = INSTALL_HOME;
process.env.USERPROFILE = INSTALL_HOME;
require(INSTALL);
test.after(() => fs.rmSync(INSTALL_HOME, { recursive: true, force: true }));
const cleanup = [];
function tempDir(prefix = "p2c-install-bench-test-") {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
cleanup.push(dir);
return dir;
}
test.after(() => {
for (const dir of cleanup.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
});
function withBenchEnv(value, fn) {
const old = process.env.PLAN2CODE_BENCH_JSON;
if (value === undefined) delete process.env.PLAN2CODE_BENCH_JSON;
else process.env.PLAN2CODE_BENCH_JSON = value;
try {
return fn();
} finally {
if (old === undefined) delete process.env.PLAN2CODE_BENCH_JSON;
else process.env.PLAN2CODE_BENCH_JSON = old;
}
}
test("timing: inactive mode is a no-op and writes nothing", () => {
const dir = tempDir();
const oldHome = process.env.HOME;
const oldUserProfile = process.env.USERPROFILE;
process.env.HOME = dir;
process.env.USERPROFILE = dir;
try {
withBenchEnv(undefined, () => {
const inactive = timing.createTiming();
assert.equal(inactive.active, false);
assert.equal(inactive.outputPath, null);
assert.equal(inactive.timingEvent("ignored"), null);
assert.equal(inactive.timingDuration("ignored", performance.now()), null);
assert.equal(typeof timing.timingEvent, "function");
assert.deepEqual(fs.readdirSync(dir), []);
});
} finally {
if (oldHome === undefined) delete process.env.HOME;
else process.env.HOME = oldHome;
if (oldUserProfile === undefined) delete process.env.USERPROFILE;
else process.env.USERPROFILE = oldUserProfile;
}
});
test("timing: active mode writes parseable JSONL and preserves extra fields", () => {
const dir = tempDir();
const target = path.join(dir, "nested", "events.jsonl");
withBenchEnv(target, () => {
const active = timing.createTiming({ ref: "v3.2.1", version: "3.2.1", mode: "warm-npx" });
assert.equal(active.active, true);
active.timingEvent("alpha", { piece: "skills", detail: { answer: 42 }, dropped: undefined });
active.timingDuration("beta", performance.now() - 5, { piece: "launcher", result: "updated" });
});
const lines = fs.readFileSync(target, "utf8").trim().split(/\r?\n/);
assert.equal(lines.length, 2);
const events = lines.map((line) => JSON.parse(line));
assert.equal(events[0].event, "alpha");
assert.equal(events[0].ref, "v3.2.1");
assert.equal(events[0].version, "3.2.1");
assert.equal(events[0].mode, "warm-npx");
assert.deepEqual(events[0].detail, { answer: 42 });
assert.equal("dropped" in events[0], false);
assert.equal(events[1].event, "beta");
assert.equal(events[1].piece, "launcher");
assert.equal(events[1].result, "updated");
assert.equal(typeof events[1].durationMs, "number");
assert.ok(events[1].durationMs >= 0);
assert.deepEqual(timing.readTimingEvents(target), events);
});
test("timing: malformed existing lines do not stop later reads", () => {
const dir = tempDir();
const target = path.join(dir, "events.jsonl");
const first = { event: "first", at: "2026-01-01T00:00:00.000Z" };
const last = { event: "last", at: "2026-01-01T00:00:01.000Z" };
fs.writeFileSync(target, `${JSON.stringify(first)}\nnot json\n{"broken":\n${JSON.stringify(last)}\n`, "utf8");
assert.deepEqual(timing.readTimingEvents(target), [first, last]);
});
test("timing: readTimingEvents returns [] for a missing file", () => {
assert.deepEqual(timing.readTimingEvents(path.join(tempDir(), "missing.jsonl")), []);
});
test("benchmark args: parses refs, mode, defaults and output options", () => {
const parsed = parseArgs(["--baseline", "v3.2.1", "--candidate", "main", "--mode", "warm-npx", "--json", "out/report.json", "--workdir", "tmp", "--keep-workdirs"]);
assert.equal(parsed.ok, true);
assert.equal(parsed.options.mode, "warm-npx");
assert.equal(parsed.options.runs, 3);
assert.equal(parsed.options.json, "out/report.json");
assert.equal(parsed.options.workdir, "tmp");
assert.equal(parsed.options.keepWorkdirs, true);
assert.deepEqual(parsed.options.refs, [
{ label: "baseline", ref: "v3.2.1" },
{ label: "candidate", ref: "main" },
]);
const runs = parseArgs(["--baseline", "main", "--mode", "cold-npx", "--runs", "5"]);
assert.equal(runs.ok, true);
assert.equal(runs.options.runs, 5);
});
test("benchmark args: usage errors cover unknown flags, missing refs, bad modes and unsafe refs", () => {
assert.match(parseArgs(["--bogus"]).error, /Unknown flag: --bogus/);
assert.match(parseArgs(["--mode", "cold-npx"]).error, /At least one of --baseline or --candidate/);
assert.match(parseArgs(["--baseline", "main"]).error, /Missing required --mode/);
assert.match(parseArgs(["--baseline", "main", "--mode", "tepid"]).error, /Unknown mode/);
assert.match(parseArgs(["--baseline", "main", "--mode", "cold-npx", "--runs", "0"]).error, /--runs/);
assert.match(parseArgs(["--baseline", "bad;ref", "--mode", "cold-npx"]).error, /Unsafe or unsupported baseline ref/);
assert.equal(parseArgs(["--help"]).help, true);
assert.match(usage(), /--mode cold-npx\|warm-npx\|warm-canonical/);
});
test("benchmark CLI: unknown flags print usage and exit 2 before doing any work", () => {
const result = spawnSync(process.execPath, [BENCH, "--definitely-unknown"], { encoding: "utf8" });
assert.equal(result.status, 2);
assert.match(result.stderr, /Usage: node scripts\/bench-install-update\.mjs/);
assert.match(result.stderr, /Unknown flag: --definitely-unknown/);
});
function fakeRealPaths(root) {
return {
home: [path.join(root, "real-home")],
npmPrefix: [path.join(root, "real-prefix")],
npmCache: [path.join(root, "real-cache")],
consoleHome: [path.join(root, "real-console")],
appData: [path.join(root, "real-appdata")],
};
}
test("benchmark isolation: a created environment is contained and passes validation", () => {
const root = tempDir();
const isolated = createIsolatedEnvironment({ root: path.join(root, "run") });
const errors = isolationErrors({ ...isolated.env, PLAN2CODE_BENCH_MODE: "cold-npx" }, fakeRealPaths(root), { boundaryRoot: root });
assert.deepEqual(errors, []);
for (const key of ["HOME", "USERPROFILE", "npm_config_prefix", "npm_config_cache", "PLAN2CODE_CONSOLE_HOME", "PLAN2CODE_BENCH_JSON", "APPDATA", "LOCALAPPDATA", "XDG_CONFIG_HOME"]) {
assert.ok(path.isAbsolute(isolated.env[key]), key);
}
assert.equal(isolated.env.HOME, isolated.env.USERPROFILE);
assert.ok(fs.existsSync(isolated.paths.npmCache));
});
test("benchmark isolation: equality with real home, npm paths or console home fails closed", () => {
const root = tempDir();
const isolated = createIsolatedEnvironment({ root: path.join(root, "run") });
const real = fakeRealPaths(root);
for (const [key, realKey] of [
["HOME", "home"],
["npm_config_prefix", "npmPrefix"],
["npm_config_cache", "npmCache"],
["PLAN2CODE_CONSOLE_HOME", "consoleHome"],
]) {
const env = { ...isolated.env, [key]: real[realKey][0] };
const errors = isolationErrors(env, real, { boundaryRoot: root });
assert.ok(errors.some((line) => line.includes(key) && line.includes("equals")), `${key}: ${errors.join("; ")}`);
assert.throws(() => assertIsolatedEnvironment(env, real, { boundaryRoot: root }), /Refusing to benchmark/);
}
});
test("benchmark isolation: paths outside the work root are rejected and controlled inherited env is replaced", () => {
const root = tempDir();
const isolated = createIsolatedEnvironment({ root: path.join(root, "run") });
const outside = path.join(os.tmpdir(), `outside-${process.pid}`);
const errors = isolationErrors({ ...isolated.env, HOME: outside, USERPROFILE: outside }, fakeRealPaths(root), { boundaryRoot: root });
assert.ok(errors.some((line) => line.includes("outside the benchmark work root")));
const merged = childProcessEnvironment(isolated.env, {
PATH: "safe-path",
HOME: "real-home",
userprofile: "real-profile",
NPM_CONFIG_CACHE: "real-cache",
PLAN2CODE_CONSOLE_HOME: "real-console",
APPDATA: "real-appdata",
GIT_DIR: "real-git-dir",
GIT_WORK_TREE: "real-work-tree",
GIT_INDEX_FILE: "real-index",
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: "core.hooksPath",
GIT_CONFIG_VALUE_0: "real-hooks",
npm_config_userconfig: "real-userconfig",
SSH_AUTH_SOCK: "auth-socket-stays",
});
assert.equal(merged.PATH, "safe-path");
assert.equal(merged.HOME, isolated.env.HOME);
assert.equal(merged.npm_config_cache, isolated.env.npm_config_cache);
assert.equal(merged.PLAN2CODE_CONSOLE_HOME, isolated.env.PLAN2CODE_CONSOLE_HOME);
assert.equal("userprofile" in merged, false);
assert.equal("NPM_CONFIG_CACHE" in merged, false);
assert.equal("GIT_DIR" in merged, false);
assert.equal("GIT_WORK_TREE" in merged, false);
assert.equal("GIT_INDEX_FILE" in merged, false);
assert.equal("GIT_CONFIG_COUNT" in merged, false);
assert.equal("GIT_CONFIG_KEY_0" in merged, false);
assert.equal("GIT_CONFIG_VALUE_0" in merged, false);
assert.equal("npm_config_userconfig" in merged, false);
assert.equal(merged.SSH_AUTH_SOCK, "auth-socket-stays");
});
test("benchmark events: durations and pieces are summarized with median-ready phase values", () => {
const start = Date.parse("2026-01-01T00:00:00.000Z");
const at = (ms) => new Date(start + ms).toISOString();
const events = [
{ event: "bootstrap-start", at: at(9000), mode: "cold-npx" },
{ event: "installer-start", at: at(9100), mode: "cold-npx" },
{ event: "skills-built", at: at(10100), durationMs: 800, mode: "cold-npx" },
{ event: "console-staged", at: at(10200), mode: "cold-npx" },
{ event: "console-committed", at: at(11200), durationMs: 950, mode: "cold-npx" },
{ event: "canonical-staged", at: at(11300), mode: "cold-npx" },
{ event: "canonical-committed", at: at(12300), durationMs: 850, mode: "cold-npx" },
{ event: "retired-removed", at: at(12400), durationMs: 50, mode: "cold-npx" },
{ event: "links-refreshed", at: at(14300), durationMs: 1800, mode: "cold-npx" },
{ event: "piece-installed", at: at(14400), durationMs: 4200, piece: "skills", result: "updated", mode: "cold-npx" },
{ event: "piece-installed", at: at(14500), durationMs: 100, piece: "launcher", result: "updated", mode: "cold-npx" },
{ event: "installer-end", at: at(15000), durationMs: 5900, mode: "cold-npx" },
];
const summary = summarizeEvents(events, { startedAt: start });
assert.equal(summary.phases.bootstrap, 9000);
assert.equal(summary.phases.skills, 800);
assert.equal(summary.phases.console, 950);
assert.equal(summary.phases.canonical, 850);
assert.equal(summary.phases["link-refresh"], 1800);
assert.equal(summary.phases.pieces, 4300);
assert.equal(summary.pieces.skills.totalMs, 4200);
assert.equal(summary.pieces.launcher.totalMs, 100);
assert.equal(summary.installerMs, 5900);
assert.equal(summary.eventCount, events.length);
assert.deepEqual(summary.missingEvents, []);
});
test("benchmark events: missing JSONL events are empty report data, not an error", () => {
const summary = summarizeEvents([], { startedAt: Date.now() });
assert.equal(summary.eventCount, 0);
assert.equal(summary.phases.bootstrap, null);
assert.equal(summary.phases.skills, null);
assert.ok(summary.missingEvents.includes("installer-start"));
assert.ok(summary.missingEvents.includes("piece-installed"));
});
test("benchmark summary: groups by ref and mode with median/min/max", () => {
const rows = [10, 30, 20].map((totalMs, index) => ({
label: "baseline",
ref: "main",
mode: "cold-npx",
exitCode: 0,
hasTimingJson: true,
totalMs,
installerMs: totalMs - 2,
eventCount: 10 + index,
phases: { bootstrap: index + 1, skills: 5, console: 6, canonical: null, "link-refresh": 8, pieces: 9 },
pieceTotals: { skills: { totalMs: 100 + index }, launcher: { totalMs: 10 } },
}));
const [summary] = summarizeRuns(rows);
assert.equal(summary.ref, "main");
assert.equal(summary.mode, "cold-npx");
assert.deepEqual(summary.totalMs, { median: 20, min: 10, max: 30, count: 3 });
assert.deepEqual(summary.phases.bootstrap, { median: 2, min: 1, max: 3, count: 3 });
assert.equal(summary.phases.canonical, null);
assert.equal(summary.pieces.skills.median, 101);
assert.equal(summary.nonZeroExitRuns, 0);
assert.deepEqual(stats([]), null);
});
test("benchmark output: common credential shapes and provided secrets are redacted", () => {
const secret = "super-secret-value-123";
const text = [
"password=ghp_abcdefgh123456",
"token=abc123",
"https://user:pass@example.com/repo",
"x-access-token:secret@github.com",
"Authorization: Bearer abcdef",
`saw ${secret} here`,
].join("\n");
const redacted = redactSecrets(text, [secret]);
assert.equal(redacted.includes(secret), false);
assert.equal(redacted.includes("ghp_abcdefgh123456"), false);
assert.equal(redacted.includes("user:pass"), false);
assert.equal(redacted.includes("Bearer abcdef"), false);
assert.match(redacted, /<redacted/);
});
test("benchmark execution: executeNpx uses the platform-appropriate npx launch shape without a real child", async () => {
const dir = tempDir();
const seen = {};
const child = new EventEmitter();
child.stdout = new EventEmitter();
child.stderr = new EventEmitter();
const spawnImpl = (command, args, options) => {
seen.command = command;
seen.args = args;
seen.options = options;
queueMicrotask(() => child.emit("close", 0, null));
return child;
};
const result = await executeNpx(
{
command: process.platform === "win32" ? "npx.cmd" : "npx",
args: ["--yes", "--allow-git=all", "git+https://github.com/jparkerweb/plan2code.git#main", "--update", "--force"],
shell: false,
cwd: dir,
env: {},
stdoutLog: path.join(dir, "stdout.log"),
stderrLog: path.join(dir, "stderr.log"),
},
spawnImpl
);
assert.equal(result.exitCode, 0);
if (process.platform === "win32") {
assert.equal(seen.command, process.env.ComSpec || "cmd.exe");
assert.deepEqual(seen.args.slice(0, 4), ["/d", "/s", "/c", "npx.cmd"]);
assert.deepEqual(seen.args.slice(4), ["--yes", "--allow-git=all", "git+https://github.com/jparkerweb/plan2code.git#main", "--update", "--force"]);
} else {
assert.equal(seen.command, "npx");
assert.equal(seen.args[0], "--yes");
}
assert.equal(seen.options.shell, false);
assert.equal(fs.readFileSync(path.join(dir, "stdout.log"), "utf8"), "");
});
function writeTimingEvents(file, env) {
const start = Date.now();
const at = (ms) => new Date(start + ms).toISOString();
const base = { ref: env.PLAN2CODE_INSTALL_REF, version: "0.0.0-test", mode: env.PLAN2CODE_BENCH_MODE };
const events = [
{ event: "bootstrap-start", at: at(5), ...base },
{ event: "installer-start", at: at(10), ...base },
{ event: "skills-built", at: at(90), durationMs: 80, ...base },
{ event: "console-staged", at: at(95), ...base },
{ event: "console-committed", at: at(140), durationMs: 45, ...base },
{ event: "canonical-staged", at: at(150), ...base },
{ event: "canonical-committed", at: at(190), durationMs: 40, ...base },
{ event: "retired-removed", at: at(200), durationMs: 10, ...base },
{ event: "links-refreshed", at: at(260), durationMs: 60, ...base },
{ event: "piece-installed", at: at(270), durationMs: 300, piece: "skills", result: "updated", ...base },
{ event: "piece-installed", at: at(280), durationMs: 50, piece: "launcher", result: "updated", ...base },
{ event: "installer-end", at: at(300), durationMs: 290, ...base },
];
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, `${events.map((event) => JSON.stringify(event)).join("\n")}\n`, "utf8");
}
async function fakeExecute(call, calls) {
calls.push({
args: call.args,
cwd: call.cwd,
env: { ...call.env },
stdoutLog: call.stdoutLog,
stderrLog: call.stderrLog,
timingPath: call.timingPath,
});
writeTimingEvents(call.timingPath, call.env);
fs.mkdirSync(path.dirname(call.stdoutLog), { recursive: true });
fs.writeFileSync(call.stdoutLog, "installer stdout\n", "utf8");
fs.writeFileSync(call.stderrLog, "", "utf8");
return { exitCode: 0, signal: null };
}
test("benchmark execution: warm-npx primes one per-ref cache but keeps each timed HOME fresh", async () => {
const workspaceRoot = tempDir();
const calls = [];
const { report } = await runBenchmark(
{ refs: [{ label: "baseline", ref: "main" }], mode: "warm-npx", runs: 2, workdir: workspaceRoot, keepWorkdirs: true },
{ execute: (call) => fakeExecute(call, calls) }
);
assert.equal(calls.length, 3, "one warm-up plus two timed runs");
const [warmup, timed, secondTimed] = calls;
assert.equal(warmup.env.npm_config_cache, timed.env.npm_config_cache, "the warm-up primes the shared cache");
assert.equal(secondTimed.env.npm_config_cache, timed.env.npm_config_cache, "timed runs reuse the warmed cache");
assert.notEqual(warmup.env.HOME, timed.env.HOME, "warm-npx deliberately does not reuse the warm-up HOME");
assert.notEqual(warmup.env.HOME, secondTimed.env.HOME);
assert.notEqual(timed.env.HOME, secondTimed.env.HOME, "each timed run still gets a fresh HOME");
assert.notEqual(warmup.env.PLAN2CODE_CONSOLE_HOME, timed.env.PLAN2CODE_CONSOLE_HOME);
assert.equal(timed.env.PLAN2CODE_BENCH_MODE, "warm-npx");
assert.equal(timed.env.PLAN2CODE_INSTALL_REF, "main");
assert.deepEqual(timed.args.slice(0, 2), ["--yes", "--allow-git=all"]);
assert.equal(timed.args[2], "git+https://github.com/jparkerweb/plan2code.git#main");
assert.deepEqual(timed.args.slice(3), ["--update", "--force"]);
assert.equal(report.warmups.length, 1);
assert.equal(report.runs.length, 2);
assert.equal(report.environments.length, 3);
const timedEnvironments = report.environments.filter((env) => env.kind === "timed");
assert.equal(timedEnvironments.length, 2);
assert.equal(timedEnvironments[0].reuse.npmCacheFromWarmup, true);
assert.equal(timedEnvironments[0].reuse.homeFromWarmup, false);
assert.equal(timedEnvironments[0].reuse.cacheSharedAcrossTimedRuns, true);
assert.equal(report.runs[0].hasTimingJson, true);
assert.equal(report.runs[0].modeCounts.matching, 12);
assert.equal(report.runs[0].modeCounts.missing, 0);
assert.equal(report.runs[0].exitCode, 0);
assert.equal(report.runs[0].phases.skills, 80);
assert.equal(report.runs[0].phases.canonical, 40);
assert.equal(report.runs[0].phases["link-refresh"], 60);
assert.equal(report.runs[0].phases.pieces, 350);
assert.equal(report.summary[0].runs, 2);
assert.equal(report.summary[0].pieces.skills.median, 300);
});
test("benchmark execution: warm-canonical reuses the same isolated HOME and cache across repetitions", async () => {
const workspaceRoot = tempDir();
const calls = [];
const { report } = await runBenchmark(
{ refs: [{ label: "candidate", ref: "v3.2.1" }], mode: "warm-canonical", runs: 2, workdir: workspaceRoot, keepWorkdirs: true },
{ execute: (call) => fakeExecute(call, calls) }
);
assert.equal(calls.length, 3, "one warm-up plus two timed repetitions");
const [warmup, timed, secondTimed] = calls;
assert.equal(warmup.env.HOME, timed.env.HOME);
assert.equal(warmup.env.npm_config_cache, timed.env.npm_config_cache);
assert.equal(secondTimed.env.HOME, timed.env.HOME);
assert.equal(secondTimed.env.npm_config_cache, timed.env.npm_config_cache);
assert.notEqual(warmup.env.PLAN2CODE_BENCH_JSON, timed.env.PLAN2CODE_BENCH_JSON, "warm-up events stay out of timed JSONL files");
assert.notEqual(secondTimed.env.PLAN2CODE_BENCH_JSON, timed.env.PLAN2CODE_BENCH_JSON, "each timed run gets its own JSONL");
const timedEnvironments = report.environments.filter((env) => env.kind === "timed");
assert.equal(timedEnvironments.length, 2);
assert.equal(timedEnvironments[0].reuse.homeFromWarmup, true);
assert.equal(timedEnvironments[0].reuse.npmCacheFromWarmup, true);
assert.equal(timedEnvironments[0].reuse.homeSharedAcrossTimedRuns, true);
});
test("benchmark execution: non-zero exits and missing JSONL are report data, not failures", async () => {
const workspaceRoot = tempDir();
const { report, workspace } = await runBenchmark(
{ refs: [{ label: "baseline", ref: "main" }], mode: "cold-npx", runs: 1, workdir: workspaceRoot, keepWorkdirs: true },
{
execute: async () => ({ exitCode: 7, signal: null }),
}
);
assert.equal(report.runs.length, 1);
assert.equal(report.runs[0].exitCode, 7);
assert.equal(report.runs[0].hasTimingJson, false);
assert.equal(report.runs[0].eventCount, 0);
assert.equal(report.runs[0].phases.bootstrap, null);
assert.equal(report.summary[0].nonZeroExitRuns, 1);
assert.equal(report.summary[0].missingJsonlRuns, 1);
assert.ok(fs.existsSync(path.join(workspace.root, report.runs[0].runId)));
});
test("benchmark execution: cold-npx runs once, and report JSON is reproducible without secrets", async () => {
const workspaceRoot = tempDir();
const calls = [];
const { report, workspace } = await runBenchmark(
{ refs: [{ label: "baseline", ref: "main" }], mode: "cold-npx", runs: 1, workdir: workspaceRoot, keepWorkdirs: true },
{ execute: (call) => fakeExecute(call, calls) }
);
assert.equal(calls.length, 1, "cold mode has no warm-up");
assert.equal(report.warmups.length, 0);
assert.equal(report.environments.length, 1);
assert.ok(workspace.root.startsWith(path.resolve(workspaceRoot)));
assert.deepEqual(Object.keys(report).sort(), ["environments", "generatedAt", "mode", "modeBehavior", "repoUrl", "runs", "summary", "warmups"].sort());
assert.equal(report.runs[0].eventCount, 12);
assert.equal(report.runs[0].missingEvents.length, 0);
assert.equal(report.summary[0].phases.skills.median, 80);
const jsonPath = path.join(tempDir(), "report", "bench.json");
writeJsonReport(jsonPath, report);
const written = JSON.parse(fs.readFileSync(jsonPath, "utf8"));
assert.ok(Array.isArray(written.runs));
assert.ok(Array.isArray(written.summary));
assert.ok(Array.isArray(written.environments));
assert.equal(written.runs[0].ref, "main");
assert.equal(written.runs[0].mode, "cold-npx");
assert.ok(Array.isArray(written.runs[0].argv));
assert.equal(written.runs[0].exitCode, 0);
assert.equal(typeof written.runs[0].eventCount, "number");
assert.equal(typeof written.environments[0].tempRoot, "string");
assert.equal(typeof written.environments[0].layout.home, "string");
assert.equal(fs.readFileSync(jsonPath, "utf8").includes("password="), false);
});
test("each ref's summary shows its slowest run against the desktop app's 300-second update timeout", () => {
assert.equal(DESKTOP_APP_TIMEOUT_MS, 300000);
assert.deepEqual(desktopTimeoutHeadroom({ median: 120000, min: 100000, max: 130500, count: 3 }), { limitMs: 300000, maxTotalMs: 130500, headroomMs: 169500, exceeded: false });
assert.equal(desktopTimeoutHeadroom({ median: 400000, min: 390000, max: 411543, count: 3 }).exceeded, true);
assert.deepEqual(desktopTimeoutHeadroom(null), { limitMs: 300000, maxTotalMs: null, headroomMs: null, exceeded: null });
const [summary] = summarizeRuns([{ ref: "r", mode: "cold-npx", label: "candidate", exitCode: 0, totalMs: 1000, hasTimingJson: true }]);
assert.equal(summary.desktopTimeout.maxTotalMs, 1000);
assert.equal(summary.desktopTimeout.exceeded, false);
});
+277
View File
@@ -0,0 +1,277 @@
// End-to-end installer validation against real local git refs. The fetches are
// real `git clone`s from a bare fixture, the installer is the repository's real
// install.js, and every write lands in an isolated HOME/npm/console/app-data
// tree. The only stand-ins are a cached no-op skills CLI (the seam production
// uses for an already-warm npx cache); release app assets are deliberately
// unreachable here, while their successful checksum path stays in
// test-install-update.mjs. Nothing here contacts GitHub or the npm registry.
import "./skill-script-helpers.mjs";
import test, { after } 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 { installRefForRelease, chooseReleaseRef, parseLsRemoteSnapshot } from "../src/web-console/update-check.mjs";
import {
createInstallE2EFixture,
installE2EExists,
installE2EJson,
installLocalNpxShim,
launcherRunEnvironment,
makeInstallE2ERunRoot,
readSkillsCliLog,
runFixtureInstaller,
writeFixtureSnapshot,
} from "./install-e2e-fixture.mjs";
let fixtureInstance = null;
function fixture() {
if (!fixtureInstance) fixtureInstance = createInstallE2EFixture();
return fixtureInstance;
}
after(() => fixtureInstance?.cleanup());
function readJson(file) {
return JSON.parse(fs.readFileSync(file, "utf8"));
}
function timingEvents(run) {
try {
return fs
.readFileSync(run.isolated.paths.benchJson, "utf8")
.split(/\r?\n/)
.filter(Boolean)
.map((line) => JSON.parse(line));
} catch {
return [];
}
}
function assertInstallerSucceeded(run) {
assert.equal(run.result.error, undefined, run.result.error?.message || "");
assert.equal(run.result.status, 0, `stdout:\n${run.stdout}\nstderr:\n${run.stderr}`);
}
function runInstalledLauncher(run, env, args) {
const launcher = path.join(run.isolated.paths.home, ".plan2code", "bin", "plan2code.js");
const result = spawnSync(process.execPath, [launcher, ...args], { env, encoding: "utf8", input: "", timeout: 240000, windowsHide: true });
return { result, stdout: result.stdout || "", stderr: result.stderr || "" };
}
function assertLauncherSucceeded(run) {
assert.equal(run.result.error, undefined, run.result.error?.message || "");
assert.equal(run.result.status, 0, `stdout:\n${run.stdout}\nstderr:\n${run.stderr}`);
}
function readJsonLines(file) {
try {
return fs
.readFileSync(file, "utf8")
.split(/\r?\n/)
.filter(Boolean)
.map((line) => JSON.parse(line));
} catch {
return [];
}
}
function canonicalManifest(run) {
return installE2EJson(run, ".agents", "skills", ".plan2code-canonical.json");
}
function consoleMarker(run, version) {
return readJson(path.join(run.isolated.paths.consoleHome, version, ".complete"));
}
test("fixture: local refs carry installable full-source releases and slim synthetic payloads", (t) => {
const fx = fixture();
const full = path.join(fx.root, "check-full");
const slim = path.join(fx.root, "check-slim");
fx.checkout("v1.0.0", full);
fx.checkout("install-v3.1.2", slim);
t.after(() => {
fs.rmSync(full, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.rmSync(slim, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
for (const required of [
"install.js",
"package.json",
"version.json",
"src/launcher/plan2code.js",
"src/web-console/console.mjs",
"src/web-console/update-check.mjs",
"src/installer/timing.js",
"src/installer/skills-cli.js",
"src/installer/canonical-skills.js",
"src/installer/console-stage.js",
]) {
assert.ok(fs.existsSync(path.join(slim, ...required.split("/"))), required);
}
assert.ok(fs.existsSync(path.join(full, "docs", "promo.md")), "the plain heavy tag carries documentation");
assert.ok(!fs.existsSync(path.join(slim, "docs", "promo.md")), "the synthetic payload drops documentation");
assert.ok(fs.existsSync(path.join(slim, ".plan2code-install-ref.json")), "the synthetic payload is bound by its manifest");
assert.ok(!fs.existsSync(path.join(full, ".plan2code-install-ref.json")), "the plain source tag is not mistaken for a synthetic payload");
assert.ok(fs.existsSync(path.join(slim, "src", "launcher", "plan2code.ico")), "binary runtime files survive the fixture byte-for-byte path");
});
// Launcher-style fetch: the launcher sets PLAN2CODE_INSTALL_REF and PLAN2CODE_RELEASE_REF, a bare
// README `npx ...#release` run sets neither. The old-launcher redirect is covered in
// scripts/test-install-update.mjs ("release redirect: ..."), against a stand-in npx.
test("e2e: a launcher-style first install through #release installs the newest slim payload completely", async (t) => {
const fx = fixture();
const root = makeInstallE2ERunRoot();
const run = runFixtureInstaller(fx, { ref: "release", releaseRef: "v3.1.2", root });
t.after(run.cleanup);
assertInstallerSucceeded(run);
assert.match(run.stdout, /Updating to 3\.1\.2/);
assert.match(run.stdout, /Installing desktop app…/, "compact unattended progress names the long app phase before it runs");
assert.match(run.stdout, /Plan2Code is up to date \(v3\.1\.2\)/);
assert.ok(!fs.existsSync(path.join(run.checkout, "docs")), "the fetched release payload is slim");
assert.ok(fs.existsSync(path.join(run.checkout, ".plan2code-install-ref.json")), "the fetched payload is synthetic");
const record = installE2EJson(run, ".plan2code", "install.json");
assert.equal(record.version, "3.1.2");
assert.equal(record.scope, "global");
assert.deepEqual(record.pieces, ["launcher", "skills"]);
assert.equal(installE2EJson(run, ".plan2code", "bin", "version.json").version, "3.1.2");
assert.ok(!installE2EExists(run, ".plan2code", "app", process.platform === "win32" ? "plan2code-app.exe" : "plan2code-app"), "the deliberately unreachable app asset did not stop the required pieces");
const canonical = canonicalManifest(run);
assert.equal(canonical.version, "3.1.2");
assert.equal(canonical.sourceRef, "v3.1.2");
assert.equal(canonical.complete, true);
assert.equal(canonical.journal, null);
assert.ok(Object.keys(canonical.skills).length >= 20, "every workflow skill is in the canonical manifest");
assert.equal(consoleMarker(run, "3.1.2").version, "3.1.2");
assert.ok(fs.existsSync(path.join(run.isolated.paths.consoleHome, "3.1.2", ".plan2code-console-manifest.json")), "the console manifest is present");
assert.equal(fs.readFileSync(path.join(run.isolated.paths.consoleHome, "console-dir"), "utf8").trim(), path.join(run.isolated.paths.consoleHome, "3.1.2"), "console-dir names the complete version folder");
});
test("e2e: exact updates roll back through install tags and fall back to a plain heavy tag", async (t) => {
const fx = fixture();
const root = makeInstallE2ERunRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
const snapshot = parseLsRemoteSnapshot(fx.lsRemote());
assert.deepEqual(chooseReleaseRef(snapshot), { releaseRef: "v3.1.2", fetchRef: "install-v3.1.2", synthetic: true, version: "3.1.2" });
assert.deepEqual(installRefForRelease("v2.0.0", snapshot), { releaseRef: "v2.0.0", fetchRef: "install-v2.0.0", synthetic: true });
assert.deepEqual(installRefForRelease("v1.0.0", snapshot), { releaseRef: "v1.0.0", fetchRef: "v1.0.0", synthetic: false });
const newest = runFixtureInstaller(fx, { ref: "install-v3.1.2", releaseRef: "v3.1.2", root });
assertInstallerSucceeded(newest);
assert.equal(installE2EJson(newest, ".plan2code", "install.json").version, "3.1.2");
assert.equal(canonicalManifest(newest).version, "3.1.2");
assert.ok(fs.existsSync(path.join(newest.checkout, ".plan2code-install-ref.json")));
const shim = installLocalNpxShim(root, fx);
const lsRemoteFile = writeFixtureSnapshot(fx, root);
const launcherEnv = launcherRunEnvironment(newest, { bin: shim.bin, lsRemoteFile });
const npxLogFile = path.join(root, "local-npx.jsonl");
launcherEnv.PLAN2CODE_LOCAL_NPX_LOG = npxLogFile;
const rollback = runInstalledLauncher(newest, launcherEnv, ["update", "--tag", "v2.0.0"]);
assertLauncherSucceeded(rollback);
assert.match(rollback.stdout, /Updating 3\.1\.2 -> 2\.0\.0/);
assert.equal(installE2EJson(newest, ".plan2code", "install.json").version, "2.0.0");
assert.equal(canonicalManifest(newest).version, "2.0.0");
assert.equal(consoleMarker(newest, "2.0.0").version, "2.0.0");
let npxLog = readJsonLines(npxLogFile);
assert.equal(npxLog.length, 1);
assert.equal(npxLog[0].ref, "install-v2.0.0", "the launcher mapped the logical rollback to its slim immutable tag");
assert.equal(npxLog[0].synthetic, true);
assert.equal(npxLog[0].docs, false);
assert.deepEqual(npxLog[0].rest, ["--update"]);
const plain = runInstalledLauncher(newest, launcherEnv, ["update", "--tag", "v1.0.0"]);
assertLauncherSucceeded(plain);
assert.match(plain.stdout, /Updating 2\.0\.0 -> 1\.0\.0/);
assert.equal(installE2EJson(newest, ".plan2code", "install.json").version, "1.0.0");
assert.equal(canonicalManifest(newest).version, "1.0.0");
npxLog = readJsonLines(npxLogFile);
assert.equal(npxLog.length, 2);
assert.equal(npxLog[1].ref, "v1.0.0", "the no-synthetic rollback stayed on the plain tag");
assert.equal(npxLog[1].synthetic, false);
assert.equal(npxLog[1].docs, true, "the fallback fetched the heavy full-source tree");
fs.mkdirSync(path.join(newest.isolated.paths.home, ".plan2code", "notepads"), { recursive: true });
fs.writeFileSync(path.join(newest.isolated.paths.home, ".plan2code", "notepads", "keep.txt"), "personal data stays\n");
const uninstall = runInstalledLauncher(newest, launcherEnv, ["uninstall", "--yes"]);
assertLauncherSucceeded(uninstall);
assert.match(uninstall.stdout, /Plan2Code is uninstalled/);
npxLog = readJsonLines(npxLogFile);
assert.equal(npxLog.length, 3);
assert.equal(npxLog[2].ref, "install-v3.1.2", "uninstall used the newest release's slim installer, not the installed rollback");
assert.deepEqual(npxLog[2].rest, ["--uninstall", "--yes"]);
assert.equal(installE2EJson(newest, ".plan2code", "install.json"), null, "the install record is removed");
assert.ok(!installE2EExists(newest, ".plan2code", "bin", "plan2code.js"), "the launcher copy is removed");
assert.ok(!installE2EExists(newest, ".plan2code", "app", process.platform === "win32" ? "plan2code-app.exe" : "plan2code-app"), "the desktop app file is removed");
assert.ok(!installE2EExists(newest, ".agents", "skills", "plan2code"), "the canonical skills are removed");
assert.equal(fs.readFileSync(path.join(newest.isolated.paths.home, ".plan2code", "notepads", "keep.txt"), "utf8"), "personal data stays\n");
});
test("e2e: --main and a branch --tag stay on the intentional refs the launcher was given", async (t) => {
const fx = fixture();
const root = makeInstallE2ERunRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
const initial = runFixtureInstaller(fx, { ref: "release", releaseRef: "v3.1.2", root });
assertInstallerSucceeded(initial);
const shim = installLocalNpxShim(root, fx);
const launcherEnv = launcherRunEnvironment(initial, { bin: shim.bin, lsRemoteFile: writeFixtureSnapshot(fx, root) });
const npxLogFile = path.join(root, "local-npx.jsonl");
launcherEnv.PLAN2CODE_LOCAL_NPX_LOG = npxLogFile;
const main = runInstalledLauncher(initial, launcherEnv, ["update", "--main", "--force"]);
assertLauncherSucceeded(main);
assert.equal(canonicalManifest(initial).sourceRef, "main", "main is stamped as main, never redirected onto a release");
let npxLog = readJsonLines(npxLogFile);
assert.equal(npxLog.length, 1);
assert.equal(npxLog[0].ref, "main");
assert.equal(npxLog[0].synthetic, false);
assert.equal(npxLog[0].docs, true, "main intentionally fetches the full-source tree");
assert.deepEqual(npxLog[0].rest, ["--update", "--force"]);
const branch = runInstalledLauncher(initial, launcherEnv, ["update", "--tag", "feature/demo", "--force"]);
assertLauncherSucceeded(branch);
assert.equal(canonicalManifest(initial).sourceRef, "feature/demo", "a branch tag is stamped as that branch");
npxLog = readJsonLines(npxLogFile);
assert.equal(npxLog.length, 2);
assert.equal(npxLog[1].ref, "feature/demo");
assert.equal(npxLog[1].synthetic, false);
assert.equal(npxLog[1].docs, true);
assert.deepEqual(npxLog[1].rest, ["--update", "--force"]);
});
test("e2e: canonical link refresh and benchmark events carry the selected ref without secrets", async (t) => {
const fx = fixture();
const root = makeInstallE2ERunRoot();
// A sentinel the installer can read (install.js takes GH_TOKEN for release assets) must never
// reach stdout, stderr or the timing JSONL.
const sentinel = "p2c-e2e-sentinel-6f1d0c9a";
const run = runFixtureInstaller(fx, { ref: "install-v2.0.0", releaseRef: "v2.0.0", root, planted: { GH_TOKEN: sentinel } });
assert.equal(run.env.GH_TOKEN, sentinel, "the sentinel reached the installer's environment");
t.after(run.cleanup);
assertInstallerSucceeded(run);
const cli = readSkillsCliLog(run.cliLog);
assert.equal(cli.length, 1, "one canonical-source link refresh, not one CLI add per skill");
assert.equal(cli[0].argv[0], "add");
assert.equal(cli[0].argv[1], path.join(run.isolated.paths.home, ".agents", "skills"));
assert.ok(cli[0].argv.includes("-g"));
assert.ok(cli[0].argv.includes("plan2code-3-implement-review"));
const events = timingEvents(run);
const names = events.map((event) => event.event);
for (const required of ["installer-start", "skills-built", "console-committed", "canonical-committed", "links-refreshed", "installer-end"]) {
assert.ok(names.includes(required), `missing ${required}: ${names.join(",")}`);
}
assert.equal(events.find((event) => event.event === "installer-start").ref, "install-v2.0.0");
assert.equal(canonicalManifest(run).sourceRef, "v2.0.0", "the logical release ref is stamped separately from the fetch ref");
const artifact = fs.readFileSync(run.isolated.paths.benchJson, "utf8") + run.stdout + run.stderr;
assert.ok(!artifact.includes(sentinel), "a token the installer can read is never copied into its output or timing events");
});
+192
View File
@@ -0,0 +1,192 @@
// Tests for the local git-ref fixtures of scripts/install-ref-fixtures.mjs,
// which later phases reuse to test ref resolution, redirect classification and
// rollback without network access. Run with: node --test scripts/test-install-refs.mjs
//
// skill-script-helpers.mjs is imported first on purpose: it scrubs the whole
// test process's git config, so the fixtures, the modules they use and any
// spawned git agree (the AGENTS.md failure-log rule). The fixtures themselves
// are real bare repositories in the OS temp dir; `git ls-remote` against a
// local path never touches the network.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync, spawnSync } from "node:child_process";
import "./skill-script-helpers.mjs";
import { createInstallRefFixture, DEFAULT_RELEASES } from "./install-ref-fixtures.mjs";
import { latestTag } from "../src/web-console/update-check.mjs";
/** `git <args>` inside a fixture's bare repo, for type/sha checks. */
const gitIn = (dir, args) => execFileSync("git", ["--git-dir", dir, ...args], { encoding: "utf8" }).trim();
const SHA = /^[0-9a-f]{40}$/;
test("fixture: a bare repository in a temp dir, no working tree", (t) => {
const fx = createInstallRefFixture();
t.after(fx.cleanup);
assert.ok(fx.root.startsWith(fs.realpathSync.native(os.tmpdir())), "the fixture lives in the OS temp dir");
assert.ok(fs.existsSync(path.join(fx.dir, "HEAD")), "a git dir");
assert.equal(gitIn(fx.dir, ["rev-parse", "--is-bare-repository"]), "true");
assert.equal(fs.existsSync(path.join(fx.root, "install.js")), false, "nothing is checked out beside it");
});
test("fixture: main and feature branches exist and point at real commits", (t) => {
const fx = createInstallRefFixture();
t.after(fx.cleanup);
assert.match(fx.refs.heads.main, SHA);
assert.match(fx.refs.heads["feature/demo"], SHA);
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/heads/main"]), "commit");
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/heads/feature/demo"]), "commit");
// A custom branch set is honored.
const custom = createInstallRefFixture({ featureBranches: ["feature/one", "bugfix/two"] });
t.after(custom.cleanup);
assert.deepEqual(Object.keys(custom.refs.heads).sort(), ["bugfix/two", "feature/one", "main", "release"].sort());
});
test("fixture: lightweight v* tags point straight at commits", (t) => {
const fx = createInstallRefFixture();
t.after(fx.cleanup);
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/tags/v1.0.0"]), "commit");
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/tags/v2.0.0"]), "commit", "the default v2.0.0 is lightweight");
assert.equal(fx.refs.peeled["v1.0.0"], undefined, "no peeled line for a lightweight tag");
});
test("fixture: annotated v* tags are tag objects and produce peeled ^{} lines", (t) => {
const fx = createInstallRefFixture();
t.after(fx.cleanup);
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/tags/v3.1.2"]), "tag", "the ref names a tag object");
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/tags/v3.1.2^{commit}"]), "commit");
// The tag object sha and the peeled commit sha differ, and both are recorded.
assert.notEqual(fx.refs.tags["v3.1.2"], fx.refs.peeled["v3.1.2"]);
assert.match(fx.refs.tags["v3.1.2"], SHA);
assert.match(fx.refs.peeled["v3.1.2"], SHA);
// Peeled lines are in the real ls-remote output and in the derived snapshot.
const peeledLine = `${fx.refs.peeled["v3.1.2"]}\trefs/tags/v3.1.2^{}`;
assert.ok(fx.lsRemote().includes(peeledLine), "real output");
assert.ok(fx.snapshotText().includes(peeledLine), "derived output");
// Exactly one peeled line: lightweight tags never grow one.
assert.equal(fx.snapshotText().split("^{}").length - 1, 1);
});
test("fixture: synthetic install-v* tags exist for the configured versions only", (t) => {
const fx = createInstallRefFixture();
t.after(fx.cleanup);
assert.match(fx.refs.tags["install-v3.1.2"], SHA);
assert.match(fx.refs.tags["install-v2.0.0"], SHA);
assert.equal(fx.refs.tags["install-v1.0.0"], undefined, "v1.0.0 has no synthetic ref: the rollback fallback case");
assert.equal(gitIn(fx.dir, ["cat-file", "-t", "refs/tags/install-v3.1.2"]), "commit");
// The slim payload carries its binding manifest and none of the heavy docs.
const listing = gitIn(fx.dir, ["ls-tree", "-r", "--name-only", "refs/tags/install-v3.1.2"]);
assert.ok(listing.split("\n").includes(".plan2code-install-ref.json"));
assert.ok(!listing.split("\n").some((n) => n.startsWith("docs/")), "the synthetic tree is slim");
assert.ok(gitIn(fx.dir, ["ls-tree", "-r", "--name-only", "refs/tags/v3.1.2^{commit}"]).split("\n").some((n) => n.startsWith("docs/")), "the full tree is not");
});
test("fixture: rollback versions exist, oldest to newest, and numeric ordering beats lexical", (t) => {
const fx = createInstallRefFixture();
t.after(fx.cleanup);
const versions = fx.versions.map((v) => v.version);
assert.deepEqual(versions, ["1.0.0", "2.0.0", "3.1.2"]);
assert.equal(fx.newest, "3.1.2");
// Every rollback target resolves to its own commit on main.
for (const v of fx.versions) assert.equal(gitIn(fx.dir, ["rev-parse", `refs/tags/v${v.version}^{commit}`]), v.commit);
// A 3.10.0 release outranks 3.9.0 numerically (lexical order would pick 3.9.0).
const numeric = createInstallRefFixture({ releases: [{ version: "3.10.0" }, { version: "3.9.0" }] });
t.after(numeric.cleanup);
assert.equal(numeric.newest, "3.10.0");
assert.deepEqual(numeric.versions.map((v) => v.version), ["3.9.0", "3.10.0"]);
});
test("fixture: the release branch is present by default at the newest synthetic tip, or absent", (t) => {
const fx = createInstallRefFixture();
t.after(fx.cleanup);
assert.match(fx.refs.heads.release, SHA);
assert.equal(fx.refs.heads.release, fx.refs.tags["install-v3.1.2"], "the published shape: release is the slim tip");
const absent = createInstallRefFixture({ releaseBranch: false });
t.after(absent.cleanup);
assert.equal(absent.refs.heads.release, undefined);
assert.equal(absent.snapshotText().includes("refs/heads/release"), false);
assert.equal(absent.lsRemote().includes("refs/heads/release"), false);
const verify = spawnSync("git", ["--git-dir", absent.dir, "rev-parse", "--verify", "-q", "refs/heads/release"], { encoding: "utf8" });
assert.notEqual(verify.status, 0, "git itself agrees the branch is absent");
});
test("fixture: the release branch can pin a stale or legacy tip", (t) => {
// A stale moving release: still on the older version's synthetic commit.
const stale = createInstallRefFixture({ releaseVersion: "2.0.0" });
t.after(stale.cleanup);
assert.equal(stale.refs.heads.release, stale.refs.tags["install-v2.0.0"]);
assert.notEqual(stale.refs.heads.release, stale.refs.tags["install-v3.1.2"]);
// No synthetic refs at all: a legacy full-source release branch on main's tip.
const legacy = createInstallRefFixture({ releases: [{ version: "1.0.0" }, { version: "2.0.0" }] });
t.after(legacy.cleanup);
assert.equal(legacy.refs.heads.release, legacy.refs.heads.main);
assert.throws(() => createInstallRefFixture({ releaseVersion: "9.9.9" }), /not one of the releases/);
});
test("fixture: the derived snapshot matches real git ls-remote output byte for byte", (t) => {
const fx = createInstallRefFixture();
t.after(fx.cleanup);
assert.equal(fx.snapshotText(), fx.lsRemote(), "--tags --heads");
assert.equal(fx.snapshotText({ heads: false }), fx.lsRemote({ heads: false }), "tags only");
assert.equal(fx.snapshotText({ tags: false }), fx.lsRemote({ tags: false }), "heads only");
// Every line is a sha, a tab and a ref: the shape the installer parses.
for (const line of fx.snapshotText().trimEnd().split("\n")) {
assert.match(line, /^[0-9a-f]{40}\trefs\/(heads|tags)\/[^\s]+(\^\{\})?$/, line);
}
});
test("fixture: the shipped parser reads the snapshot as a consumer would", (t) => {
const fx = createInstallRefFixture();
t.after(fx.cleanup);
// update-check.mjs's latestTag is the plain-release compatibility API the
// console notice uses; the snapshot must give it the newest plain release.
assert.equal(latestTag(fx.snapshotText()), "3.1.2");
assert.equal(latestTag(fx.snapshotText({ heads: false })), "3.1.2");
// install-v* and nightly tags never count as plain releases.
assert.ok(!fx.snapshotText().split("\n").some((l) => /refs\/tags\/v\d+\.\d+\.\d+$/.test(l) && l.includes("install-")));
});
test("fixture: two fixtures are independent and a non-release tag is there to be ignored", (t) => {
const a = createInstallRefFixture();
const b = createInstallRefFixture();
t.after(a.cleanup);
t.after(b.cleanup);
assert.notEqual(a.dir, b.dir);
assert.ok(fs.existsSync(a.dir) && fs.existsSync(b.dir));
// The default extra tag rides on main's tip and is not a release shape.
assert.match(a.refs.tags.nightly, SHA);
assert.equal(gitIn(a.dir, ["rev-parse", "refs/tags/nightly"]), a.refs.heads.main);
assert.equal(latestTag(a.snapshotText().replace(/^.*refs\/tags\/v3\.1\.2.*$\n?/gm, "")), "2.0.0", "nightly never interferes");
});
test("fixture: cleanup removes everything and is reliable when repeated", (t) => {
const fx = createInstallRefFixture();
assert.ok(fs.existsSync(fx.dir));
fx.cleanup();
assert.equal(fs.existsSync(fx.root), false, "the temp root and every object in it are gone");
fx.cleanup();
fx.cleanup();
assert.equal(fs.existsSync(fx.root), false, "repeated cleanup neither throws nor resurrects");
// The temp dir is not littered when several fixtures cycle. Each fixture's own root is
// checked, never a count of the whole temp dir: other test files build fixtures alongside.
const ones = [createInstallRefFixture(), createInstallRefFixture(), createInstallRefFixture()];
for (const one of ones) one.cleanup();
for (const one of ones) assert.equal(fs.existsSync(one.root), false, one.root);
t.after(() => {}); // nothing to sweep: cleanup already ran, and idempotently so
});
test("fixture: default releases cover the rollback matrix the spec asks for", () => {
// Documentation-by-test for later phases: what createInstallRefFixture()
// builds with no options.
const matrix = DEFAULT_RELEASES.map((r) => ({ version: r.version, annotated: !!r.annotated, installTag: !!r.installTag }));
assert.deepEqual(matrix, [
{ version: "1.0.0", annotated: false, installTag: false },
{ version: "2.0.0", annotated: false, installTag: true },
{ version: "3.1.2", annotated: true, installTag: true },
]);
});
File diff suppressed because it is too large. Load diff
Loaded 100 of 247 files, more files were not shown because too many files have changed in this diff. Show more