Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a03b825951 | ||
|
|
44434d5264 | ||
|
|
f997a82c4d | ||
|
|
50319aa332 | ||
|
|
7b4e8811e4 | ||
|
|
bc2325e061 | ||
|
|
ccf82c4eb7 | ||
|
|
f1d087ba47 | ||
|
|
d059dbf30c | ||
|
|
3b822a3efa | ||
|
|
ee530d36c0 | ||
|
|
634e4df10e | ||
|
|
8277c8b548 |
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.
|
||||
|
||||
@@ -9,7 +9,7 @@ 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` |
|
||||
@@ -44,8 +44,8 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `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 |
|
||||
@@ -62,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
|
||||
@@ -90,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
|
||||
@@ -103,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 |
|
||||
@@ -130,11 +134,13 @@ plan2code/
|
||||
|
||||
### 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -195,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/`)
|
||||
|
||||
|
||||
@@ -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,7 +105,7 @@ 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`, 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/` |
|
||||
@@ -102,6 +118,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.
|
||||
@@ -149,18 +167,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:**
|
||||
|
||||
@@ -170,6 +188,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 |
|
||||
|
||||
@@ -5,9 +5,12 @@ 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 |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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 @@
|
||||
U0VOQwEFJpExmufZ7/oN72H5kVdq885u/hNYDc46x6xuOJTrhD8NazvJseXfERYiTRVYpH0nQYkSGppY0m3aK2Ykt+EWExil7v8pHZAr29znkuDrc4T6PBCbcqXoJNoHSMgWUsbaQw5LfZ5LNsJHqhSMeEHzzPNYdKrVrjcTGKWIppp35poHrTj8qc0BFVu+g5sHD2VhcsxGuMiI3OZ2y3hvYhwAyNCi8Ig5gT/W65LDIIY+u+n6vopbpXvpm6wrmIMhSOiMDdZvGtUndGRJfMH4JfugcVdZj9skn3cKqRjy8dVNcFiHnN0Sm2AciPo2CdXboVx+oTjmKioH51VhKwWVoV7AxLR97A8561HDVpnbYAZpKXx9O3VhyFi+foiodSrIBNgdumkkKBXSaekVyw55Y7aMm4pMKCMmGGexmv5RN+sDNpfOF3bx2ZFIMpyei0RvZTXm4j56H8zGDXTGGQwPGSJPOCvDShh2UkbEjA4DUBL46sFRSBJqXFIppDB/A3xh9BnjkBgJssYYMKYDBW6J0BqCkP87LRuEt377HoBwv++l+ZjuLYM+rPXo3w1Mt8Nb3iEVuX0RO4IsRSaf0SBXXtaZpO6PbdINJxcqkKQjXlhEdUHANuH5/xn8kh5xZEqiPmicAivq37uJBwD06dcUVmBxzAy1krcS2QtvedqOOYkw6tEwAxhGJLtl5JAE2ccL22s4TQvDoPWE2XmWORi2KevNZBG4wwBnr2UFCShJdUoFblP1jB60P6ajlkkx44ma53qExhcXNL6meZ8tKistSbG6HuCMfV51WPXlXMtVpQWKJQDfGorLLVjBPQND/T4Zr5BJULP+kFd02txovD1FBZg4n99pKxvn+Yc7Ks77OTxn/ya8liAyyM5JZwJopkifoGNGeqtRpIIPt2xbcCW7mMyfP9bt0a9evYOOZ1VyOdFUjzm3NAEGVW4v4jzQS2wf6MnXpS7YH57Jtc616MOAihkz9gncoXEf0Vc5rJWFATk898QaL0I4dAfKTf/yQ6GToZxtDoAfCd4BGph9rSeDexvQZgbnvRggOooVRBNVchvjKQORTN5hKIqZp5jWY3zFaZSzBPyV/pJC3Z7l6Dz1+GUlxry+S6ziaxINU7yg7DvfzDOVTKpOK/YymQHoimBQuUU2eC+h07qOT/U04PqWuMYdLJPHwgSvdClNjsNdqgAZV6BfNtBNuYJBi+7y+ibthpGd/nyQ9pJHOksEBeTfXJ0cF4qQ2LnNs5g5d1Oep+fDQ5RusJoqYZw0rF9UWI2IM63qCIADaycJM6ihSasHSNExdvJT4QWLGd3WwR5c9j+E6PlutGjMHoYPsA6yfDxBvoeJw683kgwgFc0VXwRBR1Xwl4/xdoKv+W+2azpOeQWNBjqsw8LeQmsdLXIfBloN3C9zhNf4fAgYFsi5JVNlVzYi/P7eTNKovqhfaRoTEWEmUq5NkOqYZsW2H2LyKT3bsWHlDZVIEDREhpUr24wjE34SA6NxtNXJGLriFpPI7JBbs+z7V+Ejg/0R1DBTMff08ludSB2+92EA+LQcAcbg5Ffeyc1/vs/APUljaVF9JehAhFKScBKvK7Ci7lrAvQ8826ujE65q3Fflkr8do675+rrtyq/jYbymYzBzi/qkJt9mi+EFrcJXh3ly1F/zuhCe9dnuQ2bT/tw1t5P+wuwQRPrpiufayfSJKDTU8kOyX5ZgfcnToPKvK0RDbmxpI2QiFOCdj1Bedz/bTyLPj2OxOp9ZBm4hM9f5CuGfTAKTNIkNbl3gqWJNuR5EVY46+x0EBRP9vWsK03FF5gOi08eqmbqHZwxiBqmj94hb/j1L/0sPZSqJVJGfNWPf4n7cNTwzegEIcqMYXglUu+jDwjG5vnEKwH2j9RI064hvjgKxyuTDRIRx41b+gMT0ItgFp9LjW4ZaOHdtb4dJVYK5IlahztiO3wItXpDGHUTBkJm2mBuBv3htxtEIjQanz0Xgod9p+MkVhPOmezksws8yDll6ELlpW7QpAT5/uQFbktZFSDV/VnLv8+WRQdeUejxY71sFq9PJMl1pa0wj4ivM035O+LP2p67U+QYZgmPrpw5g64ylYITtfS9BaPphAntlX0pK4PFU6sj0GyveiCmXMwYNihcCWmhLDA6JEjg/86oaIPkvPZ0W+QcUnGGh87TOANSptzMDhk9ypLe46cOO1IGjclHPsgkqgKl/3zPYCB5FmLLsmPHRx6drgNbIGeMGavn4tbaQCvvZt7oWyPnG71zeQ36anaPg0annlcACxQdP6Jw1bVijPjRzX0k/Xx+hLoydZqiIwRh9ffBBLxP8ddXfLdZd+RhRPhfaY2A2EzDIvFl/BYf1uNi3SeeC4x5CV8JW2gHpwYUjkyWvNDs9YH4nE0uZ9D0WsR9kULGz1MCX1muS1gHOP4TP41kQ8juKPOJbcbZlFEiV1A/ZVfJDCI8DiH52lanGjEVvoelVWtqcrmRHEAivbS9csKmE663EF52OpSUcwvynrJhZbmld0L1QjT9vPKokG8XMzvg0US/IxmbncVh030rsIqTOfTXpiqxfFDuOV+ACNA5flTN0S1V9uXkKM7LSDMoSwGCihAdPi8hO0OuHpAfSxmN2l6DyTue13xvFBe21JZDllOUP8QqcNxFZzLDQXyaP0ZNPkLZpJWPyYAgE4mqF8w+/qMO9WCXOqB2z23xiNT9qim5UvvfK2B5r8sIDELM0XzADAH/PiCWsFoiG1aWqpYFA9QvjSwuv+Biq6UndTKXWaF6GCxm+rNCEhZagrc5kpyal404YX1E5xiiFh5CAvi81b9lKDd9JU/DRLcf+jf2M+oJYS1qyMY+VDWZtDQkg3bqdqyjMu+L5WChGcO687ko/wV+hN4FpQHsVCRQGunkjkJbAzYBOhnF2LXc/dNnZMeNQ311SRGYdrNk8D7/N7vfseGzFfqz59fkkmrm2HnnPyyowZ0oiOlDqsNK5oihzbQyzAv2kHMRHMOgSn7ms5xHoU7hvMAxgG2WBkC8Ef44noz318yy3Mqt8ujeYJODp1xF3bZGoWGALbNfgkBD53k8pcAtAc3dwWe5OJo2P5TLsFVCPDppW5tqZx33uep/GG/9cQsrummpxaJS9r065wa66LMv8SfF0S7ZJWavSfGXZv1L1Jhlt29bOITwCF2cGPJjMdWQ+eeqiA3dhc8sSZJkO7eWpXW42BAEND9P/lptAP0EEnDTb/e8e8YD9x2pbixSrlN0Pwx9mjDRZfPV7JqlQnA3TVw8d5df3WUr6qlTNBQNfK4fzy93ivqodRmUSYtagKVQ+1KCYeSXrPjW/i2DFxZfhLSEFyViOYA6H62Bqsi1FoBl01jdTbP+5mzczZz5JM9QZYkvt8K4bdbxuLcB3wC5N4Otla9SRHcm1/U6r/V0NUFL6JIuKoaxWs+/DDDQzRhDnfiWdiQXaRp9yy2DY9VMvA/fU0zvv4F13Sp+lNjuEVIqvVl5pU1PzahgILkne/PAD0bKDkj8pk9KAHznuMfGjcw3dUbE0Hd9MRJqTxQYLoVpOQF3PY6cqF1RI7nLj31koBGDS0yEzIdlAnhwdTKiZXoCvTaIhciOsZjpft+2d4chWzu7vh5wZawWvFJHxGblbbZ4IGdfXKMgO0ItG/8730RXdOZ88c/s4A6KX5F0ytXIA6eX+YBzl1sSKw9WzibrAhJUpDxyZeNMqKM3e3I2L763fQgRSjreIb6rgzgAo8VSiHiO6L7um0UjH+k2SqeYA+h47iDeHAjczqpR1E+csDpsu0nNCm1cNmtw3UWbP/y4O6rjUnNuqO30ToK9C+F/xWtIbYr7Gcac7Lyho5dKDcTkUNDJc0HlsF2cFYlwRbWTA2e7lI13KJ5sdlBSIoybwTeN/XyxmU9sNnDINaJ8LvQw1VcntkRFE2M9+tmqUot2wryMaSf+b7FHGOow2QQpbPjanXf7ovKEsdMSssBwWAPMLT0XD6NChAzZVq9g806GXTxnR4HTaubepKL1JcOAvZvtSiswyqrjdCf8NFKHp0UzmAN3z82DYdndz8xicACNc4xxdhkCMMgavadAM6Bby9TzJ9UxBSRtMnqIShtewauwx+agmvA9ytFEftC9W+Xh9HQH9420VsX7jyTdH2oZ2vHgTfhyEn/naO8++oiX/GxkTGyE5stbAU8Ok3pUfTlsnKbD1yL5d9e0ozR9HJNf1x2cXoaYiC3+D/jlvEpKddNCy8kL5jnxomnpOfreymVfBe2ImZUlqA6UnhrX4+1LPwvjjKBj6cUuWb0i7Me2KOy8A4DMjKeOARcHJ6qfjNi6DshnHdCi+uhm7nkzgY1OSztLoLnGl9aX+Kurh/JItI0ICZqfBMT6ugnVaTixeU/KbU81SezRBME06uv0iEapb+506XE/ZwKwAXTOCg4W52NtC78VR+TMJTS5ITRLqzEdOA4tiHW7x9Ye8WVDDF1qDiP3FLtW8aP41sY/hy9/DSvLsdZ5hTNgwxeexX9K2B6qQ38SX7eMDCp7KN9NQAOgV6Mffko1VUTqjjDEgFjXVcktL/50CgnSJ7RhndZeZe7H3aHgioij9rL8YGwudETzck9PTV2V/m2+j8tUerf5r1mcUM8LltIpDBYEHRGnrnbSjAIjoA7YK1mikVzRnP9aR74ln0Nrgavuj/cvV29z5Cbv6+fCNlC4Fk6bD0DkMsSY9E2DLNfMg0exhwqMt2GqWSoouBl41Sc0JhQA/5kNvJ/pfpYJOgf9z2LDREkkFdAFqH6H4a2/V6XQiu81dn31/SBmsi89xZUy74L746/QP2iNx6WI2JlMgl1c8ybUwrxq628nrg4Wex6tYsMcZ0pj0HQe6q7yJLK2vTGZMMezG98PPBmABj5pkUkUkUqDF0FFEF19Ls6jSihUw69nqSQ/dbuCgy5DidOuDY0Dp2ifSrA3wOwy7JxKxEhKMonUN3lzxelEy61ee+eObDGP+ditQVhOF5y6zCbheVDH8xRa5lk9E5CwLine truncated
|
||||
U0VOQwGUhBJO3dPZPDQc4L7k1lalN/wixLSs7lYYWIVd2ppas/1v1M+5GnT0T63hjpl7QhRFKmepKi1Rv/cr4EMWgHswWemJxRRW6q7usEhHzTawHeALuKzdQAR9hQ0+8s3Ca0iVBTa/DQ4N95fpNi3VHoHxm+UtT6wN44R/yFthry0flHOnAoQcqFLdt91HUhDa9GOvy1Tlc3nnZXtUt5hfFSNB50Z0erxBEgU/1+5EMhkmOUZzWOyzWDvZilk0oBA08ZrsCb4Acp3JJAtul7nAclcsnZaV/R41E8cQL50wBehRbyLj+GsyrM2T3M2GWqlj3X6qKwzOh39E1g/cOSpvC02WoB85O4hzazGZe1RFHYECzTmpTFa2GlzhwFp6bxZf//saCAUELOR/+ct4n6XueYNGcfW4REJL4XGMvnZFTccgTss/hXWceI9pspw3aZPuvNqZToK723pyDY9mN2b/5j7EBsqEgFYgqzxeX3JfG/V8em3wgL0XPw3DWO5WWvAKK0c2ULEdH+rwsFvQt5knPNtgEGLptrQseA8mmt0kQLvUQ2ungtX/GQs5Hm5QeJPvJbzWA4g9ukw4zJL2J1CHE7YFAWefRX4TMYVHOOMnX+txkOpZ6IPqmzJSkx21kg3hDF75+a1tFBONPFkRQouAY6PqWcC4MbwIBhEIOziieP5ll0DAFz4Oym4IQx0CVUJdeg647BFNgVaELUfVoualqwR3+1Ku3RnuqZvTdPRzEIY0z5tTuHXUQLPjGC+ETCPrmZw3NfcVG1DCjg1RE0HYQsNEPXJ6vBwmfId0deOGkJI9g4ge37xZeYH81GPYmT3GfvqkCyyxN8GMz4zlEA9prTZg4sm0XC8o2zrDw9Q0yIrziDo8RPsjfJWvUqESLaswANlto4ikM/o+7SJP1UdHanJ2Zdv0Z243wq7gTsTkAL1OJwOQriIomL+XlzwyfrC9C0t2xlg7oX1bVK2sLl/4iAU9RUpU4sB7a5ieV+AfhlUDh//N844R3Zd0yDQ6lyweUmLNJOx8UHcwEAVd30H1o0iJENUYtosyZY6rfbN+CmFNH/UG89oOKbmOl0YEcwRLGr65FxxoayIeoEyoD0OfO6Uf8qDD0lu+JjeDzrPxPr6+LIqDVfssasfRgiC/n3GAK9tIbwu8J46+3X8fZNVo/0Sl1w9CZagLd44sVKQez3ITy35j/NOJNYDmmVAWVFAwcTo1oBXXBlAvZvAPDzsFVFZPIyWgZeHcTYget2sdANrcA2Mx91/sMEFlfAf6seN46MBFkIPwZrVZmRonrjkq0hCd7cXY4go9iRmQmejz8gTDi03HamooyjzbngsbC2809yURXJMaegpqKRUDX7RzEZNSXN0PdHPKvHM+wFEZRxdzNAgj8uJgpnzOtHr6MFj+QeMHLCC6x98+gc6kHPvYfDizRTg5/Ln2tIiPAO7I+Uy8zPkr4c9USJfChonlRLBh2i0ycOrU6/io7CyQBbdnZcoyQzO5Sxfy3q1qTaX+KII90O0gZTcdFqqpD84+d9kXpuASaGe+monsVWudvKp9ajwoCoad7IWcbcluTWQ9+CtHcQtVJcfvD2RLxV+9QWYKgJWczAKyc/kliORos6JL4tHwiXuuwQC0eSvWkqBc5V5RqoKlaahlFb36wZVn/fFN1G8zDyY68NltaChuuPqy3YBH+wd5YKuVVdr3To+/4ORmjymDMaAglD7gdNX8aBVqJwCQAhYgu3WFYIp4JOEiVN9/uE7XF4EElyaXQ+ARcGDsbp8ScWOxvervWL71Vs9/WvqTpfBXXTbeq6riyXi29hV1eEmRJIXUSD5B2hMACgEoUxIUM0XmXE8SpyqcL4V48klQjdVNe+//TYM6IZxMSS1Maae0kBl0ddCL15RVrj0StyHuYqq0u8mipQ5zz2gCQccDppB+4g07heyTlIeVbjoik/xAHBBz1z2AQPN8bj22Onp8cp4Dr7UY+n5U1rNBaLdZNAoaaoIJO8GPGIC90gS0IuUg9MqDYYzrgql0pnwHcVOekrFpBYL8HY78vF9TfGzsXgpvUiF6baovZpO/hnUmUMyFKxmtsd3fSvMi859z7B0WgBxP4b1GozJTT80a0LfoNpUOFVvp/DbYC6xyOS7iZApETEllrtdqOCBFBVRgdDqXQ0NFnqMX0k5BTIuyr8uAjXqYzI9bkLC6LkBZimmWkYRHCaNE4BjewW7vCDbpNTOD6ptEhFbqTsOS+dMbpXKCeWrJIMVVPOa2OqKGBg+e0KQaUWQCzKuh0DSVdXFFkhkid32B9kwKtC5Ft1tkUs4cGAiZ/8LYxWyiWc4vaWilgEMC0DlXBmbHo1kLGB5WiBqdnPG2DbvDid9/HmcJzPAJ/rveEM6oXqh6hnzKKSRGaLzZDm2wUux6xEQ0KFdodzpkACmpS90Pkvhp7I8ooS2QpDIXaPCdtMPYXpFf3ZDflRnMmBOeiV2JjaUmbNyOh1DAmZRicUDd4pJPNx/hX3x1HlIvvwywk67FIsSFckyTFwV3zRppQFJh/aZKdkMyvDzSJMCy6HUlttNNzf44yHYKMZGkdMqKua5Nvjgw0fLEzJ/y99UCNszd0i3A5VIJIieX9XPD0Bl/MXFP/9y2efcXCY/C4gPXgzolLoWTeUwp01vw8lmNDVXOV5+2/R6unphWpInGbAVDieACQK3kDP/aVAkLwLtBjevYSke3lIEVjbAJOrtmYSu1WpQcOSdr+GENmFE3mMsmZlkcmt/XaO4i2AP4p5k78ot4ddUtckRvhOa3HoJCIXuPCKI0Qi1hC9FOHVHNVMNCfFGvgHDewJez0F3ILykYiB5j6tLYqZd2/PFkfONLliExIc+H+l9FEs0MiCGaTAlOcES/iQ55iR7wIZvf078uzN7cJhszwzOmmxSujOqEk5F0OqvfMs53gHkawAMAGjE37Czd+zNxk0SbDwRbctwCFT04a08ZY1OiluvVQtfHxYo6SHbgDAnAxd7VwPDZYXeGd99qXQtzQyP9qG2M6ldANjNuAxbre3UvhxAYqOCBSJ05FPqbwWpWEBAEfeg8nnKLDU0xUFYyHMdfHryD05ztzdNg/ujtkL7j5Ni/fmq+koQraG6cTsBGDGcfgrUkQF/7AOyq2/pzOIvsdOxV6q2pcXE4BlSx87pZ3upM2xwtbDoc6KnximeX+C2eCNBZcvEiSZh6UwggWVyC1ePUi5IvSfW1TrCOnwnpY5DKy0TUfm4J9iNlWPfSqOwmLiXr3Xb+wG+glXA1H8CMOL7JjShxC5OMvrsBoNwfswktc2ycVgsECsMrkjR2OPQ/bXr5tIkzUa6QOIk8ryRtXNl9FS2mici9NMNZxGK7Xn2zAAWNI5fL686upayZkfrHMoOXQ/dCdQUPNizF9GE1l18YIQAmdOvYrBTfiNzcA3lgw5rqw7zhraUHWAy1gyJrWo3SH7gIsNU6XGUQ7C7GxDpp+1HOqwR1pQk58Mj54lHRMtYEl9iWB5nWWDjWbs52b7nnLPkYSLUgBvXTzd8s8hHWX6Ihht4hev4lPV1hsKPUrgJXTrqeByPIAPADDlPCFQqlVQePsm+vlFPNakA93e3URpn4bguLDT1sEO0/jnPsdh+eqtuJTMCovc+NexitlDh1xlElJGu2qI5t7N1kxCM+IdJSMXj268oje2KY4giX+zvnAS4UHgrIrNwggTeodlYVHBeFZzE/iP91iHY3j+cp8KDoaSnLaraRPtL7RihfOFBaG9yeLlxpaPVAAv+r/0Oxwd+y2IAxT5q8u1Jw/J2mTGPdNCICGhRlHzlheSYI+VfTI56+IZ9mADdF/i8Ykhqx0BRyWyRLdplroQBglOMswePgVgQgeSfyJIZv8VWi6J5HdBHLz6YHFJz1WMg/2vi2xU+L3ltGZgzadmP3VmGAPa5auZJ6q4HrkBQ2dZF2SC6nPQ6bphTPcu/4JDCrW97+jEcQ7Lcwvp3ODbCbrsuUSaZF+eNxXVWNnaCsYhy8RTupI81s+Di+oGyMvNgdwSr1NwdbRI9+S8RrrcCrWjgaRGIBEwn7DeHVGLHjErU2ec6VDvfSFOjgXv5AGcsDY5AVjW6kYHAmxBCc1NUcmtBBCxVhL8fHa+S/WDzmxGUGEJN+VWUKqKA8jc6c3tI+gCbh0mf70X8YbfoYGotJ5N/hUfkm0UyhPiurbj0cqRvuGtarmfgJVuP/tEzK4Bg4SIjrTwWyVmklOqRNEHjI+3BXEPrD6aenGCSakS+QY8vHCeQmY2uHvOE2lA2ngq6N7nS9QzAVpTxdCpf8qKRx5IXVrEJDTGykN+GS9St/fUqjoULOWFiZF8Lv2tDUq2u1iQZ0n4EMKqN+7zuoVKKvSXKGGrrZ59Qr+isOa4nAPxs0ugEc5vuFzENLjmO0TlH0zZXJuczDLIzu7tqIsOMYGjegzPEji5fDHRzUBgbLm68XYhkXMt9fBxFLFFDkycdcXP3Yg5pCNvkewETAPCp12bOS6bNjK9SAxww7a8+Rh7Iba0TNhgoPqlJfUKl/vtxvD5P24fOEE7gBMaZHpReMlClq7D6rA2CTCyu6KBKzRE3JfYI4LGl7Jmne+Dm+Z0T1w9oL/3EitIpSM8jVxG1WMxHtjVgWLIzyjgTW5ZrEF5t7qaLdXUv658TkL4GJ0CBBqscbLmB6/CyxoIXPPUW991VT7DCL1MXfqLCB6YFucHklX1v7nGJdbajLnSgo5yFun8Pjy37RhO5YktbNFQ+XtwgyfBuWcc0W3g06PiFG+H0+8OSyLlHNl62jw1bSEs4TdnEZguI+d9xfqqRUMLQucJB4gSh/BCl9o/lv1bPBrakzjkHI7e+r8YOdovdA0yw4KNDvrNPKXyCC1jgRGQfOp2z7xdP3JjtJgdLSO4hGgUeduNM3sKbm7UUbDqhME19VZEKayNa2vYOKzOSNXITEW52htzzZpPwY7tjtLjkSeizakP0drUoHo/GoT9NYeS/mzhcDwjwiAcNgRr23ZvXLine truncated
|
||||
@@ -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,3 +1,4 @@
|
||||
.env
|
||||
specs/
|
||||
specs--completed/
|
||||
dist/
|
||||
|
||||
@@ -46,12 +46,6 @@
|
||||
- About: src/web-console/public/loop-parts.js
|
||||
- Noted: 2026-11-28, implement-review
|
||||
|
||||
### A test run of node install.js with a temp HOME still writes the plan2code shims into the real npm global bin, because npm's prefix does not follow HOME; also set npm_config_prefix to a temp folder.
|
||||
- Kind: correction
|
||||
- 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
|
||||
|
||||
### 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
|
||||
@@ -63,10 +57,10 @@
|
||||
- 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
|
||||
@@ -94,26 +88,16 @@
|
||||
- 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
|
||||
- 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
|
||||
- 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-17, implement-review, checked 2026-11-28
|
||||
- Noted: 2026-11-15, 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
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# 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
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -169,6 +169,7 @@ 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. |
|
||||
| `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. |
|
||||
@@ -282,8 +283,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
|
||||
|
||||
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
@@ -116,7 +117,7 @@ The easy way in is the dashboard: type `/plan2code` in your agent, or run `plan2
|
||||
- **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*.
|
||||
|
||||
|
||||
@@ -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 24-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), the app-only **Review Loop** (a card beside it, `screens/review-loop-setup.js`, the setup remembered in `~/.plan2code/console/review-loop-setup.json` owned by `review-loop-setup.mjs`; the app's `review_loop.rs` drives review-and-fix rounds, each a Review session opened with `--loop --round N --role` that reports a `roundOutcome` per `notes/review-loop.md`; its end screen is `public/review-loop-end.js`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens wheLine truncated
|
||||
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 dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), the app-only **Review Loop** (a card beside it, `screens/review-loop-setup.js`, the setup remembered in `~/.plan2code/console/review-loop-setup.json` owned by `review-loop-setup.mjs`; the app's `review_loop.rs` drives review-and-fix rounds, each a Review session opened with `--loop --round N --role` that reports a `roundOutcome` per `notes/review-loop.md`; its end screen is `public/review-loop-end.js`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, SystLine 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 (plus a Tidy up nudge from the scan's `nearCap`; More, Tidy up lessons sends the `tidy` action, which writes `tidy` waiting items the same card applies), both from the scan's `learning` field (`public/screens/learning-row.js`, `public/styles/learning.css`); skills ask for approval through the `lessons` card kind. Before that card, every waiting lesson is graded by a separate check, a fresh read-only helper where the agent has one, else a labeled second pass by the same agent (`src/shared-references/lesson-check.md`; `lessons.mjs check-input` prepares, the checker judges, `check-record` stores), and the card shows each Doubt or Fail with its reason; follows ("Following a lesson") are counted on this machine only, in `follows.ndjson`, for the lessons reader. The server's only write for it is the personal pause, on this machine only (`POST /learning/pause`, under `~/.plan2code/learning/`); every change to the project's Learning files (`.plan2code/settings.json` and `.plan2code/lessons/`) goes through the `lessons.mjs` skill script, which shares one core with the scan, `src/web-console/learning.mjs`.
|
||||
**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
|
||||
|
||||
@@ -4,6 +4,73 @@ 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.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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.2.0 · Apache 2.0 · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
Version 3.2.5 · 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.
|
||||
|
||||
|
Before Width: | Height: | Size: 71 KiB After Width: | Height: | Size: 79 KiB |
@@ -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
|
||||
@@ -326,11 +326,11 @@ findings still open, including ones an earlier round could not fix. From there:
|
||||
|
||||
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
|
||||
|
||||
|
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 36 KiB After Width: | Height: | Size: 125 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 111 KiB |
|
Before Width: | Height: | Size: 32 KiB After Width: | Height: | Size: 147 KiB |
|
Before Width: | Height: | Size: 32 KiB After Width: | Height: | Size: 131 KiB |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code",
|
||||
"version": "3.2.0",
|
||||
"version": "3.2.5",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
@@ -10,7 +10,7 @@
|
||||
"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",
|
||||
@@ -18,7 +18,8 @@
|
||||
"pretest": "node scripts/fix-line-endings.mjs",
|
||||
"test:fast": "node scripts/test-fast.mjs",
|
||||
"test:page": "node scripts/run-page-tests.mjs",
|
||||
"test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-lessons.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-learning.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-card-rows.mjs scripts/test-spec-carry.mjs scripts/test-spec-carry-page.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/tesLine truncated
|
||||
"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-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-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-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",
|
||||
|
||||
@@ -957,7 +957,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fake-agent"
|
||||
version = "3.2.0"
|
||||
version = "3.2.5"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"terminal_size",
|
||||
@@ -2647,7 +2647,7 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "plan2code-app"
|
||||
version = "3.2.0"
|
||||
version = "3.2.5"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"libc",
|
||||
|
||||
@@ -92,8 +92,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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "fake-agent"
|
||||
version = "3.2.0"
|
||||
version = "3.2.5"
|
||||
description = "A stand-in agent program for the Plan2Code app's tests"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "plan2code-app",
|
||||
"version": "3.2.0",
|
||||
"version": "3.2.5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "plan2code-app",
|
||||
"version": "3.2.0",
|
||||
"version": "3.2.5",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "2.12.4",
|
||||
"@xterm/addon-fit": "0.11.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code-app",
|
||||
"version": "3.2.0",
|
||||
"version": "3.2.5",
|
||||
"private": true,
|
||||
"description": "Plan2Code desktop app (Tauri). Separate from the repo root so the root and the web console stay dependency-free.",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "plan2code-app"
|
||||
version = "3.2.0"
|
||||
version = "3.2.5"
|
||||
description = "Plan2Code desktop app"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Plan2Code",
|
||||
"version": "3.2.0",
|
||||
"version": "3.2.5",
|
||||
"identifier": "com.plan2code.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../ui",
|
||||
|
||||
@@ -2101,7 +2101,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) {
|
||||
@@ -2117,13 +2117,45 @@ async function doChangeProject() {
|
||||
restarting = false;
|
||||
currentUrl = null;
|
||||
frameReady = false;
|
||||
afterProjectKnown();
|
||||
// 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?',
|
||||
@@ -2133,7 +2165,7 @@ async function changeProject() {
|
||||
});
|
||||
if (!yes) return;
|
||||
}
|
||||
doChangeProject();
|
||||
doChangeProject(prior);
|
||||
}
|
||||
|
||||
changeProjectBtn.onclick = () => {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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" },
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -9,7 +9,6 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { looksFromMessage, terminalFontStep, TERMINAL_FONT_DEFAULT, TERMINAL_FONT_MIN, TERMINAL_FONT_MAX, splitterFraction, splitterAria, terminalTitle, barFit, terminalAnsi, TERMINAL_ANSI, hexToRgba, helloRetryAction, retryLabel, RETRY_AFTER_SECONDS, attentionSignal, commandSegments, plainCommandText, menuStep, pageNotShownView, pageDetailsLine, redactSessionUrl, barNextSteps, continueKeys, defaultRightFraction, folderName, folderPickerRows, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS, NEW_RELEASE_COMMAND, STILL_WAITING_MS, STILL_WAITING_TEXT, waitingView, friendlyError, endedView, confirmButtons, trapTab, SHORTCUTS, shortcutAction, shortcutLabel, tipWithShortcut, shortcutFromMessage, clipboardAction, releaseAfterCheck, releaseNotesUrl, reasonSentence, UPDATE_RECHECK_MS } from "../plan2code-app/ui/meter.js";
|
||||
@@ -1136,117 +1135,6 @@ test("barFit drops the model text first, then the status line, and only when the
|
||||
assert.deepEqual(barFit({ available: 500, needed: 800 }), { model: false, status: false }, "no parts measured, none claimed");
|
||||
});
|
||||
|
||||
// The app's ui/ folder over HTTP on a free local port, for a test that needs app.js to run.
|
||||
function serveFolder(dir) {
|
||||
const TYPES = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".woff2": "font/woff2" };
|
||||
const server = http.createServer((req, res) => {
|
||||
const file = path.join(dir, decodeURIComponent(new URL(req.url, "http://x").pathname));
|
||||
if (!file.startsWith(dir) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
|
||||
res.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { "content-type": TYPES[path.extname(file)] || "application/octet-stream" });
|
||||
fs.createReadStream(file).pipe(res);
|
||||
});
|
||||
return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server)));
|
||||
}
|
||||
|
||||
test("the bar's step text uses the room the row has; model and status drop before it is cut, and its buttons never shrink", async (t) => {
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1800, height: 600 } });
|
||||
// Later start-up steps trip over the stub's nulls; the bar is wired before them,
|
||||
// and "the model alone drops" below shows fitBar() ran.
|
||||
page.on("pageerror", () => {});
|
||||
// Enough of __TAURI__ for app.js to run, so its real fitBar() lays out the row:
|
||||
// every command answers null (platform_info a platform), every window call resolves.
|
||||
await page.addInitScript(() => {
|
||||
const resolved = () => Promise.resolve();
|
||||
const win = new Proxy({}, { get: () => resolved });
|
||||
const known = {
|
||||
core: { invoke: (cmd) => Promise.resolve(cmd === "platform_info" ? { os: "linux" } : null), Channel: class {} },
|
||||
window: { getCurrentWindow: () => win },
|
||||
event: { listen: () => Promise.resolve(() => {}) },
|
||||
};
|
||||
window.__TAURI__ = new Proxy(known, { get: (all, key) => all[key] || new Proxy({}, { get: () => resolved }) });
|
||||
});
|
||||
// app.js is a module, which Chrome will not load from file://: serve the folder.
|
||||
const server = await serveFolder(path.dirname(INDEX_HTML_PATH));
|
||||
t.after(() => server.close());
|
||||
await page.goto(`http://127.0.0.1:${server.address().port}/index.html`, { waitUntil: "networkidle" });
|
||||
await page.evaluate(() => {
|
||||
const show = (id, text) => {
|
||||
const el = document.getElementById(id);
|
||||
el.hidden = false;
|
||||
if (text !== undefined) el.textContent = text;
|
||||
};
|
||||
document.getElementById("agent-none").hidden = true;
|
||||
show("project-menu-button");
|
||||
document.getElementById("project-name").textContent = "plan2code";
|
||||
show("agent-restart");
|
||||
show("agent-menu-button");
|
||||
document.getElementById("agent-name").textContent = "Claude Code";
|
||||
show("agent-model", "opus 5.5 xhigh");
|
||||
document.getElementById("agent-status").textContent = "Working: reading the plan and every phase file";
|
||||
show("next-step");
|
||||
const text = document.getElementById("next-step-text");
|
||||
text.textContent = "npx fetches it quietly first, which can take a minute or two.";
|
||||
text.className = "is-warn is-busy";
|
||||
show("next-step-button", "Update and restart");
|
||||
show("next-step-more", "+1 more");
|
||||
show("next-step-notes");
|
||||
});
|
||||
const settle = () => page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
|
||||
const measure = () =>
|
||||
page.evaluate(() => {
|
||||
const row = document.getElementById("bar-row");
|
||||
const text = document.getElementById("next-step-text");
|
||||
const box = (id) => document.getElementById(id).getBoundingClientRect();
|
||||
const menu = box("app-menu-button");
|
||||
const buttons = ["next-step-button", "next-step-more", "next-step-notes"].map(box);
|
||||
return {
|
||||
noModel: row.classList.contains("no-model"),
|
||||
noStatus: row.classList.contains("no-status"),
|
||||
cut: text.scrollWidth > text.clientWidth,
|
||||
textWidth: text.clientWidth,
|
||||
buttonWidths: buttons.map((b) => Math.round(b.width)),
|
||||
overlap: buttons.some((b) => b.right > menu.left + 0.5),
|
||||
menuInside: menu.width > 0 && menu.right <= row.getBoundingClientRect().right + 0.5,
|
||||
};
|
||||
});
|
||||
await settle();
|
||||
const wide = await measure();
|
||||
assert.deepEqual([wide.noModel, wide.noStatus, wide.cut], [false, false, false], "a wide window shows everything, the whole line included");
|
||||
assert.ok(wide.textWidth > 320, `wider than the old 320px cap (${wide.textWidth}px)`);
|
||||
const seen = new Set();
|
||||
// Down to the app's minimum width (tauri.conf.json minWidth 960).
|
||||
for (let width = 1800; width >= 960; width -= 20) {
|
||||
await page.setViewportSize({ width, height: 600 });
|
||||
await settle();
|
||||
const at = await measure();
|
||||
if (at.cut) assert.ok(at.noModel && at.noStatus, `${width}px: the line is cut only after the model and status dropped`);
|
||||
if (at.noStatus) assert.ok(at.noModel, `${width}px: the model drops before the status`);
|
||||
assert.deepEqual(at.buttonWidths, wide.buttonWidths, `${width}px: the step buttons keep their width`);
|
||||
assert.equal(at.overlap, false, `${width}px: no step button runs under the menu button`);
|
||||
assert.equal(at.menuInside, true, `${width}px: the menu button stays inside the row`);
|
||||
seen.add(`${at.noModel}/${at.noStatus}/${at.cut}`);
|
||||
}
|
||||
assert.ok(seen.has("true/false/false"), `the model alone drops at some width (${[...seen]})`);
|
||||
assert.ok(seen.has("true/true/true"), `the line is cut at the narrowest widths (${[...seen]})`);
|
||||
assert.equal(await page.evaluate(() => getComputedStyle(document.getElementById("next-step-text")).textOverflow), "ellipsis");
|
||||
// Below the minimum, the row runs out at its end as it always did: the text
|
||||
// has shrunk to nothing, but its buttons are never squeezed under the menu.
|
||||
await page.setViewportSize({ width: 400, height: 600 });
|
||||
await settle();
|
||||
const tight = await measure();
|
||||
assert.deepEqual(tight.buttonWidths, wide.buttonWidths, "400px: the step buttons keep their width");
|
||||
assert.equal(tight.overlap, false, "400px: no step button runs under the menu button");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("the top bar collapses instead of scrolling, and +N more is a button that lists the other steps", () => {
|
||||
assert.doesNotMatch(INDEX_HTML, /#bar-row \{[^}]*overflow-x: auto/, "no sideways scrolling row");
|
||||
assert.match(INDEX_HTML, /#bar-row\.no-model #agent-model, #bar-row\.no-status #agent-status \{ display: none; \}/);
|
||||
|
||||
@@ -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/);
|
||||
|
||||
@@ -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")), []);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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 },
|
||||
]);
|
||||
});
|
||||
@@ -11,8 +11,11 @@
|
||||
"test-check-versions.mjs",
|
||||
"test-getting-started.mjs",
|
||||
"test-git-repo.mjs",
|
||||
"test-install-bench.mjs",
|
||||
"test-install-refs.mjs",
|
||||
"test-install-update.mjs",
|
||||
"test-line-endings.mjs",
|
||||
"test-publish-install-refs.mjs",
|
||||
"test-script-changelog.mjs",
|
||||
"test-script-changes.mjs",
|
||||
"test-script-coverage.mjs",
|
||||
@@ -52,6 +55,7 @@
|
||||
"test-console-stub.mjs",
|
||||
"test-console-wire-budgets.mjs",
|
||||
"test-fast.mjs",
|
||||
"test-install-e2e.mjs",
|
||||
"test-launcher.mjs",
|
||||
"test-standalone-check.mjs",
|
||||
"test-ui-prototype-page.mjs",
|
||||
|
||||
@@ -14,6 +14,11 @@ import { spawn, spawnSync } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
// Imported before anything builds a git fixture: it scrubs the whole test process's git config
|
||||
// (the AGENTS.md failure-log rule), so the ref fixtures below and git agree.
|
||||
import "./skill-script-helpers.mjs";
|
||||
import { createInstallRefFixture } from "./install-ref-fixtures.mjs";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const LAUNCHER = path.join(ROOT, "src", "launcher", "plan2code.js");
|
||||
@@ -60,6 +65,8 @@ function sandbox(clis, { installed, project = true, lookup = true, agents } = {}
|
||||
'require("fs").writeFileSync(require("path").join(__dirname, process.argv[2] + ".json"), JSON.stringify(process.argv.slice(3)));\n' +
|
||||
// The ref the launcher marks its installer runs with, so install.js never redirects them.
|
||||
'if (process.env.PLAN2CODE_INSTALL_REF) require("fs").writeFileSync(require("path").join(__dirname, process.argv[2] + ".ref"), process.env.PLAN2CODE_INSTALL_REF);\n' +
|
||||
// The logical release a fetch ref stands for (an install-vX.Y.Z fetch is still vX.Y.Z).
|
||||
'if (process.env.PLAN2CODE_RELEASE_REF) require("fs").writeFileSync(require("path").join(__dirname, process.argv[2] + ".release"), process.env.PLAN2CODE_RELEASE_REF);\n' +
|
||||
"process.exitCode = Number(process.env.P2C_TEST_EXIT || 0);\n"
|
||||
);
|
||||
for (const cli of clis) {
|
||||
@@ -536,16 +543,137 @@ test("launcher: update --tag reinstalls for a branch, and not for a release tag"
|
||||
assert.ok(args.includes(`${REPO}#v3.0.2`) && !args.includes("--force"), args.join(" "));
|
||||
});
|
||||
|
||||
test("launcher: update --tag installs that ref without asking for the release list", (t) => {
|
||||
test("launcher: update --tag installs the plain release tag when the ref list cannot be read", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
// No tag list is available at all: --tag must not need one.
|
||||
// No tag list is available at all: --tag must not need one, and falls back to the plain tag.
|
||||
const result = box.run(["update", "--tag", "v3.0.2"], { PLAN2CODE_LS_REMOTE_FILE: path.join(box.dir, "missing.txt") });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v3\.0\.2\.\.\./);
|
||||
assert.ok(box.argsOf("npx").includes(`${REPO}#v3.0.2`), box.argsOf("npx").join(" "));
|
||||
});
|
||||
|
||||
/** A fixture's `git ls-remote --tags --heads` answer, written where the launcher reads it in git's place. */
|
||||
function fixtureStub(box, text) {
|
||||
const file = path.join(box.dir, "ls-remote-fixture.txt");
|
||||
fs.writeFileSync(file, text);
|
||||
return { PLAN2CODE_LS_REMOTE_FILE: file };
|
||||
}
|
||||
|
||||
/** What the last npx run got (its arguments, the fetch ref and the release ref it was marked with), cleared for the next run. */
|
||||
function lastInstall(box) {
|
||||
const bin = path.join(box.dir, "bin");
|
||||
const read = (name) => {
|
||||
const file = path.join(bin, name);
|
||||
if (!fs.existsSync(file)) return null;
|
||||
const text = fs.readFileSync(file, "utf8");
|
||||
fs.rmSync(file);
|
||||
return text;
|
||||
};
|
||||
const args = read("npx.json");
|
||||
return { args: args && JSON.parse(args), ref: read("npx.ref"), releaseRef: read("npx.release") };
|
||||
}
|
||||
|
||||
test("launcher: update fetches the newest release's install tag and names the logical release", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["update"], fixtureStub(box, fx.snapshotText()));
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v3\.1\.2\.\.\./);
|
||||
assert.doesNotMatch(result.stdout, /install-v/, "the person reads the release, never the fetch ref");
|
||||
const { args, ref, releaseRef } = lastInstall(box);
|
||||
assert.deepEqual(args, ["--yes", "--allow-git=all", `${REPO}#install-v3.1.2`, "--update"]);
|
||||
assert.equal(ref, "install-v3.1.2");
|
||||
assert.equal(releaseRef, "v3.1.2");
|
||||
});
|
||||
|
||||
test("launcher: update ignores a stale moving release branch and falls back to plain tags when no install tag is advertised", (t) => {
|
||||
const stale = createInstallRefFixture({ releaseVersion: "2.0.0" });
|
||||
t.after(stale.cleanup);
|
||||
const legacy = createInstallRefFixture({ releases: [{ version: "1.0.0" }, { version: "2.0.0", annotated: true }] });
|
||||
t.after(legacy.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["update"], fixtureStub(box, stale.snapshotText())).status, 0);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#install-v3.1.2`, "--update"], ref: "install-v3.1.2", releaseRef: "v3.1.2" });
|
||||
const result = box.run(["update"], fixtureStub(box, legacy.snapshotText()));
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v2\.0\.0\.\.\./);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#v2.0.0`, "--update"], ref: "v2.0.0", releaseRef: "v2.0.0" });
|
||||
});
|
||||
|
||||
test("launcher: update --tag vX.Y.Z rolls back through the install tag when advertised, the plain tag otherwise", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const env = fixtureStub(box, fx.snapshotText());
|
||||
for (const [tag, fetchRef] of [
|
||||
["v2.0.0", "install-v2.0.0"],
|
||||
["v3.1.2", "install-v3.1.2"],
|
||||
["v1.0.0", "v1.0.0"],
|
||||
["v0.9.0", "v0.9.0"],
|
||||
]) {
|
||||
const result = box.run(["update", "--tag", tag], env);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, new RegExp(`Updating Plan2Code to ${tag.replace(/\./g, "\\.")}\\.\\.\\.`));
|
||||
// A release rollback never forces: the installer's own version check decides.
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#${fetchRef}`, "--update"], ref: fetchRef, releaseRef: tag }, tag);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher: update --tag install-vX.Y.Z is read as its release, with a notice; a malformed install-v is refused", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const env = fixtureStub(box, fx.snapshotText());
|
||||
const result = box.run(["update", "--tag", "install-v2.0.0"], env);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /install-v2\.0\.0 is how release v2\.0\.0 is fetched; updating by its release name, v2\.0\.0\./);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v2\.0\.0\.\.\./);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#install-v2.0.0`, "--update"], ref: "install-v2.0.0", releaseRef: "v2.0.0" });
|
||||
for (const bad of ["install-v2", "install-v2.0.0-rc1", "install-vlatest", "install-v"]) {
|
||||
const refused = box.run(["update", "--tag", bad], env);
|
||||
assert.equal(refused.status, 2, bad);
|
||||
assert.match(refused.stderr, /is not a release install tag: use --tag with the release, for example --tag v3\.0\.2/, bad);
|
||||
assert.equal(lastInstall(box).args, null, bad);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher: --main and branch tags force a reinstall and carry no release ref", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
// An inherited release ref must not leak into a run that is not a release.
|
||||
const env = { ...fixtureStub(box, fx.snapshotText()), PLAN2CODE_RELEASE_REF: "v9.9.9" };
|
||||
assert.equal(box.run(["update", "--main"], env).status, 0);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", REPO, "--update", "--force"], ref: "main", releaseRef: null });
|
||||
for (const branch of ["feature/demo", "release", "install-feature"]) {
|
||||
assert.equal(box.run(["update", "--tag", branch], env).status, 0, branch);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#${branch}`, "--update", "--force"], ref: branch, releaseRef: null }, branch);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher: uninstall runs the newest release's installer through its install tag", (t) => {
|
||||
const fx = createInstallRefFixture();
|
||||
t.after(fx.cleanup);
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["uninstall", "--yes"], fixtureStub(box, fx.snapshotText())).status, 0);
|
||||
assert.deepEqual(lastInstall(box), { args: ["--yes", "--allow-git=all", `${REPO}#install-v3.1.2`, "--uninstall", "--yes"], ref: "install-v3.1.2", releaseRef: "v3.1.2" });
|
||||
});
|
||||
|
||||
test("launcher: normalizeUpdateTagInput maps only an exact install tag, refuses a malformed one, leaves the rest", () => {
|
||||
const { normalizeUpdateTagInput } = require(LAUNCHER);
|
||||
assert.deepEqual(normalizeUpdateTagInput("install-v3.10.0"), { ref: "v3.10.0", notice: "install-v3.10.0 is how release v3.10.0 is fetched; updating by its release name, v3.10.0." });
|
||||
assert.match(normalizeUpdateTagInput("install-v3.1").error, /install-v3\.1 is not a release install tag/);
|
||||
for (const ref of ["v3.0.2", "main", "release", "feature/install-v1.0.0", "install-feature"]) assert.deepEqual(normalizeUpdateTagInput(ref), { ref }, ref);
|
||||
});
|
||||
|
||||
test("launcher: update --force reaches the installer", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
@@ -695,7 +823,10 @@ test("launcher: on Windows the saved user PATH fills in folders the inherited PA
|
||||
addSavedWindowsPath();
|
||||
const dirs = process.env[pathKey].split(";");
|
||||
assert.equal(dirs[0], "C:\\stale-terminal-path", "the inherited PATH keeps its place in front");
|
||||
assert.ok(dirs.includes(first), `${first} is added from the saved PATH`);
|
||||
// Compared as the launcher dedupes them: the machine PATH may already hold the
|
||||
// same folder spelled another way (a trailing backslash, another case), and that copy wins.
|
||||
const id = (dir) => path.resolve(dir.replace(/^"|"$/g, "")).toLowerCase();
|
||||
assert.ok(dirs.map(id).includes(id(first)), `${first} is added from the saved PATH`);
|
||||
const length = dirs.length;
|
||||
addSavedWindowsPath();
|
||||
assert.equal(process.env[pathKey].split(";").length, length, "a second call adds nothing twice");
|
||||
@@ -1793,8 +1924,8 @@ test("launcher menus: the agent tip shows once, and the model menu prints ids in
|
||||
assert.doesNotMatch(first.stdout, /That runs outside the desktop app/, "no app installed, so no line about it");
|
||||
// ids padded to the longest (opusplan), then the description; the first run's Enter is the agent's.
|
||||
assert.match(first.stdout, /^ {2}1\) default {3}your account setting$/m);
|
||||
assert.match(first.stdout, /^ {2}2\) sonnet {4}latest Sonnet$/m);
|
||||
assert.match(first.stdout, /^ {2}5\) opusplan {2}Opus in plan mode, Sonnet otherwise$/m);
|
||||
assert.match(first.stdout, /^ {2}3\) sonnet {4}latest Sonnet$/m);
|
||||
assert.match(first.stdout, /^ {2}7\) opusplan {2}Opus in plan mode, Sonnet otherwise$/m);
|
||||
assert.match(first.stdout, /Choice \[agent default\]: /);
|
||||
assert.ok(box.argsOf("claude").includes("opus"), "a typed description picks its model");
|
||||
const state = JSON.parse(fs.readFileSync(box.stateFile, "utf8"));
|
||||
@@ -1806,8 +1937,8 @@ test("launcher menus: the agent tip shows once, and the model menu prints ids in
|
||||
assert.equal(second.status, 0, second.stderr);
|
||||
assert.equal(second.sent, 3, second.stdout);
|
||||
assert.doesNotMatch(second.stdout, /skip this launcher/);
|
||||
assert.match(second.stdout, /^ {2}3\) opus {6}latest Opus \(last used\)$/m);
|
||||
assert.match(second.stdout, /Choice \[3\]: /);
|
||||
assert.match(second.stdout, /^ {2}4\) opus {6}latest Opus \(last used\)$/m);
|
||||
assert.match(second.stdout, /Choice \[4\]: /);
|
||||
assert.ok(box.argsOf("claude").includes("opus"));
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,595 @@
|
||||
// Tests for scripts/publish-install-refs.mjs, the release workflow's slim
|
||||
// install ref publisher, against local fixtures: a bare `origin.git` and a
|
||||
// full source checkout beside it in the OS temp dir. Every push goes to that
|
||||
// bare repository, never anywhere else. Also checks the shape of the
|
||||
// release-app workflow's publish job. Run with:
|
||||
// node --test scripts/test-publish-install-refs.mjs
|
||||
//
|
||||
// skill-script-helpers.mjs is imported first on purpose: it scrubs the whole
|
||||
// test process's git config, so the fixtures and the spawned publisher agree
|
||||
// (the AGENTS.md failure-log rule). The scrubbed config names no user, which
|
||||
// also exercises the publisher's stand-in commit identity.
|
||||
|
||||
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 crypto from "node:crypto";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
|
||||
import { ROOT, scrubbedEnv } from "./skill-script-helpers.mjs";
|
||||
import {
|
||||
GIT_DEP_LIFECYCLE,
|
||||
INSTALL_REF_MANIFEST,
|
||||
RUNTIME_PAYLOAD,
|
||||
runtimePayloadAllowlist,
|
||||
isAllowedPayloadPath,
|
||||
workflowSkillSources,
|
||||
assemblePayload,
|
||||
validatePayload,
|
||||
parseArgs,
|
||||
} from "./publish-install-refs.mjs";
|
||||
|
||||
const SCRIPT = path.join(ROOT, "scripts", "publish-install-refs.mjs");
|
||||
const WORKFLOW = path.join(ROOT, ".github", "workflows", "release-app.yml");
|
||||
const env = scrubbedEnv();
|
||||
|
||||
const git = (dir, args, options = {}) => execFileSync("git", ["-C", dir, ...args], { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], env, ...options }).trim();
|
||||
const gitOk = (dir, args) => spawnSync("git", ["-C", dir, ...args], { env, encoding: "utf8" }).status === 0;
|
||||
const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
|
||||
|
||||
const INSTALL_JS = `// fixture installer
|
||||
const SHARED_SCRIPTS_ALWAYS = ['common.mjs'];
|
||||
const SOURCE_PROMPTS = [
|
||||
{
|
||||
source: 'plan2code.md',
|
||||
scripts: ['lessons.mjs'],
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/lessons.md', target: 'lessons.md' }
|
||||
]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-3-implement.md',
|
||||
scripts: ['specs.mjs', 'lessons.mjs'],
|
||||
additionalReferences: [{ source: 'shared-references/test-runs.md', target: 'test-runs.md' }]
|
||||
}
|
||||
];
|
||||
module.exports = { SOURCE_PROMPTS };
|
||||
`;
|
||||
|
||||
// Bytes git must carry through unchanged: CRLF, a NUL and high bytes.
|
||||
const BINARY = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff, 0xfe, 0x0d, 0x0a]);
|
||||
|
||||
/** The runtime files of a release commit, `{ path: { content, mode? } }`. */
|
||||
function runtimeTree(version) {
|
||||
return {
|
||||
"install.js": { content: INSTALL_JS },
|
||||
"package.json": { content: json({ name: "plan2code", version }) },
|
||||
"version.json": { content: json({ name: "Plan2Code", version, releaseDate: "2026-12-01" }) },
|
||||
"LICENSE": { content: "license\n" },
|
||||
"NOTICE": { content: "notice\n" },
|
||||
"src/launcher/plan2code.js": { content: `#!/usr/bin/env node\n// launcher ${version}\n`, mode: "100755" },
|
||||
"src/web-console/update-check.mjs": { content: `// update-check ${version}\n` },
|
||||
"src/web-console/console.mjs": { content: `// console ${version}\n` },
|
||||
"src/web-console/public/logo.png": { content: BINARY },
|
||||
"src/installer/timing.js": { content: "// timing\n" },
|
||||
"src/installer/skills-cli.js": { content: "// skills-cli\n" },
|
||||
"src/installer/canonical-skills.js": { content: "// canonical-skills\n" },
|
||||
"src/installer/console-stage.js": { content: "// console-stage\n" },
|
||||
"src/web-console-stub/console.mjs": { content: "// stub\n" },
|
||||
"src/statusline-claude/statusline.js": { content: "// statusline\n" },
|
||||
"src/launcher/models.json": { content: "{}\n" },
|
||||
"src/launcher/agents.json": { content: "{}\n" },
|
||||
"src/web-console/agent-lookup.mjs": { content: "// agent-lookup\n" },
|
||||
"src/launcher/plan2code.ico": { content: BINARY },
|
||||
"src/web-console/public/favicon.png": { content: BINARY },
|
||||
"src/plan2code.md": { content: "# Dashboard\n" },
|
||||
"src/plan2code-3-implement.md": { content: "# Implement\r\nCRLF kept as committed\r\n" },
|
||||
"src/skill-scripts/common.mjs": { content: "// common\n" },
|
||||
"src/skill-scripts/lessons.mjs": { content: "// lessons\n" },
|
||||
"src/skill-scripts/specs.mjs": { content: "// specs\n" },
|
||||
"src/shared-references/lessons.md": { content: "# Lessons\n" },
|
||||
"src/shared-references/test-runs.md": { content: "# Test runs\n" },
|
||||
};
|
||||
}
|
||||
|
||||
/** What a full checkout also carries and the payload must leave out. */
|
||||
const HEAVY = {
|
||||
"README.md": { content: "# readme\n" },
|
||||
"CHANGELOG.md": { content: "# changelog\n" },
|
||||
"docs/promo.md": { content: "# heavy docs\n" },
|
||||
"scripts/publish-install-refs.mjs": { content: "// the publisher itself\n" },
|
||||
"specs/idea/overview.md": { content: "# spec\n" },
|
||||
"skills/plan2code/SKILL.md": { content: "# built skill\n" },
|
||||
"plan2code-app/package.json": { content: "{}\n" },
|
||||
"plan2code-metrics/index.js": { content: "// metrics\n" },
|
||||
"plan2code-bot/index.js": { content: "// bot\n" },
|
||||
".github/workflows/release-app.yml": { content: "name: release-app\n" },
|
||||
"src/node_modules/junk/index.js": { content: "// vendored junk\n" },
|
||||
"src/web-console/fixtures/sample.json": { content: "{}\n" },
|
||||
};
|
||||
|
||||
const fullTree = (version) => ({ ...runtimeTree(version), ...HEAVY });
|
||||
|
||||
const data = (content) => {
|
||||
const buf = Buffer.isBuffer(content) ? content : Buffer.from(content);
|
||||
return Buffer.concat([Buffer.from(`data ${buf.length}\n`), buf, Buffer.from("\n")]);
|
||||
};
|
||||
|
||||
/**
|
||||
* A source checkout `work/` whose origin is a bare `origin.git`, both in one
|
||||
* temp folder. `release: "legacy"` gives origin a full-source release branch
|
||||
* (the pre-migration shape); `"none"` gives it none.
|
||||
*/
|
||||
function createSource({ release = "legacy" } = {}) {
|
||||
const root = fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), "p2c-publish-refs-"));
|
||||
const work = path.join(root, "work");
|
||||
const origin = path.join(root, "origin.git");
|
||||
execFileSync("git", ["init", "-q", "--bare", "-b", "main", origin], { env, stdio: "pipe" });
|
||||
execFileSync("git", ["init", "-q", "-b", "main", work], { env, stdio: "pipe" });
|
||||
git(work, ["remote", "add", "origin", origin]);
|
||||
let ts = 1700000000;
|
||||
|
||||
/** Commits `files` as the whole tree of main (optionally tagging it), pushes, and checks it out. */
|
||||
function commit(files, { tag = null, annotated = false, message = "commit" } = {}) {
|
||||
ts += 60;
|
||||
const parent = gitOk(work, ["rev-parse", "--verify", "--quiet", "refs/heads/main"]) ? git(work, ["rev-parse", "refs/heads/main"]) : null;
|
||||
const who = `Fixture <fixture@example.com> ${ts} +0000`;
|
||||
const parts = [Buffer.from(`commit refs/heads/main\nauthor ${who}\ncommitter ${who}\n`), data(message)];
|
||||
if (parent) parts.push(Buffer.from(`from ${parent}\n`));
|
||||
parts.push(Buffer.from("deleteall\n"));
|
||||
for (const [name, { content, mode = "100644" }] of Object.entries(files)) parts.push(Buffer.from(`M ${mode} inline ${name}\n`), data(content));
|
||||
if (tag && annotated) parts.push(Buffer.from(`tag ${tag}\nfrom refs/heads/main\ntagger ${who}\n`), data(`release ${tag}\n`));
|
||||
git(work, ["fast-import", "--quiet"], { input: Buffer.concat(parts) });
|
||||
if (tag && !annotated) git(work, ["update-ref", `refs/tags/${tag}`, "refs/heads/main"]);
|
||||
git(work, ["checkout", "-q", "-f", "main"]);
|
||||
git(work, ["push", "-q", "origin", "main", ...(tag ? [`refs/tags/${tag}`] : [])]);
|
||||
return git(work, ["rev-parse", "HEAD"]);
|
||||
}
|
||||
|
||||
let legacyTip = null;
|
||||
if (release === "legacy") {
|
||||
legacyTip = commit(fullTree("1.0.0"), { tag: "v1.0.0", message: "legacy release 1.0.0" });
|
||||
git(work, ["push", "-q", "origin", `${legacyTip}:refs/heads/release`]);
|
||||
}
|
||||
|
||||
return {
|
||||
root,
|
||||
work,
|
||||
origin,
|
||||
legacyTip,
|
||||
commit,
|
||||
/** Commits a full tree for `version`, tagged `vX.Y.Z`; `mutate(files)` edits it first. */
|
||||
release(version, { annotated = false, mutate } = {}) {
|
||||
const files = fullTree(version);
|
||||
if (mutate) mutate(files);
|
||||
return commit(files, { tag: `v${version}`, annotated, message: `release ${version}` });
|
||||
},
|
||||
remoteRef: (ref) => {
|
||||
const out = git(origin, ["for-each-ref", "--format=%(objectname)", ref]);
|
||||
return out || null;
|
||||
},
|
||||
cleanup: () => fs.rmSync(root, { recursive: true, force: true }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs the publisher CLI from the checkout; `result` is its --json output when it wrote one. */
|
||||
function publish(fx, args) {
|
||||
const jsonPath = path.join(fx.root, `result-${crypto.randomBytes(3).toString("hex")}.json`);
|
||||
const r = spawnSync(process.execPath, [SCRIPT, "--repo", fx.work, "--json", jsonPath, ...args], { cwd: fx.work, env, encoding: "utf8" });
|
||||
const result = fs.existsSync(jsonPath) ? JSON.parse(fs.readFileSync(jsonPath, "utf8")) : null;
|
||||
return { status: r.status, stdout: r.stdout, stderr: r.stderr, result };
|
||||
}
|
||||
|
||||
/** `{ path: mode }` of every file in a commit's tree in origin. */
|
||||
function remoteTree(fx, commit) {
|
||||
const out = git(fx.origin, ["ls-tree", "-r", "--full-tree", commit]);
|
||||
const files = {};
|
||||
for (const line of out.split("\n").filter(Boolean)) {
|
||||
const [meta, name] = line.split("\t");
|
||||
files[name] = meta.split(" ")[0];
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
const indexHash = (fx) => crypto.createHash("sha256").update(fs.readFileSync(path.join(fx.work, ".git", "index"))).digest("hex");
|
||||
|
||||
test("allowlist: one constant-driven structure of explicit files and prefixes", () => {
|
||||
const allow = runtimePayloadAllowlist();
|
||||
assert.equal(allow, RUNTIME_PAYLOAD);
|
||||
assert.deepEqual([...allow.files], ["install.js", "package.json", "version.json", "LICENSE", "NOTICE"]);
|
||||
assert.deepEqual([...allow.prefixes], ["src/"]);
|
||||
assert.ok(Object.isFrozen(allow) && Object.isFrozen(allow.files) && Object.isFrozen(allow.required));
|
||||
for (const ok of ["install.js", "src/launcher/plan2code.js", "src/web-console/public/activities/snake.js"]) assert.equal(isAllowedPayloadPath(ok), true, ok);
|
||||
for (const bad of ["README.md", "docs/a.md", "scripts/publish-install-refs.mjs", "specs/x.md", "skills/a/SKILL.md", "plan2code-app/x", "plan2code-metrics/x", "plan2code-bot/x", ".github/x.yml", ".git/HEAD", "src/node_modules/a.js", "src/x/fixtures/a.json", "src/", "src/../install.js", "src\\a.js", ""]) {
|
||||
assert.equal(isAllowedPayloadPath(bad), false, bad);
|
||||
}
|
||||
});
|
||||
|
||||
test("allowlist: every skill build input comes from install.js's SOURCE_PROMPTS", () => {
|
||||
assert.deepEqual(workflowSkillSources(INSTALL_JS), [
|
||||
"src/plan2code.md",
|
||||
"src/plan2code-3-implement.md",
|
||||
"src/skill-scripts/lessons.mjs",
|
||||
"src/skill-scripts/specs.mjs",
|
||||
"src/skill-scripts/common.mjs",
|
||||
"src/web-console",
|
||||
"src/shared-references/lessons.md",
|
||||
"src/shared-references/test-runs.md",
|
||||
]);
|
||||
assert.deepEqual(workflowSkillSources("// no prompts here\n"), []);
|
||||
// The real installer: every input it names exists in this checkout's src/.
|
||||
const real = workflowSkillSources(fs.readFileSync(path.join(ROOT, "install.js"), "utf8"));
|
||||
assert.ok(real.includes("src/plan2code-3-implement-review.md") && real.includes("src/skill-scripts/specs.mjs") && real.includes("src/web-console"));
|
||||
for (const rel of real) assert.ok(fs.existsSync(path.join(ROOT, ...rel.split("/"))), rel);
|
||||
});
|
||||
|
||||
test("arguments: unknown, missing and malformed arguments print the usage and exit 2", () => {
|
||||
assert.equal(parseArgs(["--tag", "v1.2.3", "--dry-run"]).options.dryRun, true);
|
||||
assert.match(parseArgs(["--tag", "1.2.3"]).error, /exact vX\.Y\.Z/);
|
||||
assert.match(parseArgs(["--tag", "v1.2"]).error, /exact vX\.Y\.Z/);
|
||||
assert.match(parseArgs(["--tag", "install-v1.2.3"]).error, /exact vX\.Y\.Z/);
|
||||
assert.match(parseArgs([]).error, /--tag is required/);
|
||||
assert.match(parseArgs(["--tag"]).error, /needs a value/);
|
||||
for (const args of [["--tag", "v1.2.3", "--force"], ["--tag", "v1.2.3-rc.1"], ["--repo", "."]]) {
|
||||
const r = spawnSync(process.execPath, [SCRIPT, ...args], { env, encoding: "utf8" });
|
||||
assert.equal(r.status, 2, args.join(" "));
|
||||
assert.match(r.stderr, /Usage: node scripts\/publish-install-refs\.mjs/);
|
||||
}
|
||||
});
|
||||
|
||||
test("the real repository can be published: no lifecycle script npm would prepare a git package for, and every required file is here", () => {
|
||||
const root = ROOT;
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
|
||||
assert.deepEqual(Object.keys(pkg.scripts || {}).filter((name) => GIT_DEP_LIFECYCLE.has(name)), [], "rename the script: the release run refuses it after the release is public");
|
||||
const required = [...RUNTIME_PAYLOAD.required, ...workflowSkillSources(fs.readFileSync(path.join(root, "install.js"), "utf8"))];
|
||||
assert.deepEqual(required.filter((rel) => !fs.existsSync(path.join(root, rel))), []);
|
||||
});
|
||||
|
||||
test("first publication: parents the legacy release tip, pushes one slim commit to both refs", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
const tagCommit = fx.release("1.2.0");
|
||||
const statusBefore = git(fx.work, ["status", "--porcelain"]);
|
||||
const indexBefore = indexHash(fx);
|
||||
|
||||
const r = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
const res = r.result;
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(res.pushed, true);
|
||||
assert.equal(res.parent, fx.legacyTip, "the first migration parents the legacy full-source tip");
|
||||
assert.equal(res.parentKind, "release");
|
||||
assert.equal(res.sourceCommit, tagCommit);
|
||||
assert.deepEqual(res.refs, { tag: "refs/tags/install-v1.2.0", branch: "refs/heads/release" });
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), res.commit);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), res.commit);
|
||||
assert.equal(git(fx.origin, ["rev-parse", `${res.commit}^{tree}`]), res.tree);
|
||||
assert.equal(git(fx.origin, ["rev-parse", `${res.commit}^1`]), fx.legacyTip);
|
||||
assert.equal(gitOk(fx.origin, ["rev-parse", "--verify", "--quiet", `${res.commit}^2`]), false, "exactly one parent");
|
||||
assert.match(r.stdout, /Published [0-9a-f]{40}/);
|
||||
|
||||
const files = remoteTree(fx, res.commit);
|
||||
const expected = [...Object.keys(runtimeTree("1.2.0")), INSTALL_REF_MANIFEST].sort();
|
||||
assert.deepEqual(Object.keys(files).sort(), expected, "exactly the runtime allowlist plus the manifest");
|
||||
assert.equal(files["src/launcher/plan2code.js"], "100755", "the executable bit survives");
|
||||
assert.equal(files["install.js"], "100644");
|
||||
assert.equal(res.files, expected.length);
|
||||
assert.ok(res.excluded >= Object.keys(HEAVY).length);
|
||||
|
||||
const blob = (name) => execFileSync("git", ["-C", fx.origin, "cat-file", "blob", `${res.commit}:${name}`], { env });
|
||||
assert.deepEqual(blob("src/web-console/public/logo.png"), BINARY, "binary bytes are carried unchanged");
|
||||
assert.equal(blob("src/plan2code-3-implement.md").toString(), "# Implement\r\nCRLF kept as committed\r\n");
|
||||
assert.equal(res.bytes, expected.reduce((sum, name) => sum + blob(name).length, 0));
|
||||
|
||||
const manifest = JSON.parse(blob(INSTALL_REF_MANIFEST).toString());
|
||||
assert.deepEqual(Object.keys(manifest), ["kind", "version", "sourceTag", "sourceCommit", "files"]);
|
||||
assert.equal(manifest.kind, "install-ref");
|
||||
assert.equal(manifest.version, "1.2.0");
|
||||
assert.equal(manifest.sourceTag, "v1.2.0");
|
||||
assert.equal(manifest.sourceCommit, tagCommit);
|
||||
assert.equal(manifest.files[INSTALL_REF_MANIFEST], undefined, "the manifest never lists itself");
|
||||
assert.deepEqual(Object.keys(manifest.files).sort(), Object.keys(runtimeTree("1.2.0")).sort());
|
||||
for (const [name, hash] of Object.entries(manifest.files)) {
|
||||
assert.equal(hash, crypto.createHash("sha256").update(blob(name)).digest("hex"), name);
|
||||
}
|
||||
|
||||
assert.equal(git(fx.work, ["status", "--porcelain"]), statusBefore, "the working tree is untouched");
|
||||
assert.equal(indexHash(fx), indexBefore, "the normal index is untouched");
|
||||
assert.deepEqual(fs.readdirSync(path.join(fx.work, ".git")).filter((n) => n.startsWith("p2c-install-index")), [], "the temporary index is removed");
|
||||
assert.equal(git(fx.origin, ["log", "-1", "--format=%an <%ae>", res.commit]), "github-actions[bot] <41898099+github-actions[bot]@users.noreply.github.com>");
|
||||
});
|
||||
|
||||
test("subsequent publication: parents the previous synthetic commit and fast-forwards release", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0");
|
||||
const first = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(first.status, 0, first.stderr);
|
||||
git(fx.work, ["fetch", "-q", "--no-tags", "origin", "+refs/heads/release:refs/remotes/origin/release"]);
|
||||
|
||||
const tagCommit = fx.release("1.3.0");
|
||||
const second = publish(fx, ["--tag", "v1.3.0"]);
|
||||
assert.equal(second.status, 0, second.stderr);
|
||||
assert.equal(second.result.parent, first.result.commit, "the synthetic chain, never the full-source commit");
|
||||
assert.notEqual(second.result.parent, tagCommit);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), second.result.commit);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), first.result.commit, "the older install tag stays where it was");
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.3.0"), second.result.commit);
|
||||
assert.equal(gitOk(fx.origin, ["merge-base", "--is-ancestor", first.result.commit, second.result.commit]), true);
|
||||
});
|
||||
|
||||
test("the release tip must be in the checkout: an unfetched tip fails before anything is pushed", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0");
|
||||
// Another runner moved origin's release branch to a commit this checkout never fetched.
|
||||
const elsewhere = path.join(fx.root, "elsewhere");
|
||||
execFileSync("git", ["clone", "-q", fx.origin, elsewhere], { env, stdio: "pipe" });
|
||||
git(elsewhere, ["-c", "user.name=x", "-c", "user.email=x@example.com", "commit", "-q", "--allow-empty", "-m", "moved"]);
|
||||
git(elsewhere, ["push", "-q", "origin", "HEAD:refs/heads/release"]);
|
||||
const moved = fx.remoteRef("refs/heads/release");
|
||||
|
||||
const r = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(r.status, 1);
|
||||
assert.match(r.stderr, /fetch refs\/heads\/release first/);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), moved);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), null);
|
||||
});
|
||||
|
||||
test("tag collision: an existing install tag, remote or local, is never overwritten", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0");
|
||||
const first = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(first.status, 0, first.stderr);
|
||||
|
||||
// A second run for the same, fully published release (the workflow has more than one trigger)
|
||||
// succeeds and pushes nothing, rather than failing red after a good release.
|
||||
const again = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(again.status, 0, again.stderr);
|
||||
assert.equal(again.result.alreadyPublished, true);
|
||||
assert.equal(again.result.pushed, false);
|
||||
assert.match(again.stdout, /v1\.2\.0 is already published/);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), first.result.commit);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), first.result.commit);
|
||||
|
||||
git(fx.work, ["fetch", "-q", "--no-tags", "origin", "+refs/heads/release:refs/remotes/origin/release"]);
|
||||
fx.release("1.3.0");
|
||||
git(fx.work, ["tag", "install-v1.3.0", "HEAD"]);
|
||||
const local = publish(fx, ["--tag", "v1.3.0"]);
|
||||
assert.equal(local.status, 1);
|
||||
assert.match(local.stderr, /already exists in this checkout/);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.3.0"), null);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), first.result.commit);
|
||||
});
|
||||
|
||||
test("missing release branch: refused without the allowance, parents the source tag commit with it", (t) => {
|
||||
const fx = createSource({ release: "none" });
|
||||
t.after(fx.cleanup);
|
||||
const tagCommit = fx.release("1.2.0");
|
||||
|
||||
const refused = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(refused.status, 1);
|
||||
assert.match(refused.stderr, /refs\/heads\/release does not exist on origin; pass --allow-missing-release-branch/);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), null);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), null);
|
||||
|
||||
const allowed = publish(fx, ["--tag", "v1.2.0", "--allow-missing-release-branch"]);
|
||||
assert.equal(allowed.status, 0, allowed.stderr);
|
||||
assert.equal(allowed.result.parent, tagCommit);
|
||||
assert.equal(allowed.result.parentKind, "source-tag");
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), allowed.result.commit);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), allowed.result.commit);
|
||||
});
|
||||
|
||||
test("payload contamination: validation lists every unexpected path and forbidden top-level entry", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
const tagCommit = fx.release("1.2.0");
|
||||
const out = path.join(fx.root, "payload");
|
||||
const { modes, excluded } = assemblePayload({ repo: fx.work, commit: tagCommit, output: out });
|
||||
assert.equal(modes["src/launcher/plan2code.js"], "100755");
|
||||
assert.equal(excluded, Object.keys(HEAVY).length);
|
||||
const clean = validatePayload(out);
|
||||
assert.equal(clean.ok, true, clean.report.join("\n"));
|
||||
assert.equal(clean.manifest, false);
|
||||
|
||||
for (const name of ["docs/promo.md", "scripts/publish-install-refs.mjs", "README.md", "src/node_modules/junk/index.js", "plan2code-bot/index.js"]) {
|
||||
fs.mkdirSync(path.dirname(path.join(out, name)), { recursive: true });
|
||||
fs.writeFileSync(path.join(out, name), "contamination\n");
|
||||
}
|
||||
const dirty = validatePayload(out);
|
||||
assert.equal(dirty.ok, false);
|
||||
assert.deepEqual(dirty.unexpected, ["README.md", "docs/promo.md", "plan2code-bot/index.js", "scripts/publish-install-refs.mjs", "src/node_modules/junk/index.js"]);
|
||||
assert.deepEqual(dirty.forbidden, ["docs", "scripts", "plan2code-bot"]);
|
||||
assert.ok(dirty.report.includes("+ docs/promo.md"));
|
||||
assert.ok(dirty.report.includes("+ docs/ (forbidden top-level entry)"));
|
||||
|
||||
// An --output folder that already holds anything is refused before assembly.
|
||||
const r = publish(fx, ["--tag", "v1.2.0", "--output", out, "--dry-run"]);
|
||||
assert.equal(r.status, 1);
|
||||
assert.match(r.stderr, /is not empty/);
|
||||
});
|
||||
|
||||
test("missing required runtime files: the diff-like report names each one and nothing is pushed", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0", {
|
||||
mutate: (files) => {
|
||||
delete files["src/installer/console-stage.js"];
|
||||
delete files["src/plan2code-3-implement.md"];
|
||||
delete files["src/skill-scripts/specs.mjs"];
|
||||
delete files["src/shared-references/test-runs.md"];
|
||||
// The whole src/web-console folder, a reference SOURCE_PROMPTS names.
|
||||
delete files["src/web-console/console.mjs"];
|
||||
delete files["src/web-console/update-check.mjs"];
|
||||
delete files["src/web-console/public/logo.png"];
|
||||
delete files["src/web-console/agent-lookup.mjs"];
|
||||
delete files["src/web-console/public/favicon.png"];
|
||||
},
|
||||
});
|
||||
const r = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(r.status, 1);
|
||||
assert.match(r.stderr, /runtime payload of v1\.2\.0 is not valid/);
|
||||
const reported = [
|
||||
"src/installer/console-stage.js",
|
||||
"src/plan2code-3-implement.md",
|
||||
"src/shared-references/test-runs.md",
|
||||
"src/skill-scripts/specs.mjs",
|
||||
"src/web-console",
|
||||
"src/web-console/agent-lookup.mjs",
|
||||
"src/web-console/console.mjs",
|
||||
"src/web-console/public/favicon.png",
|
||||
"src/web-console/update-check.mjs",
|
||||
];
|
||||
for (const name of reported) {
|
||||
assert.match(r.stderr, new RegExp(`^- ${name.replace(/\./g, "\\.")}$`, "m"), name);
|
||||
}
|
||||
assert.deepEqual(
|
||||
r.result.details.filter((l) => l.startsWith("- ")),
|
||||
reported.map((name) => `- ${name}`),
|
||||
);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), null);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), fx.legacyTip);
|
||||
});
|
||||
|
||||
test("version mismatch: version.json, package.json and the checkout's HEAD must all agree with the tag", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0", { mutate: (files) => (files["package.json"] = { content: json({ name: "plan2code", version: "1.2.1" }) }) });
|
||||
const pkg = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(pkg.status, 1);
|
||||
assert.match(pkg.stderr, /do not match the tag v1\.2\.0: package\.json says 1\.2\.1/);
|
||||
|
||||
fx.release("1.3.0", { mutate: (files) => (files["version.json"] = { content: json({ version: "1.2.9" }) }) });
|
||||
const ver = publish(fx, ["--tag", "v1.3.0"]);
|
||||
assert.equal(ver.status, 1);
|
||||
assert.match(ver.stderr, /version\.json says 1\.2\.9/);
|
||||
|
||||
fx.release("1.4.0");
|
||||
fx.commit(fullTree("1.4.0"), { message: "work after the tag" });
|
||||
const head = publish(fx, ["--tag", "v1.4.0"]);
|
||||
assert.equal(head.status, 1);
|
||||
assert.match(head.stderr, /the checkout's HEAD [0-9a-f]{40} is not the commit v1\.4\.0 names/);
|
||||
|
||||
const missing = publish(fx, ["--tag", "v9.9.9"]);
|
||||
assert.equal(missing.status, 1);
|
||||
assert.match(missing.stderr, /the tag v9\.9\.9 does not exist/);
|
||||
|
||||
for (const ref of ["refs/tags/install-v1.2.0", "refs/tags/install-v1.3.0", "refs/tags/install-v1.4.0"]) assert.equal(fx.remoteRef(ref), null, ref);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), fx.legacyTip);
|
||||
});
|
||||
|
||||
test("annotated and lightweight source tags both resolve to their commit", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
const light = fx.release("1.2.0");
|
||||
assert.equal(git(fx.work, ["cat-file", "-t", "refs/tags/v1.2.0"]), "commit");
|
||||
const a = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(a.status, 0, a.stderr);
|
||||
assert.equal(a.result.sourceCommit, light);
|
||||
|
||||
git(fx.work, ["fetch", "-q", "--no-tags", "origin", "+refs/heads/release:refs/remotes/origin/release"]);
|
||||
const annotatedCommit = fx.release("1.3.0", { annotated: true });
|
||||
assert.equal(git(fx.work, ["cat-file", "-t", "refs/tags/v1.3.0"]), "tag");
|
||||
const b = publish(fx, ["--tag", "v1.3.0"]);
|
||||
assert.equal(b.status, 0, b.stderr);
|
||||
assert.equal(b.result.sourceCommit, annotatedCommit, "the annotated tag peels to its commit");
|
||||
const manifest = JSON.parse(execFileSync("git", ["-C", fx.origin, "cat-file", "blob", `${b.result.commit}:${INSTALL_REF_MANIFEST}`], { env, encoding: "utf8" }));
|
||||
assert.equal(manifest.sourceCommit, annotatedCommit);
|
||||
});
|
||||
|
||||
test("dry run: builds and checks the commit, pushes nothing, keeps --output", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0");
|
||||
const out = path.join(fx.root, "kept-payload");
|
||||
const r = publish(fx, ["--tag", "v1.2.0", "--dry-run", "--output", out]);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(r.result.dryRun, true);
|
||||
assert.equal(r.result.pushed, false);
|
||||
assert.match(r.stdout, /^Would publish [0-9a-f]{40}/);
|
||||
assert.equal(r.result.payload, out);
|
||||
assert.equal(fs.existsSync(path.join(out, INSTALL_REF_MANIFEST)), true);
|
||||
assert.equal(git(fx.work, ["cat-file", "-t", r.result.commit]), "commit", "the commit exists locally");
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), null);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), fx.legacyTip);
|
||||
});
|
||||
|
||||
/** The publish job's steps from release-app.yml, `[{ name, text }]` in order. */
|
||||
function publishSteps() {
|
||||
const yml = fs.readFileSync(WORKFLOW, "utf8").replace(/\r\n/g, "\n");
|
||||
const job = yml.slice(yml.indexOf("\n publish:\n"));
|
||||
assert.ok(job.length > 1, "release-app.yml has a publish job");
|
||||
const steps = job.slice(job.indexOf("\n steps:\n")).split("\n - ").slice(1);
|
||||
return { yml, steps: steps.map((text) => ({ name: (/^(?:name:\s*(.+)|uses:\s*(.+))/.exec(text) || [])[1] || text.split("\n")[0], text })) };
|
||||
}
|
||||
|
||||
test("release workflow: synthetic-ref publication is the publish job's last step, after the release is public", () => {
|
||||
const { yml, steps } = publishSteps();
|
||||
const names = steps.map((s) => s.name.trim());
|
||||
const attach = names.indexOf("Attach to the release, creating it last");
|
||||
const pub = names.indexOf("Publish the slim install refs");
|
||||
assert.ok(attach !== -1, "the step that creates and publishes the release is there");
|
||||
assert.ok(pub > attach, "publication comes after the release is public");
|
||||
assert.equal(pub, steps.length - 1, "publication is the last step");
|
||||
assert.match(steps[attach].text, /gh release edit "\$TAG" --draft=false/);
|
||||
const run = steps[pub].text;
|
||||
assert.match(steps[0].text, /persist-credentials:\s*false/, "the publish checkout does not persist the workflow token in .git/config");
|
||||
assert.match(run, /GIT_ASKPASS="\$RUNNER_TEMP\/p2c-git-askpass\.sh"/);
|
||||
assert.match(run, /GIT_TERMINAL_PROMPT=0/);
|
||||
assert.match(run, /GCM_INTERACTIVE=never/);
|
||||
assert.match(run, /credential\.username x-access-token/);
|
||||
assert.doesNotMatch(run, /extraheader|credential-helper output/, "no token or credential-helper output is written or echoed");
|
||||
assert.match(run, /node scripts\/publish-install-refs\.mjs --tag "\$TAG" --repo "\$GITHUB_WORKSPACE"/);
|
||||
assert.match(run, /git fetch --no-tags --unshallow origin/);
|
||||
assert.match(run, /refs\/heads\/release:refs\/remotes\/origin\/release/);
|
||||
assert.match(run, /refs\/tags\/\$\{TAG\}:refs\/tags\/\$\{TAG\}/);
|
||||
assert.doesNotMatch(run, /continue-on-error|\|\| true/, "a failed publication fails the workflow");
|
||||
assert.equal(names.includes("Move the release branch to this tag"), false, "the old branch move is gone");
|
||||
const code = yml
|
||||
.split("\n")
|
||||
.filter((line) => !/^\s*#/.test(line))
|
||||
.join("\n");
|
||||
assert.doesNotMatch(code, /--force|git push[^\n]*\s-f\b|git push[^\n]*\s\+/, "no force push anywhere in the workflow");
|
||||
assert.doesNotMatch(code, /git push/, "the publisher does the only push");
|
||||
});
|
||||
|
||||
test("an older or equal release never moves the release branch back, unless --allow-older says so", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.3.0");
|
||||
const newer = publish(fx, ["--tag", "v1.3.0"]);
|
||||
assert.equal(newer.status, 0, newer.stderr);
|
||||
git(fx.work, ["fetch", "-q", "--no-tags", "origin", "+refs/heads/release:refs/remotes/origin/release"]);
|
||||
|
||||
// A hotfix tagged after it, from an older line: refused, nothing pushed.
|
||||
fx.release("1.2.9");
|
||||
const older = publish(fx, ["--tag", "v1.2.9"]);
|
||||
assert.equal(older.status, 1);
|
||||
assert.match(older.stderr, /already installs 1\.3\.0; refusing to move it to 1\.2\.9/);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.9"), null);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), newer.result.commit);
|
||||
|
||||
// The deliberate override still works.
|
||||
const forced = publish(fx, ["--tag", "v1.2.9", "--allow-older"]);
|
||||
assert.equal(forced.status, 0, forced.stderr);
|
||||
assert.equal(fx.remoteRef("refs/heads/release"), forced.result.commit);
|
||||
});
|
||||
|
||||
test("a package.json script that makes npm do a full dev install of a git package refuses the publication", (t) => {
|
||||
const fx = createSource();
|
||||
t.after(fx.cleanup);
|
||||
fx.release("1.2.0", {
|
||||
mutate: (files) => {
|
||||
files["package.json"] = { content: json({ name: "plan2code", version: "1.2.0", scripts: { prepare: "node build.js", test: "node --test" } }) };
|
||||
},
|
||||
});
|
||||
const r = publish(fx, ["--tag", "v1.2.0"]);
|
||||
assert.equal(r.status, 1);
|
||||
assert.match(r.stderr, /package\.json has prepare/);
|
||||
assert.equal(fx.remoteRef("refs/tags/install-v1.2.0"), null);
|
||||
});
|
||||
@@ -166,12 +166,12 @@ test("pathfinder trail: exact footer for forms A, B and C", () => {
|
||||
assert.equal(P("trail", "audit-export", "--form", "B", "--item", "1", "--item", "2", "--item", "3", "--item", "4").code, 5, "three-probe cap");
|
||||
assert.equal(P("trail", "audit-export", "--form", "C").json.error, "claim-open", "no menu while a claim is open");
|
||||
const a = P("trail", "audit-export", "--form", "A", "--text").stdout;
|
||||
assert.ok(a.endsWith("NEXT STEP · start a new conversation and run:\n`/plan2code-0-pathfinder specs/audit-export/pathfinder --web`\n"), a);
|
||||
assert.ok(a.endsWith("NEXT STEP · start a new conversation and run:\n`/plan2code-0-pathfinder specs/audit-export/pathfinder`\nAdd `--web` for the web console.\n"), a);
|
||||
fs.appendFileSync(path.join(root, pf, "questions/03-testing-posture.md"), "\n## Answer\n\nUnit; `Run after each phase`; `Critical paths`.\n\n**Gist:** Unit tests, run after each phase.\n");
|
||||
P("resolve", "audit-export", "03");
|
||||
const c = P("trail", "audit-export", "--form", "C", "--resolved-this-session", "3");
|
||||
assert.equal(c.code, 0, c.stderr);
|
||||
assert.ok(c.json.text.endsWith("OR START FRESH · new conversation, paste:\n`/plan2code-0-pathfinder specs/audit-export/pathfinder --web`"));
|
||||
assert.ok(c.json.text.endsWith("OR START FRESH · new conversation, paste:\n`/plan2code-0-pathfinder specs/audit-export/pathfinder`\nAdd `--web` for the web console."));
|
||||
assert.deepEqual(c.json.menu.options.map((o) => o.label), ["Row-count ceiling", "Start fresh"]);
|
||||
assert.equal(c.json.menu.recommended, "Start fresh", "the checkpoint after ~3 decisions");
|
||||
assert.equal(c.json.menu.options.find((o) => o.label === "Start fresh").fresh, true, "the page reads it as a clean start");
|
||||
@@ -192,11 +192,12 @@ test("pathfinder trail: a cleared map arrives; init first only while AGENTS.md i
|
||||
" Confidence: solid, but Requirements, Risk are borderline.",
|
||||
"",
|
||||
"NEXT STEP · start a new conversation and run:",
|
||||
"`/plan2code-init`, then `/plan2code-1-plan --web`",
|
||||
"`/plan2code-init`, then `/plan2code-1-plan`",
|
||||
"Add `--web` for the web console.",
|
||||
"",
|
||||
].join("\n"));
|
||||
write(root, "AGENTS.md", "# AGENTS.md\n");
|
||||
assert.match(P("trail", "done", "--form", "A", "--text").stdout, /run:\n`\/plan2code-1-plan --web`\n$/);
|
||||
assert.match(P("trail", "done", "--form", "A", "--text").stdout, /run:\n`\/plan2code-1-plan`\nAdd `--web` for the web console\.\n$/);
|
||||
assert.equal(P("trail", "done", "--form", "C").code, 5, "no menu on a cleared map");
|
||||
});
|
||||
|
||||
|
||||
@@ -14,12 +14,18 @@ const skillNames = () => fs.readdirSync(SKILLS).filter((name) => !name.startsWit
|
||||
|
||||
/* ================================================================ install */
|
||||
|
||||
test("npm test runs every scripts/test-*.mjs file, and names none that is missing", () => {
|
||||
const command = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).scripts.test;
|
||||
const listed = [...command.matchAll(/scripts\/(test-[\w-]+\.mjs)/g)].map((m) => m[1]).sort();
|
||||
test("npm test and npm run test:games together run every scripts/test-*.mjs file once, games only in test:games", () => {
|
||||
const scripts = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).scripts;
|
||||
const files = (command) => [...String(command || "").matchAll(/scripts\/(test-[\w-]+\.mjs)/g)].map((m) => m[1]);
|
||||
// The Activities games are an add-on: their tests run only on request (npm run test:games), never in npm test.
|
||||
const isGame = (f) => /^test-web-console-(activities[\w-]*|page-activities)\.mjs$/.test(f);
|
||||
const main = files(scripts.test);
|
||||
const games = files(scripts["test:games"]);
|
||||
assert.deepEqual(main.filter(isGame), [], "npm test runs no game tests");
|
||||
assert.deepEqual(games.filter((f) => !isGame(f)), [], "test:games runs only game tests");
|
||||
// test-fast.mjs runs the fast lane (npm run test:fast); it is a runner, not a test file.
|
||||
const onDisk = fs.readdirSync(path.join(ROOT, "scripts")).filter((f) => /^test-[\w-]+\.mjs$/.test(f) && f !== "test-fast.mjs").sort();
|
||||
assert.deepEqual(listed, onDisk);
|
||||
assert.deepEqual([...main, ...games].sort(), onDisk, "every test file is named once, in one of the two");
|
||||
});
|
||||
|
||||
test("every skill with scripts ships common.mjs and version.json; the dashboard ships only Learning's", () => {
|
||||
|
||||
@@ -97,6 +97,19 @@ test("wait's existing outcomes are pinned: submit, images, waiting, cancel, carr
|
||||
|
||||
/* --------------------------------------------- quick question: the channel */
|
||||
|
||||
// `chat` checks the server's /health with a 1.5 s limit, so on a machine loaded by the rest of the
|
||||
// suite a server this test just started, and knows is running, can be reported gone (20). Where the
|
||||
// server must be up, ask again a few times before judging the answer; a real 20 stays 20 when the
|
||||
// server has been stopped (those checks call cli directly).
|
||||
async function chatWhileUp(s) {
|
||||
let r = cli(["chat", "--session", s.sid]);
|
||||
for (let i = 0; i < 4 && r.status === 20; i++) {
|
||||
await sleep(500);
|
||||
r = cli(["chat", "--session", s.sid]);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
test("a chat message and a card send can both be pending, in either order, and wait hands both over at once", async () => {
|
||||
const s = openSession();
|
||||
@@ -160,11 +173,11 @@ test("wait returns within 100 ms of a chat message landing", async () => {
|
||||
test("the chat command answers at once: 0 with entries, 10 with none, 20 when the server is gone, and never takes a card send", async () => {
|
||||
const s = openSession();
|
||||
try {
|
||||
assert.equal(cli(["chat", "--session", s.sid]).status, 10, "a reset alone is nothing to hand over");
|
||||
assert.equal((await chatWhileUp(s)).status, 10, "a reset alone is nothing to hand over");
|
||||
assert.equal((await s.send("/submit", EXPORT_A)).status, 200);
|
||||
assert.equal((await ask(s, "Mid-build question")).status, 200);
|
||||
assert.equal((await (await s.send("/ping", {})).json()).pendingChat, 1, "an uncollected question shows on the heartbeat");
|
||||
const got = cli(["chat", "--session", s.sid]);
|
||||
const got = await chatWhileUp(s);
|
||||
assert.equal(got.status, 0);
|
||||
assert.equal(got.json.chat.length, 1);
|
||||
assert.match(got.json.reply, /Quick question \(\d+\): Mid-build question/);
|
||||
@@ -172,7 +185,7 @@ test("the chat command answers at once: 0 with entries, 10 with none, 20 when th
|
||||
assert.equal(onDisk.consumedAt, undefined, "the card send is still waiting for wait");
|
||||
assert.equal((await (await s.send("/ping", {})).json()).pendingChat, 0);
|
||||
|
||||
const none = cli(["chat", "--session", s.sid]);
|
||||
const none = await chatWhileUp(s);
|
||||
assert.equal(none.status, 10);
|
||||
assert.deepEqual(none.json, {});
|
||||
|
||||
@@ -197,10 +210,10 @@ test("a torn trailing inbox line is skipped, then collected once it is whole", a
|
||||
const line = JSON.stringify({ kind: "message", conversation: 1, text: "torn in two", seq, at: new Date().toISOString() });
|
||||
fs.appendFileSync(file, line.slice(0, 20));
|
||||
assert.equal(readChat(s.session).some((e) => e.seq === seq), false, "a half-written line is not parsed");
|
||||
assert.equal(cli(["chat", "--session", s.sid]).status, 10);
|
||||
assert.equal((await chatWhileUp(s)).status, 10);
|
||||
fs.appendFileSync(file, line.slice(20) + "\n");
|
||||
assert.ok(readChat(s.session).some((e) => e.seq === seq));
|
||||
const got = cli(["chat", "--session", s.sid]);
|
||||
const got = await chatWhileUp(s);
|
||||
assert.equal(got.status, 0);
|
||||
assert.match(got.json.reply, /Quick question \(\d+\): torn in two/);
|
||||
} finally {
|
||||
|
||||
@@ -119,6 +119,36 @@ test("scan.learning.nearCap: true at 22 general lessons or 30 in an area, false
|
||||
assert.deepEqual(listing(full), before, "the scan writes nothing");
|
||||
});
|
||||
|
||||
test("scan.learning.nearCap stays false once a tidy-up found nothing, until the saved lessons change", async (t) => {
|
||||
const dir = project({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 23) });
|
||||
assert.equal(learningScan(dir).nearCap, true);
|
||||
const s = dashboard(t, dir);
|
||||
const res = await s.post("/learning/tidy-quiet", {});
|
||||
assert.equal(res.status, 200);
|
||||
const body = await res.json();
|
||||
assert.equal(body.ok, true);
|
||||
assert.equal(body.learning.nearCap, false, "the answer carries the patched scan");
|
||||
assert.equal(readState(s.session).scan.learning.nearCap, false, "the page repaints from the patched scan");
|
||||
assert.equal(learningScan(dir).nearCap, false, "a later scan agrees");
|
||||
assert.ok(fs.existsSync(path.join(storeDir(dir), "tidy-quiet.json")), "it lives in the learning store on this machine");
|
||||
// The lessons change (a merge, a new lesson): the nudge may come back.
|
||||
fs.writeFileSync(path.join(dir, ".plan2code", "lessons", "general.md"), lessonFile("General", 24));
|
||||
assert.equal(learningScan(dir).nearCap, true);
|
||||
});
|
||||
|
||||
test("POST /learning/tidy-quiet is 409 when the project is not on and writes nothing into the project", async (t) => {
|
||||
for (const files of [{}, SETTINGS("off")]) {
|
||||
const s = dashboard(t, project(files));
|
||||
const res = await s.post("/learning/tidy-quiet", {});
|
||||
assert.equal(res.status, 409);
|
||||
assert.deepEqual(await res.json(), { error: "not-on" });
|
||||
}
|
||||
const dir = project({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 23) });
|
||||
const before = listing(dir);
|
||||
await dashboard(t, dir).post("/learning/tidy-quiet", {});
|
||||
assert.deepEqual(listing(dir), before);
|
||||
});
|
||||
|
||||
test("a failure in Learning's core never fails the scan", () => {
|
||||
const boom = () => {
|
||||
throw new Error("the core broke");
|
||||
|
||||
@@ -170,7 +170,8 @@ test("the die sits right of the megaphone and opens on the picker, a ledger row
|
||||
await pastTheIntro(s);
|
||||
await iconUsable(s, "the dashboard");
|
||||
const next = await s.page.evaluate(() => document.getElementById("btn-feedback").nextElementSibling?.id);
|
||||
assert.equal(next, "btn-activities");
|
||||
assert.equal(next, "text-size", "the text size control sits between the megaphone and the die");
|
||||
assert.equal(await s.page.evaluate(() => document.getElementById("text-size").nextElementSibling?.id), "btn-activities");
|
||||
await openPicker(s);
|
||||
// Snake's seeded best makes it the one played row; the rest sit under Not played yet, A to Z.
|
||||
assert.deepEqual(await cardTitles(s), ["Snake", "Bounce Road", "Bug Hunt", "Bumper Ring", "Crossing Rush", "Flock Dash", "Ghoul Rush", "Hot Potato", "Light Trails", "Mini golf", "Rapids Run", "Stack Deploy", "Sunset Drive"]);
|
||||
|
||||
@@ -282,6 +282,17 @@ test("the banner nudges a tidy-up when lessons are near their limit, and only th
|
||||
assert.equal(await below.main.locator(".learn-banner").count(), 0, "no banner below the line");
|
||||
});
|
||||
|
||||
test("Not now hides the tidy-up nudge at once and it stays hidden for the same lessons", async (t) => {
|
||||
const full = await dashboard(t, { ...PROJECT("on"), ".plan2code/lessons/general.md": lessonFile("General", 22) });
|
||||
const banner = full.main.locator(".learn-banner");
|
||||
await banner.waitFor();
|
||||
await banner.getByRole("button", { name: "Not now" }).click();
|
||||
await until(async () => (await full.main.locator(".learn-banner").count()) === 0, 5000);
|
||||
const state = await full.s.page.evaluate(() => fetch("/learning/state").then((r) => r.json()));
|
||||
assert.equal(state.nearCap, false, "the server remembers it");
|
||||
assert.equal(await full.main.locator(".learn-banner").count(), 0, "still hidden after the repaint");
|
||||
});
|
||||
|
||||
test("a launch from a dashboard showing lessons waiting carries fromBanner", async (t) => {
|
||||
const { s, main } = await dashboard(t, PROJECT("on"), (p) =>
|
||||
writeWaiting(p, { id: "20261113-120000-eeeeee", type: "lesson", text: "Waits.", noted: new Date().toISOString() })
|
||||
|
||||
@@ -85,6 +85,59 @@ test("the violet highlight and dark theme chosen in preferences stick across a r
|
||||
assert.deepEqual(await firstPaintAttrs(s), { theme: null, accent: null }, "the first paint still carries the old looks");
|
||||
});
|
||||
|
||||
// The top bar's text size buttons: seven steps, saved with the looks, in the first paint.
|
||||
const bodySize = (s) => s.page.evaluate(() => getComputedStyle(document.body).fontSize);
|
||||
const sizeLabel = (s) => s.page.locator("#btn-text-size").innerText();
|
||||
const savedTextSize = (s) => s.page.evaluate(async () => ((await (await fetch("/looks")).json()).looks || {}).textSize);
|
||||
|
||||
test("the text size buttons step the console's type up and down between the megaphone and the die, stop at the ends, and the label returns to 100%", async (t) => {
|
||||
noSavedLooks(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const order = await s.page.evaluate(() => [...document.getElementById("btn-feedback").parentElement.children].map((n) => n.id));
|
||||
assert.deepEqual(order.slice(order.indexOf("btn-feedback"), order.indexOf("btn-feedback") + 3), ["btn-feedback", "text-size", "btn-activities"], "the control sits between the megaphone and the die");
|
||||
assert.equal(await sizeLabel(s), "100%");
|
||||
assert.equal(await root(s, "data-text-size"), null, "the default size leaves the page unmarked");
|
||||
assert.equal(await bodySize(s), "15px");
|
||||
|
||||
await s.page.click("#btn-text-larger");
|
||||
assert.equal(await sizeLabel(s), "110%");
|
||||
assert.equal(await root(s, "data-text-size"), "110");
|
||||
assert.equal(await s.page.locator("#btn-text-size").getAttribute("aria-label"), "Text size 110%, back to 100%", "a screen reader hears the size");
|
||||
assert.equal(await bodySize(s), "16.5px");
|
||||
await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).textSize === 110);
|
||||
|
||||
// The first paint carries it, and so does a reload.
|
||||
const html = await (await s.context.request.get(s.url)).text();
|
||||
assert.match(html.match(/<html\b[^>]*>/i)?.[0] ?? `no html tag in: ${html.slice(0, 200)}`, /data-text-size="110"/, "the first paint carries the saved size");
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
assert.equal(await sizeLabel(s), "110%");
|
||||
assert.equal(await bodySize(s), "16.5px");
|
||||
|
||||
// The label puts it back.
|
||||
await s.page.click("#btn-text-size");
|
||||
assert.equal(await sizeLabel(s), "100%");
|
||||
assert.equal(await root(s, "data-text-size"), null);
|
||||
assert.equal(await bodySize(s), "15px");
|
||||
|
||||
// Largest and smallest: the button at the end is spent, not wrapped.
|
||||
for (let i = 0; i < 6; i++) if (await s.page.locator("#btn-text-larger").isEnabled()) await s.page.click("#btn-text-larger");
|
||||
assert.equal(await sizeLabel(s), "150%");
|
||||
assert.equal(await s.page.locator("#btn-text-larger").getAttribute("aria-disabled"), "true");
|
||||
await s.page.click("#btn-text-size");
|
||||
for (let i = 0; i < 6; i++) if ((await s.page.locator("#btn-text-smaller").getAttribute("aria-disabled")) !== "true") await s.page.click("#btn-text-smaller");
|
||||
assert.equal(await sizeLabel(s), "80%");
|
||||
assert.equal(await bodySize(s), "12px");
|
||||
await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).textSize === 80);
|
||||
|
||||
// Back to default in Preferences returns it too.
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.click("#looks-reset");
|
||||
await s.page.waitForFunction(() => !document.documentElement.hasAttribute("data-text-size"));
|
||||
assert.equal(await sizeLabel(s), "100%");
|
||||
assert.equal(await savedTextSize(s) ?? 100, 100);
|
||||
});
|
||||
|
||||
// The Agents & models tab: a roster of agent cards, the picked agent's form in
|
||||
// a drawer over it (Models & strengths and Launch tabs), and the Add agent
|
||||
// chooser, where the starter templates are an opt-in.
|
||||
|
||||
@@ -351,7 +351,7 @@ test("the session sweep removes only month-old session dirs, never the one being
|
||||
}
|
||||
});
|
||||
|
||||
test("the scratch sweep removes old patches and helpers, never looks, the pointer, the update cache or a directory", async () => {
|
||||
test("the scratch sweep removes old patches and helpers, never looks, the interface, the pointer, the update cache or a directory", async () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-scratch-"));
|
||||
try {
|
||||
const file = (name, stale = true) => {
|
||||
@@ -363,6 +363,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe
|
||||
const removable = [file("p2.json"), file("helper.mjs")];
|
||||
const kept = [
|
||||
file("looks.json"),
|
||||
file("interface.json"),
|
||||
file("workspaces.json"),
|
||||
file("loop-setup.json"),
|
||||
file("review-loop-setup.json"),
|
||||
@@ -383,13 +384,14 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe
|
||||
const stale = staleScratch(dir, Date.now(), SESSION_MAX_AGE_MS).sort();
|
||||
assert.deepEqual(stale, ["helper.mjs", "p2.json"]);
|
||||
assert.deepEqual(
|
||||
(await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "loop-setup.json", "review-loop-setup.json", "loop-reports.json", "subagents.json", "spec-carry.json", "pr-hosts.json", "../p.json", "console-dir", "update-check.json"])).sort(),
|
||||
(await removeScratch(dir, [...stale, "looks.json", "interface.json", "workspaces.json", "loop-setup.json", "review-loop-setup.json", "loop-reports.json", "subagents.json", "spec-carry.json", "pr-hosts.json", "../p.json", "console-dir", "update-check.json"])).sort(),
|
||||
["helper.mjs", "p2.json"]
|
||||
);
|
||||
for (const p of removable) assert.equal(fs.existsSync(p), false, p);
|
||||
for (const p of kept) assert.ok(fs.existsSync(p), p);
|
||||
assert.deepEqual([...PROTECTED_CONSOLE_FILES].sort(), [
|
||||
"console-dir",
|
||||
"interface.json",
|
||||
"looks.json",
|
||||
"loop-reports.json",
|
||||
"loop-setup.json",
|
||||
@@ -435,7 +437,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
|
||||
const drafted = session("20250801-101010-dddddd", true);
|
||||
put(path.join(drafted, "draft.json"));
|
||||
const kept = [
|
||||
...["looks.json", "workspaces.json", "subagents.json", "console-dir", "update-check.json"].map((n) =>
|
||||
...["looks.json", "interface.json", "workspaces.json", "subagents.json", "console-dir", "update-check.json"].map((n) =>
|
||||
put(path.join(consoleDir, n))
|
||||
),
|
||||
put(path.join(plan2code, "launcher.json")),
|
||||
@@ -1666,3 +1668,76 @@ test("a setup console without the app signal never calls a leftover announce URL
|
||||
stub.close();
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------------------------- terminal or web console */
|
||||
|
||||
// Its own console home, so a default saved here never reaches another test.
|
||||
function interfaceCli(home, args) {
|
||||
return cli(["interface", ...args], { expectFail: true, env: { PLAN2CODE_CONSOLE_HOME: home } });
|
||||
}
|
||||
|
||||
test("interface reports no default on a fresh home, and its rule says to ask and save nothing", () => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-interface-"));
|
||||
try {
|
||||
const res = interfaceCli(home, []);
|
||||
assert.equal(res.status, 0);
|
||||
assert.equal(res.json.interface, null);
|
||||
assert.match(res.json.rule, /Save nothing from the answer/);
|
||||
assert.match(res.json.rule, /make the terminal \(or web console\) my default/);
|
||||
assert.equal(fs.existsSync(path.join(home, "interface.json")), false);
|
||||
assert.match(res.json.rule, /interface --set web\|terminal/);
|
||||
assert.match(res.json.rule, /--web/);
|
||||
assert.match(res.json.rule, /--terminal/);
|
||||
} finally {
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("interface --set saves one default that every later call reads back, and ask clears it", () => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-interface-"));
|
||||
try {
|
||||
for (const choice of ["terminal", "web"]) {
|
||||
assert.deepEqual(interfaceCli(home, ["--set", choice]).json, { ok: true, interface: choice });
|
||||
const res = interfaceCli(home, []);
|
||||
assert.equal(res.json.interface, choice);
|
||||
assert.match(res.json.rule, /saved default, so do not ask/);
|
||||
assert.doesNotMatch(res.json.rule, /Save nothing/);
|
||||
}
|
||||
assert.deepEqual(interfaceCli(home, ["--set", "ask"]).json, { ok: true, interface: null });
|
||||
assert.equal(fs.existsSync(path.join(home, "interface.json")), false);
|
||||
assert.equal(interfaceCli(home, []).json.interface, null);
|
||||
} finally {
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("interface refuses an unknown or missing value, and reads a damaged file as no default", () => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-interface-"));
|
||||
try {
|
||||
for (const bad of [["--set", "browser"], ["--set"]]) {
|
||||
const res = interfaceCli(home, bad);
|
||||
assert.equal(res.status, 2, bad.join(" "));
|
||||
assert.equal(fs.existsSync(path.join(home, "interface.json")), false);
|
||||
}
|
||||
for (const body of ["{not json", JSON.stringify({ interface: "browser" }), "[]"]) {
|
||||
fs.writeFileSync(path.join(home, "interface.json"), body);
|
||||
assert.equal(interfaceCli(home, []).json.interface, null, body);
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// The rule lives in the interface command, so no skill may go back to asking
|
||||
// up front or spell out its own version of the rule.
|
||||
test("every skill but the dashboard picks its interface through the interface command", () => {
|
||||
const skills = fs.readdirSync(path.join(ROOT, "src")).filter((f) => /^plan2code-.*\.md$/.test(f));
|
||||
assert.equal(skills.length, 21);
|
||||
for (const f of skills) {
|
||||
const text = fs.readFileSync(path.join(ROOT, "src", f), "utf8");
|
||||
const iface = text.indexOf('console.mjs" interface`');
|
||||
assert.ok(iface > -1, `${f} runs the interface command`);
|
||||
assert.ok(iface < text.search(/console\.mjs" open(?! --resume)/), `${f} runs it before open`);
|
||||
assert.doesNotMatch(text, /ask \*\*web console\*\*/, `${f} no longer asks up front`);
|
||||
}
|
||||
});
|
||||
@@ -869,7 +869,7 @@ test("prefs: the dialog opens on the tab asked for, else Appearance", () => {
|
||||
});
|
||||
|
||||
test("prefs: Back to default resets Appearance or Sounds & activities only, and nothing on the other two", () => {
|
||||
assert.deepEqual(prefsResetScope("appearance"), ["theme", "width", "accent", "role", "skipIntro"]);
|
||||
assert.deepEqual(prefsResetScope("appearance"), ["theme", "width", "textSize", "accent", "role", "skipIntro"]);
|
||||
const sounds = prefsResetScope("sounds");
|
||||
assert.deepEqual(sounds, ["sound", ...Object.keys(SOUND_EVENTS).map(soundKey), ...PICKABLE_SOUNDS.map(soundFileKey), "hideActivities", "activitySounds", "gameMusic"]);
|
||||
for (const key of [...prefsResetScope("appearance"), ...sounds]) {
|
||||
|
||||
@@ -189,7 +189,7 @@ test("shape: no page module sets a style attribute from script", () => {
|
||||
// no routes of its own: its buttons are sends (`__git`), through /submit.
|
||||
const ROUTE_ORDER = [
|
||||
"/health", "/s/", "/handover", "/", "SERVABLE", "/overview", "/agents-doc", "/prototypes", "/prototype", "/handoff", "/version", "/state", "/events", "/draft",
|
||||
"/looks", "/looks", "/subagents", "/learning/pause", "/learning/state", "/learning/lessons", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/agents/use-path", "/cleanup", "/upload",
|
||||
"/looks", "/looks", "/subagents", "/learning/pause", "/learning/tidy-quiet", "/learning/state", "/learning/lessons", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/agents/use-path", "/cleanup", "/upload",
|
||||
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab",
|
||||
"/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/tab/sent", "/notepad/images/",
|
||||
"/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/open-prototype", "/chat", "/chat/decision", "/workspace",
|
||||
|
||||
@@ -0,0 +1,731 @@
|
||||
'use strict';
|
||||
|
||||
// The canonical skills store, written once per install: every skill is copied into a staging
|
||||
// folder beside the store, checked byte for byte, then swapped in with a backup and a journal,
|
||||
// so an interrupted install can be put back or finished. The skills CLI then links agents to the
|
||||
// store; it never copies the tree again. Zero dependencies, CommonJS.
|
||||
//
|
||||
// Layout, for a scope's store `<base>/.agents/skills`:
|
||||
// <base>/.agents/skills/<name>/ one canonical copy per skill
|
||||
// <base>/.agents/skills/.plan2code-canonical.json the validity manifest (metadata, not a skill)
|
||||
// <base>/.agents/.skills-stage-<pid>-<timestamp>/ a stage, while it is built
|
||||
// <base>/.agents/.skills-backup-<operation>/ the replaced skills, while a swap runs
|
||||
// <base>/.agents/.plan2code-canonical-journal.json what a swap has done so far
|
||||
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const MANIFEST_NAME = '.plan2code-canonical.json';
|
||||
const JOURNAL_NAME = '.plan2code-canonical-journal.json';
|
||||
const STAGE_PREFIX = '.skills-stage-';
|
||||
const BACKUP_PREFIX = '.skills-backup-';
|
||||
const MANIFEST_VERSION = 1;
|
||||
const SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
||||
// Ours, as everywhere else in the installer: `plan2code` itself or `plan2code-<name>`.
|
||||
const OUR_NAME = /^plan2code(?:-|$)/;
|
||||
|
||||
/** The skills CLI's canonical store for a scope: `<home>/.agents/skills` globally, `<cwd>/.agents/skills` in a project. */
|
||||
function canonicalRoot(scope, cwd = process.cwd(), home = os.homedir()) {
|
||||
return path.join(scope === 'global' ? home : cwd, '.agents', 'skills');
|
||||
}
|
||||
|
||||
function manifestPath(root) {
|
||||
return path.join(root, MANIFEST_NAME);
|
||||
}
|
||||
|
||||
function journalPath(root) {
|
||||
return path.join(path.dirname(root), JOURNAL_NAME);
|
||||
}
|
||||
|
||||
/** An error with a `code` the installer can name. */
|
||||
function canonicalError(code, message, extra = {}) {
|
||||
return Object.assign(new Error(message), { code }, extra);
|
||||
}
|
||||
|
||||
/** The lstat of `file`, or null when nothing is there. Never follows a link. */
|
||||
function lstatOrNull(file) {
|
||||
try {
|
||||
return fs.lstatSync(file);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(file) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Windows briefly refuses a rename over a file that was just replaced (an indexer or virus
|
||||
// scanner still has it open): EPERM, EACCES or EBUSY that clear within milliseconds.
|
||||
const TRANSIENT_RENAME = new Set(['EPERM', 'EACCES', 'EBUSY']);
|
||||
const RENAME_ATTEMPTS = 8;
|
||||
|
||||
/** Block for `ms` milliseconds without spinning. */
|
||||
function pause(ms) {
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
||||
}
|
||||
|
||||
/** fs.renameSync, retried with a growing pause while Windows reports the source or target busy. */
|
||||
function renameWithRetry(from, to) {
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try {
|
||||
fs.renameSync(from, to);
|
||||
return;
|
||||
} catch (err) {
|
||||
if (process.platform !== 'win32' || !TRANSIENT_RENAME.has(err.code) || attempt >= RENAME_ATTEMPTS) throw err;
|
||||
pause(10 * attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A rename Windows refused because something holds the folder (a terminal or Explorer in it, a scanner). */
|
||||
function isLockError(err) {
|
||||
return process.platform === 'win32' && err && TRANSIENT_RENAME.has(err.code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make `dest` hold exactly what `src` holds without renaming `dest` itself: copy every file over
|
||||
* it, then remove what `src` does not have. The fallback for a skill folder Windows will not let
|
||||
* go of, as the skills CLI did before (it copied over a folder it could not remove).
|
||||
*/
|
||||
function replaceInPlace(src, dest) {
|
||||
fs.mkdirSync(dest, { recursive: true });
|
||||
fs.cpSync(src, dest, { recursive: true, force: true });
|
||||
const prune = (from, into) => {
|
||||
for (const entry of fs.readdirSync(into, { withFileTypes: true })) {
|
||||
const there = path.join(from, entry.name);
|
||||
const here = path.join(into, entry.name);
|
||||
const keep = lstatOrNull(there);
|
||||
if (!keep) fs.rmSync(here, { recursive: true, force: true });
|
||||
else if (entry.isDirectory() && keep.isDirectory()) prune(there, here);
|
||||
}
|
||||
};
|
||||
prune(src, dest);
|
||||
}
|
||||
|
||||
/** Write JSON through a temp file and a rename, so a reader never sees half a file. */
|
||||
function writeJsonAtomic(file, value) {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
||||
try {
|
||||
fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n');
|
||||
renameWithRetry(tmp, file);
|
||||
} catch (err) {
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function sha256(buffer) {
|
||||
return crypto.createHash('sha256').update(buffer).digest('hex');
|
||||
}
|
||||
|
||||
/** One hash for a set of `{ rel: sha256 }`: the sorted relative paths with their file hashes. */
|
||||
function treeHashOf(hashes) {
|
||||
const hash = crypto.createHash('sha256');
|
||||
for (const rel of Object.keys(hashes).sort()) hash.update(`${rel}\0${hashes[rel]}\n`);
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
/** Refuse a name that could leave the store (`..`, separators) or is not a plain skill folder name. */
|
||||
function assertSkillName(name) {
|
||||
if (typeof name !== 'string' || !SKILL_NAME.test(name) || name.includes('..')) {
|
||||
throw canonicalError('bad-name', `Refusing skill name ${JSON.stringify(name)}: not a plain folder name`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every regular file under `dir` as sorted forward-slash paths relative to it. A symlink or
|
||||
* junction anywhere (lstat sees both as links) is refused rather than followed, as is anything
|
||||
* that is neither a file nor a folder.
|
||||
*/
|
||||
// Files an OS writes into any folder a person opens: not part of a skill, never a reason to call
|
||||
// the store changed.
|
||||
const OS_JUNK = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini']);
|
||||
|
||||
function listTree(dir) {
|
||||
const files = [];
|
||||
const walk = (current, rel) => {
|
||||
for (const name of fs.readdirSync(current).sort()) {
|
||||
if (OS_JUNK.has(name)) continue;
|
||||
const full = path.join(current, name);
|
||||
const relPath = rel ? `${rel}/${name}` : name;
|
||||
const stat = fs.lstatSync(full);
|
||||
if (stat.isSymbolicLink()) throw canonicalError('link-in-tree', `Refusing ${full}: links are not copied`);
|
||||
if (stat.isDirectory()) walk(full, relPath);
|
||||
else if (stat.isFile()) files.push(relPath);
|
||||
else throw canonicalError('special-file', `Refusing ${full}: not a regular file`);
|
||||
}
|
||||
};
|
||||
walk(dir, '');
|
||||
return files.sort();
|
||||
}
|
||||
|
||||
/** `{ rel: sha256 }` for a skill folder, with every rel prefixed by `prefix/` when given. */
|
||||
function hashTree(dir, prefix = '') {
|
||||
const hashes = {};
|
||||
for (const rel of listTree(dir)) hashes[prefix ? `${prefix}/${rel}` : rel] = sha256(fs.readFileSync(path.join(dir, ...rel.split('/'))));
|
||||
return hashes;
|
||||
}
|
||||
|
||||
/** The hash of one skill folder, or null when it is missing, a link, or holds a link. */
|
||||
function skillTreeHash(dir) {
|
||||
const stat = lstatOrNull(dir);
|
||||
if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) return null;
|
||||
try {
|
||||
return treeHashOf(hashTree(dir));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Journal
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const JOURNAL_OPS = ['staged', 'backup-created', 'canonical-swapped', 'committed', 'rolled-back'];
|
||||
|
||||
function readJournal(root) {
|
||||
const journal = readJson(journalPath(root));
|
||||
return journal && Array.isArray(journal.records) ? journal : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add one record to the journal beside `root` (written atomically): `{ op, scope, operationId,
|
||||
* skill, source, destination, at }` plus any `extra`. `op` is one of JOURNAL_OPS.
|
||||
*/
|
||||
function journalRecord(root, { op, scope, operationId, skill = null, source = null, destination = null, extra = {} }) {
|
||||
if (!JOURNAL_OPS.includes(op)) throw canonicalError('bad-journal-op', `Unknown journal operation ${op}`);
|
||||
const file = journalPath(root);
|
||||
const current = readJournal(root);
|
||||
const journal = current && current.operationId === operationId ? current : { version: MANIFEST_VERSION, scope, operationId, root, records: [] };
|
||||
const record = { op, scope, operationId, skill, source, destination, at: new Date().toISOString(), ...extra };
|
||||
journal.records.push(record);
|
||||
writeJsonAtomic(file, journal);
|
||||
return record;
|
||||
}
|
||||
|
||||
function removeJournal(root) {
|
||||
fs.rmSync(journalPath(root), { force: true });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Manifest
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** The validity manifest in a scope's store, or null when there is none or it is unreadable. */
|
||||
function readCanonicalManifest(scope, cwd = process.cwd(), home = os.homedir()) {
|
||||
const manifest = readJson(manifestPath(canonicalRoot(scope, cwd, home)));
|
||||
return manifest && typeof manifest === 'object' && !Array.isArray(manifest) ? manifest : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the store for `scope` holds a complete, current copy of every expected skill:
|
||||
* `{ complete, problems, manifest }`. Complete means a manifest marked complete with no journal,
|
||||
* naming each expected skill, each one a real folder (never a link) whose files hash to the
|
||||
* recorded tree hash, and, when `version` is given, written for that version.
|
||||
*/
|
||||
function validateCanonicalManifest(scope, expectedNames, { cwd = process.cwd(), home = os.homedir(), version = null } = {}) {
|
||||
const root = canonicalRoot(scope, cwd, home);
|
||||
const manifest = readCanonicalManifest(scope, cwd, home);
|
||||
const problems = [];
|
||||
if (!manifest) problems.push('no manifest');
|
||||
else {
|
||||
if (manifest.complete !== true) problems.push('manifest not complete');
|
||||
if (manifest.journal) problems.push('a swap did not finish');
|
||||
if (version && manifest.version !== version) problems.push(`manifest is for ${manifest.version || 'no version'}`);
|
||||
const skills = manifest.skills && typeof manifest.skills === 'object' ? manifest.skills : {};
|
||||
for (const name of expectedNames) {
|
||||
if (typeof skills[name] !== 'string') {
|
||||
problems.push(`${name}: not in the manifest`);
|
||||
continue;
|
||||
}
|
||||
const actual = skillTreeHash(path.join(root, name));
|
||||
if (actual === null) problems.push(`${name}: missing`);
|
||||
else if (actual !== skills[name]) problems.push(`${name}: changed on disk`);
|
||||
}
|
||||
}
|
||||
return { complete: problems.length === 0, problems, manifest };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Stage
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** Remove a folder, returning a warning line instead of throwing. */
|
||||
function removeQuietly(dir, warnings) {
|
||||
try {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
} catch (err) {
|
||||
warnings.push(`Could not remove ${dir}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy every expected skill from `builtDir` into a new stage beside the store, once each, and
|
||||
* check the copy against the source before anything in the store changes. Refuses a missing
|
||||
* skill, a name that could leave the store, and any link inside the built tree. Returns
|
||||
* `{ stageDir, scope, root, operationId, names, files, hashes, skills, treeHash, manifest }`:
|
||||
* `files` the sorted relative paths, `hashes` their sha256, `skills` each skill's tree hash.
|
||||
*/
|
||||
function stageCanonicalSkills({ scope, builtDir, expectedNames, cwd = process.cwd(), home = os.homedir(), version = null, sourceRef = null }) {
|
||||
const root = canonicalRoot(scope, cwd, home);
|
||||
const names = [...new Set(expectedNames)].sort();
|
||||
for (const name of names) assertSkillName(name);
|
||||
for (const name of names) {
|
||||
const stat = lstatOrNull(path.join(builtDir, name));
|
||||
if (!stat) throw canonicalError('missing-skill', `The build has no ${name} skill`);
|
||||
if (stat.isSymbolicLink() || !stat.isDirectory()) throw canonicalError('link-in-tree', `Refusing ${path.join(builtDir, name)}: not a plain folder`);
|
||||
}
|
||||
|
||||
const operationId = `${process.pid}-${Date.now()}`;
|
||||
const stageDir = path.join(path.dirname(root), `${STAGE_PREFIX}${operationId}`);
|
||||
fs.mkdirSync(stageDir, { recursive: true });
|
||||
try {
|
||||
const hashes = {};
|
||||
const sizes = {};
|
||||
const skills = {};
|
||||
for (const name of names) {
|
||||
const source = path.join(builtDir, name);
|
||||
const own = {};
|
||||
for (const rel of listTree(source)) {
|
||||
const from = path.join(source, ...rel.split('/'));
|
||||
const to = path.join(stageDir, name, ...rel.split('/'));
|
||||
const bytes = fs.readFileSync(from);
|
||||
fs.mkdirSync(path.dirname(to), { recursive: true });
|
||||
fs.writeFileSync(to, bytes);
|
||||
own[rel] = sha256(bytes);
|
||||
hashes[`${name}/${rel}`] = own[rel];
|
||||
sizes[`${name}/${rel}`] = bytes.length;
|
||||
}
|
||||
skills[name] = treeHashOf(own);
|
||||
}
|
||||
// The copy is checked before the store is touched: byte counts first, then the hashes.
|
||||
for (const [rel, hash] of Object.entries(hashes)) {
|
||||
const copied = path.join(stageDir, ...rel.split('/'));
|
||||
const stat = lstatOrNull(copied);
|
||||
if (!stat || !stat.isFile() || stat.size !== sizes[rel]) throw canonicalError('stage-mismatch', `The staged copy of ${rel} has the wrong size`);
|
||||
if (sha256(fs.readFileSync(copied)) !== hash) throw canonicalError('stage-mismatch', `The staged copy of ${rel} does not match the build`);
|
||||
}
|
||||
const files = Object.keys(hashes).sort();
|
||||
const treeHash = treeHashOf(hashes);
|
||||
const manifest = { version, sourceRef, complete: false, skills, files: Object.fromEntries(files.map((rel) => [rel, hashes[rel]])), treeHash, journal: null };
|
||||
writeJsonAtomic(path.join(stageDir, MANIFEST_NAME), manifest);
|
||||
journalRecord(root, { op: 'staged', scope, operationId, source: builtDir, destination: stageDir });
|
||||
return { stageDir, scope, root, operationId, names, files, hashes, skills, treeHash, manifest };
|
||||
} catch (err) {
|
||||
removeQuietly(stageDir, []);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Check a stage on disk still matches what was staged: every file present with its hash. */
|
||||
function validateStage(stage) {
|
||||
for (const name of stage.names) {
|
||||
let hashes;
|
||||
try {
|
||||
hashes = hashTree(path.join(stage.stageDir, name), name);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const expected = Object.keys(stage.hashes).filter((rel) => rel.startsWith(`${name}/`));
|
||||
if (Object.keys(hashes).length !== expected.length) return false;
|
||||
for (const rel of expected) if (hashes[rel] !== stage.hashes[rel]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Commit
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** Put one swapped skill back as it was: drop the new copy, then return the backup or the link. */
|
||||
function restoreEntry(entry, root, rename) {
|
||||
const dest = path.join(root, entry.name);
|
||||
if (entry.inPlace) {
|
||||
// The folder could not be moved, so its old files were copied aside and are copied back.
|
||||
if (entry.backup && lstatOrNull(entry.backup)) replaceInPlace(entry.backup, dest);
|
||||
return;
|
||||
}
|
||||
if (entry.swapped) {
|
||||
const stat = lstatOrNull(dest);
|
||||
if (stat && stat.isSymbolicLink()) fs.unlinkSync(dest);
|
||||
else if (stat) fs.rmSync(dest, { recursive: true, force: true });
|
||||
}
|
||||
if (entry.backup && lstatOrNull(entry.backup)) rename(entry.backup, dest);
|
||||
else if (entry.linkTarget) fs.symlinkSync(entry.linkTarget, dest, process.platform === 'win32' ? 'junction' : 'dir');
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap a validated stage into the store. Each existing expected skill moves to a backup folder
|
||||
* (a link is removed itself, never followed, and its target remembered), then its staged copy
|
||||
* is renamed in. Any failure puts back every skill already swapped, records `rolled-back`, and
|
||||
* throws with `retryable: true`. A skill folder Windows will not let go of is written over in place
|
||||
* instead (replaceInPlace), its old files copied aside first. Success finalizes (finalizeCommit).
|
||||
* `options.rename`, `options.isLock` and
|
||||
* `options.hooks.afterSwap(name)` let tests inject a failure or an interruption.
|
||||
*/
|
||||
function commitCanonicalSkills(stage, options = {}) {
|
||||
const rename = options.rename || renameWithRetry;
|
||||
const isLock = options.isLock || isLockError;
|
||||
const hooks = options.hooks || {};
|
||||
const { root, scope, operationId } = stage;
|
||||
if (!validateStage(stage)) throw canonicalError('stage-mismatch', 'The staged skills changed before the swap; nothing in the store was touched', { retryable: true });
|
||||
|
||||
fs.mkdirSync(root, { recursive: true });
|
||||
const previousManifest = readJson(manifestPath(root));
|
||||
const backupDir = path.join(path.dirname(root), `${BACKUP_PREFIX}${operationId}`);
|
||||
const done = [];
|
||||
try {
|
||||
// While the swap runs the store is not complete, whatever happens to this process.
|
||||
writeJsonAtomic(manifestPath(root), { ...(previousManifest || {}), complete: false, journal: operationId });
|
||||
fs.mkdirSync(backupDir, { recursive: true });
|
||||
for (const name of stage.names) {
|
||||
const dest = path.join(root, name);
|
||||
const entry = { name, backup: null, linkTarget: null, swapped: false };
|
||||
done.push(entry);
|
||||
const stat = lstatOrNull(dest);
|
||||
if (stat && stat.isSymbolicLink()) {
|
||||
try {
|
||||
entry.linkTarget = fs.readlinkSync(dest);
|
||||
} catch {}
|
||||
fs.unlinkSync(dest);
|
||||
journalRecord(root, { op: 'backup-created', scope, operationId, skill: name, source: dest, destination: null, extra: { link: entry.linkTarget } });
|
||||
} else if (stat) {
|
||||
const backup = path.join(backupDir, name);
|
||||
try {
|
||||
rename(dest, backup);
|
||||
} catch (err) {
|
||||
if (!isLock(err)) throw err;
|
||||
// Held open: keep a copy of the old files for a rollback, then write the new ones over it.
|
||||
fs.cpSync(dest, backup, { recursive: true });
|
||||
entry.backup = backup;
|
||||
entry.inPlace = true;
|
||||
journalRecord(root, { op: 'backup-created', scope, operationId, skill: name, source: dest, destination: backup, extra: { inPlace: true } });
|
||||
replaceInPlace(path.join(stage.stageDir, name), dest);
|
||||
entry.swapped = true;
|
||||
journalRecord(root, { op: 'canonical-swapped', scope, operationId, skill: name, source: path.join(stage.stageDir, name), destination: dest, extra: { inPlace: true } });
|
||||
if (hooks.afterSwap) hooks.afterSwap(name);
|
||||
continue;
|
||||
}
|
||||
entry.backup = backup;
|
||||
journalRecord(root, { op: 'backup-created', scope, operationId, skill: name, source: dest, destination: backup });
|
||||
}
|
||||
rename(path.join(stage.stageDir, name), dest);
|
||||
entry.swapped = true;
|
||||
journalRecord(root, { op: 'canonical-swapped', scope, operationId, skill: name, source: path.join(stage.stageDir, name), destination: dest });
|
||||
if (hooks.afterSwap) hooks.afterSwap(name);
|
||||
}
|
||||
// Checked and recorded inside the swap, so a mismatch or a failed manifest write rolls back too.
|
||||
verifySwapped(stage);
|
||||
writeJsonAtomic(manifestPath(root), { version: stage.manifest.version, sourceRef: stage.manifest.sourceRef, complete: true, skills: stage.skills, journal: null });
|
||||
} catch (err) {
|
||||
const rollbackErrors = [];
|
||||
for (const entry of done.reverse()) {
|
||||
try {
|
||||
restoreEntry(entry, root, rename);
|
||||
journalRecord(root, { op: 'rolled-back', scope, operationId, skill: entry.name, source: entry.backup, destination: path.join(root, entry.name) });
|
||||
} catch (restoreErr) {
|
||||
rollbackErrors.push(`${entry.name}: ${restoreErr.message}`);
|
||||
}
|
||||
}
|
||||
if (rollbackErrors.length === 0) {
|
||||
// Everything is back as it was, so the old manifest is true again.
|
||||
try {
|
||||
if (previousManifest) writeJsonAtomic(manifestPath(root), previousManifest);
|
||||
else fs.rmSync(manifestPath(root), { force: true });
|
||||
} catch {}
|
||||
removeQuietly(stage.stageDir, []);
|
||||
removeQuietly(backupDir, []);
|
||||
}
|
||||
throw canonicalError('commit-failed', `Could not swap the skills into ${root}: ${err.message}`, { retryable: true, cause: err, rollbackErrors });
|
||||
}
|
||||
return finalizeCommit(stage, backupDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* The last step of a swap, once the store matched the stage and the complete manifest
|
||||
* `{ version, sourceRef, complete: true, skills, journal: null }` is written: record `committed`,
|
||||
* then clear the stage, the backups and the journal. A cleanup that fails is a warning only: the
|
||||
* store is already complete.
|
||||
*/
|
||||
function verifySwapped(stage) {
|
||||
for (const name of stage.names) {
|
||||
if (skillTreeHash(path.join(stage.root, name)) !== stage.skills[name]) {
|
||||
throw canonicalError('commit-mismatch', `${name} in ${stage.root} does not match what was staged`, { retryable: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function finalizeCommit(stage, backupDir) {
|
||||
const { root, scope, operationId } = stage;
|
||||
const warnings = [];
|
||||
try {
|
||||
journalRecord(root, { op: 'committed', scope, operationId, source: stage.stageDir, destination: root });
|
||||
} catch (err) {
|
||||
warnings.push(`Could not record the finished swap: ${err.message}`);
|
||||
}
|
||||
removeQuietly(stage.stageDir, warnings);
|
||||
if (backupDir) removeQuietly(backupDir, warnings);
|
||||
try {
|
||||
removeJournal(root);
|
||||
} catch (err) {
|
||||
warnings.push(`Could not remove the journal: ${err.message}`);
|
||||
}
|
||||
return { complete: true, root, skills: stage.skills, warnings };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Reconcile
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Whether an earlier run left anything beside a scope's store: a journal, a stage (a run killed
|
||||
* mid-copy leaves one before its first journal record) or a backup folder.
|
||||
*/
|
||||
function hasCanonicalResidue(scope, cwd = process.cwd(), home = os.homedir()) {
|
||||
const root = canonicalRoot(scope, cwd, home);
|
||||
const left = residue(root);
|
||||
return fs.existsSync(journalPath(root)) || left.stages.length > 0 || left.backups.length > 0;
|
||||
}
|
||||
|
||||
/** Whether `pid` is another process that is still running (console-stage.js's rule). */
|
||||
function otherProcessAlive(pid) {
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) return false;
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (err) {
|
||||
return err.code === 'EPERM';
|
||||
}
|
||||
}
|
||||
|
||||
/** The pid in a stage or backup folder's name (`<prefix><pid>-<timestamp>`), or null. */
|
||||
function residuePid(name, prefix) {
|
||||
const match = /^(\d+)-\d+$/.exec(name.slice(prefix.length));
|
||||
return match ? Number(match[1]) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage and backup folders left beside the store, by kind. A folder whose install is still running
|
||||
* in another process (the app's update beside a terminal's, say) is not residue: it is counted in
|
||||
* `live` and never touched, so two installs at once cannot delete each other's work.
|
||||
*/
|
||||
function residue(root) {
|
||||
const parent = path.dirname(root);
|
||||
let names = [];
|
||||
try {
|
||||
names = fs.readdirSync(parent);
|
||||
} catch {}
|
||||
let live = 0;
|
||||
const left = (prefix) =>
|
||||
names
|
||||
.filter((n) => n.startsWith(prefix))
|
||||
.filter((n) => {
|
||||
if (!otherProcessAlive(residuePid(n, prefix))) return true;
|
||||
live++;
|
||||
return false;
|
||||
})
|
||||
.map((n) => path.join(parent, n));
|
||||
const stages = left(STAGE_PREFIX);
|
||||
const backups = left(BACKUP_PREFIX);
|
||||
return { stages, backups, live };
|
||||
}
|
||||
|
||||
/**
|
||||
* After an interruption, put back each backed-up expected skill whose canonical folder is gone
|
||||
* (the swap stopped between moving the old copy out and the new one in). Returns the names restored.
|
||||
*/
|
||||
function restoreOrphanedBackups(root, backups, expectedNames) {
|
||||
const expected = new Set(expectedNames);
|
||||
const restored = [];
|
||||
for (const backupDir of backups) {
|
||||
let names = [];
|
||||
try {
|
||||
names = fs.readdirSync(backupDir);
|
||||
} catch {}
|
||||
for (const name of names) {
|
||||
const dest = path.join(root, name);
|
||||
if (!expected.has(name) || lstatOrNull(dest)) continue;
|
||||
try {
|
||||
fs.mkdirSync(root, { recursive: true });
|
||||
renameWithRetry(path.join(backupDir, name), dest);
|
||||
restored.push(name);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
return restored;
|
||||
}
|
||||
|
||||
/** Whether `builtDir` holds a folder for every expected skill. */
|
||||
function builtSourceAvailable(builtDir, expectedNames) {
|
||||
if (!builtDir) return false;
|
||||
return expectedNames.every((name) => {
|
||||
const stat = lstatOrNull(path.join(builtDir, name));
|
||||
return Boolean(stat && stat.isDirectory() && !stat.isSymbolicLink());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and repair what an interrupted or damaged install left: stage folders, an unfinished
|
||||
* journal, backups, skills that changed on disk or are missing. A complete store with nothing
|
||||
* left over returns `{ complete: true }` without copying anything. Otherwise orphaned backups
|
||||
* are put back first; then, with the built skills at hand, the store is staged and committed
|
||||
* again (`repaired: true`), or, without them, `{ complete: false, issues }` says what is wrong.
|
||||
* Leftover stages, backups and journal are removed only once the store is complete.
|
||||
*/
|
||||
function reconcileCanonicalSkills(scope, builtDir, expectedNames, { cwd = process.cwd(), home = os.homedir(), version = null, sourceRef = null } = {}) {
|
||||
const root = canonicalRoot(scope, cwd, home);
|
||||
const issues = [];
|
||||
const left = residue(root);
|
||||
if (left.stages.length) issues.push(`${left.stages.length} unfinished stage(s)`);
|
||||
if (left.backups.length) issues.push(`${left.backups.length} backup folder(s)`);
|
||||
if (fs.existsSync(journalPath(root))) issues.push('an unfinished journal');
|
||||
|
||||
const restored = restoreOrphanedBackups(root, left.backups, expectedNames);
|
||||
if (restored.length) issues.push(`restored ${restored.join(', ')} from a backup`);
|
||||
|
||||
const check = validateCanonicalManifest(scope, expectedNames, { cwd, home, version });
|
||||
issues.push(...check.problems);
|
||||
|
||||
const clearResidue = () => {
|
||||
const warnings = [];
|
||||
for (const dir of [...left.stages, ...left.backups]) removeQuietly(dir, warnings);
|
||||
// The journal is shared: while another install is running, it is that install's to clear.
|
||||
if (left.live === 0) {
|
||||
try {
|
||||
removeJournal(root);
|
||||
} catch (err) {
|
||||
warnings.push(`Could not remove the journal: ${err.message}`);
|
||||
}
|
||||
}
|
||||
return warnings;
|
||||
};
|
||||
|
||||
if (check.complete) {
|
||||
if (issues.length === 0) return { complete: true, repaired: false, issues };
|
||||
return { complete: true, repaired: false, issues, warnings: clearResidue() };
|
||||
}
|
||||
if (!builtSourceAvailable(builtDir, expectedNames)) return { complete: false, repaired: false, issues };
|
||||
|
||||
const stage = stageCanonicalSkills({ scope, builtDir, expectedNames, cwd, home, version, sourceRef });
|
||||
const committed = commitCanonicalSkills(stage);
|
||||
return { complete: true, repaired: true, issues, warnings: [...committed.warnings, ...clearResidue()] };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Retired skills
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The Plan2Code skills in a scope's store this build no longer has: every entry whose name
|
||||
* starts with `plan2code` and is not expected (folders, stray copies without a SKILL.md, and
|
||||
* links). Expected names are always kept.
|
||||
*/
|
||||
function retiredSkillNames(scope, expectedNames, { cwd = process.cwd(), home = os.homedir() } = {}) {
|
||||
const root = canonicalRoot(scope, cwd, home);
|
||||
const keep = new Set(expectedNames);
|
||||
let names = [];
|
||||
try {
|
||||
names = fs.readdirSync(root);
|
||||
} catch {}
|
||||
return names.filter((name) => OUR_NAME.test(name) && !keep.has(name) && SKILL_NAME.test(name)).sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove retired skills from the store, once the skills CLI has been asked to unlink them: a link
|
||||
* is unlinked itself, a folder removed. Returns `{ removed, warnings }`.
|
||||
*/
|
||||
function removeRetiredCanonical(scope, retiredNames, { cwd = process.cwd(), home = os.homedir() } = {}) {
|
||||
const root = canonicalRoot(scope, cwd, home);
|
||||
const removed = [];
|
||||
const warnings = [];
|
||||
for (const name of retiredNames) {
|
||||
if (!OUR_NAME.test(name) || !SKILL_NAME.test(name)) continue;
|
||||
const entry = path.join(root, name);
|
||||
const stat = lstatOrNull(entry);
|
||||
if (!stat) continue;
|
||||
try {
|
||||
if (stat.isSymbolicLink()) fs.unlinkSync(entry);
|
||||
else fs.rmSync(entry, { recursive: true, force: true });
|
||||
removed.push(name);
|
||||
} catch (err) {
|
||||
warnings.push(`Could not remove ${entry}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
return { removed, warnings };
|
||||
}
|
||||
|
||||
/** Unlink every `plan2code*` link in the store whose target is gone (the link itself, never what it pointed at). */
|
||||
function sweepBrokenLinks(scope, { cwd = process.cwd(), home = os.homedir() } = {}) {
|
||||
const root = canonicalRoot(scope, cwd, home);
|
||||
const removed = [];
|
||||
let names = [];
|
||||
try {
|
||||
names = fs.readdirSync(root);
|
||||
} catch {}
|
||||
for (const name of names) {
|
||||
if (!OUR_NAME.test(name)) continue;
|
||||
const entry = path.join(root, name);
|
||||
const stat = lstatOrNull(entry);
|
||||
if (!stat || !stat.isSymbolicLink() || fs.existsSync(entry)) continue;
|
||||
try {
|
||||
fs.unlinkSync(entry);
|
||||
removed.push(name);
|
||||
} catch {}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything this module adds beside a store, for an uninstall: the manifest, the journal and any
|
||||
* stage or backup folder an interrupted run left. Skill folders are the caller's to remove.
|
||||
* Returns `{ removed, failed }` (paths, and `path: message` lines).
|
||||
*/
|
||||
function removeCanonicalMetadata(root) {
|
||||
const result = { removed: [], failed: [] };
|
||||
const targets = [manifestPath(root), journalPath(root)];
|
||||
try {
|
||||
for (const name of fs.readdirSync(path.dirname(root))) {
|
||||
if (name.startsWith(STAGE_PREFIX) || name.startsWith(BACKUP_PREFIX)) targets.push(path.join(path.dirname(root), name));
|
||||
}
|
||||
} catch {}
|
||||
for (const target of targets) {
|
||||
if (!lstatOrNull(target)) continue;
|
||||
try {
|
||||
fs.rmSync(target, { recursive: true, force: true });
|
||||
result.removed.push(target);
|
||||
} catch (err) {
|
||||
result.failed.push(`${target}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
removeCanonicalMetadata,
|
||||
MANIFEST_NAME,
|
||||
JOURNAL_NAME,
|
||||
canonicalRoot,
|
||||
journalPath,
|
||||
readJournal,
|
||||
journalRecord,
|
||||
stageCanonicalSkills,
|
||||
commitCanonicalSkills,
|
||||
reconcileCanonicalSkills,
|
||||
hasCanonicalResidue,
|
||||
validateCanonicalManifest,
|
||||
readCanonicalManifest,
|
||||
retiredSkillNames,
|
||||
removeRetiredCanonical,
|
||||
sweepBrokenLinks,
|
||||
skillTreeHash,
|
||||
};
|
||||
@@ -0,0 +1,470 @@
|
||||
'use strict';
|
||||
|
||||
// The shared console, installed as one validated folder per version: the built tree is copied
|
||||
// into a stage beside the version folder, checked byte for byte, marked complete last, then
|
||||
// renamed into place with the old folder kept as a backup until the new one validates. A folder a
|
||||
// running server holds open is replaced in place instead, and says so. Zero dependencies, CommonJS.
|
||||
//
|
||||
// Layout, under the console home (~/.plan2code/console, or PLAN2CODE_CONSOLE_HOME):
|
||||
// <version>/ the installed console
|
||||
// <version>/.plan2code-console-manifest.json every file with its sha256 and byte count
|
||||
// <version>/.complete written last: the version and when
|
||||
// <version>.install-<pid>-<timestamp>/ a stage, while it is built
|
||||
// <version>.backup-<pid>-<timestamp>/ the replaced folder, while a swap runs
|
||||
// console-dir the path of the current version folder
|
||||
// Nothing else in the home (sessions/, looks.json, workspaces.json, runtime files) is touched.
|
||||
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const MANIFEST_NAME = '.plan2code-console-manifest.json';
|
||||
const COMPLETE_NAME = '.complete';
|
||||
const POINTER_NAME = 'console-dir';
|
||||
const MANIFEST_VERSION = 1;
|
||||
const VERSION_DIR = /^\d+\.\d+\.\d+$/;
|
||||
const RESIDUE = /^(\d+\.\d+\.\d+)\.(install|backup)-(\d+)-(\d+)$/;
|
||||
// The codes a rename gets when a running server or the platform holds the folder open.
|
||||
const LOCKED = new Set(['EPERM', 'EACCES', 'EBUSY']);
|
||||
const RENAME_ATTEMPTS = 8;
|
||||
|
||||
const DEFAULT_OPS = {
|
||||
rename: (from, to) => fs.renameSync(from, to),
|
||||
rm: (target, options) => fs.rmSync(target, options),
|
||||
cp: (from, to, options) => fs.cpSync(from, to, options),
|
||||
};
|
||||
|
||||
/**
|
||||
* The folder the shared console lives in: PLAN2CODE_CONSOLE_HOME when set (the console's own
|
||||
* override, which the tests use), else ~/.plan2code/console. Read when called, never at load.
|
||||
*/
|
||||
function consoleHomeDir(env = process.env) {
|
||||
return env.PLAN2CODE_CONSOLE_HOME || path.join(os.homedir(), '.plan2code', 'console');
|
||||
}
|
||||
|
||||
/** An error with a `code` the installer can name. */
|
||||
function consoleError(code, message, extra = {}) {
|
||||
return Object.assign(new Error(message), { code }, extra);
|
||||
}
|
||||
|
||||
function lstatOrNull(file) {
|
||||
try {
|
||||
return fs.lstatSync(file);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(file) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function sha256(buffer) {
|
||||
return crypto.createHash('sha256').update(buffer).digest('hex');
|
||||
}
|
||||
|
||||
function assertVersion(version) {
|
||||
if (typeof version !== 'string' || !VERSION_DIR.test(version)) {
|
||||
throw consoleError('bad-version', `Refusing console version ${JSON.stringify(version)}: not x.y.z`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Block for `ms` milliseconds without spinning. */
|
||||
function pause(ms) {
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
||||
}
|
||||
|
||||
/** A rename, retried with a growing pause while Windows reports the folder busy for a moment. */
|
||||
function renameWithRetry(rename, from, to) {
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try {
|
||||
rename(from, to);
|
||||
return;
|
||||
} catch (err) {
|
||||
if (process.platform !== 'win32' || !LOCKED.has(err.code) || attempt >= RENAME_ATTEMPTS) throw err;
|
||||
pause(10 * attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Write text through a temp file and a rename, so a reader never sees half a file. */
|
||||
function writeFileAtomic(file, text) {
|
||||
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
||||
try {
|
||||
fs.writeFileSync(tmp, text);
|
||||
renameWithRetry(DEFAULT_OPS.rename, tmp, file);
|
||||
} catch (err) {
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove a folder, adding a warning line instead of throwing. */
|
||||
function removeQuietly(dir, warnings, rm = DEFAULT_OPS.rm) {
|
||||
try {
|
||||
rm(dir, { recursive: true, force: true });
|
||||
return true;
|
||||
} catch (err) {
|
||||
warnings.push(`Could not remove ${dir}: ${err.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every regular file under `dir` as sorted forward-slash paths relative to it, leaving out the
|
||||
* two markers at its top. A link anywhere is refused rather than followed.
|
||||
*/
|
||||
function listTree(dir) {
|
||||
const files = [];
|
||||
const walk = (current, rel) => {
|
||||
for (const name of fs.readdirSync(current).sort()) {
|
||||
if (!rel && (name === MANIFEST_NAME || name === COMPLETE_NAME)) continue;
|
||||
const full = path.join(current, name);
|
||||
const relPath = rel ? `${rel}/${name}` : name;
|
||||
const stat = fs.lstatSync(full);
|
||||
if (stat.isSymbolicLink()) throw consoleError('link-in-tree', `Refusing ${full}: links are not copied`);
|
||||
if (stat.isDirectory()) walk(full, relPath);
|
||||
else if (stat.isFile()) files.push(relPath);
|
||||
else throw consoleError('special-file', `Refusing ${full}: not a regular file`);
|
||||
}
|
||||
};
|
||||
walk(dir, '');
|
||||
return files.sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a console folder against its own manifest: `{ complete, problems, manifest, marker }`.
|
||||
* Complete means a manifest for `version`, every file it lists present with its byte count and
|
||||
* hash, and a `.complete` for the same version. `hashes: false` checks the byte counts only, for a
|
||||
* folder whose bytes were already hashed and only renamed since.
|
||||
*/
|
||||
function verifyConsoleDir(dir, version, { hashes = true } = {}) {
|
||||
const problems = [];
|
||||
const manifest = readJson(path.join(dir, MANIFEST_NAME));
|
||||
const marker = readJson(path.join(dir, COMPLETE_NAME));
|
||||
if (!manifest || !Array.isArray(manifest.files)) problems.push('no manifest');
|
||||
else {
|
||||
if (manifest.version !== version) problems.push(`manifest is for ${manifest.version || 'no version'}`);
|
||||
for (const entry of manifest.files) {
|
||||
const file = path.join(dir, ...String(entry.path).split('/'));
|
||||
const stat = lstatOrNull(file);
|
||||
if (!stat || !stat.isFile()) problems.push(`${entry.path}: missing`);
|
||||
else if (stat.size !== entry.bytes || (hashes && sha256(fs.readFileSync(file)) !== entry.sha256)) problems.push(`${entry.path}: changed on disk`);
|
||||
}
|
||||
}
|
||||
if (!marker) problems.push('no .complete');
|
||||
else if (marker.version !== version) problems.push(`.complete is for ${marker.version || 'no version'}`);
|
||||
return { complete: problems.length === 0, problems, manifest, marker };
|
||||
}
|
||||
|
||||
/** A folder from before the markers: valid only with console.mjs and its version in version.txt or version.json. */
|
||||
function preMarkerValid(dir, version) {
|
||||
if (!fs.existsSync(path.join(dir, 'console.mjs'))) return false;
|
||||
let text = null;
|
||||
try {
|
||||
text = fs.readFileSync(path.join(dir, 'version.txt'), 'utf8').trim();
|
||||
} catch {}
|
||||
if (text === version) return true;
|
||||
const json = readJson(path.join(dir, 'version.json'));
|
||||
return Boolean(json && json.version === version);
|
||||
}
|
||||
|
||||
/**
|
||||
* How one version folder stands: `{ state, problems }`, state `missing`, `complete` (markers that
|
||||
* verify), `pre-marker` (no markers, but console.mjs and a matching version file) or `incomplete`.
|
||||
*/
|
||||
function destState(dir, version) {
|
||||
const stat = lstatOrNull(dir);
|
||||
if (!stat) return { state: 'missing', problems: ['not installed'] };
|
||||
if (stat.isSymbolicLink() || !stat.isDirectory()) return { state: 'incomplete', problems: ['not a plain folder'] };
|
||||
const hasMarkers = fs.existsSync(path.join(dir, MANIFEST_NAME)) || fs.existsSync(path.join(dir, COMPLETE_NAME));
|
||||
if (!hasMarkers) {
|
||||
return preMarkerValid(dir, version)
|
||||
? { state: 'pre-marker', problems: [] }
|
||||
: { state: 'incomplete', problems: ['no .complete, and no console.mjs with a matching version file'] };
|
||||
}
|
||||
const verified = verifyConsoleDir(dir, version);
|
||||
return verified.complete ? { state: 'complete', problems: [] } : { state: 'incomplete', problems: verified.problems };
|
||||
}
|
||||
|
||||
/** Whether the folder for `version` is a usable console: complete with markers, or a valid pre-marker one. */
|
||||
function isCompleteConsoleInstall({ version, home = consoleHomeDir() } = {}) {
|
||||
assertVersion(version);
|
||||
const { state } = destState(path.join(home, version), version);
|
||||
return state === 'complete' || state === 'pre-marker';
|
||||
}
|
||||
|
||||
/** The stages and backups an earlier run left in the home, each `{ name, dir, version, kind, pid }`. */
|
||||
function listResidue(home) {
|
||||
let entries = [];
|
||||
try {
|
||||
entries = fs.readdirSync(home, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const found = [];
|
||||
for (const entry of entries) {
|
||||
const m = RESIDUE.exec(entry.name);
|
||||
if (!m || !entry.isDirectory()) continue;
|
||||
found.push({ name: entry.name, dir: path.join(home, entry.name), version: m[1], kind: m[2], pid: Number(m[3]), at: Number(m[4]) });
|
||||
}
|
||||
return found.sort((a, b) => b.at - a.at);
|
||||
}
|
||||
|
||||
/** Whether another process with this pid is running (a concurrent install still building its stage). */
|
||||
function otherProcessAlive(pid) {
|
||||
if (pid === process.pid) return false;
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (err) {
|
||||
return err.code === 'EPERM';
|
||||
}
|
||||
}
|
||||
|
||||
function readPointer(home) {
|
||||
try {
|
||||
return fs.readFileSync(path.join(home, POINTER_NAME), 'utf8').trim() || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything about the console install for `version`: `{ version, home, dest, state, complete,
|
||||
* problems, staging, backups, pointer, pointerOk }`. `staging` lists stages left behind for any
|
||||
* version (never usable once their run ended), `backups` the backups of this version. Complete
|
||||
* means a usable folder, `console-dir` naming it, and no stage or backup of this version left.
|
||||
*/
|
||||
function consoleInstallState({ version, home = consoleHomeDir() } = {}) {
|
||||
assertVersion(version);
|
||||
const dest = path.join(home, version);
|
||||
const { state, problems } = destState(dest, version);
|
||||
const residue = listResidue(home);
|
||||
const staging = residue.filter((r) => r.kind === 'install');
|
||||
const backups = residue.filter((r) => r.kind === 'backup' && r.version === version);
|
||||
const pointer = readPointer(home);
|
||||
const pointerOk = pointer !== null && path.resolve(pointer) === path.resolve(dest);
|
||||
const all = [...problems];
|
||||
if (!pointerOk) all.push(pointer ? `console-dir names ${pointer}` : 'no console-dir');
|
||||
for (const s of staging.filter((r) => r.version === version)) all.push(`an interrupted copy is left in ${s.name}`);
|
||||
for (const b of backups) all.push(`a backup is left in ${b.name}`);
|
||||
const usable = state === 'complete' || state === 'pre-marker';
|
||||
return { version, home, dest, state, complete: usable && all.length === 0, problems: all, staging, backups, pointer, pointerOk };
|
||||
}
|
||||
|
||||
/** A new, empty `<version>.install-<pid>-<timestamp>` folder; a name taken in the same millisecond moves on a step. */
|
||||
function makeStageDir(home, version) {
|
||||
const start = Date.now();
|
||||
for (let step = 0; ; step++) {
|
||||
const stageDir = path.join(home, `${version}.install-${process.pid}-${start + step}`);
|
||||
try {
|
||||
fs.mkdirSync(stageDir);
|
||||
return stageDir;
|
||||
} catch (err) {
|
||||
if (err.code !== 'EEXIST' || step >= 9) throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy the built console at `source` into `<version>.install-<pid>-<timestamp>` under `home`, write
|
||||
* the manifest, check every copied file against it, and only then write `.complete`. Refuses a
|
||||
* source without console.mjs; a failed stage is removed. Returns `{ stageDir, home, version, dest,
|
||||
* source, manifest }`.
|
||||
*/
|
||||
function stageConsole({ version, source, home = consoleHomeDir() } = {}) {
|
||||
assertVersion(version);
|
||||
if (!source || !fs.existsSync(path.join(source, 'console.mjs'))) throw consoleError('not-built', `${source} is not built`);
|
||||
fs.mkdirSync(home, { recursive: true });
|
||||
const stageDir = makeStageDir(home, version);
|
||||
try {
|
||||
const files = [];
|
||||
for (const rel of listTree(source)) {
|
||||
const from = path.join(source, ...rel.split('/'));
|
||||
const to = path.join(stageDir, ...rel.split('/'));
|
||||
fs.mkdirSync(path.dirname(to), { recursive: true });
|
||||
// copyFileSync, not a write of the bytes read: on Windows the platform copy is several
|
||||
// times faster than writing each new file, and the hash below still checks the copy.
|
||||
fs.copyFileSync(from, to);
|
||||
const bytes = fs.readFileSync(from);
|
||||
files.push({ path: rel, sha256: sha256(bytes), bytes: bytes.length });
|
||||
}
|
||||
const manifest = { manifestVersion: MANIFEST_VERSION, version, files };
|
||||
fs.writeFileSync(path.join(stageDir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + '\n');
|
||||
// The copy is checked before the marker goes in: a stage without .complete is never used.
|
||||
for (const entry of files) {
|
||||
const copied = path.join(stageDir, ...entry.path.split('/'));
|
||||
const stat = lstatOrNull(copied);
|
||||
if (!stat || !stat.isFile() || stat.size !== entry.bytes || sha256(fs.readFileSync(copied)) !== entry.sha256) {
|
||||
throw consoleError('stage-mismatch', `The staged copy of ${entry.path} does not match the build`);
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(path.join(stageDir, COMPLETE_NAME), JSON.stringify({ version, completedAt: new Date().toISOString() }) + '\n');
|
||||
return { stageDir, home, version, dest: path.join(home, version), source, manifest };
|
||||
} catch (err) {
|
||||
removeQuietly(stageDir, []);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finish or undo what an earlier run left for `version` before a new commit: remove stages that
|
||||
* are not `keep` (and not still being built by another running install); with a complete folder
|
||||
* in place remove its backups; with none, put the newest backup that is usable back. Returns
|
||||
* `{ removed, restored, warnings }`.
|
||||
*/
|
||||
function recoverConsoleInstall({ version, home, keep = null, ops = DEFAULT_OPS }) {
|
||||
const warnings = [];
|
||||
const removed = [];
|
||||
let restored = null;
|
||||
for (const stage of listResidue(home).filter((r) => r.kind === 'install')) {
|
||||
if (keep && path.resolve(stage.dir) === path.resolve(keep)) continue;
|
||||
if (otherProcessAlive(stage.pid)) continue;
|
||||
if (removeQuietly(stage.dir, warnings, ops.rm)) removed.push(stage.name);
|
||||
}
|
||||
const dest = path.join(home, version);
|
||||
const backups = listResidue(home).filter((r) => r.kind === 'backup' && r.version === version);
|
||||
const { state } = destState(dest, version);
|
||||
if (state !== 'complete' && state !== 'pre-marker') {
|
||||
const usable = backups.find((b) => {
|
||||
const s = destState(b.dir, version).state;
|
||||
return s === 'complete' || s === 'pre-marker';
|
||||
});
|
||||
if (usable) {
|
||||
try {
|
||||
if (state !== 'missing') ops.rm(dest, { recursive: true, force: true });
|
||||
renameWithRetry(ops.rename, usable.dir, dest);
|
||||
restored = usable.name;
|
||||
} catch (err) {
|
||||
warnings.push(`Could not put back the backup ${usable.name}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (restored || state === 'complete' || state === 'pre-marker') {
|
||||
for (const b of backups) {
|
||||
if (b.name === restored) continue;
|
||||
if (removeQuietly(b.dir, warnings, ops.rm)) removed.push(b.name);
|
||||
}
|
||||
}
|
||||
return { removed, restored, warnings };
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the stages and backups other versions left behind (an update interrupted on its way to a
|
||||
* version that never went in), keeping `keepVersion`'s, which commitConsole() recovers, and any
|
||||
* stage another running install is still building. Returns `{ removed, warnings }`.
|
||||
*/
|
||||
function sweepConsoleResidue({ home = consoleHomeDir(), keepVersion } = {}) {
|
||||
const warnings = [];
|
||||
const removed = [];
|
||||
for (const entry of listResidue(home)) {
|
||||
if (entry.version === keepVersion || otherProcessAlive(entry.pid)) continue;
|
||||
if (removeQuietly(entry.dir, warnings)) removed.push(entry.name);
|
||||
}
|
||||
return { removed, warnings };
|
||||
}
|
||||
|
||||
/** The in-place copy for a folder that cannot be renamed: everything but .complete, then .complete. */
|
||||
function copyInPlace(stage, ops) {
|
||||
try {
|
||||
ops.rm(stage.dest, { recursive: true, force: true });
|
||||
} catch {
|
||||
// A running server holds files open on Windows: the copy below overwrites them in place.
|
||||
}
|
||||
ops.cp(stage.stageDir, stage.dest, { recursive: true, force: true, filter: (from) => path.basename(from) !== COMPLETE_NAME || path.dirname(from) !== stage.stageDir });
|
||||
ops.cp(path.join(stage.stageDir, COMPLETE_NAME), path.join(stage.dest, COMPLETE_NAME), { force: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a validated stage in place as `<version>`. With no folder there the stage is renamed in;
|
||||
* with one, it is renamed to `<version>.backup-<pid>-<timestamp>`, the stage renamed in, and the
|
||||
* backup removed once the new folder validates. A rename a lock refuses falls back to copying the
|
||||
* stage over the folder in place, verified the same way (`fallbackUsed`, with a warning). Leftovers
|
||||
* from an earlier run are recovered first. `console-dir` is written through a temp file and a
|
||||
* rename. Returns `{ committed, dest, backupDir, fallbackUsed, warnings, recovered }`.
|
||||
*/
|
||||
function commitConsole(stage, { ops: given = {} } = {}) {
|
||||
const ops = { ...DEFAULT_OPS, ...given };
|
||||
const { version, home, dest, stageDir } = stage;
|
||||
assertVersion(version);
|
||||
// stageConsole() hashed every copied file; here the stage only has to be whole still.
|
||||
const stageCheck = verifyConsoleDir(stageDir, version, { hashes: false });
|
||||
if (!stageCheck.complete) throw consoleError('stage-invalid', `The staged console is not complete: ${stageCheck.problems.join('; ')}`);
|
||||
|
||||
const recovered = recoverConsoleInstall({ version, home, keep: stageDir, ops });
|
||||
const warnings = [...recovered.warnings];
|
||||
let backupDir = null;
|
||||
let fallbackUsed = false;
|
||||
|
||||
const fallback = (err) => {
|
||||
if (!LOCKED.has(err.code)) throw err;
|
||||
copyInPlace(stage, ops);
|
||||
fallbackUsed = true;
|
||||
warnings.push(`The console in ${dest} is in use (${err.code}), so it was copied over in place instead of swapped; restart any open console to use the new one`);
|
||||
};
|
||||
|
||||
if (!lstatOrNull(dest)) {
|
||||
try {
|
||||
renameWithRetry(ops.rename, stageDir, dest);
|
||||
} catch (err) {
|
||||
fallback(err);
|
||||
}
|
||||
} else {
|
||||
const candidate = path.join(home, `${version}.backup-${process.pid}-${Date.now()}`);
|
||||
let movedAside = false;
|
||||
try {
|
||||
renameWithRetry(ops.rename, dest, candidate);
|
||||
movedAside = true;
|
||||
backupDir = candidate;
|
||||
renameWithRetry(ops.rename, stageDir, dest);
|
||||
} catch (err) {
|
||||
if (movedAside && !lstatOrNull(dest)) {
|
||||
try {
|
||||
renameWithRetry(ops.rename, candidate, dest);
|
||||
backupDir = null;
|
||||
} catch {
|
||||
// The backup stays beside the folder; the next run puts it back.
|
||||
}
|
||||
}
|
||||
fallback(err);
|
||||
}
|
||||
}
|
||||
|
||||
// A rename moves the hashed stage as it is; a copy in place is hashed again.
|
||||
const check = verifyConsoleDir(dest, version, { hashes: fallbackUsed });
|
||||
if (!check.complete) {
|
||||
if (backupDir && lstatOrNull(backupDir)) {
|
||||
try {
|
||||
ops.rm(dest, { recursive: true, force: true });
|
||||
renameWithRetry(ops.rename, backupDir, dest);
|
||||
backupDir = null;
|
||||
} catch {}
|
||||
}
|
||||
throw consoleError('commit-invalid', `The installed console in ${dest} did not validate: ${check.problems.join('; ')}`);
|
||||
}
|
||||
if (backupDir && lstatOrNull(backupDir)) removeQuietly(backupDir, warnings, ops.rm);
|
||||
if (lstatOrNull(stageDir)) removeQuietly(stageDir, warnings, ops.rm);
|
||||
writeFileAtomic(path.join(home, POINTER_NAME), `${dest}\n`);
|
||||
return { committed: true, dest, backupDir, fallbackUsed, warnings, recovered };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
MANIFEST_NAME,
|
||||
COMPLETE_NAME,
|
||||
POINTER_NAME,
|
||||
consoleHomeDir,
|
||||
stageConsole,
|
||||
commitConsole,
|
||||
consoleInstallState,
|
||||
isCompleteConsoleInstall,
|
||||
verifyConsoleDir,
|
||||
sweepConsoleResidue,
|
||||
};
|
||||
@@ -0,0 +1,248 @@
|
||||
'use strict';
|
||||
|
||||
// The adaptive skills CLI runner: which exact `skills` version this Node can run, where npx
|
||||
// already cached that version, and how to run it. Zero dependencies, CommonJS, so install.js can
|
||||
// require it from a fresh npx copy before anything else is installed.
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { spawn, spawnSync } = require('child_process');
|
||||
|
||||
// Exact pins only, never `latest` or a range: a new skills release can never change an install
|
||||
// between two runs of the same Plan2Code. 1.7.x needs Node 22.20.0+, so older Node (down to
|
||||
// Plan2Code's own Node 18 floor) runs the last 1.5.x.
|
||||
const SKILLS_CLI_PINS = Object.freeze({ legacy: '1.5.18', current: '1.7.6', nodeFloor: '22.20.0' });
|
||||
|
||||
/**
|
||||
* `{ numbers: [major, minor, patch], prerelease }` from a version like `v22.20.0` or
|
||||
* `22.20.0-rc.1`, or null when it is not one.
|
||||
*/
|
||||
function parseVersion(version) {
|
||||
const match = /^v?(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?/.exec(String(version || '').trim());
|
||||
return match ? { numbers: [Number(match[1]), Number(match[2]), Number(match[3])], prerelease: Boolean(match[4]) } : null;
|
||||
}
|
||||
|
||||
/** Negative, zero or positive as `a` is below, equal to or above `b` (both `[major, minor, patch]`). */
|
||||
function compareVersions(a, b) {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (a[i] !== b[i]) return a[i] - b[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The skills CLI version for this Node: the legacy pin below the floor (or an unreadable version),
|
||||
* the current one at or above it. A prerelease of the floor itself (`22.20.0-rc.1`) is below it,
|
||||
* as semver orders them.
|
||||
*/
|
||||
function selectSkillsCliVersion(nodeVersion = process.versions.node) {
|
||||
const node = parseVersion(nodeVersion);
|
||||
const floor = parseVersion(SKILLS_CLI_PINS.nodeFloor);
|
||||
if (!node) return SKILLS_CLI_PINS.legacy;
|
||||
const order = compareVersions(node.numbers, floor.numbers);
|
||||
return order > 0 || (order === 0 && !node.prerelease) ? SKILLS_CLI_PINS.current : SKILLS_CLI_PINS.legacy;
|
||||
}
|
||||
|
||||
/** A value from `env` by its name in any case (Windows environments are case-insensitive). */
|
||||
function envValue(env, name) {
|
||||
if (!env) return '';
|
||||
if (typeof env[name] === 'string' && env[name]) return env[name];
|
||||
const wanted = name.toLowerCase();
|
||||
for (const [key, value] of Object.entries(env)) {
|
||||
if (key.toLowerCase() === wanted && typeof value === 'string' && value) return value;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* The npm cache folders to look in, most likely first: `npm_config_cache` when set, then the
|
||||
* platform default (`%LocalAppData%/npm-cache` on Windows, `~/.npm` elsewhere), then the
|
||||
* `%AppData%/npm-cache` older npm versions used on Windows. Pure: reads only its arguments.
|
||||
*/
|
||||
function npmCacheCandidates(env = process.env, platform = process.platform, home = os.homedir()) {
|
||||
const join = platform === 'win32' ? path.win32.join : path.posix.join;
|
||||
const candidates = [];
|
||||
const configured = envValue(env, 'npm_config_cache');
|
||||
if (configured) candidates.push(configured);
|
||||
if (platform === 'win32') {
|
||||
candidates.push(join(envValue(env, 'LOCALAPPDATA') || join(home, 'AppData', 'Local'), 'npm-cache'));
|
||||
candidates.push(join(envValue(env, 'APPDATA') || join(home, 'AppData', 'Roaming'), 'npm-cache'));
|
||||
} else {
|
||||
candidates.push(join(home, '.npm'));
|
||||
}
|
||||
return [...new Set(candidates)];
|
||||
}
|
||||
|
||||
/** A JSON file's contents, or null when it is missing or not JSON. */
|
||||
function readJson(file) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The CLI file of a cached `skills@<pin>` in one npx folder (`<cache>/_npx/<hash>`), or null.
|
||||
* The package must name exactly the pin, carry bin/cli.mjs, and have each dependency it declares
|
||||
* installed beside it: a half-written cache entry is no hit.
|
||||
*/
|
||||
function cachedCliIn(npxDir, pin) {
|
||||
const modules = path.join(npxDir, 'node_modules');
|
||||
const pkg = readJson(path.join(modules, 'skills', 'package.json'));
|
||||
if (!pkg || pkg.version !== pin) return null;
|
||||
const cliFile = path.join(modules, 'skills', 'bin', 'cli.mjs');
|
||||
try {
|
||||
if (!fs.statSync(cliFile).isFile()) return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const deps = pkg.dependencies && typeof pkg.dependencies === 'object' ? Object.keys(pkg.dependencies) : [];
|
||||
for (const dep of deps) {
|
||||
if (!fs.existsSync(path.join(modules, ...dep.split('/'), 'package.json'))) return null;
|
||||
}
|
||||
return cliFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* How to run `skills@<pin>`: straight from npx's cache when an exact copy is already there
|
||||
* (`{ kind: "cached", executable, argsPrefix: [cliFile], pin }`), otherwise through npx
|
||||
* (`{ kind: "npx", command: "npx", argsPrefix: ["--yes", "skills@<pin>"], pin }`). The cache
|
||||
* is only a shortcut: the npx folder names are npm's private hashes, so every one is scanned,
|
||||
* and anything unreadable falls back to npx.
|
||||
*/
|
||||
function resolveSkillsCli(pin, options = {}) {
|
||||
const { env = process.env, platform = process.platform, home = os.homedir(), execPath = process.execPath } = options;
|
||||
const caches = options.caches || npmCacheCandidates(env, platform, home);
|
||||
for (const cache of caches) {
|
||||
const npxRoot = path.join(cache, '_npx');
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(npxRoot, { withFileTypes: true });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const entry of entries.filter((e) => e.isDirectory()).map((e) => e.name).sort()) {
|
||||
const cliFile = cachedCliIn(path.join(npxRoot, entry), pin);
|
||||
if (cliFile) return { kind: 'cached', executable: execPath, argsPrefix: [cliFile], pin };
|
||||
}
|
||||
}
|
||||
return { kind: 'npx', command: 'npx', argsPrefix: ['--yes', `skills@${pin}`], pin };
|
||||
}
|
||||
|
||||
/** One argument quoted for cmd.exe when it needs it (spaces or cmd's special characters). */
|
||||
function quoteForCmd(arg) {
|
||||
const text = String(arg);
|
||||
if (text && !/[\s"&|<>^()%!]/.test(text)) return text;
|
||||
return `"${text.replace(/"/g, '""')}"`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What to spawn for `cli` and `args`: `{ file, args, shell }`. The cached CLI runs node directly
|
||||
* with an argument list, so nothing passes through a shell. npx on Windows is npx.cmd, which
|
||||
* only a shell can start, so there the whole line is quoted for cmd.exe; elsewhere npx is a
|
||||
* plain executable and runs without a shell too.
|
||||
*/
|
||||
function spawnPlan(cli, args, platform = process.platform) {
|
||||
const full = [...cli.argsPrefix, ...args];
|
||||
if (cli.kind === 'cached') return { file: cli.executable, args: full, shell: false };
|
||||
if (platform === 'win32') return { file: [cli.command, ...full].map(quoteForCmd).join(' '), args: [], shell: true };
|
||||
return { file: cli.command, args: full, shell: false };
|
||||
}
|
||||
|
||||
/** The environment a CLI run gets: the caller's, with npm's `npm notice` lines kept quiet. */
|
||||
function cliEnv(env = process.env) {
|
||||
return { ...env, npm_config_loglevel: 'error' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the CLI and wait: `{ ok, output }`, the trimmed stdout on success, stdout and stderr
|
||||
* together on a failure. Output is captured, never streamed: the CLI prints a banner and a box
|
||||
* per agent that the installer's own summary replaces.
|
||||
*/
|
||||
function execSkillsCliSyncOnce(cli, args, { env = process.env, platform = process.platform, cwd } = {}) {
|
||||
const plan = spawnPlan(cli, args, platform);
|
||||
const result = spawnSync(plan.file, plan.args, {
|
||||
encoding: 'utf8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env: cliEnv(env),
|
||||
shell: plan.shell,
|
||||
windowsHide: true,
|
||||
cwd,
|
||||
});
|
||||
const stdout = result.stdout || '';
|
||||
const stderr = result.stderr || '';
|
||||
if (result.error) return { ok: false, output: `${stdout}\n${stderr || result.error.message}`.trim() };
|
||||
return result.status === 0 ? { ok: true, output: stdout.trim() } : { ok: false, output: `${stdout}\n${stderr}`.trim() };
|
||||
}
|
||||
|
||||
/** execSkillsCliSync without blocking, so a spinner can tick while the CLI works. Same `{ ok, output }`. */
|
||||
function execSkillsCliAsyncOnce(cli, args, { env = process.env, platform = process.platform, cwd } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const plan = spawnPlan(cli, args, platform);
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let child;
|
||||
try {
|
||||
child = spawn(plan.file, plan.args, {
|
||||
shell: plan.shell,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env: cliEnv(env),
|
||||
windowsHide: true,
|
||||
cwd,
|
||||
});
|
||||
} catch (err) {
|
||||
resolve({ ok: false, output: err.message });
|
||||
return;
|
||||
}
|
||||
child.stdin.end();
|
||||
child.stdout.setEncoding('utf8');
|
||||
child.stderr.setEncoding('utf8');
|
||||
child.stdout.on('data', (chunk) => { stdout += chunk; });
|
||||
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
||||
child.on('error', (err) => resolve({ ok: false, output: `${stdout}\n${stderr || err.message}`.trim() }));
|
||||
child.on('close', (code) => {
|
||||
resolve(code === 0 ? { ok: true, output: stdout.trim() } : { ok: false, output: `${stdout}\n${stderr}`.trim() });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** The command a person can paste to run the same thing by hand: always the npx form, with the pin. */
|
||||
function skillsCliDisplay(pin) {
|
||||
return `npx --yes skills@${pin}`;
|
||||
}
|
||||
|
||||
// A cached copy npm pruned part of (a dependency gone from its node_modules) fails before it does
|
||||
// anything; that copy is never fixed by running it again, so the same pin goes through npx instead.
|
||||
const BROKEN_CACHED_CLI = /Cannot find (?:module|package)|ERR_MODULE_NOT_FOUND|MODULE_NOT_FOUND/;
|
||||
|
||||
/** The npx form of a cached CLI, for when the cached copy is broken. */
|
||||
function npxFallback(cli) {
|
||||
return { kind: 'npx', command: 'npx', argsPrefix: ['--yes', `skills@${cli.pin}`], pin: cli.pin };
|
||||
}
|
||||
|
||||
/** Run the CLI and wait: `{ ok, output }`. A broken cached copy is retried once through npx. */
|
||||
function execSkillsCliSync(cli, args, options = {}) {
|
||||
const result = execSkillsCliSyncOnce(cli, args, options);
|
||||
if (result.ok || cli.kind !== 'cached' || !BROKEN_CACHED_CLI.test(result.output)) return result;
|
||||
return execSkillsCliSyncOnce(options.fallback || npxFallback(cli), args, options);
|
||||
}
|
||||
|
||||
/** Run the CLI without blocking: resolves `{ ok, output }`. A broken cached copy is retried once through npx. */
|
||||
async function execSkillsCliAsync(cli, args, options = {}) {
|
||||
const result = await execSkillsCliAsyncOnce(cli, args, options);
|
||||
if (result.ok || cli.kind !== 'cached' || !BROKEN_CACHED_CLI.test(result.output)) return result;
|
||||
return execSkillsCliAsyncOnce(options.fallback || npxFallback(cli), args, options);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SKILLS_CLI_PINS,
|
||||
selectSkillsCliVersion,
|
||||
npmCacheCandidates,
|
||||
resolveSkillsCli,
|
||||
spawnPlan,
|
||||
execSkillsCliSync,
|
||||
execSkillsCliAsync,
|
||||
skillsCliDisplay,
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function cleanFields(fields) {
|
||||
const out = {};
|
||||
for (const [key, value] of Object.entries(fields || {})) {
|
||||
if (value !== undefined) out[key] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function createTiming({ outputPath, ref, version, mode } = {}) {
|
||||
const target = outputPath !== undefined ? outputPath : process.env.PLAN2CODE_BENCH_JSON || null;
|
||||
const active = Boolean(target);
|
||||
const base = cleanFields({ ref, version, mode });
|
||||
|
||||
function write(record) {
|
||||
if (!active) return null;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.appendFileSync(target, `${JSON.stringify(record)}\n`, 'utf8');
|
||||
return record;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function timingEvent(name, extra = {}) {
|
||||
if (!active || typeof name !== 'string' || !name) return null;
|
||||
return write({ event: name, at: new Date().toISOString(), ...base, ...cleanFields(extra) });
|
||||
}
|
||||
|
||||
function timingDuration(name, startMark, extra = {}) {
|
||||
const durationMs = typeof startMark === 'number' ? Math.max(0, performance.now() - startMark) : 0;
|
||||
return timingEvent(name, { ...extra, durationMs });
|
||||
}
|
||||
|
||||
return { active, outputPath: target, timingEvent, timingDuration };
|
||||
}
|
||||
|
||||
function timingEvent(name, extra = {}) {
|
||||
return createTiming().timingEvent(name, extra);
|
||||
}
|
||||
|
||||
function timingDuration(name, startMark, extra = {}) {
|
||||
return createTiming().timingDuration(name, startMark, extra);
|
||||
}
|
||||
|
||||
function readTimingEvents(file) {
|
||||
let text;
|
||||
try {
|
||||
text = fs.readFileSync(file, 'utf8');
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const events = [];
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
if (!line.trim()) continue;
|
||||
try {
|
||||
const event = JSON.parse(line);
|
||||
if (event && typeof event === 'object' && !Array.isArray(event)) events.push(event);
|
||||
} catch {
|
||||
// Malformed lines are ignored so one partial write does not hide later events.
|
||||
}
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
module.exports = { createTiming, timingEvent, timingDuration, readTimingEvents };
|
||||
@@ -5,6 +5,10 @@
|
||||
"id": "default",
|
||||
"label": "your account setting"
|
||||
},
|
||||
{
|
||||
"id": "haiku",
|
||||
"label": "fast and efficient Haiku"
|
||||
},
|
||||
{
|
||||
"id": "sonnet",
|
||||
"label": "latest Sonnet"
|
||||
@@ -13,14 +17,6 @@
|
||||
"id": "opus",
|
||||
"label": "latest Opus"
|
||||
},
|
||||
{
|
||||
"id": "haiku",
|
||||
"label": "fast and efficient Haiku"
|
||||
},
|
||||
{
|
||||
"id": "opusplan",
|
||||
"label": "Opus in plan mode, Sonnet otherwise"
|
||||
},
|
||||
{
|
||||
"id": "fable",
|
||||
"label": "Fable for your hardest tasks"
|
||||
@@ -28,6 +24,10 @@
|
||||
{
|
||||
"id": "best",
|
||||
"label": "same model as Opus"
|
||||
},
|
||||
{
|
||||
"id": "opusplan",
|
||||
"label": "Opus in plan mode, Sonnet otherwise"
|
||||
}
|
||||
],
|
||||
"devin": [
|
||||
@@ -35,6 +35,10 @@
|
||||
"id": "adaptive",
|
||||
"label": "Adaptive"
|
||||
},
|
||||
{
|
||||
"id": "swe-2-flash-high",
|
||||
"label": "SWE-2 Flash High"
|
||||
},
|
||||
{
|
||||
"id": "swe-2-medium",
|
||||
"label": "SWE-2 Medium"
|
||||
@@ -44,20 +48,16 @@
|
||||
"label": "SWE-2 High"
|
||||
},
|
||||
{
|
||||
"id": "claude-opus-5-5-low",
|
||||
"label": "Claude Opus 5.5 Low"
|
||||
"id": "swe-2-1-medium",
|
||||
"label": "SWE-2.1 Medium"
|
||||
},
|
||||
{
|
||||
"id": "claude-opus-5-5-medium",
|
||||
"label": "Claude Opus 5.5 Medium"
|
||||
"id": "swe-2-1-high",
|
||||
"label": "SWE-2.1 High"
|
||||
},
|
||||
{
|
||||
"id": "claude-opus-5-5-high",
|
||||
"label": "Claude Opus 5.5 High"
|
||||
},
|
||||
{
|
||||
"id": "claude-sonnet-5-5-low",
|
||||
"label": "Claude Sonnet 5.5 Low"
|
||||
"id": "claude-haiku-5-5-high",
|
||||
"label": "Claude Haiku 5.5 High"
|
||||
},
|
||||
{
|
||||
"id": "claude-sonnet-5-5-medium",
|
||||
@@ -68,56 +68,12 @@
|
||||
"label": "Claude Sonnet 5.5 High"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-luna-low",
|
||||
"label": "GPT-6 Luna Low Thinking"
|
||||
"id": "claude-opus-5-5-medium",
|
||||
"label": "Claude Opus 5.5 Medium"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-luna-medium",
|
||||
"label": "GPT-6 Luna Medium Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-luna-high",
|
||||
"label": "GPT-6 Luna High Thinking"
|
||||
},
|
||||
{
|
||||
"id": "glm-5-3-high",
|
||||
"label": "GLM-5.3 High"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-1-sol-low",
|
||||
"label": "GPT-6.1 Sol Low Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-1-sol-medium",
|
||||
"label": "GPT-6.1 Sol Medium Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-1-sol-high",
|
||||
"label": "GPT-6.1 Sol High Thinking"
|
||||
},
|
||||
{
|
||||
"id": "claude-haiku-5-5-high",
|
||||
"label": "Claude Haiku 5.5 High"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-astra-low",
|
||||
"label": "GPT-6 Astra Low Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-astra-medium",
|
||||
"label": "GPT-6 Astra Medium Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-astra-high",
|
||||
"label": "GPT-6 Astra High Thinking"
|
||||
},
|
||||
{
|
||||
"id": "swe-2-flash-high",
|
||||
"label": "SWE-2 Flash High"
|
||||
},
|
||||
{
|
||||
"id": "claude-fable-5-2-low",
|
||||
"label": "Claude Fable 5.2 Low"
|
||||
"id": "claude-opus-5-5-high",
|
||||
"label": "Claude Opus 5.5 High"
|
||||
},
|
||||
{
|
||||
"id": "claude-fable-5-2-medium",
|
||||
@@ -128,8 +84,40 @@
|
||||
"label": "Claude Fable 5.2 High"
|
||||
},
|
||||
{
|
||||
"id": "gemini-4-hydrogen-low",
|
||||
"label": "Gemini 4 Hydrogen Low"
|
||||
"id": "fusion-claude-opus-5-5-medium-sidekick-swe-2-1-medium",
|
||||
"label": "Fusion (Claude Opus 5.5 Medium + SWE-2.1 Medium)"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-luna-medium",
|
||||
"label": "GPT-6 Luna Medium Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-luna-high",
|
||||
"label": "GPT-6 Luna High Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-1-sol-medium",
|
||||
"label": "GPT-6.1 Sol Medium Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-1-sol-high",
|
||||
"label": "GPT-6.1 Sol High Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-astra-medium",
|
||||
"label": "GPT-6 Astra Medium Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-astra-high",
|
||||
"label": "GPT-6 Astra High Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gemini-3-8-flash-medium",
|
||||
"label": "Gemini 3.8 Flash Medium"
|
||||
},
|
||||
{
|
||||
"id": "gemini-3-8-flash-high",
|
||||
"label": "Gemini 3.8 Flash High"
|
||||
},
|
||||
{
|
||||
"id": "gemini-4-hydrogen-medium",
|
||||
@@ -140,8 +128,12 @@
|
||||
"label": "Gemini 4 Hydrogen High"
|
||||
},
|
||||
{
|
||||
"id": "gemini-4-neon-low",
|
||||
"label": "Gemini 4 Neon Low"
|
||||
"id": "gemini-4-carbon-medium",
|
||||
"label": "Gemini 4 Carbon Medium"
|
||||
},
|
||||
{
|
||||
"id": "gemini-4-carbon-high",
|
||||
"label": "Gemini 4 Carbon High"
|
||||
},
|
||||
{
|
||||
"id": "gemini-4-neon-medium",
|
||||
@@ -150,32 +142,36 @@
|
||||
{
|
||||
"id": "gemini-4-neon-high",
|
||||
"label": "Gemini 4 Neon High"
|
||||
},
|
||||
{
|
||||
"id": "glm-5-3-high",
|
||||
"label": "GLM-5.3 High"
|
||||
}
|
||||
],
|
||||
"codex": [
|
||||
{
|
||||
"id": "gpt-6-astra",
|
||||
"label": "GPT-6 Astra"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6.1-sol",
|
||||
"label": "GPT-6.1 Sol"
|
||||
"id": "gpt-6-luna",
|
||||
"label": "GPT-6 Luna"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6.1-terra",
|
||||
"label": "GPT-6.1 Terra"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-luna",
|
||||
"label": "GPT-6 Luna"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6.2-astra",
|
||||
"label": "GPT-6.2 Astra"
|
||||
"id": "gpt-6.1-sol",
|
||||
"label": "GPT-6.1 Sol"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6.2-sol",
|
||||
"label": "GPT-6.2 Sol"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-astra",
|
||||
"label": "GPT-6 Astra"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6.2-astra",
|
||||
"label": "GPT-6.2 Astra"
|
||||
}
|
||||
],
|
||||
"strengths": {
|
||||
@@ -198,7 +194,7 @@
|
||||
"model": "swe-2-flash-high"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "swe-2-high"
|
||||
"model": "swe-2-1-high"
|
||||
},
|
||||
"best": {
|
||||
"model": "claude-opus-5-5-medium"
|
||||
|
||||
@@ -1678,48 +1678,75 @@ function spawnCommand(file, args, options) {
|
||||
* npx's exit code through. No agent starts. That one install updates the skills, this launcher
|
||||
* and the desktop app (when it is installed) together, so the three never drift apart.
|
||||
*
|
||||
* It installs the newest `vX.Y.Z` release tag, found with the same `git ls-remote --tags` rule
|
||||
* the console's release check uses (update-check.mjs, copied beside this file), so a person is
|
||||
* never moved onto work a published release does not have yet. `--main` is the old behavior (the
|
||||
* tip of `main`); `--tag <ref>` installs that tag or branch (the desktop app's Update skills
|
||||
* button pins the app's own tag this way, and it is how to go back to an earlier release);
|
||||
* `--force` reinstalls even when the version is already current. `--main`, and a `--tag` naming a
|
||||
* branch rather than a vX.Y.Z release, always reinstall: unreleased work keeps the last release's
|
||||
* version, so the installer's "Already on" check would otherwise install nothing.
|
||||
* It installs the newest release, found in one `git ls-remote --tags --heads` snapshot read with
|
||||
* the rules of update-check.mjs (copied beside this file), so a person is never moved onto work a
|
||||
* published release does not have yet. A release is named by its logical `vX.Y.Z` everywhere the
|
||||
* person reads it, while npx fetches its slim immutable `install-vX.Y.Z` tag when the snapshot
|
||||
* advertises one (the plain tag otherwise). `--main` is the old behavior (the tip of `main`);
|
||||
* `--tag <ref>` installs that tag or branch (the desktop app's Update skills button pins the app's
|
||||
* own tag this way, and it is how to go back to an earlier release: a `vX.Y.Z` there is mapped to
|
||||
* its install tag the same way, and falls back to the plain tag when the snapshot has none or
|
||||
* cannot be read); `--force` reinstalls even when the version is already current. `--main`, and a
|
||||
* `--tag` naming a branch rather than a vX.Y.Z release, always reinstall: unreleased work keeps
|
||||
* the last release's version, so the installer's "Already on" check would otherwise install
|
||||
* nothing.
|
||||
*/
|
||||
async function runUpdate({ tag, main, force } = {}) {
|
||||
let ref = tag;
|
||||
if (ref === undefined && !main) {
|
||||
const latest = await newestReleaseTag();
|
||||
if (!latest) {
|
||||
async function runUpdate({ tag, main, force, notice } = {}) {
|
||||
if (notice) console.log(c.dim(notice));
|
||||
const release = tag !== undefined && RELEASE_TAG.test(tag);
|
||||
let refs;
|
||||
if (tag === undefined && !main) {
|
||||
refs = await newestRelease();
|
||||
if (!refs) {
|
||||
console.error(`${ce.red('plan2code:')} could not find the newest Plan2Code release (git ls-remote did not answer).`);
|
||||
console.error('Check your network, then run plan2code update again, or use --main (the newest work, not a release) or --tag <release> (for example --tag v3.0.2).');
|
||||
return process.exit(1);
|
||||
}
|
||||
ref = `v${latest}`;
|
||||
} else if (release) {
|
||||
const found = await readRefSnapshot();
|
||||
refs = (found && found.checker.installRefForRelease(tag, found.snapshot)) || { releaseRef: tag, fetchRef: tag };
|
||||
} else if (tag !== undefined) {
|
||||
refs = { fetchRef: tag };
|
||||
}
|
||||
console.log(ref === undefined ? 'Updating Plan2Code to the newest work on main...' : `Updating Plan2Code to ${ref}...`);
|
||||
console.log(refs ? `Updating Plan2Code to ${refs.releaseRef || refs.fetchRef}...` : 'Updating Plan2Code to the newest work on main...');
|
||||
console.log(c.dim('One update covers the skills, the plan2code command and the desktop app (when installed).'));
|
||||
console.log(c.dim('npx fetches it quietly first, which can take a minute or two.'));
|
||||
const unreleased = main || (tag !== undefined && !/^v\d+\.\d+\.\d+$/.test(tag));
|
||||
return runInstaller(['--update', ...(force || unreleased ? ['--force'] : [])], ref);
|
||||
const unreleased = main || (tag !== undefined && !release);
|
||||
return runInstaller(['--update', ...(force || unreleased ? ['--force'] : [])], refs);
|
||||
}
|
||||
|
||||
/** A logical release ref, `vX.Y.Z`. */
|
||||
const RELEASE_TAG = /^v\d+\.\d+\.\d+$/;
|
||||
|
||||
/**
|
||||
* One `git ls-remote --tags --heads` snapshot, parsed: `{ checker, snapshot }` with `checker` the
|
||||
* update-check.mjs module (beside this file once installed, or in the repository's web-console
|
||||
* folder when run from a checkout), or null when it cannot be read. PLAN2CODE_LS_REMOTE_FILE
|
||||
* names a file holding `git ls-remote` output to use instead of asking git: the tests' stand-in
|
||||
* for the network. Nothing is cached: each update asks once.
|
||||
*/
|
||||
async function readRefSnapshot() {
|
||||
try {
|
||||
const file = [path.join(__dirname, 'update-check.mjs'), path.join(__dirname, '..', 'web-console', 'update-check.mjs')].find((f) => fs.existsSync(f));
|
||||
if (!file) return null;
|
||||
const checker = await import(require('url').pathToFileURL(file).href);
|
||||
const stub = process.env.PLAN2CODE_LS_REMOTE_FILE;
|
||||
const text = stub ? fs.readFileSync(stub, 'utf8') : await checker.runLsRemote();
|
||||
if (typeof text !== 'string') return null;
|
||||
return { checker, snapshot: checker.parseLsRemoteSnapshot(text) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The newest release's version (X.Y.Z), or null when it cannot be found. The tag list comes from
|
||||
* update-check.mjs's own `git ls-remote --tags` run and its own pick, beside this file once
|
||||
* installed (or in the repository's web-console folder when run from a checkout).
|
||||
* PLAN2CODE_LS_REMOTE_FILE names a file holding `git ls-remote --tags` output to use instead of
|
||||
* asking git: the tests' stand-in for the network.
|
||||
* The newest release as update-check.mjs's chooseReleaseRef() maps it, `{ releaseRef, fetchRef,
|
||||
* synthetic, version }`, or null when it cannot be found.
|
||||
*/
|
||||
async function newestReleaseTag() {
|
||||
async function newestRelease() {
|
||||
try {
|
||||
const checker = [path.join(__dirname, 'update-check.mjs'), path.join(__dirname, '..', 'web-console', 'update-check.mjs')].find((file) => fs.existsSync(file));
|
||||
if (!checker) return null;
|
||||
const mod = await import(require('url').pathToFileURL(checker).href);
|
||||
const stub = process.env.PLAN2CODE_LS_REMOTE_FILE;
|
||||
const text = stub ? fs.readFileSync(stub, 'utf8') : await mod.runLsRemote();
|
||||
return mod.latestTag(text);
|
||||
const found = await readRefSnapshot();
|
||||
return found ? found.checker.chooseReleaseRef(found.snapshot) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -1734,21 +1761,28 @@ async function newestReleaseTag() {
|
||||
*/
|
||||
async function runUninstall(flags) {
|
||||
console.log('Uninstalling Plan2Code...');
|
||||
const latest = await newestReleaseTag();
|
||||
return runInstaller(['--uninstall', ...flags], latest ? `v${latest}` : undefined);
|
||||
return runInstaller(['--uninstall', ...flags], (await newestRelease()) || undefined);
|
||||
}
|
||||
|
||||
/** Run install.js through npx with the given flags, passing npx's exit code through. */
|
||||
function runInstaller(installerArgs, tag) {
|
||||
/**
|
||||
* Run install.js through npx with the given flags, passing npx's exit code through. `refs` is a
|
||||
* ref name (the fetch ref), or `{ fetchRef, releaseRef }` when the fetched ref stands for a
|
||||
* logical release; neither means the tip of main.
|
||||
*/
|
||||
function runInstaller(installerArgs, refs) {
|
||||
const { fetchRef, releaseRef } = typeof refs === 'string' ? { fetchRef: refs } : refs || {};
|
||||
const npx = findOnPath('npx');
|
||||
if (!npx) {
|
||||
console.error(`${ce.red('plan2code:')} npx was not found on your PATH. It comes with Node.js 18+ (https://nodejs.org).`);
|
||||
return process.exit(127);
|
||||
}
|
||||
const spec = tag ? `git+${REPO_URL}#${tag}` : `git+${REPO_URL}`;
|
||||
const spec = fetchRef ? `git+${REPO_URL}#${fetchRef}` : `git+${REPO_URL}`;
|
||||
// The ref was picked on purpose (main included): install.js's release redirect, there for
|
||||
// launchers older than the release channel, must leave this run where it is.
|
||||
const env = { ...process.env, PLAN2CODE_INSTALL_REF: tag || 'main' };
|
||||
// launchers older than the release channel, must leave this run where it is. The logical
|
||||
// release travels beside it, so an `install-vX.Y.Z` fetch still knows it is `vX.Y.Z`.
|
||||
const env = { ...process.env, PLAN2CODE_INSTALL_REF: fetchRef || 'main' };
|
||||
if (releaseRef) env.PLAN2CODE_RELEASE_REF = releaseRef;
|
||||
else delete env.PLAN2CODE_RELEASE_REF;
|
||||
const child = spawnCommand(npx, ['--yes', '--allow-git=all', spec, ...installerArgs], { stdio: 'inherit', env });
|
||||
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
||||
process.on(signal, () => {});
|
||||
@@ -1802,7 +1836,19 @@ async function releaseNotice() {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/** `{ tag, main, force }` from the words after `update`, or `{ error }` naming what is wrong. */
|
||||
/**
|
||||
* A `--tag` value as the update uses it: an exact `install-vX.Y.Z` (the fetch ref of a release)
|
||||
* becomes its logical `vX.Y.Z` with a one-line `notice`, so going back is always by release name;
|
||||
* any other `install-v...` is `{ error }`; every other branch or tag is left as it is, `{ ref }`.
|
||||
*/
|
||||
function normalizeUpdateTagInput(ref) {
|
||||
if (typeof ref !== 'string' || !ref.startsWith('install-v')) return { ref };
|
||||
const m = /^install-(v\d+\.\d+\.\d+)$/.exec(ref);
|
||||
if (!m) return { error: `${ref} is not a release install tag: use --tag with the release, for example --tag v3.0.2` };
|
||||
return { ref: m[1], notice: `${ref} is how release ${m[1]} is fetched; updating by its release name, ${m[1]}.` };
|
||||
}
|
||||
|
||||
/** `{ tag, main, force, notice? }` from the words after `update`, or `{ error }` naming what is wrong. */
|
||||
function parseUpdateArgs(args) {
|
||||
const out = { main: false, force: false };
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
@@ -1812,7 +1858,10 @@ function parseUpdateArgs(args) {
|
||||
else if (arg === '--tag') {
|
||||
const ref = args[i + 1];
|
||||
if (!ref || ref.startsWith('--')) return { error: '--tag needs a release or branch, for example --tag v3.0.2' };
|
||||
out.tag = ref;
|
||||
const normalized = normalizeUpdateTagInput(ref);
|
||||
if (normalized.error) return { error: normalized.error };
|
||||
out.tag = normalized.ref;
|
||||
if (normalized.notice) out.notice = normalized.notice;
|
||||
i++;
|
||||
} else return { error: `unknown option for update: ${arg}` };
|
||||
}
|
||||
@@ -2024,4 +2073,4 @@ async function launch() {
|
||||
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
||||
if (require.main === module) launch();
|
||||
|
||||
module.exports = { nodeVersionProblem, usageText, droppedForApp, bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd, sameFolder, readRecent, pushRecent, listRecent, recordFolder, folderMenuRows, folderMenuPick, isEmptyFolder };
|
||||
module.exports = { nodeVersionProblem, usageText, normalizeUpdateTagInput, droppedForApp, bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd, sameFolder, readRecent, pushRecent, listRecent, recordFolder, folderMenuRows, folderMenuPick, isEmptyFolder };
|
||||
@@ -52,7 +52,7 @@ Q2 Ceiling behavior past the cap (re-ask) · Q3 Who sees the truncation warning
|
||||
|
||||
## Form A — the turn ends the session
|
||||
|
||||
The command follows the map's status: `/plan2code-0-pathfinder specs/<idea>/pathfinder --web` while `Charting` / `Working`; `/plan2code-1-plan --web` once `Cleared`; and `/plan2code-init` first when `## Ground rules` records `AGENTS.md` absent and it still is. The path is the exact argument Auto-Discovery resolves an idea from, so the human pastes it back with zero edits.
|
||||
The command follows the map's status: `/plan2code-0-pathfinder specs/<idea>/pathfinder` while `Charting` / `Working`; `/plan2code-1-plan` once `Cleared`; and `/plan2code-init` first when `## Ground rules` records `AGENTS.md` absent and it still is. The path is the exact argument Auto-Discovery resolves an idea from, so the human pastes it back with zero edits. It is printed bare, with `Add --web for the web console.` under it.
|
||||
|
||||
## Form B — the turn asks the human something
|
||||
|
||||
|
||||
@@ -1143,6 +1143,9 @@ function wrapJoin(parts, indent = " ", width = 100) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Printed bare so it pastes as is; WEB_NOTE under it offers the console.
|
||||
const WEB_NOTE = "Add `--web` for the web console.";
|
||||
|
||||
// Init comes first only while the ground rules record AGENTS.md absent AND it is
|
||||
// still missing: one written since charting needs no init detour.
|
||||
function needsInit(loc, map) {
|
||||
@@ -1151,9 +1154,9 @@ function needsInit(loc, map) {
|
||||
|
||||
function resumeCommand(loc, map) {
|
||||
if (/^cleared$/i.test(map.status || "")) {
|
||||
return needsInit(loc, map) ? "`/plan2code-init`, then `/plan2code-1-plan --web`" : "`/plan2code-1-plan --web`";
|
||||
return needsInit(loc, map) ? "`/plan2code-init`, then `/plan2code-1-plan`" : "`/plan2code-1-plan`";
|
||||
}
|
||||
return `\`/plan2code-0-pathfinder ${loc.relPf} --web\``;
|
||||
return `\`/plan2code-0-pathfinder ${loc.relPf}\``;
|
||||
}
|
||||
|
||||
// What the human reads a question as: its name on the checklist row (the
|
||||
@@ -1212,7 +1215,7 @@ async function cmdTrail(loc, args) {
|
||||
let part2;
|
||||
let menu;
|
||||
if (form === "A") {
|
||||
part2 = ["NEXT STEP · start a new conversation and run:", cmd];
|
||||
part2 = ["NEXT STEP · start a new conversation and run:", cmd, WEB_NOTE];
|
||||
} else if (form === "B") {
|
||||
const items = args.item || [];
|
||||
if (!items.length) fail(EXIT.USAGE, "missing-items", "Form B names every outstanding item: pass 1-3 --item.", 'Example: --item "Q1 Duration model" --item "Q2 Contract while held"');
|
||||
@@ -1226,7 +1229,7 @@ async function cmdTrail(loc, args) {
|
||||
// Nothing takeable means there is no menu to offer: an empty frontier is a
|
||||
// stop (Work Step 4), and a stop is Form A.
|
||||
if (!f.frontier.length) fail(EXIT.REFUSED, "no-frontier", "Nothing on the frontier to offer: every open question is blocked, or none is left.", "Use --form A (report the blocked chain, or go to The Clearing Gate).");
|
||||
part2 = ["OR START FRESH · new conversation, paste:", cmd];
|
||||
part2 = ["OR START FRESH · new conversation, paste:", cmd, WEB_NOTE];
|
||||
const resolvedThisSession = Number(args["resolved-this-session"] || 0);
|
||||
const checkpoint = resolvedThisSession >= 3 || !!args.heavy;
|
||||
const options = f.frontier.slice(0, 3).map((x) => {
|
||||
|
||||
@@ -12,7 +12,7 @@ Read references/grilling.md at the first question you grill (Chart Step 2, or a
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before Step 0: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow pathfinder` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/pathfinder.md. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Step 0.
|
||||
The FIRST thing you do, before anything else in this file — before Step 0: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow pathfinder` before reading, then read <D>/console.md and <D>/notes/pathfinder.md. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Step 0.
|
||||
|
||||
## Backend
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Senior software architect and technical PM. Analyze requirements critically, ask
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before looking for a draft: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow plan` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/plan.md. Switchable anytime. The console is far easier for sign-offs with a non-engineer. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then the AGENTS.md check.
|
||||
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before looking for a draft: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow plan` before reading, then read <D>/console.md and <D>/notes/plan.md. The console is far easier for sign-offs with a non-engineer. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then the AGENTS.md check.
|
||||
|
||||
## Project Context (BLOCKING)
|
||||
|
||||
@@ -181,7 +181,7 @@ State assessment and ask user to confirm.
|
||||
3. Create `specs/<feature-name>/PLAN-DRAFT-<YYYYMMDD>.md` with Phases 1-3
|
||||
4. Set status: `Phase 3 Complete - Resume at Phase 4`
|
||||
5. Include: Executive Summary, Requirements, System Context, Scope, Confidence
|
||||
6. Instruct: "Large project. Progress saved. Start NEW conversation with `/plan2code-1-plan --web` to resume at Phase 4." On the web console, the finish carries that command.
|
||||
6. Instruct: "Large project. Progress saved. Start NEW conversation with `/plan2code-1-plan` (add `--web` for the web console) to resume at Phase 4." On the web console, the finish carries that command.
|
||||
7. STOP
|
||||
|
||||
### PHASE 4: Tech Stack
|
||||
@@ -306,7 +306,7 @@ When complete (PLAN-DRAFT created), tell user:
|
||||
> ╰┬─┬╯
|
||||
> ```"
|
||||
|
||||
In the terminal, end with `NEXT STEP: /plan2code-2-document --web` in a NEW conversation. The web console's finish carries it, so print nothing there.
|
||||
In the terminal, end with `NEXT STEP: /plan2code-2-document` (add `--web` for the web console) in a NEW conversation. The web console's finish carries it, so print nothing there.
|
||||
|
||||
## Abort / Recovery
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Senior software architect updating implementation specs when requirements change
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before Step 1, before reading a spec: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow revise-plan` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-1b-revise-plan/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir; add `--spec specs/<feature-name>` if known, else post `specDir` later), then read <D>/console.md and <D>/notes/revise-plan.md; the Step 1 confirmation, the Step 2 approval and every cleanup question go through it. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Step 1.
|
||||
The FIRST thing you do, before anything else in this file — before Step 1, before reading a spec: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-1b-revise-plan/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow revise-plan` before reading (add `--spec specs/<feature-name>` if known, else post `specDir` later), then read <D>/console.md and <D>/notes/revise-plan.md; the Step 1 confirmation, the Step 2 approval and every cleanup question go through it. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Step 1.
|
||||
|
||||
## Rules
|
||||
|
||||
@@ -202,7 +202,7 @@ Report and resolve issues (every `error` in `checks` included), then rerun `stat
|
||||
|
||||
```
|
||||
|
||||
In the terminal, end with `REVISION COMPLETE: start a NEW conversation and run /plan2code-3-implement --web with specs/<feature-name>/overview.md` (it finds the next phase itself). The web console's finish carries it, so print nothing there.
|
||||
In the terminal, end with `REVISION COMPLETE: start a NEW conversation and run /plan2code-3-implement with specs/<feature-name>/overview.md` (it finds the next phase itself; add `--web` for the web console). The web console's finish carries it, so print nothing there.
|
||||
|
||||
### STEP 6: Revision Cleanup
|
||||
|
||||
@@ -242,6 +242,6 @@ Work summary — tell user: change type, tasks added/modified/removed, phases re
|
||||
|
||||
**Pending phases after revision** — list `status`'s `pending` (every phase not `[x]`, re-opened ones included) with its task count so the user can plan next implementation sessions.
|
||||
|
||||
Returning context: Revised specs in `specs/<feature-name>/`. Run `/plan2code-3-implement --web` in a new conversation to continue implementation.
|
||||
Returning context: Revised specs in `specs/<feature-name>/`. Run `/plan2code-3-implement` in a new conversation to continue implementation (add `--web` for the web console).
|
||||
|
||||
**On the web console:** specs change only at Step 3, so stopping before then saves nothing. The finish command is `/plan2code-3-implement specs/<feature-name>/overview.md` when revised, or the revise-plan command on an abort.
|
||||
@@ -8,7 +8,7 @@ Technical writer transforming planning documents into precise, complete implemen
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before Auto-Discovery: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow document` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec` once known), then read <D>/console.md and <D>/notes/document.md. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Auto-Discovery.
|
||||
The FIRST thing you do, before anything else in this file — before Auto-Discovery: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow document` before reading (`--spec` once known), then read <D>/console.md and <D>/notes/document.md. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Auto-Discovery.
|
||||
|
||||
## Scripts
|
||||
|
||||
@@ -235,7 +235,7 @@ Paste the `comment` from `specs.mjs metrics specs/<feature-name> --step document
|
||||
**Tell user:**
|
||||
1. What was created (spec files list)
|
||||
2. Path for next session: `specs/<feature-name>/overview.md`
|
||||
3. Next command: `/plan2code-3-implement-review --web` (quality-gated) or `/plan2code-3-implement --web` (implementation only)
|
||||
3. Next command: `/plan2code-3-implement-review` (quality-gated) or `/plan2code-3-implement` (implementation only)
|
||||
4. Start NEW conversation for implementation
|
||||
|
||||
**Phase Overview** — present a table from `status`'s `phases`: phase name, task count (`tasks.total`), one-sentence goal (`goal`, tightened if it runs long; write one yourself when it is null). Helps the user plan sessions and identify review gates.
|
||||
@@ -248,7 +248,7 @@ Paste the `comment` from `specs.mjs metrics specs/<feature-name> --step document
|
||||
╰┬─┬╯
|
||||
```
|
||||
|
||||
In the terminal, end with `NEXT STEP: start a NEW conversation and run /plan2code-3-implement-review --web` (or `/plan2code-3-implement --web` for implementation without the review gate). The web console's finish carries it, so print nothing there.
|
||||
In the terminal, end with `NEXT STEP: start a NEW conversation and run /plan2code-3-implement-review` (or `/plan2code-3-implement` for implementation without the review gate; add `--web` to either for the web console). The web console's finish carries it, so print nothing there.
|
||||
|
||||
## Abort Handling
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Orchestrate one implementation phase and its focused independent review as a sin
|
||||
|
||||
## Web Console
|
||||
|
||||
The FIRST thing you do, before anything else in this file: Implementation Mode's Interface question — **web console** or **terminal**? On the web console, run `node "<D>/console.mjs" open --workflow implement-review` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-3-implement-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md, <D>/building.md and <D>/notes/implement.md in one batch (all of it; its Implement + Review section covers Stages 2–5), and <D>/building-review.md when Stage 2 starts: the Stage 2 findings go out as the page's fix list, Stage 4 is the only sign-off item, and the Stage 5 `finish` never carries the review offer. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. `--loop` (only inside the desktop app): read <D>/notes/loop.md after console.md; it replaces the sign-off, marking and git steps, and Stages 2 to 4 run as its review section says. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the spec.
|
||||
The FIRST thing you do, before anything else in this file: Implementation Mode's Interface question — **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-3-implement-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. On the web console, run `node "<D>/console.mjs" open --workflow implement-review` before reading, then read <D>/console.md, <D>/building.md and <D>/notes/implement.md in one batch (all of it; its Implement + Review section covers Stages 2–5), and <D>/building-review.md when Stage 2 starts: the Stage 2 findings go out as the page's fix list, Stage 4 is the only sign-off item, and the Stage 5 `finish` never carries the review offer. `--loop` (only inside the desktop app): read <D>/notes/loop.md after console.md; it replaces the sign-off, marking and git steps, and Stages 2 to 4 run as its review section says. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the spec.
|
||||
|
||||
## Controlling Contract
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Senior software engineer building exactly what the spec says, keeping progress c
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before reading a spec, before Phase 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow implement` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-3-implement/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md, <D>/building.md and <D>/notes/implement.md in one batch; progress, every question and the sign-off go through it. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. `--loop` (only inside the desktop app): read <D>/notes/loop.md after console.md; it replaces the sign-off, marking and git steps below. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the spec.
|
||||
The FIRST thing you do, before anything else in this file — before reading a spec, before Phase 1: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-3-implement/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow implement` before reading, then read <D>/console.md, <D>/building.md and <D>/notes/implement.md in one batch; progress, every question and the sign-off go through it. `--loop` (only inside the desktop app): read <D>/notes/loop.md after console.md; it replaces the sign-off, marking and git steps below. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the spec.
|
||||
|
||||
## Scripts
|
||||
|
||||
@@ -75,7 +75,7 @@ Never reset `[/]` to `[ ]`: started work stays marked so resuming is a conscious
|
||||
| `ask-resume` | Prompt: "Phase X is in progress. Resume? (yes/no)" Relay `warning` when present. |
|
||||
| `auto-start` | Mark it `[/]` and begin. Relay `warning` when present. |
|
||||
| `checkoff` | Every phase is approved but tasks in them are still open (manual steps, blockers). Never say "nothing left to do": run Manual Check-Off below. |
|
||||
| `none` | Nothing to implement: say why (`reason`). Every phase complete → `/plan2code-4-finalize --web` |
|
||||
| `none` | Nothing to implement: say why (`reason`). Every phase complete → `/plan2code-4-finalize` (add `--web` for the web console) |
|
||||
|
||||
Before acting on `ask-resume` or `choose`, read the Notes of each `[/]` phase on offer: a waiting `**Plan change:**` line replaces the resume question (Plan Change Mid-Phase). After selection, claim it (Process 1), read `phase-X.md`, begin.
|
||||
|
||||
@@ -88,7 +88,7 @@ Before acting on `ask-resume` or `choose`, read the Notes of each `[/]` phase on
|
||||
3. Yes → `node "<S>/specs.mjs" tick <spec> --task <id>` (writes `[x]` and a "Confirmed done by the user" line). Not yet → leave it as it stands. A note asking for help: help, then ask again.
|
||||
4. Next task.
|
||||
|
||||
After the last one: `tick`'s `remaining` empty (`next` is `none`) → "NEXT STEP: Start NEW conversation and run: `/plan2code-4-finalize --web`". Otherwise list what is still open, say Finalize opens once they are checked off, and that rerunning Implement asks again. Never tick a task the person did not confirm.
|
||||
After the last one: `tick`'s `remaining` empty (`next` is `none`) → "NEXT STEP: Start NEW conversation and run: `/plan2code-4-finalize` (add `--web` for the web console)". Otherwise list what is still open, say Finalize opens once they are checked off, and that rerunning Implement asks again. Never tick a task the person did not confirm.
|
||||
|
||||
## Code Consistency Rules
|
||||
|
||||
@@ -211,9 +211,9 @@ On user "approved":
|
||||
| Phase X+1: [Name] | Z | [One-sentence goal] |
|
||||
|
||||
5. Before this, follow `references/lessons.md` → End. (Not under `--loop`.) Then write a one-line subject for the phase, then give the user the `command` from `commit-msg.mjs --subject "<subject>" --files <path> ...`, one `--files` per file the phase created or changed. It enforces the format: subject ≤100 chars and EXACTLY TWO -m flags (subject, `AI Assisted`), no body. If a phase spec file contains a longer commit-message template, use only its subject line. The diff is the body; the PR is the explanation. On Windows PowerShell 5.1 (no `&&`), give `add` and `commit` as two commands instead.
|
||||
6. **If more phases:** "NEXT STEP: Start NEW conversation and run: `/plan2code-3-implement specs/<feature>/overview.md --web`"
|
||||
7. **If final phase:** "NEXT STEP: Start NEW conversation and run: `/plan2code-4-finalize --web`"
|
||||
8. Mention `/plan2code-1b-revise-plan --web` option
|
||||
6. **If more phases:** "NEXT STEP: Start NEW conversation and run: `/plan2code-3-implement specs/<feature>/overview.md` (add `--web` for the web console)"
|
||||
7. **If final phase:** "NEXT STEP: Start NEW conversation and run: `/plan2code-4-finalize` (add `--web` for the web console)"
|
||||
8. Mention `/plan2code-1b-revise-plan` option
|
||||
9. **On the web console:** the finish carries the next step, never a review offer (it was on the sign-off card).
|
||||
|
||||
Planny (continuing):
|
||||
@@ -242,7 +242,7 @@ If user says "abort", "cancel", or similar:
|
||||
- List completed vs remaining tasks
|
||||
- Note created/modified files
|
||||
- Do NOT change phase checkbox (stays `[/]`)
|
||||
- Explain: "Run `/plan2code-3-implement --web` again to resume."
|
||||
- Explain: "Run `/plan2code-3-implement` again to resume (add `--web` for the web console)."
|
||||
3. Stop implementation. On the web console, the finish carries that command.
|
||||
|
||||
## Recovery
|
||||
@@ -262,7 +262,7 @@ When the person decides the plan must change before this phase can finish (a new
|
||||
<done and still open by task id in prose ("done 9.1, 9.3-9.5; open 9.2, 9.6-9.9"), never checkbox lines; decisions made so far>
|
||||
```
|
||||
|
||||
NEXT STEP: `/plan2code-1b-revise-plan specs/<feature>/overview.md --web`. The dashboard and Revise the plan look for that `**Plan change:**` line; Revise the plan rewrites it to `**Plan change (applied <date>):**` once the spec is updated.
|
||||
NEXT STEP: `/plan2code-1b-revise-plan specs/<feature>/overview.md` (add `--web` for the web console). The dashboard and Revise the plan look for that `**Plan change:**` line; Revise the plan rewrites it to `**Plan change (applied <date>):**` once the spec is updated.
|
||||
|
||||
A phase whose Notes still hold a waiting `**Plan change:**` gets one question in place of "Resume?" (console: a `choice`): **Revise the plan first** (recommended) or **Resume Phase X anyway**. Revise first: change nothing and end as a pause with the NEXT STEP above (console: that `finish.command`, headline starting "Paused"). Resume anyway: rewrite the line to `**Plan change (dropped <YYYY-MM-DD>):**`, then carry on.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ QA engineer and technical lead performing rigorous final validation. Verify spec
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before the Required Context check, before Step 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow finalize` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec specs/<feature-name>` if known, else post `specDir` later), then read <D>/console.md and <D>/notes/finalize.md; the audit options, the final review, the doc-update approval and every cleanup confirmation go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then the Required Context check.
|
||||
The FIRST thing you do, before anything else in this file — before the Required Context check, before Step 1: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow finalize` before reading (`--spec specs/<feature-name>` if known, else post `specDir` later), then read <D>/console.md and <D>/notes/finalize.md; the audit options, the final review, the doc-update approval and every cleanup confirmation go through it. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then the Required Context check.
|
||||
|
||||
## Scripts
|
||||
|
||||
@@ -350,7 +350,7 @@ Paste the `comment` from `specs.mjs metrics <spec's current path: specs--complet
|
||||
| Completion | Action |
|
||||
|-----------|--------|
|
||||
| **≥75%** | Finalize with notice. List incomplete items. Note remaining tasks for follow-up cycle. |
|
||||
| **<75%** | Recommend returning to implementation. List incomplete phases with task counts. Options: 1) Return via `/plan2code-3-implement --web` 2) Proceed with partial finalization. |
|
||||
| **<75%** | Recommend returning to implementation. List incomplete phases with task counts. Options: 1) Return via `/plan2code-3-implement` (add `--web` for the web console) 2) Proceed with partial finalization. |
|
||||
|
||||
## Abort Handling
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Careful release scribe. Work out the right version from the default branch, find
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before reading the repository: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow changelog` before reading (<D>: references/web-console/ beside this SKILL.md, ~/.agents/skills/plan2code-changelog/references/web-console/ globally, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/changelog.md. Every question goes through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`) take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Step 1.
|
||||
The FIRST thing you do, before anything else in this file, before reading the repository: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md, ~/.agents/skills/plan2code-changelog/references/web-console/ globally, or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow changelog` before reading, then read <D>/console.md and <D>/notes/changelog.md. Every question goes through it. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Step 1.
|
||||
|
||||
## Scripts
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Finds unused code paths and dead code in the person's own project. Shows each fi
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before running a script: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow dead-code` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-dead-code/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/dead-code.md. The start questions, the findings list, the checks, the report and the save offers all go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
The FIRST thing you do, before anything else in this file, before running a script: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-dead-code/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow dead-code` before reading, then read <D>/console.md and <D>/notes/dead-code.md. The start questions, the findings list, the checks, the report and the save offers all go through it. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
|
||||
## Project Context
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ Plain words for the person: version list (lockfile), package list (manifest), sm
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before running a script: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow deps` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-deps/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/deps.md. Every card, the progress and the report go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
The FIRST thing you do, before anything else in this file, before running a script: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-deps/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow deps` before reading, then read <D>/console.md and <D>/notes/deps.md. Every card, the progress and the report go through it. Switchable anytime. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
|
||||
## Project Context
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Bug detective. Find a bug's cause and write it up, **without fixing it**: reprod
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before asking about the bug: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow diagnose` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-diagnose/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/diagnose.md. The bug questions, the growing cause, the bug name and the hand-off all go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
The FIRST thing you do, before anything else in this file, before asking about the bug: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-diagnose/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow diagnose` before reading, then read <D>/console.md and <D>/notes/diagnose.md. The bug questions, the growing cause, the bug name and the hand-off all go through it. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
|
||||
## Project Context (BLOCKING)
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Careful git operator. Read where the repository stands, do what the person asks
|
||||
|
||||
## Interface
|
||||
|
||||
An instruction in the argument (`/plan2code-git switch to main`, `/plan2code-git commit and push`, a commit subject) runs in the terminal at once: do not ask about the console. With no argument, the FIRST thing you do, before anything else in this file, before reading the repository: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow git` before reading (<D>: references/web-console/ beside this SKILL.md, ~/.agents/skills/plan2code-git/references/web-console/ globally, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/git.md. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`) take it and do not ask; drop the flag. Launched by the dashboard, or by a **Commit it now** or Changelog hand-off? Its session is already open: resume it with `--workflow git` (console-launches.md). Handed off to commit (Commit it now, Changelog's yes): post `reread`, then run the Commit flow from step 1 over every changed file (risky ones left out and named), its cards on the board; afterwards the board is theirs with Push lit.
|
||||
An instruction in the argument (`/plan2code-git switch to main`, `/plan2code-git commit and push`, a commit subject) runs in the terminal at once: do not ask about the console. With no argument, the FIRST thing you do, before anything else in this file, before reading the repository: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md, ~/.agents/skills/plan2code-git/references/web-console/ globally, or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow git` before reading, then read <D>/console.md and <D>/notes/git.md. Launched by the dashboard, or by a **Commit it now** or Changelog hand-off? Its session is already open: resume it with `--workflow git` (console-launches.md). Handed off to commit (Commit it now, Changelog's yes): post `reread`, then run the Commit flow from step 1 over every changed file (risky ones left out and named), its cards on the board; afterwards the board is theirs with Push lit.
|
||||
|
||||
## Project context
|
||||
|
||||
@@ -68,7 +68,7 @@ On a non-zero exit, save git's stderr to the session folder, run `classify-error
|
||||
## Actions
|
||||
|
||||
- **refresh, pull, switch, create** run on the click when the plan says `ask: false` (a clean tree, a fast-forward).
|
||||
- **push, publish, delete, cleanup** always ask first, with the plan's `confirm`.
|
||||
- **push, publish, delete, cleanup** always ask first, with the plan's `confirm`, except a push picked in the commit's own card (Commit flow step 7).
|
||||
- **switch** with changes: **Switch and bring them** runs the switch; **Commit first** runs the Commit flow over the changed files, then the switch; **Cancel** does nothing but the `git-result` line. A pull's `dirty` card works the same way, with the pull in place of the switch.
|
||||
- **create** with `then: "commit"` creates the branch, then continues the Commit flow on it with the action's `files` (and `ignore`, as for commit).
|
||||
- **commit** commits only the paths in `files`. With `ignore[]`, first propose those `.gitignore` lines as a doc plus a `review` card (approve / change), write them on approve, and add `.gitignore` to the commit.
|
||||
@@ -96,9 +96,9 @@ In the terminal the same stops are asked in prose, with the diff printed.
|
||||
2. **Nothing to commit.** If `push` is not null, go to 7. Otherwise say the tree is clean and everything is pushed (or that there is no remote), and stop.
|
||||
3. **Branch.** On the board, skip this: the Save step's **Start a branch and commit** already offered it, and its answer arrives as `create` with `then: "commit"`. In the terminal, when `onDefault` (or `detached`) and `hasCommits`, offer one drafted branch name `<type>/<short-description>` (types: feature, fix, chore, docs, refactor, test; `feature/export-csv`). Run any name the person types through `branch-check`, then `plan create`. Skipping is always fine (on a detached HEAD, warn that commits there are easy to lose). When `defaultBranch` is null say why there is no offer.
|
||||
4. **Read the changes.** `git diff`, `git diff --cached` and the untracked files (an `untracked` path ending in `/` is a folder: list its files with `git ls-files -o --exclude-standard -- <folder>` and stage them by name). If the person staged some files, work from that staged set and leave the rest alone (say what was left). On the board, only the paths the action named, or every changed file on a hand-off. Decide whether the work is one concern or several.
|
||||
5. **Message.** One concern: draft a subject, or use the argument and skip approval; ask **Yes** / **Edit** / **No**. Several: always suggest whole-file groups, each with a subject, naming any file that mixes concerns and which group took it; ask **Approve** / **Change it** / **One commit instead** (asked even when the subject came as the argument). Name the `sensitive` and `large` files you are leaving out.
|
||||
5. **Message.** One concern: draft a subject, or use the argument and skip approval; ask **Yes** / **Edit** / **No**, with **Yes and push** beside Yes when a push is possible (on the console, the subject and **Commit only** / **Commit and push** go in ONE post, notes/git.md). Several: always suggest whole-file groups, each with a subject, naming any file that mixes concerns and which group took it; ask **Approve** / **Change it** / **One commit instead** (asked even when the subject came as the argument). Name the `sensitive` and `large` files you are leaving out.
|
||||
6. **Commit.** For each group in order: with more than one group, run `git reset -q` first so only that group is staged; then run `commit-msg.mjs --subject "<s>" --files <a> --files <b>` (`--files` once per path) and its `command` (or `add`, then `commit`). Finish with `git log --oneline -<n>`. On the console post `run: { "event": "git-commits", "id": "<first short hash>", "commits": <n> }` with the `reread` and a `git-result` line naming the hashes with `op: "commit"`, so the board lights Push.
|
||||
7. **Push.** In the terminal, stop after committing with a one-line push hint and no push prompt. `commit and push` (or a push the person asks for) runs `plan push` / `plan publish` and asks its `confirm`. A rejected push: report it, suggest Pull, run nothing more.
|
||||
7. **Push.** In the terminal, stop after committing with a one-line push hint and no push prompt. `commit and push`, or **Commit and push** / **Yes and push** picked with the message, runs `plan push` / `plan publish` straight after the commit: that choice was the yes. A push asked for any other way runs the same plan and asks its `confirm`. A rejected push: report it, suggest Pull, run nothing more.
|
||||
|
||||
## Terminal
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ and can open files, but they cannot see this conversation. Write for them.
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before inferring the next task: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow handoff` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-handoff/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/handoff.md. The next-task confirmation and any clarifying questions go through it, and the finished handoff lands on the page as a doc with the download the page offers. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the one hard rule.
|
||||
The FIRST thing you do, before anything else in this file — before inferring the next task: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-handoff/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow handoff` before reading, then read <D>/console.md and <D>/notes/handoff.md. The next-task confirmation and any clarifying questions go through it, and the finished handoff lands on the page as a doc with the download the page offers. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the one hard rule.
|
||||
|
||||
## The one hard rule: capture the next task, and confirm it with the user
|
||||
|
||||
@@ -60,8 +60,8 @@ writing with `node "<S>/specs.mjs" status specs/<feature>` (`<S>` is `scripts/`
|
||||
- Cite that file and its checkbox state directly in **Current state** and
|
||||
**Key files & pointers**, instead of relying on conversation memory alone.
|
||||
- Let **Suggested skills** name the specific next pipeline command
|
||||
(`/plan2code-3-implement --web` to keep implementing the phase,
|
||||
`/plan2code-4-finalize --web` once all phases are checked) — but only as a
|
||||
(`/plan2code-3-implement` to keep implementing the phase,
|
||||
`/plan2code-4-finalize` once all phases are checked) — but only as a
|
||||
suggestion; the confirmed **Next task** above still governs what the reader
|
||||
does first.
|
||||
|
||||
@@ -106,9 +106,9 @@ a command that must be run a specific way. Save the reader from re-discovering
|
||||
these the hard way.>
|
||||
|
||||
## Suggested skills
|
||||
<Which skills the next agent should use, and when — e.g. /plan2code-3-implement --web
|
||||
to continue a phase, /plan2code-review before finishing, /plan2code-4-finalize --web
|
||||
to wrap up. Skip if none apply.>
|
||||
<Which skills the next agent should use, and when — e.g. /plan2code-3-implement
|
||||
to continue a phase, /plan2code-review before finishing, /plan2code-4-finalize
|
||||
to wrap up; add --web to any of them for the web console. Skip if none apply.>
|
||||
|
||||
## Verification
|
||||
<How the reader confirms their work: exact test/build commands, what "done"
|
||||
|
||||
@@ -14,7 +14,7 @@ Interactive Q&A flow to update an existing `AGENTS.md` with new learnings and pr
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before the Awareness Context: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow init-update` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-init-update/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/init.md. Every question in the Q&A flow and the restructure offer go through it. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Awareness Context.
|
||||
The FIRST thing you do, before anything else in this file — before the Awareness Context: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-init-update/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow init-update` before reading, then read <D>/console.md and <D>/notes/init.md. Every question in the Q&A flow and the restructure offer go through it. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Awareness Context.
|
||||
|
||||
## Scripts
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Analyze this codebase and create `AGENTS.md` to guide future AI coding agents (C
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before exploring the codebase: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow init` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-init/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/init.md. Every confirmation — the restructure offer, the AI-agent file-sync prompt — goes through it, and the finished AGENTS.md lands on the page as a doc marked `saved` (the file is already on disk — no download offered). Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Content.
|
||||
The FIRST thing you do, before anything else in this file — before exploring the codebase: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-init/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow init` before reading, then read <D>/console.md and <D>/notes/init.md. Every confirmation — the restructure offer, the AI-agent file-sync prompt — goes through it, and the finished AGENTS.md lands on the page as a doc marked `saved` (the file is already on disk — no download offered). Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Content.
|
||||
|
||||
## Scripts
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Gets a branch ready for review. Picks the checks its changes need, runs the ones
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before reading the branch: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow pr-prep` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-pr-prep/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/pr-prep.md. Every question, the check plan, the report and the description go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
The FIRST thing you do, before anything else in this file, before reading the branch: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-pr-prep/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow pr-prep` before reading, then read <D>/console.md and <D>/notes/pr-prep.md. Every question, the check plan, the report and the description go through it. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
|
||||
## Project Context
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Senior software architect. Analyze requirements, ask clarifying questions, deliv
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before asking what to build: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow quick-task` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-quick-task/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md, <D>/building.md and <D>/notes/quick-task.md in one batch. Every question, the scope check and the plan go through it; once the task is built, the finish offers a review of it on the page. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the AGENTS.md check.
|
||||
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before asking what to build: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-quick-task/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow quick-task` before reading, then read <D>/console.md, <D>/building.md and <D>/notes/quick-task.md in one batch. Every question, the scope check and the plan go through it; once the task is built, the finish offers a review of it on the page. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the AGENTS.md check.
|
||||
|
||||
## Project Context (BLOCKING)
|
||||
|
||||
@@ -128,11 +128,11 @@ After achieving clarity, assess scope:
|
||||
[Files examined, patterns noted]
|
||||
|
||||
---
|
||||
**Next:** New conversation with `/plan2code-1-plan --web`, attach this file.
|
||||
**Next:** New conversation with `/plan2code-1-plan` (add `--web` for the web console), attach this file.
|
||||
Resume at Phase 2 (System Context).
|
||||
```
|
||||
|
||||
Then tell user: "Created `specs/<feature-name>/PLAN-DRAFT-<date>.md`. Start new conversation with `/plan2code-1-plan --web` to continue."
|
||||
Then tell user: "Created `specs/<feature-name>/PLAN-DRAFT-<date>.md`. Start new conversation with `/plan2code-1-plan` to continue (add `--web` for the web console)."
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Critical review specialist -- experienced senior engineer providing independent
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before the scope detection: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow review` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/review.md. Scope questions, the findings report and the pick-what-gets-fixed menu all go through it; the report lands on the page as a doc. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. `--loop` (only inside the desktop app, a Review Loop round): open with `open --loop --workflow review --round <n> --role <role> --scope-file <path>` from the arguments, read `<D>/notes/review-loop.md` after `console.md`, and follow it; it replaces the scope question, the fix menu, the sign-off, Lessons End and every git step below. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Process. Read inside a build session for its review button? Skip this section — building-review.md's overrides govern, the session is already running.
|
||||
The FIRST thing you do, before anything else in this file — before the scope detection: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow review` before reading, then read <D>/console.md and <D>/notes/review.md. Scope questions, the findings report and the pick-what-gets-fixed menu all go through it; the report lands on the page as a doc. `--loop` (only inside the desktop app, a Review Loop round): open with `open --loop --workflow review --round <n> --role <role> --scope-file <path>` from the arguments, read `<D>/notes/review-loop.md` after `console.md`, and follow it; it replaces the scope question, the fix menu, the sign-off, Lessons End and every git step below. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Process. Read inside a build session for its review button? Skip this section — building-review.md's overrides govern, the session is already running.
|
||||
|
||||
## Scripts
|
||||
|
||||
@@ -184,7 +184,7 @@ Work summary — tell user: scope reviewed, findings count by severity (Critical
|
||||
|
||||
Read references/session-end.md
|
||||
|
||||
> Fallback: route plan2code artifacts (plan/spec docs/phases) on the reviewed feature's own `specs/<feature>/` state to the earliest unmet pipeline stage whose input exists — `PLAN-*` or `overview.md` without `phase-*.md` → `/plan2code-2-document`; unchecked `- [ ]` phase tasks → `/plan2code-3-implement`; all checked → `/plan2code-4-finalize`; archived → complete, summary only. Read the state with `specs.mjs status <spec>` (gitignored `specs/` defeats search tools). Non-pipeline artifacts (code/PRs/docs/logs) → summary only. Unresolved Criticals → fixing them (H/A/S) is the next step. Ambiguous or multiple candidate specs → ask one targeted question. Output: "Next (NEW conversation): `/plan2code-<step>` — [why + how you know]", appending ` --web` when the routed step offers the web console; else "Review complete -- [summary]."
|
||||
> Fallback: route plan2code artifacts (plan/spec docs/phases) on the reviewed feature's own `specs/<feature>/` state to the earliest unmet pipeline stage whose input exists — `PLAN-*` or `overview.md` without `phase-*.md` → `/plan2code-2-document`; unchecked `- [ ]` phase tasks → `/plan2code-3-implement`; all checked → `/plan2code-4-finalize`; archived → complete, summary only. Read the state with `specs.mjs status <spec>` (gitignored `specs/` defeats search tools). Non-pipeline artifacts (code/PRs/docs/logs) → summary only. Unresolved Criticals → fixing them (H/A/S) is the next step. Ambiguous or multiple candidate specs → ask one targeted question. Output: "Next (NEW conversation): `/plan2code-<step>` — [why + how you know]; add `--web` for the web console"; else "Review complete -- [summary]."
|
||||
|
||||
- **Commit** (code changes): the `command` from `commit-msg.mjs --subject "fix: [desc]" --files <file>` repeated once per fixed file. On Windows PowerShell 5.1 (no `&&`), give `add` and `commit` as two commands.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Finds code no test covers and writes the missing tests. Asks where to look, find
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before reading the code: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow test` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-test/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/test.md. Every question, the plan and the results go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
The FIRST thing you do, before anything else in this file, before reading the code: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-test/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow test` before reading, then read <D>/console.md and <D>/notes/test.md. Every question, the plan and the results go through it. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
|
||||
## Project Context
|
||||
|
||||
@@ -133,11 +133,11 @@ Write the missing tests for [scope]: [N] source files with no test, across [runn
|
||||
[Commands confirmed, coverage run or skipped, nearest tests read]
|
||||
|
||||
---
|
||||
**Next:** New conversation with `/plan2code-1-plan --web`, attach this file.
|
||||
**Next:** New conversation with `/plan2code-1-plan` (add `--web` for the web console), attach this file.
|
||||
Resume at Phase 2 (System Context).
|
||||
```
|
||||
|
||||
3. Say: "Created `specs/<name>/PLAN-DRAFT-<date>.md`. Start a new conversation with `/plan2code-1-plan --web` to continue." End the run (Session End, escalated).
|
||||
3. Say: "Created `specs/<name>/PLAN-DRAFT-<date>.md`. Start a new conversation with `/plan2code-1-plan` (add `--web` for the web console) to continue." End the run (Session End, escalated).
|
||||
|
||||
### Step 4: Style
|
||||
|
||||
@@ -191,7 +191,7 @@ Work summary: the scope, how gaps were found (matching, and coverage run or skip
|
||||
|
||||
**Next step**, as the closing line:
|
||||
- A bug was kept: "NEXT STEP (NEW conversation): `/plan2code-diagnose` with `[test file]` › `[case]` as the reproduction."
|
||||
- Escalated: "NEXT STEP (NEW conversation): `/plan2code-1-plan --web` with `specs/<name>/PLAN-DRAFT-<date>.md`."
|
||||
- Escalated: "NEXT STEP (NEW conversation): `/plan2code-1-plan` (add `--web` for the web console) with `specs/<name>/PLAN-DRAFT-<date>.md`."
|
||||
- Otherwise: "Commit the new tests with `/plan2code-git`."
|
||||
|
||||
On the console, post `finish` with the tests added and their results in `headline`, `"dashboard": true`, and `command` `/plan2code-diagnose` when a bug was kept (`/plan2code-1-plan` when escalated), else no `command`. No `commit` field: `body` says to commit the new tests with `/plan2code-git`.
|
||||
|
||||
@@ -8,7 +8,7 @@ Product designer who shows several real options instead of describing them. Draw
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before running a script: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow ui-prototype` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-ui-prototype/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/ui-prototype.md. The starting screen, the paste, the next steps and the save questions all go through it; the prototype itself always opens as its own browser tab. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
The FIRST thing you do, before anything else in this file, before running a script: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-ui-prototype/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow ui-prototype` before reading, then read <D>/console.md and <D>/notes/ui-prototype.md. The starting screen, the paste, the next steps and the save questions all go through it; the prototype itself always opens as its own browser tab. Switchable anytime. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
|
||||
## Run from another skill
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Codebase guide. Two jobs, one card: **explain** how and why an area of the code
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before the mode question: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow xray` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-xray/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/xray.md. The mode question, the answer or the ranked list, and the save offer all go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
The FIRST thing you do, before anything else in this file, before the mode question: **terminal** or **web console**? Run `node "<D>/console.mjs" interface` (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-xray/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir) and follow its rule: the request or the saved default decides; ask only if it says so or the command fails. Console → run `node "<D>/console.mjs" open --workflow xray` before reading, then read <D>/console.md and <D>/notes/xray.md. The mode question, the answer or the ranked list, and the save offer all go through it. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
|
||||
## Project Context (BLOCKING)
|
||||
|
||||
|
||||
@@ -143,6 +143,11 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
finish to post). --force stops a dead page or an abandoned session
|
||||
anyway (the desktop app passes it on its own shutdowns); --all
|
||||
never asks.
|
||||
interface [--set web|terminal|ask]
|
||||
Every skill's first step. Prints { interface, rule }: the person's
|
||||
saved default ("web", "terminal" or null) and the rule for picking
|
||||
this session's interface. Follow the rule. --set saves the default
|
||||
for every skill in every project; ask clears it.
|
||||
|
||||
${workflowLines()}
|
||||
|
||||
@@ -174,6 +179,7 @@ export const HELP_TOPICS = {
|
||||
dashboard: "console-launches.md",
|
||||
meter: "console-meter.md",
|
||||
trouble: "console-trouble.md",
|
||||
interface: "console-interface.md",
|
||||
};
|
||||
for (const f of fs.existsSync(path.join(HERE, "notes")) ? fs.readdirSync(path.join(HERE, "notes")) : []) {
|
||||
if (f.endsWith(".md")) HELP_TOPICS[f.slice(0, -3)] ??= `notes/${f}`;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// Plan2Code Web Console - the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop.
|
||||
// Plan2Code Web Console - the small commands: keep, forget, delete-spec, handoff, delete-handoff, status, stop and interface.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { SESSIONS_DIR, appendEvent, readJson } from "./files.mjs";
|
||||
import { HERE, HOME_DIR, INTERFACE_FILE, INTERFACES, SESSIONS_DIR, appendEvent, ensureDir, nowIso, readJson, savedInterface, writeJsonAtomic } from "./files.mjs";
|
||||
import { SERVER_MAX_LIFE_MS, attachmentName, healthOk, listHandles, pidAlive, projectRoot, repoRoots, resultWaiting, sessionDir } from "./sessions.mjs";
|
||||
import { removeSpec } from "./scan.mjs";
|
||||
import { isOpen, rule } from "./patches.mjs";
|
||||
@@ -304,3 +304,54 @@ export async function cmdStop() {
|
||||
}
|
||||
print({ ok: true, stopped, ...(skipped ? { skippedStaleHandles: skipped } : {}) });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ interface */
|
||||
|
||||
// Every skill's first step: terminal or web console? The answer comes from the
|
||||
// person's request, else their one saved default, and only when neither says
|
||||
// does a skill ask. An answer is never saved on its own: the person opts in to
|
||||
// a default by asking for one. The rule is printed here rather than written
|
||||
// into every skill prompt: those sit at their size limit, and one copy
|
||||
// cannot drift.
|
||||
const INTERFACE_NAMES = { web: "web console", terminal: "terminal" };
|
||||
const INTERFACE_CUES =
|
||||
"Cues for the web console: --web, `Use the web console for this session.`, or words such as " +
|
||||
"web console, Plan2Code UI, browser page, interactive HTML session. Cues for the terminal: " +
|
||||
"--terminal, or asking for the terminal. A task that is merely about web code is not a cue. " +
|
||||
"Drop a flag from the argument.";
|
||||
|
||||
function interfaceRule(saved) {
|
||||
const set = `node "${path.join(HERE, "console.mjs")}" interface --set web|terminal`;
|
||||
const switching =
|
||||
'Mid-session, "web console" or "terminal" from the person switches (console-interface.md → Switching mid-session) and leaves the default alone.';
|
||||
if (saved) {
|
||||
return (
|
||||
`Use the ${INTERFACE_NAMES[saved]}: it is the person's saved default, so do not ask. ` +
|
||||
`Only a cue in their request for this skill overrides it, for this session only. ${INTERFACE_CUES} ` +
|
||||
`${switching} Asked to change the default: ${set}; --set ask clears it, so the next skill asks again.`
|
||||
);
|
||||
}
|
||||
return (
|
||||
`No default saved. A cue in the person's request decides. ${INTERFACE_CUES} ` +
|
||||
"Without one, ask: web console (suggested: a browser page, easier for sign-offs) or terminal. " +
|
||||
"Save nothing from the answer. After asking, add one line: say \"make the terminal (or web console) my default\" " +
|
||||
`and no skill asks again. Asked for a default: ${set}. ${switching}`
|
||||
);
|
||||
}
|
||||
|
||||
export function cmdInterface() {
|
||||
if (args.set === undefined) {
|
||||
const saved = savedInterface();
|
||||
print({ interface: saved, rule: interfaceRule(saved) });
|
||||
return;
|
||||
}
|
||||
if (args.set === "ask") {
|
||||
fs.rmSync(INTERFACE_FILE, { force: true });
|
||||
print({ ok: true, interface: null });
|
||||
return;
|
||||
}
|
||||
if (!INTERFACES.includes(args.set)) die("--set takes web, terminal or ask", 2);
|
||||
ensureDir(HOME_DIR);
|
||||
writeJsonAtomic(INTERFACE_FILE, { interface: args.set, at: nowIso() });
|
||||
print({ ok: true, interface: args.set });
|
||||
}
|
||||