mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-12-05 08:15:41 -08:00
Compare commits
21
Commits
v3.2.3
...
macos-support
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eba3c3bf0c | ||
|
|
ec45430eda | ||
|
|
615e98e11e | ||
|
|
a9e0bf49f0 | ||
|
|
31edc2d5c9 | ||
|
|
8b5932c351 | ||
|
|
59d226c2a6 | ||
|
|
ddbc85f73d | ||
|
|
91479b21a1 | ||
|
|
b629f5ef04 | ||
|
|
8c028c1ce0 | ||
|
|
6a93395148 | ||
|
|
98bdbc97c3 | ||
|
|
1d007737b1 | ||
|
|
4ced32be5c | ||
|
|
603c871720 | ||
|
|
658c813428 | ||
|
|
9629961f36 | ||
|
|
a03b825951 | ||
|
|
44434d5264 | ||
|
|
f997a82c4d |
No files matched your search
@@ -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.
|
- **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.
|
- **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 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`.
|
||||||
@@ -66,6 +66,8 @@ Key design points:
|
|||||||
- **Starting ticks are staged by the page, never answered by the server.** A `multi` row with `ticked: true` is seeded into the person's staged answer once (`seedStaged`, marked in `page.local.seeded`); an `answer` on the item would settle the card before anyone saw it, and a staged answer already flows through Send, drafts, the settled record and the reply words.
|
- **Starting ticks are staged by the page, never answered by the server.** A `multi` row with `ticked: true` is seeded into the person's staged answer once (`seedStaged`, marked in `page.local.seeded`); an `answer` on the item would settle the card before anyone saw it, and a staged answer already flows through Send, drafts, the settled record and the reply words.
|
||||||
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
|
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
|
||||||
|
|
||||||
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-relative-urls`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
||||||
|
|
||||||
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files tables (the server and contract in [the console file](./AGENTS-architecture-console.md), a `public/` file in [the page file](./AGENTS-architecture-console-page.md), a game file in [Activities](./AGENTS-architecture-activities.md) or the Ghoul Rush files), which the docs-table test (same file) checks.
|
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files tables (the server and contract in [the console file](./AGENTS-architecture-console.md), a `public/` file in [the page file](./AGENTS-architecture-console-page.md), a game file in [Activities](./AGENTS-architecture-activities.md) or the Ghoul Rush files), which the docs-table test (same file) checks.
|
||||||
|
|
||||||
|
**Every URL the page uses is page-relative** (`fetch("state")`, `href="app.css"`, never a leading `/`), and so is every link the server hands it (`uploads/<id>.jpg`): the macOS app's frame gets no cookie and is signed in by the path prefix `/f/<key>/` (`takeFramePrefix()` in `routes.mjs`), so a slash-leading URL misses the prefix and gets a 403 there, and only there. `scripts/test-web-console-relative-urls.mjs` names each one, and `scripts/test-web-console-page-frame.mjs` runs the page under the prefix; a game module is resolved against the page (`new URL(entry.module, document.baseURI)`), since `import()` takes no bare path.
|
||||||
@@ -21,7 +21,7 @@ One row per file under `src/web-console/public/` (the games and their sound are
|
|||||||
| `public/render.js` | Markdown to DOM, safely: no HTML string is ever produced, only nodes built with `createElement` and `textContent`; also the shared page helpers (`el`, `md`, `copyButton`, `lightDismiss`) |
|
| `public/render.js` | Markdown to DOM, safely: no HTML string is ever produced, only nodes built with `createElement` and `textContent`; also the shared page helpers (`el`, `md`, `copyButton`, `lightDismiss`) |
|
||||||
| `public/selectors.js` | what the page reads off its state: the questions, the finish, the scan, who has the ball |
|
| `public/selectors.js` | what the page reads off its state: the questions, the finish, the scan, who has the ball |
|
||||||
| `public/send-state.js` | whether Send is available, and what its button says |
|
| `public/send-state.js` | whether Send is available, and what its button says |
|
||||||
| `public/skills.js` | the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (`SKILL_CATALOG`, `START_POSES`, `CONSOLE_WORKFLOWS` and the rest, in `answers.js`) are lookups on it. Each entry also carries `weight` (what its launch and `run` score on the meter, or null), `started` and `ran` (the meter's labels for them, or null), `resume` (`"overview"`, `"folder"` or null: what the resume command takes after the skill's command) and an optional `card.help` (Help's line for the card when it differs from `blurb`). `WORKFLOWS` (every entry's workflow, in order) and `isWorkflow()` are what the CLI checks a `--workflow` against. The meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS`, `resumeCommand()`, Help's card list and `cmd-help`'s workflow list are all derived from it, so a new skill is one entry here, not an edit to each of those |
|
| `public/skills.js` | the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (`SKILL_CATALOG`, `START_POSES`, `CONSOLE_WORKFLOWS` and the rest, in `answers.js`) are lookups on it. Each entry also carries `weight` (what its launch and `run` score on the meter, or null), `started` and `ran` (the meter's labels for them, or null), `resume` (`"overview"`, `"folder"` or null: what the resume command takes after the skill's command) and an optional `card.help` (Help's line for the card when it differs from `blurb`). An optional `loop` names the card-less app-only loop entry a confirm pane offers; those entries carry only availability facts, with `card: null`. `WORKFLOWS` (every entry's workflow, in order) and `isWorkflow()` are what the CLI checks a `--workflow` against. The meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS`, `resumeCommand()`, Help's card list and `cmd-help`'s workflow list are all derived from it, so a new skill is one entry here, not an edit to each of those |
|
||||||
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click; seven cues (not Planny snoring or waking) play the file picked in Preferences, saved flat as `soundFile<Event>` (`soundFileQuestion`) out of the 19 files `sound-01` to `sound-19` in `public/sounds/` |
|
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click; seven cues (not Planny snoring or waking) play the file picked in Preferences, saved flat as `soundFile<Event>` (`soundFileQuestion`) out of the 19 files `sound-01` to `sound-19` in `public/sounds/` |
|
||||||
| `public/spec-states.js` | the spec states (`diagnosed`, `fixed`, `upgrade`, `upgraded`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
|
| `public/spec-states.js` | the spec states (`diagnosed`, `fixed`, `upgrade`, `upgraded`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
|
||||||
| `public/card-rows.js` | how many cards a dashboard group draws per row (`steadyColumns(count, width)`): one card width per group, what fits or one column more or fewer to leave no card alone on a row (one empty corner is fine from three across), a last row still short centered; `screens/dashboard.js` applies it as `--dash-cols` and `is-centered` on draw and on resize; tested in `scripts/test-web-console-card-rows.mjs` |
|
| `public/card-rows.js` | how many cards a dashboard group draws per row (`steadyColumns(count, width)`): one card width per group, what fits or one column more or fewer to leave no card alone on a row (one empty corner is fine from three across), a last row still short centered; `screens/dashboard.js` applies it as `--dash-cols` and `is-centered` on draw and on resize; tested in `scripts/test-web-console-card-rows.mjs` |
|
||||||
@@ -31,11 +31,11 @@ One row per file under `src/web-console/public/` (the games and their sound are
|
|||||||
| `public/screens/cards.js` | question cards: every kind (one builder per kind in `BUILDERS`), the pager, settled and in-flight records. The `lessons` kind's builder is `buildLessons()`: the approval card for noted lessons, one row per waiting item (`lessonRow()`) decided on its own with the words its type takes, the choices kept as a draft (`lessons-<id>`) until Send, or the first ask's three answers when the card carries `firstAsk`; a `suggested` map (row id to one of that row's choices, or `{ choice, text?, why? }` where the words go only with Reword, Reword and move or Rename; checked in `lessonsProblems()` in `patches.mjs`, read by `lessonSuggestion()` in `answers.js`) draws a dashed `is-suggested` ring on those buttons without picking them, and its words fill that row's edit boxes once the suggested edit is open (`lessonsFillSuggested()`, once per suggestion, remembered in the draft's `applied`, so later typing stays); on the dashboard it is drawn in the Lessons to review dialog (`renderLessonsDialog()` in `screens/learning-row.js`). A `multi` option may carry `ticked: true` (the row starts ticked the first time the card shows, never on a `locked` row) and `tag` (1 to 16 characters, drawn as a neutral `.pill.tag` beside the label and read in the checkbox's accessible name after the `k: text`); on a card with a ticked row, unticking the last box (or pressing a lit preset off) stages `ks: []`, an answer that reads `none`, where other cards stage nothing. |
|
| `public/screens/cards.js` | question cards: every kind (one builder per kind in `BUILDERS`), the pager, settled and in-flight records. The `lessons` kind's builder is `buildLessons()`: the approval card for noted lessons, one row per waiting item (`lessonRow()`) decided on its own with the words its type takes, the choices kept as a draft (`lessons-<id>`) until Send, or the first ask's three answers when the card carries `firstAsk`; a `suggested` map (row id to one of that row's choices, or `{ choice, text?, why? }` where the words go only with Reword, Reword and move or Rename; checked in `lessonsProblems()` in `patches.mjs`, read by `lessonSuggestion()` in `answers.js`) draws a dashed `is-suggested` ring on those buttons without picking them, and its words fill that row's edit boxes once the suggested edit is open (`lessonsFillSuggested()`, once per suggestion, remembered in the draft's `applied`, so later typing stays); on the dashboard it is drawn in the Lessons to review dialog (`renderLessonsDialog()` in `screens/learning-row.js`). A `multi` option may carry `ticked: true` (the row starts ticked the first time the card shows, never on a `locked` row) and `tag` (1 to 16 characters, drawn as a neutral `.pill.tag` beside the label and read in the checkbox's accessible name after the `k: text`); on a card with a ticked row, unticking the last box (or pressing a lit preset off) stages `ks: []`, an answer that reads `none`, where other cards stage nothing. |
|
||||||
| `public/screens/cleanup.js` | User Preferences' Cleanup section, on the System tab |
|
| `public/screens/cleanup.js` | User Preferences' Cleanup section, on the System tab |
|
||||||
| `public/screens/core.js` | the core every screen sits inside: connection, the render loop, the page chrome and Send; the only file that imports the screens, and only `app.js` imports it |
|
| `public/screens/core.js` | the core every screen sits inside: connection, the render loop, the page chrome and Send; the only file that imports the screens, and only `app.js` imports it |
|
||||||
| `public/screens/dashboard.js` | the dashboard: cards, the spec picker, handoff chips, delete, the first-open wake-up, and Learning's waiting banner (`learningBanner()`: the line from `learningBannerText()` and a **Review** button sending `__learning` `review`, last of the banners), which places Learning's row through `hooks.renderLearningRow` |
|
| `public/screens/dashboard.js` | the dashboard: cards, the spec picker, the confirm pane's launch options (the Review box and the Loop box; app-only entries have no dashboard cards), handoff chips, delete, the first-open wake-up, and Learning's waiting banner (`learningBanner()`: the line from `learningBannerText()` and a **Review** button sending `__learning` `review`, last of the banners), which places Learning's row through `hooks.renderLearningRow` |
|
||||||
| `public/screens/learning-row.js` | Learning's row on the dashboard (`renderLearningRow(scan, position)`): four states in two places (under the picker while not set up, off or paused; after the last card group while on), Pause for me posting `/learning/pause` with no agent, More, Open the lessons and the Remove confirm, plus `renderLessonsDialog()`, the Lessons to review dialog that draws an open `lessons` card over the menu; the agent-run controls send `__learning` through `hooks.sendLearning` and gray out under `learningBlocked()` |
|
| `public/screens/learning-row.js` | Learning's row on the dashboard (`renderLearningRow(scan, position)`): four states in two places (under the picker while not set up, off or paused; after the last card group while on), Pause for me posting `/learning/pause` with no agent, More, Open the lessons and the Remove confirm, plus `renderLessonsDialog()`, the Lessons to review dialog that draws an open `lessons` card over the menu; the agent-run controls send `__learning` through `hooks.sendLearning` and gray out under `learningBlocked()` |
|
||||||
| `public/screens/review-loop-setup.js` | the Review Loop's setup screen on the dashboard (app only): scope, round cap, commit and the pre-run commit tick, Suggestions, strength, silence, notify (the lifted `notifyFields` and `silenceField` of `loop-setup.js`), the hands-off and reviewer lines, the Start checks, and the `review-loop-start` request to the app. |
|
| `public/screens/review-loop-setup.js` | the Review Loop's setup screen (app only), opened from the Loop box on Review's confirm pane: scope, round cap, commit and the pre-run commit tick, Suggestions, strength, silence, notify (the lifted `notifyFields` and `silenceField` of `loop-setup.js`), the hands-off and reviewer lines, the Start checks, and the `review-loop-start` request to the app. |
|
||||||
| `public/review-loop-end.js` | how a Review Loop run ends (`renderLoopEnd` hands a `loopEnd` with `kind: "review"` to `renderReviewLoopEnd`): a heading by `reason` (Clean, Stopped at the round cap, Stopped by you, Failed) with `line`, the `report` doc behind Read the full report, after Stop now (`partial`) the partial diff drawn by `diff-view.js` with Keep and Discard (`review-loop-partial`), Continue ("Run one more round" at the cap) only when `canContinue` and no `partial` (`review-loop-continue`), the Suggestions pick (nothing ticked) and the squash switch (only when `canSquash`, off) kept in module state per ending, and Sign off (`review-loop-sign-off` with `picks` and `squash`, always on offer); once `signedOff`, the finished screen: PR Prep and Fix what's left by hand (hidden when `open` is empty) send `review-loop-next` (`pr-prep` or `quick-task`), Back to the dashboard sends `loop-dashboard`. The app's answers land in `page.reviewAction` (`wireLoopMessages`) and show under the card; a pressed button stays disabled until the ending changes or an answer carries an error |
|
| `public/review-loop-end.js` | how a Review Loop run ends (`renderLoopEnd` hands a `loopEnd` with `kind: "review"` to `renderReviewLoopEnd`): a heading by `reason` (Clean, Stopped at the round cap, Stopped by you, Failed) with `line`, the `report` doc behind Read the full report, after Stop now (`partial`) the partial diff drawn by `diff-view.js` with Keep and Discard (`review-loop-partial`), Continue ("Run one more round" at the cap) only when `canContinue` and no `partial` (`review-loop-continue`), the Suggestions pick (nothing ticked) and the squash switch (only when `canSquash`, off) kept in module state per ending, and Sign off (`review-loop-sign-off` with `picks` and `squash`, always on offer); once `signedOff`, the finished screen: PR Prep and Fix what's left by hand (hidden when `open` is empty) send `review-loop-next` (`pr-prep` or `quick-task`), Back to the dashboard sends `loop-dashboard`. The app's answers land in `page.reviewAction` (`wireLoopMessages`) and show under the card; a pressed button stays disabled until the ending changes or an answer carries an error |
|
||||||
| `public/screens/loop-setup.js` | the Implementation Loop's setup screen on the dashboard (app only): the fields, their defaults and read-only facts, the Start checks, and the request to the app. The **Strength per phase** field (`strengthField`) is a grid: four headed columns (Match my session, Thrifty, Balanced, Best; level 0 to 3) and one `radiogroup` row per phase left, one radio per column (`#loop-strength-<n>-<word>`, `match` for Match my session; an unmapped word's radio is disabled and its header says "(not mapped)"), the cell's dot (`strengthBars`) over the hidden radio, and the model the pick becomes at the row's end. **Set all to** stays a select (`#loop-strength-all`, blank again after use). **Suggest for me** (`#loop-strength-suggest`, right of it) sends a no-hop `__loopSuggest` (`id`, `spec`, `phases`, the mapped `strengths`) to the dashboard agent and grays the field under `.loop-suggest-overlay` (`.is-suggesting`, `aria-busy`); the agent posts `loopSuggest` (`{ id, spec, picks: [{ n, strength, why }] }`, checked by `loopSuggestProblems` in `patches.mjs`), and the page applies only the answer whose `id` and `spec` match its own request, mapped words only, with each `why` as a `.loop-strength-why` line that a hand change or Set all to clears; `SUGGEST_WAIT_MS` (two minutes) gives the field back with a note when nobody answers. The dashboard skill answers it under "A strength suggestion arrives". `drawStrengthLine(grid)` draws the grid's SVG from the checked nodes' measured positions, never from state: a very light dashed `line.col` per column and a thick square-step `path.step` from each row's node to the next (one path fewer than rows, none under two rows or with the toggle off). It redraws on the window's resize, a `ResizeObserver` on the grid (Preferences' page width), fonts loading and every redraw of the section, and stops once the grid is gone. The colors are the `--lvl-0` to `--lvl-3` tokens (`--lvl-0` is the neutral gray of Match my session); tests wait for the drawn state before reading the line. The page locks while `state.loop.driving` is set (`loopDriving()` in `selectors.js`) until the app posts `loopEnd`; Activities, Notebook, Help and Preferences stay usable. `loopEnd` takes a third `kind`, `"review"` (the Review Loop's end, `reviewLoopEndProblems` in `patches.mjs`: `reason`, `report`, `canContinue`, `canSquash`, optional `partial`, `suggestions`, `open`, `signedOff`, `note`; `report` and `partial.diff` name docs on the page, no `phases` or `uncommitted` needed); `loopEnd.can` accepts `ask` (`LOOP_CAN` in `patches.mjs`); the app adds it first to every stop that offers `resume`, and the stopped screen's **Ask a question** wakes an ordinary agent on the same session |
|
| `public/screens/loop-setup.js` | the Implementation Loop's setup screen (app only), opened from the Loop box on Implement's confirm pane: the fields, their defaults and read-only facts, the Start checks, and the request to the app. The **Strength per phase** field (`strengthField`) is a grid: four headed columns (Match my session, Thrifty, Balanced, Best; level 0 to 3) and one `radiogroup` row per phase left, one radio per column (`#loop-strength-<n>-<word>`, `match` for Match my session; an unmapped word's radio is disabled and its header says "(not mapped)"), the cell's dot (`strengthBars`) over the hidden radio, and the model the pick becomes at the row's end. **Set all to** stays a select (`#loop-strength-all`, blank again after use). **Suggest for me** (`#loop-strength-suggest`, right of it) sends a no-hop `__loopSuggest` (`id`, `spec`, `phases`, the mapped `strengths`) to the dashboard agent and grays the field under `.loop-suggest-overlay` (`.is-suggesting`, `aria-busy`); the agent posts `loopSuggest` (`{ id, spec, picks: [{ n, strength, why }] }`, checked by `loopSuggestProblems` in `patches.mjs`), and the page applies only the answer whose `id` and `spec` match its own request, mapped words only, with each `why` as a `.loop-strength-why` line that a hand change or Set all to clears; `SUGGEST_WAIT_MS` (two minutes) gives the field back with a note when nobody answers. The dashboard skill answers it under "A strength suggestion arrives". `drawStrengthLine(grid)` draws the grid's SVG from the checked nodes' measured positions, never from state: a very light dashed `line.col` per column and a thick square-step `path.step` from each row's node to the next (one path fewer than rows, none under two rows or with the toggle off). It redraws on the window's resize, a `ResizeObserver` on the grid (Preferences' page width), fonts loading and every redraw of the section, and stops once the grid is gone. The colors are the `--lvl-0` to `--lvl-3` tokens (`--lvl-0` is the neutral gray of Match my session); tests wait for the drawn state before reading the line. The page locks while `state.loop.driving` is set (`loopDriving()` in `selectors.js`) until the app posts `loopEnd`; Activities, Notebook, Help and Preferences stay usable. `loopEnd` takes a third `kind`, `"review"` (the Review Loop's end, `reviewLoopEndProblems` in `patches.mjs`: `reason`, `report`, `canContinue`, `canSquash`, optional `partial`, `suggestions`, `open`, `signedOff`, `note`; `report` and `partial.diff` name docs on the page, no `phases` or `uncommitted` needed); `loopEnd.can` accepts `ask` (`LOOP_CAN` in `patches.mjs`); the app adds it first to every stop that offers `resume`, and the stopped screen's **Ask a question** wakes an ordinary agent on the same session |
|
||||||
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button |
|
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button |
|
||||||
| `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home; a Diagnose finish whose `doc` is saved shows that file whole as a Bug report box with Copy report (the raw Markdown), above Next step |
|
| `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home; a Diagnose finish whose `doc` is saved shows that file whole as a Bug report box with Copy report (the raw Markdown), above Next step |
|
||||||
| `public/screens/git-host.js` | hosts the git board: the tools fold-out (`board.tools`, saved with the board), tabs, panels and what each click sends |
|
| `public/screens/git-host.js` | hosts the git board: the tools fold-out (`board.tools`, saved with the board), tabs, panels and what each click sends |
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ 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 |
|
| `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 |
|
| `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 |
|
| `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.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` · `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) |
|
| `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 |
|
| `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 |
|
||||||
|
|||||||
@@ -62,6 +62,8 @@ plan2code/
|
|||||||
│ └── public/ # Page assets served to the browser
|
│ └── public/ # Page assets served to the browser
|
||||||
├── scripts/ # Development scripts
|
├── scripts/ # Development scripts
|
||||||
│ ├── bench-web-console.mjs # Start-path timing
|
│ ├── 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`)
|
│ ├── 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
|
│ ├── 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
|
│ ├── 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
|
├── 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)
|
│ └── screenshots/ # Web console screenshots, <shot>-light.webp and <shot>-dark.webp (generated)
|
||||||
├── specs/ # Feature specs (if any in-progress)
|
├── 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)
|
├── package.json # Root package (husky only, private: true)
|
||||||
├── version.json # Version metadata
|
├── version.json # Version metadata
|
||||||
├── CHANGELOG.md, QUICK-REFERENCE.md, LICENSE
|
├── CHANGELOG.md, QUICK-REFERENCE.md, LICENSE
|
||||||
@@ -103,7 +106,8 @@ plan2code/
|
|||||||
|
|
||||||
| File | Purpose |
|
| 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") |
|
| `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` |
|
| `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 |
|
| `scripts/validate-char-count.js` | Pre-commit validator ensuring all source prompts ≤ 20,000 chars |
|
||||||
@@ -130,11 +134,13 @@ plan2code/
|
|||||||
|
|
||||||
### Release channel
|
### 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.
|
`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
|
## 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/`)
|
## Repo-Local Skills (`.claude/skills/`)
|
||||||
|
|
||||||
|
|||||||
@@ -4,10 +4,12 @@
|
|||||||
## Common Commands
|
## Common Commands
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Install dev dependencies (sets up husky pre-commit hooks only; each sub-package
|
# Install dev dependencies, then turn on the husky pre-commit hooks, once per clone. Never put
|
||||||
# below needs its own npm install. Running `npm test` needs Node 20+; users of
|
# 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+)
|
# the installed skills still need only Node 18+)
|
||||||
npm install
|
npm install
|
||||||
|
npm run setup:hooks
|
||||||
|
|
||||||
# Run the interactive installer
|
# Run the interactive installer
|
||||||
node install.js
|
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,
|
# 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 +
|
# 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
|
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
|
# Put every text file git sees back to LF (also runs by itself as pretest and in
|
||||||
# the pre-commit hook); --check only lists
|
# the pre-commit hook); --check only lists
|
||||||
npm run fix:eol
|
npm run fix:eol
|
||||||
@@ -43,6 +50,10 @@ node --test --test-name-pattern "<regex>" scripts/test-web-console-<area>.mjs
|
|||||||
# playwright-core, which `npm install` already provides)
|
# playwright-core, which `npm install` already provides)
|
||||||
node scripts/bench-web-console.mjs [--runs 7] [--workflow dashboard]
|
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).
|
# 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
|
# 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.
|
# before committing: right screen, both themes, no username or home path in frame.
|
||||||
@@ -94,10 +105,11 @@ The same areas as one-command rows live in the [Test map](./AGENTS-test-map.md),
|
|||||||
|
|
||||||
| What changed | Run |
|
| 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) |
|
| 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/`) |
|
| 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/` |
|
| One web console area (server routes, chat, git board, workspace, notepad, Implementation Loop...) | that area's `scripts/test-web-console-<area>.mjs` (the loop's is `test-web-console-loop.mjs`, the Review Loop's `test-web-console-review-loop.mjs` with `test-web-console-page-review-loop.mjs`), and its `test-web-console-page-<area>.mjs` when the page changed; `node scripts/parse-check.mjs` after editing any browser module under `public/` |
|
||||||
|
| A URL the page uses, or a link the server builds for it | `node --test scripts/test-web-console-relative-urls.mjs scripts/test-web-console-page-frame.mjs` |
|
||||||
| The launcher (`src/launcher/`) | `node --test scripts/test-launcher.mjs` |
|
| The launcher (`src/launcher/`) | `node --test scripts/test-launcher.mjs` |
|
||||||
| A skill's script | `npm run build:skills`, then `node --test scripts/test-script-<skill>.mjs` (and `test-skill-scripts.mjs` for the shared plumbing) |
|
| A skill's script | `npm run build:skills`, then `node --test scripts/test-script-<skill>.mjs` (and `test-skill-scripts.mjs` for the shared plumbing) |
|
||||||
| Dead Code (`src/plan2code-dead-code-scripts/`, `scripts/fixtures/dead-code/`) | `npm run build:skills`, then `node scripts/node-test.mjs scripts/test-script-dead-code.mjs` |
|
| Dead Code (`src/plan2code-dead-code-scripts/`, `scripts/fixtures/dead-code/`) | `npm run build:skills`, then `node scripts/node-test.mjs scripts/test-script-dead-code.mjs` |
|
||||||
@@ -107,6 +119,8 @@ The same areas as one-command rows live in the [Test map](./AGENTS-test-map.md),
|
|||||||
| A new skill or console workflow | First update the hand-written tables that list every workflow: the `SUBAGENT_WORKFLOWS` count and the meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS` in `test-web-console-logic.mjs`, `notesFor` in `test-web-console-speed.mjs`, the event list in `src/web-console/console-meter.md` (checked by `test-web-console-chat-stress.mjs`) and a `BUDGETS.notes` entry in `test-console-wire-budgets.mjs`. Then run those four suites plus `test-web-console-skills.mjs` and `test-web-console-spec-states.mjs`; the PR Prep and Test build missed all five tables and only the full suite caught them |
|
| 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` |
|
| 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.
|
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.
|
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.
|
||||||
@@ -154,18 +168,18 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|
|||||||
|------|--------|
|
|------|--------|
|
||||||
| `--build-skills` | Regenerate `skills/` from `src/`, pruning stale skills and reference files |
|
| `--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 |
|
| `--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 |
|
| `--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
|
## How the Installer Works
|
||||||
|
|
||||||
1. **Builds `skills/` from `src/`** — one Agent Skill per source prompt, including uncommitted source edits.
|
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. **Checks the skills CLI is reachable** with `npx --yes skills@1.7.6 --version` (the version is pinned: `SKILLS_CLI_VERSION` in `install.js`).
|
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. **Sweeps pre-2.2 install paths** and removes installed `plan2code-*` skills so renamed or retired prompts cannot survive as orphans.
|
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. **Delegates installation** to `npx --yes skills@1.7.6 add "<repo>/skills" -g -s <skill names> -y`.
|
4. **Sweeps pre-2.2 install paths** (`cleanLegacyPaths()`), files the `skills` CLI knows nothing about
|
||||||
5. **Installs the global `plan2code` command** (only when step 4 succeeded). Advanced → `L` runs the same flow without `-g` and without the launcher.
|
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:**
|
**Invocation choices:**
|
||||||
|
|
||||||
@@ -175,6 +189,17 @@ The skills CLI owns distribution from step 4 onward. It stores canonical skills
|
|||||||
| No `-a` / `--agent '*'` | Uses the CLI's supported default agent set instead of requesting incompatible scope/agent combinations. |
|
| 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. |
|
| 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
|
## Skill Format
|
||||||
|
|
||||||
| Item | Value |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
||||||
@@ -16,6 +19,7 @@ Which checks cover which files, read by PR Prep and Test (`test-map.mjs read` ch
|
|||||||
| Learning on the console | `src/web-console/learning.mjs`, `src/web-console/public/screens/learning-row.js`, `src/web-console/public/styles/learning.css` | `node scripts/node-test.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-page-learning.mjs` | no |
|
| Learning on the console | `src/web-console/learning.mjs`, `src/web-console/public/screens/learning-row.js`, `src/web-console/public/styles/learning.css` | `node scripts/node-test.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-page-learning.mjs` | no |
|
||||||
| Review Loop on the console | `src/web-console/review-loop-setup.mjs`, `src/web-console/notes/review-loop.md`, `src/web-console/public/screens/review-loop-setup.js`, `src/web-console/public/loop-parts.js`, `src/web-console/public/review-loop-end.js` | `node scripts/node-test.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-loop.mjs && npm run test:page -- scripts/test-web-console-page-review-loop.mjs` | no |
|
| Review Loop on the console | `src/web-console/review-loop-setup.mjs`, `src/web-console/notes/review-loop.md`, `src/web-console/public/screens/review-loop-setup.js`, `src/web-console/public/loop-parts.js`, `src/web-console/public/review-loop-end.js` | `node scripts/node-test.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-loop.mjs && npm run test:page -- scripts/test-web-console-page-review-loop.mjs` | no |
|
||||||
| Workflow prompts | `src/plan2code-*.md` | `node scripts/validate-char-count.js && node scripts/check-skill-table.mjs` | no |
|
| Workflow prompts | `src/plan2code-*.md` | `node scripts/validate-char-count.js && node scripts/check-skill-table.mjs` | no |
|
||||||
|
| App smoke scripts | `plan2code-app/scripts/smoke-*.mjs` | `node scripts/node-test.mjs scripts/test-app-smoke-agent.mjs scripts/test-app-smoke-frame.mjs` | no |
|
||||||
| Desktop app | `plan2code-app/**` | `cd plan2code-app && cargo test` | no |
|
| Desktop app | `plan2code-app/**` | `cd plan2code-app && cargo test` | no |
|
||||||
| Metrics | `plan2code-metrics/**` | `cd plan2code-metrics && npm test` | no |
|
| Metrics | `plan2code-metrics/**` | `cd plan2code-metrics && npm test` | no |
|
||||||
| Bot | `plan2code-bot/**` | `cd plan2code-bot && npm test` | no |
|
| Bot | `plan2code-bot/**` | `cd plan2code-bot && npm test` | no |
|
||||||
|
|||||||
@@ -118,7 +118,7 @@ If the user supplies a suffix, set `title = "v$CHANGELOG_VERSION " + <suffix>` (
|
|||||||
|
|
||||||
### Step 9 - Publish (on approval)
|
### 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):
|
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):
|
||||||
|
|
||||||
@@ -149,7 +149,7 @@ gh run list --repo jparkerweb/plan2code --workflow release-app.yml --event workf
|
|||||||
gh run watch <databaseId> --repo jparkerweb/plan2code --exit-status
|
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
|
### Step 10 - Verify
|
||||||
|
|
||||||
@@ -159,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)'
|
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
|
## Rules
|
||||||
|
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
U0VOQwEoj1gX/XfHFT3Q8HyNPu1butBnNDqkYBTPY9eHv5y8X/2wZIk+mJJvQ+io10NBVFql1qQCWCoFSA0nCXKY+jUMOB5W9O/IRXJFeBl2Pv1we6XAbNwOO8hK/9w5NdICSAukFhOAn7t1e7G4chh8xfzGNAdi+p+3qZgGaS+zUYmsEHFY4bPwdk7snglZz5RgS3dLS+PIbtNdTxQY/qAwSg0g5TnzwHWdkXALjRaWyy7LtQ7wpC1VnH7iEeTLGphuFKxfbsZCv3sqLb7ibplQi+R+Ck729nr9raxu7QxIKARxgJht0zssssE7RjOb1D5ZfzkcLOMT71+jUEEilWgbQlwDIlRUujeqYgtNXgUBca2tReHUeh2E7vlILEsruYpHfjpYMIqrYFGTlvkR2e6XXX7xBywJi7nPnATzw/jRUiHxoYjWsje7IlNvHt8bwMCKMErtmVWYGjr0TvnfphkVAicByQHC/r1l/jHrxvr/ePCNVImLB+bu1a+gyYIwlrSqgIydwZPtm8ZZD7GCfTcwAGB166giNpyKgvFQQ31wVKjfjwLgRHtw+neFZNQJHT0uamlXDXhWi7PG6ttVHNPXuyd8RLTPushNxfqEOYk0ku/nhFIfTlWMpTWXnXETbTtcD35NPhUlP4851Wk4bqNHerrwMDzHBOdUcAmaFs3m9MQXZWgcaWtW2paKVN+HTwXg+BTp46ib6zAJri0FuIcGjaKIwJlbgZq6LKXTRA9LPf+Zf9Ji10pDpGy3enTtbhkwontfyenwxBEX5eRUvB+tltFEToQZFKLcnDPzYzhbh4MKCu8UWbBMO5FXIJW6w5nAxzslWy+1W+XKcJTnktVtDEuhoTJcnHePs7XiEzcF+0t+npRtMUxgKl4erJ4HiYz9rjfziLPhvIaBJkGzHRP5xF16afYF8/vt3fReF5ohbS1dNeSOIkoTjWQc0qCVg1CxaGI6IEdNp9Ia1AYeqYZZbMQW7wYGiPMf+OcPcd7lxYI5POFFSqc3HRayaV/f+48NUHyFSmILtil2XexJdGwtTpc+PVdkdgj//5ogU2kMd4VYph5XB6wMKGS9qZxWd5rM0TqPxCUc42yJiiY7veshj9W2OmAhrYfL4DO56fANh7bbqTStpkyUVdFMrUJkwMQJju72tzmT8vx0f81rLGF7sMtr/cuR1wvLCggKQl9dCOrLTkWfn2hWMgdU0FZT0jt27CSRcONF2CxXJchfs3tZ65+NWj8YAjc3QbiBwtPMqcBl1oDCVRIv02tNKyQHXEdEoIyPHWERH4FSWwNmVxdTB+dDJkPSsXWRHiPpTvP6RGuNMkF1KoSFJTcOUWUS9beB/Up6Ep45gdRk1Bf4m9bfh0bhUCbzpQCXJCLdeBqBa1eL/NUmtvvM0Vt2F5QfK1768So4G8bAm8Yfr6cWD1nq/rLXUeSuOfR+Kzcnvs9h1/bCS6EuchemguTR/ypY3rdzI0Y+tmaKxXbuGCFTSnofPcLVPtwIqgq7AWrmeTtwdKkHEkc4rfovqAq6YRHyYjSXqGeij8OTxmRgtl3ZwjZ5PdgzcDzOachrhmFO+8Nne39wcrBlu/TzdMlSHUsEuUFFegxvLVpm81dfAfMo9PaS9LKNTDn7XlRIHiaQYH7I1phd49fDRHpTnEU0W41H6Q5cvEdVzA8NwLW79gTVLXVF93bjnPqVRpz6xKrb0I/Ma5hyQaj4tYM6TuLkpb2P6B5oPmgI+W5d+n4VZjYK/+smpkqacPf3l+Vx8gKdSmM8TvGeK5OpyYVO0qv9Osi5N6AXPPn/b3xO64AtpjHR9ja8cenRe0QuggBXnvX2o7tUoNzNlDSV8ywBQ5D1rFgDvX8uwIOQhSrnQrF8irZ/Igb1jY+Q8ahMVXQEvUy2gTXENNrkc4Cv5W+m336H6OKYEgAGOBA8kMrriA98KqOudCIUu/BkeTW6A8cqTZpebrFVfKNb13+XXLKOnKzWfcswz51Ja1TjJeNogmufrKoD499Pw88/5dszEyJGofm2+CWrkS6hGSLIp8tNM4KfE1nLiouqoW0w/1EAcFgdrwLWAxpSaViWqyBhXBopwo3v+cSt0d8WOMMDIZjRVyqYm0pjbf9CNgce0h2S54R90761K60GNN9Bx8NCyxm35qAnIcjLDUWrFuIYEIvCUWuLYPaf9z48D/2VdrmsfYj4ydHWXVNKAfJY+LogHIyCc2qDRGWihqMYSm3dp2BSZ9Bq3gvxK0W7GsWjzzwhaDpUsj+daXFGcplNckH+5h2aUTSDagdieT7UMDMHm0eSM88L9iNdn5Sx+fDG96OB1nuI+NhtUE7zoPbAffAN3espPWFBZOx7SFwbjsaqbQHQhaIP4AuLgRDal9AXIioWh+p4TBoly7A8jEe8KxbC/2PF88mSoQ9eDhVaGKYdrAy+T5UXoBkit3uJITKaWbYTbc+RLw/DUkXZjCVrumTVmk/COoRN20eHAEvMS2nGJNa79uIX6RzOWSw0t72VBjWOwqUzWv5b22p6Ks64+fBtTg4iEWdKZfKe2AdkMBYVP4Ee3dM12fAR5WJsBYDU9gfXDIqMUXqRL0A/946pN1WN3h+6O+Z+fOh6PGxcpYwi320PxGxGkjl4TQp39xzRQqrQI/xAMx0SqAdSYO39QRWMsXnOI2Qven0MT1kQB0vM4Yc7CWg5kI6CrkKsmTr/U50NAVZbunUNzP7ttuLQxRlUkXWRQZ1RAoDI0WNloYBU4mumA/qL6l1rPVdCY0WvqLDsNLR92VBAGu7n1ZlLFGkZJ/szmhc9mWFye5HLZ8TQiH2MisluqqvaMKMnmXIw0bl2vvUdj4QY5t7rjtpTLhrDf33rjAsfGC1OnWjUdRw5CXVe9zX0MYqHR0mTtWzQ4r0wRWH8O6f1PyD9P6ZMhQzrf0ynIN7qwueTGXpjNUwCyeYMH0DLvhv4od9x/IzzbCFhCyU3MaRC1cDJgr/GJLdfy1+ifhi8IEUVdmHMQnBGKdKWfWWxAmImbiB63ExoHoMBETl+3L8AsX6HD2fUWC8Rp3pjh2BXjYSFqHyK0FJKNweQnAVZv4eb+2g33YFlhOpeXalvWwQb4KHP56TDcuwzKRxfDfBYTEjPRXfi16ise8eDwHCSeE5FqJwDcYScnt8P0s2PsNTkj4KgyUK2PaYiAdOJUdNNhJn1RCMIli0mdJe/l7HRgJUs/JA4eZAE2crJVWaN4Vb907Og9eNu6w+LJDAMKj3jaF85ayhsBJ7MaIZmmL5/PMk0XtnxkN7hBIzMGzMEVhI2G7VLaR8OiPHjm2YVbj1rLZYqoEeJ/M5IJNzmWrwEbdPHZeoYVgnbQe5CZIU9/OxTlvLG6htaMt+lJdsPnFmVgc7b0NL73bxR06/ldvztp6xI067d3igSr5IruvNZeda+sBBcfSB0xGIBXNZ83BzeYid1gr4QKSBpvi82XN3CzZJ2qC6uqfN2dlcMYm1eBXOz/d2uGotZlNgx9gtBd4od3dVlBy2WtVk+XK2xJHC5ob9mOgyZoQnKl9Iop1G+ZxwquWtjAxjoAnPBufXSlTQ2JAcRZdZ6Ak/kRtukJ1QL5tFWIP20CxlDymyNQ2buY3LxWg1gUdFAPoNRkz8IJo+aTvxsjZo6rZKlZLdlEnioR3VDbZhbPc1o0DM2qrKsf/sBLuJ23mGOUOsWYyZtjnR81ybWZZdjUqbB1TkG73bPwug6uPaPqwTBSsDJutCoSZ+wZUf57/E8JrZUoOfAK7qHLJX6+JBrN/F5gCkFFarneiF+yqM9dG4Cg39ew+QTaj/xv4hAUL2ULlQY3e4Lx+SxKWEsTs4C2i4sFxAUPExdKGLAwCuTDMKcZouP52eU8d17wyXJ44wR1qBTWqEWcnc4fOLMqyfeFXh02IpxNd78QErAQmCCBmvwYOMdHocjHYKvZYeIAKdS+jgrxpk2RwuNY9zLSvDu4LAQXWfA/PFwVcvGwF4zRWH0e+A8m29tS0fSTQ+kOOpQpcPKhHv0HaR1deZOCZT6qxKLnMslQVZLuv0rEn7HPegDNskUndVKVnE83VrIC2O21n8ZWtMs1FAReX9HM/waXM/uJ80zV0vjvaDsAf8/8U0Vk8mdaGr/tnMAVx99o11rryzY50H0atXBNfyV/E26X98HSaXMrKUQeGcQY0WC2DG6nC7iTyLckivQ/3LCYDIAB/tgGi55EcQgHFhijK4db+UVrALTRE7wfPkgTst6wxPOaHrlNQXZDUxS1F6wCizzwHWTQoW7/VZRAmrCQ+XohEVhmsIv6JL5rLykBwv1sb18AF6MdmQAUmwO07h3A5Rl5owwDmEV3DyMqfggcZtsEoEI8EkvvOfdqgF+HAB/9uEF+kwZqQKQQsZXZXDVt3qVpRpY1SopOA2aV5qEWPCSNNy2pGpZRLgF0r6lqxAb6ID89bbdpn9ZkmNP7f192Aqy38oE53zSYFaonK1TI7vE+aKsccjcfQ9ygSBiJVAVgLyBTRCxx5WpxoY8hMpzYoHEmniuV4TtUw7DMrAc+dQmytthq/BivfR+SOuHjgBys+2Md2C4uH6M7b2MwnhuqJuQd3ZF4LAvS8vSUi599TTziBko/90Qg0p/NMo+kEBKfs3zYpnQcS3RTriigbazWThlv2EYzXNIRpnt+ZREwo2IgjeL7einD6OSWFS4OfpaHZP3zRhK0Z2AiIMionngIgGngpcJcIRhuOgb9ji5VkaU5+OmMY0LQQoZdjJY+1y5ZBwIX8sdPSa9rtTSyrUCIaH3aGt9oMQBCAIK5tHuv6A/Io9uvczbWkHiAq3OHVdXc7RI4OwPNGNMljrezkS10uMiOk+5xVO+RSFUVL8tszufcv66oOzq+w7BfUqPUzkI6ZmpL3LdFPbePvaqjVPkKJpq5VzIZAKR/rtsux18ouypnxQQ8BP9Q+lwir/IEo5aO7KLCeNZvF1PFrJZBwxlhE4c2izYJ5duGoFJBj8/JjLxXZUg48DI/bz21FGkS6uPu39Line truncated
|
U0VOQwEw0ns8YDG0jTWYQ1y0Hg0RIor5A8hnRTDbcQ+YqcVsLf+9TkxJ+IsTX+Kr6cOanzwn1m6z3bZgAOURfifURlMcUgSskVHUq41QobVGUOjXbcCTWiBTAF3k4FUsFEk80AZCAh8de/Yv7AlmrnfXUUt1bpxBfqi3zYjO8jT4V4HLzhdA1hdNHiazuc6LCajSThzM6GR9fLS+cv9H5bsRuxH/0UfNa+4Fki4BA1xtO1xi0DJGh+DkxLwnZ8hhgvCSH77f+3Fr/3R7rdXBvuPWAAh5Tq305tg9peD3KI44VHCXJPOySW4ruDN+XbsA8BX4OnA6x1FgT0wfHJ7gb+vfYVO5CZ37Z+vr/GjBRanLwPf62ASbb7zNk4pz15W2448GYlV5oJ2WyN7Ai7kadyr9FVquwGvvMucxeVtCP2rjh8TypQAee35pJISQMHPNs0+FABA0OyQwwmKW3nK0B2Xckfdv+xX3f0wbMB9pPJnmEBl0l35XUE1RJG45mDV5K7Mnni8G8XU4PKfcnlhugypo0N9HXjPr1zriI741Msj7m5CMDxks6HtTd+8hNjbcKFUIs/IzT45Xnq7ZvLXgVW1u+Fxz9dtG17GL7sjNndg1aRmUVH35BcihvqNCZmZiVWSmxUCAwSGq/AZLWXsqlj024qY/phZ8WkuuH6KmRMORhK698ybJKi+Cgnf1hzmeqFXLy9lZMQAC+CHecmWg5icNIVe+zKckkdRTazU8lj+/RTYCJjsqdYm5zJXPu8VugSkDv1KUNiTRZT5bjwRTZwHHWhLAY8IomD4nSzb8ak4ugs4d60tqCML4FqPaUmH2D+6u9dt2B4Txb2yojG/xhyZENHuep0lT9GUOrT6Yh0TB6O/bC2Wd1cKoa1zjD48+v08FZlncqWzn4zs8eQwN/X+r5pD2JqbwhC2ts/kL6LIMFBSmHVgPCD5Tq+gxihWqbi3/szjB1YejV68N+v0ALhsJVnW5AgtqXqNcdmdx+M1WfUEHBe6F6cKd1kEeDpxaQbH04DE9RiSpO+Ed2n5d+yhXrcibBpJi9nNTvQWAtoR09P6IOAyLlaFNxrb+VDaDhFS/L+KuV8nHJpa3eNNpRf+GlgogOQuNYUJb/oOnSNlEAYWq9By/hdNOJuJVGwJPUqd8cc2+JTe9qslwQPACiPz5I31I6z8aoMWCK4gi/WlZQk+Hew3hBMRLbDI3ucVx1x/io1YvVvMyL8PLEPHWHpYesnRw6X6zw3a4TnRwvvwpf8Q2n8stfpPLme1IQX0veOyDvn1IVIv8uOPmm3BDe6WfDd+jvoCFVTB9Q0B5z8/2WlpZIwfyBK+jAHPzrXuFGZThOTRU1rxT4uf3s+SxRMEi4NCwOH7aGkDLYYu83XdAIt9uuNjmHLqnTup1l16RSO03+L2GMvciwcHkH79oj5zK4jTkifAW2FFOijPIkJChXlDkU1fEtyIzYkOn/TqyaarUZ+O95UpoZEV37pwRrCLvftGhdM/rRuPwyw6lkbr1kWNx2ExswbIezICAxeW7ICPsVgrQJ2URlH++RBL/s030mciYyyo8Uc+Eo3jaGsXbt5g+JvrQUWiUn8/alGxyo4N/IjhkMsWjNkxEfpBwxhjQ1CLk3p70v4xYYeoHI0v/VGt94IvFO5VE2VOBpmZPMpezJeOnbCzFa2N61zMfCPm/sMCFASl4Ssh/AAZTbtEmf99M9WIuvxTg11Q+bvv3QnJF5gSbVQxQmJU3eju4fEinj/hRNK7qHVWg3IfDaN+LvoxWu3nHOzOLnueo06PI0NyibS8tX3LJ/SbS34zvHfBLd2AI78aLG5V+olXeMvNIhtndaBs/6FmxkqoaZR2SHESTl5exaMIzekF5Hv+O1Cuapv7SO2QaB15LX770bP8TuY2G1uTLCtjEvqBV5QiIGiSCxv1vYFYLEpp1wxvfM06ZsbfUXw7pPs306yxe8mQp3smh5YZrV31cBYJFNLToK5Et/Y+wToTuVYSlzhLEjOOhvBfueyXkIQawEwaly5LeH9fNe+M1pM4E7duP2/UEGr8UR9pVLsR99nwclMehVZ1bts7Wf1WRSwaiEJJVVysMdMXp82VIriAyhQmU9TQzBaIhN1Ktmrns3O76JZwgodG/N+e0jU3cc7CcsGyGU/NR+8I01HKCSus6bn8kyoWa1iCIA2QriqzlipMcxJ6qVgWgX59KtgUB0CZD5tXYX1rfABkigw3p8pKPJJVoCDoIpoxLub7EJcX80JH0Ky7C41htOUQGbzININtHvCZ4+plWY/IyM2ski3A73DMmwR6x7ljCYx20HonX7LrbxvonazNQuB2mIo6JGQ4dmu7uAOx+3rgQSYoT6r6Rrd8VnggoT+8wY8J61yoIgMY4MZZmTHAa+w0e2glQPPYrpszzyrm+5eTk6TiC85FA4MpdtmqUYd4z4mpRhQDRgJTLdjDK0e3c3eX1t01eGh/OSPLqqXz+wuaFvcOjxxnB6F4Wa1/+iQVdXPoW2oX5fgmgR/DyipBkKIG5zwDoCCzkdSmyM6GJ6h6jjP92D3nN1yx+EKBqF6c5g9DDWJ+reoSR1F1ij/qwZDxjJpulKmy+928l+fRZHOXT8iVqX7vy6nMvuuT24q/IUhKPonTwoSDH2pe/kCCn4uGhi/ccMQ5rQCGQWYKl3JuY3xZhPLNEtvSj/9rJwiwPpLNYlG7MVsePdxMZLmcrML7AUhNOeUJs+Niqg3uCmixvm5V+Ef8y7USxCJa0m998nTKWvu/1pDivs3U1Puo5bOOm3VZR+8Q9Iyfme9LUJ4iURJIHVlc4hksrmJgt7ZARTU72EELZVdnfDV4W81V8qiBDOxh/JBwxeZl+eMw4RRprxTmLflNTemnXmjacCOvhlj/oY6RrKOR2MbTTE9vaevwiCD4AxQYe/6b3FBk3wwoD2leuKMVv0z4eo7UFgj8iSMqAbYziD6ekrRZOrwYPFCrQ+8kP27Tw4FUcG2pOxlBDesRQy++wtY6VdzKhPclI91SeM6GN7wOExG3nyc2oIs8vhEHDU5hh7tlWmRuRlA4MRcZShfTIp6j9RSvjVxn8hvpzmv7EmjAglhe6wz3aCmuSxUIj8XYhmfJ1qvFifir/Jg7/dPsEZWoSEwC8fIk9+nrPz/LAH975H8YSk8RsRoe5q7TAr/0cu1nWyjLIiwA2HIfNQYUupLLSVrrEzfzVEcKBxyTIkGZI2fb6SYqcDp2kaYoycD/MTSz7D5vbDnfG7cWD0nf50AymwLRzlL/YNWEwXunPGO9wsP2wdNxxrOCxMGe2t9iCQPtOESMTmHi5g/P1uuJXUqWjA/D+7Wi0zRWLQ+g41tMThtABP2wi58/wi5y6XLLY1DSoe7e329C1RLF/JglZM7LEHBI+dx+s/V0pj3prCDLmSy0o+fVt+Qt9kHtpWi4yNZFFIyG+kL+leyrCdn12+SIUzynYPi5Aflbu1PHk6wZlNlAWPNlCA9CiiEVPl35+qRteV4xlhvU7uVELvSXaYWE+jR1tImdaTG4zrI9mEGBkg/ybG+VgrYv9JtohcmY/KBXdPtf0wsfpuSTqp98J5qy5SeihjmfInLQufmFa327h92lreMRVwnA11Ml0NmqnMzsGgUnQp76OxiJq3SGkp2vN5C8heJ28Exi4rKwWwXPwgQpBGgjKOUlZ1EdvAzuSikckpo7xB5LDXp+jh2ubYpqko+tDXtnbI4fpNDZe/YarWhR0nqH5rypv77XPygi4h+XIvQ0FD+q2dMzluiSf72+SR9Kb6bWtsDc3grI23znMrc303THdcJTPTgdV0eHSKlIykIW0gh9Ih8MsK7il5EA/BpO9R8vEmY4iV4GbNuPQqxukrnHbze33xqxGircMDefVAbixikqWQQtjqqIPN/HSnK7WluXIQ12JzQw1xYtyjL2nvZZdr8OH8LDxi+TdkIXHNyky2Z1Jf5xHXsN38GqvBvghiZU5nFHelo51LdV6OSXUsnG/KBOnVokIWyNWASAKRGHlcDcJm005Miim+PQjavii5d029AqRQ8M+no7bR57k4JiJMtGk+rutmEn8MFLveWwgAigqb48PagfBsCRXMVrJXwY9k+KbRSbEqZc8IeJHeXx9l5mby0nnPiwMXYpjnBricwSygmhn9nc9RTB5diwFbGvgVKCfhulXM5SSsAqQBNfISpGbUglja2/ue7UY73Xb0Dp5EPUYHm70I7nXxWM1W9X9ZU3JRRt+Lm93syXG58Y7FPoda+Yd8hPzbDQkUTuB3uCUJUAUB+VCIIIuJIP+ul2rHFe6BKFF8KizAFfYuR9J9X1HEqB5/kBzA4WMKns4aHmf+FcFWcUs1vUDj4wulAYA2YpcOrRKkrEnxl7AAwRdmerfBcpaSFu1sgP8+iMRUww0H4yNMuCenf65hrgBgapvAZjFXF7vNFhzbWg6cs7b+QNIjs41m4N33MzWYuspqYeZBP4Dgzse23XVkBFfqDl8obwJtU+2940Ad+IukVPOAh+7RCwOL++txhaXQm+EspVwN7hvEfnofRgoHQyZvH4lb+ksaYsmv5RUTNrjLeBBLmEzfeMdhIHKmantMVk/A50q11ci0ACoWiwkpICadwgkCwG/vUZ93z3E4mXTEJb2Vi1g5x1QHzVKsc11s54VSdwVZPJrcG83VAhl8s5/XXY9WRtPevzEOlgtbto7M42U3wgqndRnCaogcCL3kocSOoRtotZoGoF2vf1vk1fDXxS3rXEGL6AMM4/NW6F/84+a9z7LExC15GeZUj7NQM7rUIS3/38Sp9f6yILZJ3zM59Twr6BevjsmajNlCMSq64PXo0IcjmWyzKtvhmUhYdiyg4bSl8CgxcZ9E+KRhIL6Cptpd9ERu8WFzYADUs+oB/yd78QHjvtYQbPEt19ce4D7mJpYSqFdz/8gxoRQ4jh8qRhbiyoU3C2p/a/LrXMIRQgzuuxvscA4GEmEJvE2udg25i9c3YECrGzDfJCrQQGn1RHNaSDLine truncated
|
||||||
@@ -178,6 +178,32 @@ jobs:
|
|||||||
echo "plan2code-app exited within 5s (exit code $?); smoke test failed"
|
echo "plan2code-app exited within 5s (exit code $?); smoke test failed"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
- name: Smoke-test the dashboard frame connects (macOS)
|
||||||
|
if: runner.os == 'macOS'
|
||||||
|
shell: bash
|
||||||
|
# A window whose dashboard frame never signs in still passes the alive check above
|
||||||
|
# (WebKit gives the frame no cookie, so macOS signs it in by a path prefix:
|
||||||
|
# takeFramePrefix in routes.mjs). Here the app autostarts
|
||||||
|
# scripts/smoke-agent.mjs, which opens a real console as an agent would, and
|
||||||
|
# scripts/smoke-frame.mjs waits up to 60s for that console's /health to count the
|
||||||
|
# frame as a browser. Runs only where the matrix has macOS: manual runs and pull
|
||||||
|
# requests labeled `full-matrix`.
|
||||||
|
run: |
|
||||||
|
project="$(mktemp -d)"
|
||||||
|
export PLAN2CODE_CONSOLE_HOME="$(mktemp -d)"
|
||||||
|
export PLAN2CODE_CONSOLE_DIR="$GITHUB_WORKSPACE/src/web-console"
|
||||||
|
export PLAN2CODE_APP_AGENT_BIN="$(pwd)/scripts/smoke-agent.mjs"
|
||||||
|
# No browser of the console's own, so only the app's frame can count as one.
|
||||||
|
export PLAN2CODE_NO_BROWSER=1
|
||||||
|
target/release/plan2code-app --project "$project" --agent claude &
|
||||||
|
pid=$!
|
||||||
|
status=0
|
||||||
|
node scripts/smoke-frame.mjs "$PLAN2CODE_CONSOLE_HOME" || status=$?
|
||||||
|
kill "$pid" 2>/dev/null || true
|
||||||
|
# The console is detached from the agent, so it outlives the app: stop it from the
|
||||||
|
# project folder it was opened in, under the same console home.
|
||||||
|
(cd "$project" && node "$PLAN2CODE_CONSOLE_DIR/console.mjs" stop --all) || true
|
||||||
|
exit "$status"
|
||||||
|
|
||||||
node-tests:
|
node-tests:
|
||||||
name: npm test (${{ matrix.os }})
|
name: npm test (${{ matrix.os }})
|
||||||
|
|||||||
@@ -137,6 +137,8 @@ jobs:
|
|||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7.0.1
|
- uses: actions/checkout@v7.0.1
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
- uses: actions/download-artifact@v8.0.2
|
- uses: actions/download-artifact@v8.0.2
|
||||||
with:
|
with:
|
||||||
path: dist
|
path: dist
|
||||||
@@ -187,18 +189,47 @@ jobs:
|
|||||||
if [ "$state" = "true" ]; then
|
if [ "$state" = "true" ]; then
|
||||||
gh release edit "$TAG" --draft=false
|
gh release edit "$TAG" --draft=false
|
||||||
fi
|
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
|
# 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
|
# get the newest release and never a half-finished main, and exact updates fetch the
|
||||||
# public: a failure earlier leaves the branch on the previous release. Fast-forward only
|
# immutable `install-vX.Y.Z` tag. scripts/publish-install-refs.mjs builds one synthetic
|
||||||
# (no --force), so a tag that is not ahead of the branch fails loudly instead of
|
# commit holding only the runtime payload (install.js, package.json, version.json, LICENSE, NOTICE, src/)
|
||||||
# rewinding what people install.
|
# 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: |
|
run: |
|
||||||
# The checkout is shallow, and git decides "fast-forward" locally: without the full
|
# The push authenticates with the workflow token through an askpass helper: the helper
|
||||||
# history the branch's old tip is unknown here and the push is refused as "fetch first".
|
# 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
|
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
|
||||||
git fetch --no-tags --unshallow origin
|
git fetch --no-tags --unshallow origin
|
||||||
fi
|
fi
|
||||||
git fetch --no-tags origin "refs/tags/${TAG}:refs/tags/${TAG}"
|
git fetch --no-tags origin "refs/tags/${TAG}:refs/tags/${TAG}"
|
||||||
sha="$(git rev-parse "refs/tags/${TAG}^{commit}")"
|
if git ls-remote --exit-code --heads origin release > /dev/null; then
|
||||||
git push origin "${sha}:refs/heads/release"
|
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"
|
||||||
@@ -46,12 +46,6 @@
|
|||||||
- About: src/web-console/public/loop-parts.js
|
- About: src/web-console/public/loop-parts.js
|
||||||
- Noted: 2026-11-28, implement-review
|
- 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.
|
### 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
|
- Kind: how-it-works
|
||||||
- About: plan2code-app/src-tauri/src/loop_driver.rs
|
- About: plan2code-app/src-tauri/src/loop_driver.rs
|
||||||
@@ -63,16 +57,21 @@
|
|||||||
- Why: The new tools fold-out reused git-tools and the Branches row's flex rule laid it out side by side.
|
- 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
|
- 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.
|
### 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: how-it-works
|
- Kind: command
|
||||||
- About: install.js
|
- About: scripts/test-app-meter.mjs, plan2code-app/scripts/vendor.mjs
|
||||||
- Noted: 2026-11-17, implement-review
|
- 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.
|
### 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
|
- Kind: how-it-works
|
||||||
- About: src/web-console/public/styles/tokens.css, src/web-console/public/styles/learning.css
|
- About: src/web-console/public/styles/tokens.css, src/web-console/public/styles/learning.css
|
||||||
- Noted: 2026-11-19, quick-task
|
- Noted: 2026-11-19, quick-task
|
||||||
|
|
||||||
|
### From a desktop app terminal, run console tests with its PLAN2CODE_* vars unset (env -u PLAN2CODE_IN_APP ...): test-web-console-server.mjs and the loop tests read process.env directly.
|
||||||
|
- Kind: command
|
||||||
|
- About: scripts/web-console-test-helpers.mjs
|
||||||
|
- Noted: 2026-12-04, implement-review
|
||||||
|
|
||||||
### In a Markdown field (md-field.js), CodeMirror's scroller and content are only as tall as the text, not the bordered host: code that hit-tests the scroller must not assume it fills the box.
|
### In a Markdown field (md-field.js), CodeMirror's scroller and content are only as tall as the text, not the bordered host: code that hit-tests the scroller must not assume it fills the box.
|
||||||
- Kind: how-it-works
|
- Kind: how-it-works
|
||||||
- About: src/web-console/public/md-field.js
|
- About: src/web-console/public/md-field.js
|
||||||
@@ -94,11 +93,6 @@
|
|||||||
- About: src/web-console/public/screens/agents
|
- About: src/web-console/public/screens/agents
|
||||||
- Noted: 2026-11-17, implement-review
|
- 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.
|
### 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
|
- Kind: convention
|
||||||
- About: plan2code-app/ui/theme-early.js
|
- About: plan2code-app/ui/theme-early.js
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Installer
|
||||||
|
Paths: install.js, src/installer/**, scripts/bench-install-update.mjs, scripts/publish-install-refs.mjs, scripts/test-install-*.mjs, scripts/install-*.mjs
|
||||||
|
|
||||||
|
### A new src/installer/ module that install.js requires must join the file list npxCopy() copies in scripts/test-install-update.mjs, or every release redirect test fails.
|
||||||
|
- Kind: convention
|
||||||
|
- About: scripts/test-install-update.mjs, install.js
|
||||||
|
- Why: Adding skills-cli.js and canonical-skills.js failed five release redirect tests until npxCopy() copied them too.
|
||||||
|
- Noted: 2026-12-03, implement-review
|
||||||
|
|
||||||
|
### A test run of node install.js with a temp HOME still writes the plan2code shims into the real npm global bin, because npm's prefix does not follow HOME; also set npm_config_prefix to a temp folder.
|
||||||
|
- Kind: correction
|
||||||
|
- About: install.js
|
||||||
|
- Why: A piped --update test run repointed the real plan2code shims at a temp folder until they were fixed by hand.
|
||||||
|
- Noted: 2026-11-17, implement-review
|
||||||
|
|
||||||
|
### A test that calls install() must point APPDATA and LOCALAPPDATA at the temp HOME first: its cleanLegacyPaths() sweep reads the VS Code prompts and Crush skills folders from them, outside HOME.
|
||||||
|
- Kind: how-it-works
|
||||||
|
- About: install.js, scripts/test-install-update.mjs
|
||||||
|
- Noted: 2026-12-03, implement-review
|
||||||
|
|
||||||
|
### An install-ref fixture test checks each fixture's own root for cleanup, never a count of p2c-install-refs-* in the temp dir: other test files build fixtures in parallel.
|
||||||
|
- Kind: correction
|
||||||
|
- About: scripts/test-install-refs.mjs, scripts/install-ref-fixtures.mjs
|
||||||
|
- Why: The cleanup test counted the temp dir and failed once other test files built fixtures alongside it.
|
||||||
|
- Noted: 2026-12-03, implement-review
|
||||||
|
|
||||||
|
### Each recordInstalled() in install.js stamps the version being installed into install.json, so a failed update must restore the old one with setRecordVersion(), or a retry says Already on.
|
||||||
|
- Kind: how-it-works
|
||||||
|
- About: install.js
|
||||||
|
- Noted: 2026-11-17, implement-review
|
||||||
|
|
||||||
|
### Give bench-install-update.mjs no --workdir whose path holds a UUID, since npm 12 redacts UUIDs in paths to *** and every isolated path breaks; the default temp workdir is safe.
|
||||||
|
- Kind: how-it-works
|
||||||
|
- About: scripts/bench-install-update.mjs
|
||||||
|
- Noted: 2026-12-03, implement-review
|
||||||
|
|
||||||
|
### skills@1.5.x skips every agent link when skills add gets the canonical store as its source, so agentLinkSource() gives that pin the built skills/ folder.
|
||||||
|
- Kind: how-it-works
|
||||||
|
- About: src/installer/skills-cli.js, install.js
|
||||||
|
- Noted: 2026-12-03, implement-review
|
||||||
|
|
||||||
|
### The app's webview data sits outside ~/.plan2code, in Tauri's app_local_data_dir() on Windows and Linux (%LOCALAPPDATA%/com.plan2code.desktop); appWebviewDirs() in install.js lists it per OS.
|
||||||
|
- Kind: how-it-works
|
||||||
|
- About: install.js
|
||||||
|
- Noted: 2026-11-17, implement-review
|
||||||
|
|
||||||
|
### update() says Already on from the record, command, skills and console; the app file is judged only by install.json's appVersion, so a piece that can stay old needs its own recorded version.
|
||||||
|
- Kind: how-it-works
|
||||||
|
- About: install.js
|
||||||
|
- Noted: 2026-12-04, quick-task
|
||||||
@@ -161,7 +161,7 @@ Security, six controls, about 60 lines:
|
|||||||
1. Bind `127.0.0.1`.
|
1. Bind `127.0.0.1`.
|
||||||
2. **`Host` header allowlist.** This is the DNS-rebinding defense and the highest-value line in the server. Vite shipped GHSA-vg6x-rcgg-rjx6 for exactly this omission.
|
2. **`Host` header allowlist.** This is the DNS-rebinding defense and the highest-value line in the server. Vite shipped GHSA-vg6x-rcgg-rjx6 for exactly this omission.
|
||||||
3. 128-bit token **in the URL path**, not the query string. Path placement also kills the Windows `cmd /c start` `&`-injection hazard, because the URL then contains no `&`.
|
3. 128-bit token **in the URL path**, not the query string. Path placement also kills the Windows `cmd /c start` `&`-injection hazard, because the URL then contains no `&`.
|
||||||
4. First `GET /s/<token>/` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free.
|
4. First `GET /s/<token>/` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free. The macOS desktop app's frame is the exception: WebKit gives a cross-site frame no cookie, so there the 302 goes to `/f/<sha256(token)[0:32]>/` on the same `127.0.0.1` address, the router takes that exact prefix off the raw request line once, and a request under it passes the token gate. The page uses only page-relative URLs, so it works at `/` and under the prefix alike. Not a `<key>.localhost` host name: macOS tries it on `[::1]` first, where another process can take the port.
|
||||||
5. `Origin` check on every mutating request.
|
5. `Origin` check on every mutating request.
|
||||||
6. Strict CSP with no `unsafe-inline`, which is why JS and CSS are separate files rather than one inlined HTML.
|
6. Strict CSP with no `unsafe-inline`, which is why JS and CSS are separate files rather than one inlined HTML.
|
||||||
|
|
||||||
|
|||||||
@@ -133,6 +133,11 @@ this:
|
|||||||
visiting from talking to it through a DNS rebinding trick.
|
visiting from talking to it through a DNS rebinding trick.
|
||||||
- A 128-bit token in the link, swapped for an `HttpOnly; SameSite=Strict` cookie
|
- A 128-bit token in the link, swapped for an `HttpOnly; SameSite=Strict` cookie
|
||||||
on first load so it leaves your address bar, your history and any screenshot.
|
on first load so it leaves your address bar, your history and any screenshot.
|
||||||
|
In the macOS desktop app the page's frame gets no cookie (WebKit blocks
|
||||||
|
cookies for a frame from another site), so the link sends that frame to
|
||||||
|
`/f/<key>/` on the same `127.0.0.1` address instead, where the key is a hash
|
||||||
|
of the token, and the server lets in only requests under that exact prefix.
|
||||||
|
The frame has no address bar, and a browser tab still gets the cookie.
|
||||||
- A strict Content Security Policy with no inline script allowed.
|
- A strict Content Security Policy with no inline script allowed.
|
||||||
- Markdown written by the agent is turned into page elements directly and never
|
- Markdown written by the agent is turned into page elements directly and never
|
||||||
into an HTML string, so a document that quotes a hostile README cannot run
|
into an HTML string, so a document that quotes a hostile README cannot run
|
||||||
|
|||||||
@@ -475,14 +475,16 @@ the `/plan2code` command instead. That command is on both of these screens
|
|||||||
anyway, for starting the dashboard in a fresh conversation — the better choice
|
anyway, for starting the dashboard in a fresh conversation — the better choice
|
||||||
after a long skill, since a fresh conversation starts with a clean context.
|
after a long skill, since a fresh conversation starts with a clean context.
|
||||||
|
|
||||||
The Implementation Loop's own end screen works the same way: finished or
|
The Implementation Loop is app only: with a spec picked, open **Implement** on the dashboard, tick its
|
||||||
stopped, its actions sit beside a **Back to the dashboard** button that opens
|
**Loop** checkbox, and press **Set up Implementation Loop**. Its setup asks how many review rounds
|
||||||
|
per phase to allow (default 2): when a phase's own review leaves Critical or Warning, fresh reviewers
|
||||||
|
run up to that many more rounds before the phase is committed. Its own end screen works the same way:
|
||||||
|
finished or stopped, its actions sit beside a **Back to the dashboard** button that opens
|
||||||
a fresh dashboard in the frame, no agent needed, and its status line marks it
|
a fresh dashboard in the frame, no agent needed, and its status line marks it
|
||||||
as your move rather than leaving a stale "starting" line behind.
|
as your move rather than leaving a stale "starting" line behind.
|
||||||
|
|
||||||
Review rounds per phase (default 2): when a phase's own review leaves Critical or Warning, fresh reviewers run up to this many more rounds before the phase is committed.
|
The **Review Loop** is app only too: open **Review** on the dashboard, tick its **Loop** checkbox, and
|
||||||
|
press **Set up Review Loop**. It reviews and fixes a
|
||||||
The **Review Loop** card, also app only, sits beside the Implementation Loop's: it reviews and fixes a
|
|
||||||
finished change in rounds while you are away (round 1 the whole change, each later round only the last
|
finished change in rounds while you are away (round 1 the whole change, each later round only the last
|
||||||
round's fixes, a fresh reviewer every time), stops on a clean round, the round cap, your stop or a failure,
|
round's fixes, a fresh reviewer every time), stops on a clean round, the round cap, your stop or a failure,
|
||||||
and ends on its own screen with the report, **Continue**, the Suggestions pick, an optional squash, **PR
|
and ends on its own screen with the report, **Continue**, the Suggestions pick, an optional squash, **PR
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ Details: [Status line](./.agents-docs/AGENTS-architecture-statusline.md)
|
|||||||
|
|
||||||
## Web Console
|
## 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`. 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
|
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console/<version>/` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. Whether a skill starts in the terminal or the console is asked each run until the person saves a default (`console.mjs interface`, saved in `~/.plan2code/console/interface.json`); `--web` / `--terminal` or plain words override it for one session. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review, and in Implement, Implement + Review and Quick task a **Changes** tab: a `diff` doc block fed by the `changes.mjs` skill script, parsed by `public/diff-parse.js` and drawn by `public/diff-view.js`), build progress, the living document, a spec's saved prototypes (a **Prototypes** tab: an `.md` read in place, an `.html` opened in the default browser), an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (a Save, Share, Review, Tidy path, one task card for the step you are on, and the Changes, Branches and Sync tabs folded into **All branches and tools**; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick task, Diagnose, UI Prototype or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker of game rows in two columns, ordered Recently played or A to Z (saved in `activityOrder`), with never-picked games under Not played yet, once two are listed, that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest<Id>` keys in `looks.json` (and the time each game was last picked in `activityPlayed<Id>`) (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 24-topic Help, the app-only **Implementation Loop** (a **Loop** checkbox on Implement's confirm pane, disabled outside the app, and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), the app-only **Review Loop** (a **Loop** checkbox on Review's confirm pane, disabled outside the app, `screens/review-loop-setup.js`, the setup remembered in `~/.plan2code/console/review-loop-setup.json` owned by `review-loop-setup.mjs`; the app's `review_loop.rs` drives review-and-fix rounds, each a Review session opened with `--loop --round N --role` that reports a `roundOutcome` per `notes/review-loop.md`; its end screen is `publicLine truncated
|
||||||
|
|
||||||
One agent list and one lookup rule serve the launcher, the console and the app: `src/launcher/agents.json` (the built-ins and starter templates with per-OS install data) and `src/web-console/agent-lookup.mjs` (`loadAgentList()` and `findAgent()`, both copied by `install.js` into `~/.plan2code/bin/`); the app carries a Rust twin held to the same cases by `scripts/fixtures/agent-lookup-cases.json`.
|
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`.
|
||||||
|
|
||||||
@@ -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".
|
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)
|
Details: [Development Commands](./.agents-docs/AGENTS-development-commands.md)
|
||||||
|
|
||||||
## Test map
|
## Test map
|
||||||
@@ -118,5 +120,5 @@ When you make a mistake, get corrected, or discover something about this codebas
|
|||||||
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
|
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
|
||||||
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → System → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
|
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → System → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
|
||||||
- When a test checks how `cmd.exe` finds a `.cmd`/`.bat` (current folder before PATH), clear `NoDefaultCurrentDirectoryInExePath` for the run under test (`env_remove` in Rust, `undefined` in a `test-launcher.mjs` `box.run` env): some shells (Claude Code's among them) already set it, and the decoy `.cmd` test for custom agents passed without its fix until it did.
|
- When a test checks how `cmd.exe` finds a `.cmd`/`.bat` (current folder before PATH), clear `NoDefaultCurrentDirectoryInExePath` for the run under test (`env_remove` in Rust, `undefined` in a `test-launcher.mjs` `box.run` env): some shells (Claude Code's among them) already set it, and the decoy `.cmd` test for custom agents passed without its fix until it did.
|
||||||
- Never set a `Secure` cookie for the app's `tauri://localhost` frame (Linux and macOS): WebKit drops a Secure cookie sent over plain `http://127.0.0.1`, so every request after the sign-in got a 403 and the Linux app showed "its page did not show in this window" while working on Windows, where WebView2 counts loopback as secure. `cookieSameSite()` in `src/web-console/routes.mjs` sends Lax there and None; Secure only to `tauri.localhost`; check an embed change in a WebKit view, not only Chrome.
|
- Never set a `Secure` cookie for the app's `tauri://localhost` frame (Linux and macOS): WebKit drops a Secure cookie sent over plain `http://127.0.0.1`, so every request after the sign-in got a 403 and the Linux app showed "its page did not show in this window" while working on Windows, where WebView2 counts loopback as secure. `cookieSameSite()` in `src/web-console/routes.mjs` sends Lax there and None; Secure only to `tauri.localhost`; check an embed change in a WebKit view, not only Chrome. On macOS WebKit gives the frame no cookie even with Lax, so it signs in by the path prefix `/f/<key>/` (`takeFramePrefix()` in `routes.mjs`), and every URL the page uses must be page-relative (`scripts/test-web-console-relative-urls.mjs`).
|
||||||
- On Windows, treat a console the agent opened as dying with the agent: the app ends the agent's whole Job Object, so a `detached` server goes too, with no `exit` event. A `console.mjs post` still succeeds because it writes the session's files, so it proves nothing about the server; only the window's reconnect brings the page back. Every loop phase ends this way, and a reconnect budget that never refilled once lost the loop's stop card after Phase 3.
|
- On Windows, treat a console the agent opened as dying with the agent: the app ends the agent's whole Job Object, so a `detached` server goes too, with no `exit` event. A `console.mjs post` still succeeds because it writes the session's files, so it proves nothing about the server; only the window's reconnect brings the page back. Every loop phase ends this way, and a reconnect budget that never refilled once lost the loop's stop card after Phase 3.
|
||||||
@@ -4,6 +4,69 @@ 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. -->
|
<!-- Format from 3.1.0 on: `## vX.Y.Z (YYYY-MM-DD)` with the date from version.json; a minor release opens with a three-bullet `### Highlights`; sections run Added, Changed, Fixed; game changes sit under one Activities line; tooling and test lines go under "For contributors". Older headings have no date and are not backfilled. -->
|
||||||
|
|
||||||
|
## v3.2.7 (2026-12-05)
|
||||||
|
|
||||||
|
### 🐛 Fixed
|
||||||
|
|
||||||
|
- **Desktop app**: on macOS the dashboard now shows in the app's window. Before, WebKit gave that part of the window no sign-in cookie, so every request was refused.
|
||||||
|
- **Desktop app**: on macOS and Linux, quitting now stops the running agent together with what it started, and the dashboards it opened, however you quit: the close button, the menu, the Dock, Ctrl+C, a closed terminal or a plain `kill`. An agent that ends by itself still leaves a dev server it was asked to keep running.
|
||||||
|
- **Desktop app**: on macOS, Cmd+Q and the menu's Quit ask first while an agent is running, as the close button does, and one click answers the question even when the window was in the background.
|
||||||
|
- **Desktop app**: on macOS and Linux, starting from the Dock, Finder or a desktop entry now finds Node and agents set up only in your shell's interactive config, such as nvm in `~/.zshrc`. A slow or hung shell profile holds up the start by about 5 seconds at most; before, there was no limit.
|
||||||
|
- **Desktop app**: on macOS, Ctrl+V in the terminal reaches the agent, so Claude Code can take a pasted picture, and Cmd+V pastes without a Paste menu first.
|
||||||
|
- **Desktop app**: on macOS, the Dock shows Planny's icon while the app runs, and the window opens in front of the terminal that started it.
|
||||||
|
- **Desktop app**: after Change project, "The console stopped" no longer covers the new project, and Stop now in either loop no longer holds up the window while the agent ends.
|
||||||
|
- **Web console and launcher**: on macOS, a folder picker that fails no longer acts like Cancel: Workspace says Browse is not available, and `plan2code` asks you to type the folder. On every system, Browse opens at the nearest folder still there when the last one is gone.
|
||||||
|
- **Web console**: the Card width choices in User Preferences no longer run into each other at the Narrow width, and the page's closing signal is no longer refused in Safari and the macOS app.
|
||||||
|
- **Quick Task**: the See it running card, shown after a build, no longer says that nothing has been changed yet.
|
||||||
|
- **For contributors**: every URL the console page uses must be page-relative (`fetch("state")`, never `fetch("/state")`), because one that starts with a slash fails in the macOS app and nowhere else. `scripts/test-web-console-relative-urls.mjs` names any that does.
|
||||||
|
- **For contributors**: on macOS, the `app` workflow now fails when the dashboard never connects inside the app (manual runs and pull requests labeled `full-matrix`), and the release checklist covers the macOS fixes above.
|
||||||
|
|
||||||
|
## v3.2.6 (2026-12-04)
|
||||||
|
|
||||||
|
### ✨ Added
|
||||||
|
|
||||||
|
- **Web console**: when the Notes panel is stacked under the question (window 1080px wide or narrower), a drag handle on its top edge makes it taller or shorter; arrow keys nudge it, a double-click gives back the automatic height, and the size is kept between sessions.
|
||||||
|
|
||||||
|
### 🔧 Changed
|
||||||
|
|
||||||
|
- **Web console**: the dashboard's Implementation Loop and Review Loop cards are gone; Implement's and Review's confirm panes carry a Loop checkbox instead (app only, disabled outside the app and while a loop runs), whose Start opens the matching loop setup screen.
|
||||||
|
- **Skills**: every skill prompt, the console card and the Ask chat contract now say to reply in US English unless the person asks for another language, so replies and question cards stay in English when the person's messages or the project's files are not.
|
||||||
|
- **Desktop app**: when the skills are newer than the app, the bar now reads "Update to latest: vX.Y.Z" with an Update and restart button, instead of "Skills vX.Y.Z are newer than this app" with no way forward.
|
||||||
|
- **Launcher**: Devin's Balanced choice maps to Sonnet 5.5 Medium instead of SWE-2.1 High.
|
||||||
|
|
||||||
|
### 🐛 Fixed
|
||||||
|
|
||||||
|
- **Installer**: `plan2code update` and the app's Update and restart now fetch the desktop app again when `install.json` does not record it at this version, instead of stopping at Already on while the app file stays on an older release; the record keeps the app's version as `appVersion`, so a machine already on the app gets one app reinstall on its next update.
|
||||||
|
- **Web console**: after you press Finalize, Continue building, Fix together or Back to the dashboard on the Implementation Loop end screen, the button now shows a spinner and a working label and stays disabled until the page moves on; the Review Loop end screen's pressed button shows the same spinner.
|
||||||
|
|
||||||
|
## v3.2.5 (2026-12-03)
|
||||||
|
|
||||||
|
### 🔧 Changed
|
||||||
|
|
||||||
|
- **Installer**: the slim install refs also carry `LICENSE` and `NOTICE`.
|
||||||
|
- **For contributors**: run `npm run setup:hooks` once after `npm install` to turn on the pre-commit hooks; the `prepare` script that did it is gone.
|
||||||
|
|
||||||
|
### 🐛 Fixed
|
||||||
|
|
||||||
|
- **Installer**: the slim install refs announced in v3.2.4 were not published with it, because the release step refuses a `package.json` with a `prepare` script, so first installs kept getting v3.2.3. `npm test` now checks the real `package.json` for such scripts.
|
||||||
|
|
||||||
|
## v3.2.4 (2026-12-03)
|
||||||
|
|
||||||
|
### ✨ Added
|
||||||
|
|
||||||
|
- **Installer**: first installs and updates fetch a slim, runtime-only `release` branch and immutable `install-vX.Y.Z` tags instead of the whole repository, which the release workflow now publishes after each release. `--main`, branches and plain `vX.Y.Z` tags still work as before.
|
||||||
|
|
||||||
|
### 🔧 Changed
|
||||||
|
|
||||||
|
- **Installer**: each skill is copied into the shared skills store once, with a journal and rollback, and agents are linked by a single `skills add`; before, every agent's copy was rewritten, which made installs and updates slow.
|
||||||
|
- **Installer**: the shared console is staged in a checksummed folder and switched in only when complete, so an interrupted install or update no longer leaves a half-written console; the pinned `skills` CLI is now an exact version chosen by your Node version.
|
||||||
|
- **Update check**: `plan2code update` picks the newest release and fetches its slim ref when one exists, and falls back to the full tag when it does not.
|
||||||
|
- **For contributors**: `npm test` leaves out the Activities game suites; run them with `npm run test:games` when a game changes.
|
||||||
|
|
||||||
|
### 🐛 Fixed
|
||||||
|
|
||||||
|
- **Desktop app**: Change project, and picking a recent folder, now starts the same agent again in the new folder, on the same model, effort and permission mode; before, the new folder showed the launch card and an empty terminal until you pressed Start.
|
||||||
|
|
||||||
## v3.2.3 (2026-12-02)
|
## v3.2.3 (2026-12-02)
|
||||||
|
|
||||||
### 🔧 Changed
|
### 🔧 Changed
|
||||||
|
|||||||
+1
-1
@@ -17,7 +17,7 @@ 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) |
|
| 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 |
|
| 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) |
|
| 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 |
|
| 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) | Opens the page for this session, whatever your saved default |
|
| Straight into a skill | `/plan2code-1-plan --web` (any step) | Opens the page for this session, whatever your saved default |
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
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.3 · Apache 2.0 · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
Version 3.2.7 · Apache 2.0 · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -128,7 +128,7 @@ cd plan2code
|
|||||||
node install.js
|
node install.js
|
||||||
|
|
||||||
# Only if you plan to modify or contribute to Plan2Code itself
|
# Only if you plan to modify or contribute to Plan2Code itself
|
||||||
npm install && npx husky
|
npm install && npm run setup:hooks
|
||||||
```
|
```
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
@@ -309,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
|
**Too many or too few phases.** Fix it in Step 2 — a phase should be a logical grouping of work, not
|
||||||
a fixed size.
|
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 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
|
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.
|
work in the terminal, which loses nothing.
|
||||||
|
|||||||
+9
-9
@@ -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
|
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
|
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
|
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
|
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
|
to that offers the same **Reconnect the console** button — never "Restart the console" in one place and
|
||||||
@@ -146,9 +146,9 @@ agent CLI.
|
|||||||
## Implementation Loop
|
## Implementation Loop
|
||||||
|
|
||||||
The Implementation Loop builds every remaining phase of a documented spec for you, one after another,
|
The Implementation Loop builds every remaining phase of a documented spec for you, one after another,
|
||||||
while you do something else. It is in the app only: the dashboard shows an **Implementation Loop**
|
while you do something else. It is in the app only: with a spec picked, open **Implement** on the
|
||||||
card there, and nowhere else. Pick a spec, answer a short setup, press **Start the loop**, and the app
|
dashboard, tick its **Loop** checkbox, and press **Set up Implementation Loop**. Answer a short setup,
|
||||||
confirms it once in its own window before anything runs.
|
press **Start the loop**, and the app confirms it once in its own window before anything runs.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
@@ -267,13 +267,13 @@ the quick check and the commits are the app's own. The finish screen counts each
|
|||||||
the full report** opens it, saved as `specs/<feature>/LOOP-SUMMARY-<date>.md` (`-2` and so on for another
|
the full report** opens it, saved as `specs/<feature>/LOOP-SUMMARY-<date>.md` (`-2` and so on for another
|
||||||
the same day). After a stop, **Read why, and the report so far** shows it on the stop screen. While a build
|
the same day). After a stop, **Read why, and the report so far** shows it on the stop screen. While a build
|
||||||
is unfinished it lives in `~/.plan2code/console/loop-reports.json`, not the project, because Continue building needs a
|
is unfinished it lives in `~/.plan2code/console/loop-reports.json`, not the project, because Continue building needs a
|
||||||
clean tree. The in-app **Help** has a matching topic, **Implementation Loop**, which the loop card links to as "How the loop works".
|
clean tree. The in-app **Help** has a matching topic, **Implementation Loop**, linked as **How the loop works** on the loop setup screen.
|
||||||
|
|
||||||
## Review Loop
|
## Review Loop
|
||||||
|
|
||||||
The Review Loop reviews and fixes a finished change for you, round after round, while you do something
|
The Review Loop reviews and fixes a finished change for you, round after round, while you do something
|
||||||
else. Like the Implementation Loop it is in the app only: the dashboard shows a **Review Loop** card beside
|
else. Like the Implementation Loop it is in the app only: open **Review** on the dashboard and tick its
|
||||||
the Implementation Loop's, grayed out while either loop runs (one loop per window).
|
**Loop** checkbox to reach the setup screen. The checkbox is disabled while either loop runs (one loop per window).
|
||||||
|
|
||||||
**How rounds work.** Round 1 reviews everything you chose. Every later round reviews only what the round
|
**How rounds work.** Round 1 reviews everything you chose. Every later round reviews only what the round
|
||||||
before it changed, so the work shrinks as it goes. Each round's reviewer is a fresh one that never saw the
|
before it changed, so the work shrinks as it goes. Each round's reviewer is a fresh one that never saw the
|
||||||
@@ -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**
|
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
|
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
|
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
|
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
|
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
|
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
|
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
|
says so when it cannot check (git missing, or no answer from GitHub). The dashboard's own **Update
|
||||||
|
|||||||
+657
-148
File diff suppressed because it is too large.
Load diff
+4
-3
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "plan2code",
|
"name": "plan2code",
|
||||||
"version": "3.2.3",
|
"version": "3.2.7",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
"plan2code-install": "./install.js"
|
"plan2code-install": "./install.js"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepare": "husky",
|
"setup:hooks": "husky",
|
||||||
"build:skills": "node install.js --build-skills",
|
"build:skills": "node install.js --build-skills",
|
||||||
"fix:eol": "node scripts/fix-line-endings.mjs",
|
"fix:eol": "node scripts/fix-line-endings.mjs",
|
||||||
"set-version": "node scripts/set-version.mjs",
|
"set-version": "node scripts/set-version.mjs",
|
||||||
@@ -18,7 +18,8 @@
|
|||||||
"pretest": "node scripts/fix-line-endings.mjs",
|
"pretest": "node scripts/fix-line-endings.mjs",
|
||||||
"test:fast": "node scripts/test-fast.mjs",
|
"test:fast": "node scripts/test-fast.mjs",
|
||||||
"test:page": "node scripts/run-page-tests.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-app-smoke-agent.mjs scripts/test-app-smoke-frame.mjs scripts/test-browser-helper.mjs scripts/test-check-console-openings.mjs scripts/test-check-doc-size.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-test-lanes.mjs scripts/test-check-versions.mjs scripts/test-console-stub.mjs scripts/test-console-wire-budgets.mjs scripts/test-getting-started.mjs scripts/test-git-repo.mjs scripts/test-install-bench.mjs scripts/test-install-e2e.mjs scripts/test-install-refs.mjs scripts/test-install-update.mjs scripts/test-launcher.mjs scripts/test-line-endings.mjs scripts/test-publish-install-refs.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-script-coverage.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-finalize.mjs scripts/test-script-git.mjs scripts/test-script-lessons.mjs scripts/test-script-pathfinder.mjs scripts/test-script-pr-prep.mjs scripts/test-script-run-check.mjs scripts/test-script-test-commands.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-xray.mjs scripts/test-set-version.mjs scripts/test-skill-scripts.mjs scripts/test-skill-test-runs.mjs scripts/test-spec-carry-page.mjs scripts/test-spec-carry.mjs scripts/test-standalone-check.mjs scripts/test-ui-prototype-page.mjs scripts/test-us-english.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-card-rows.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-git.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-notepad.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-frame.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-review-loop.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-setup.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-relative-urls.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-shape.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-source.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-workspace.mjs",
|
||||||
|
"test:games": "node scripts/node-test.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-page-activities.mjs"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"gpt-tokenizer": "2.9.0",
|
"gpt-tokenizer": "2.9.0",
|
||||||
|
|||||||
Generated
+5
-2
@@ -957,7 +957,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fake-agent"
|
name = "fake-agent"
|
||||||
version = "3.2.3"
|
version = "3.2.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"terminal_size",
|
"terminal_size",
|
||||||
@@ -2647,10 +2647,13 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "plan2code-app"
|
name = "plan2code-app"
|
||||||
version = "3.2.3"
|
version = "3.2.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chrono",
|
"chrono",
|
||||||
"libc",
|
"libc",
|
||||||
|
"objc2",
|
||||||
|
"objc2-app-kit",
|
||||||
|
"objc2-foundation",
|
||||||
"portable-pty",
|
"portable-pty",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"serde",
|
"serde",
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ There is no dot while busy or once a finished step has nothing left to press; a
|
|||||||
| `src-tauri/` | The Rust app |
|
| `src-tauri/` | The Rust app |
|
||||||
| `ui/` | The app page (plain HTML, CSS and JavaScript, no framework) |
|
| `ui/` | The app page (plain HTML, CSS and JavaScript, no framework) |
|
||||||
| `fake-agent/` | A stand-in agent program the tests run in a real pseudo-terminal |
|
| `fake-agent/` | A stand-in agent program the tests run in a real pseudo-terminal |
|
||||||
|
| `scripts/` | `vendor.mjs` (copies the xterm files into `ui/vendor/`), and CI's macOS frame check: `smoke-agent.mjs`, a stand-in agent that opens a real console, and `smoke-frame.mjs`, which waits for the console's `/health` to count the app's frame |
|
||||||
| `package.json` | The app's own npm packages (xterm, the Tauri CLI). Separate from the repo root so the root and the console stay dependency-free |
|
| `package.json` | The app's own npm packages (xterm, the Tauri CLI). Separate from the repo root so the root and the console stay dependency-free |
|
||||||
|
|
||||||
## Build and run
|
## Build and run
|
||||||
|
|||||||
@@ -37,11 +37,26 @@ file directly after checking it against the release's checksum list.
|
|||||||
- [ ] `plan2code --classic` runs the agent in the terminal with the app installed
|
- [ ] `plan2code --classic` runs the agent in the terminal with the app installed
|
||||||
- [ ] Linux only: with `DISPLAY` and `WAYLAND_DISPLAY` unset, `plan2code` runs the terminal flow
|
- [ ] Linux only: with `DISPLAY` and `WAYLAND_DISPLAY` unset, `plan2code` runs the terminal flow
|
||||||
- [ ] The desktop shortcut opens the folder menu (Choose a folder first, recent folders under it) and then the app
|
- [ ] The desktop shortcut opens the folder menu (Choose a folder first, recent folders under it) and then the app
|
||||||
|
- [ ] macOS: started from the desktop shortcut or `plan2code` in Terminal, the app's window opens in
|
||||||
|
front of Terminal, as the active app
|
||||||
- [ ] macOS: the first start is stopped by Gatekeeper, **Open Anyway** in System Settings (Privacy &
|
- [ ] macOS: the first start is stopped by Gatekeeper, **Open Anyway** in System Settings (Privacy &
|
||||||
Security) lets it through, and `docs/desktop-app.md` describes what you saw
|
Security) lets it through, and `docs/desktop-app.md` describes what you saw
|
||||||
- [ ] macOS and Linux: start the app from the Dock, Finder or a `.desktop` file (not a terminal) on
|
- [ ] macOS and Linux: start the app from the Dock, Finder or a `.desktop` file (not a terminal) on
|
||||||
a machine where Node is only on PATH through nvm, Homebrew or Volta: the first-run checklist
|
a machine where Node is only on PATH through nvm, Homebrew or Volta: the first-run checklist
|
||||||
still finds Node and the installed CLIs, and the console and an agent still start
|
still finds Node and the installed CLIs, and the console and an agent still start
|
||||||
|
- [ ] macOS: the same from Finder with Node set up by nvm in `~/.zshrc` only (not `~/.zprofile`):
|
||||||
|
Node and the agent are still found. With Node and an agent on the login PATH instead
|
||||||
|
(Homebrew, or nvm in `~/.zprofile`), `~/.zshrc` is not read at start, only on Check again;
|
||||||
|
with Homebrew's Node there but the agent installed by npm under nvm in `~/.zshrc`, the agent
|
||||||
|
is still found at start. A hung `~/.zprofile`
|
||||||
|
delays the start by 3 s at most and a hung `~/.zshrc` by 2 s; only a slow `~/.zprofile`
|
||||||
|
followed by a hung `~/.zshrc` reaches 5 s
|
||||||
|
- [ ] macOS and Linux: when the installer puts the `plan2code` command in a folder that is not on
|
||||||
|
PATH, its closing steps say so and name the line to add and the startup file to add it to;
|
||||||
|
done as written, `plan2code` runs in a new terminal
|
||||||
|
- [ ] macOS: canceling the folder picker (the `plan2code` launcher's, or Workspace's add folder)
|
||||||
|
reads as a cancel; a picker that fails instead (an `osascript` error other than -128) shows
|
||||||
|
an error in the console, and makes the launcher ask for the folder path to be typed
|
||||||
- [ ] Windows: SmartScreen's **More info**, then **Run anyway**, lets it through, and
|
- [ ] Windows: SmartScreen's **More info**, then **Run anyway**, lets it through, and
|
||||||
`docs/desktop-app.md` describes what you saw
|
`docs/desktop-app.md` describes what you saw
|
||||||
- [ ] `plan2code update` updates the skills, the command and the app, including while the app is
|
- [ ] `plan2code update` updates the skills, the command and the app, including while the app is
|
||||||
@@ -55,6 +70,8 @@ file directly after checking it against the release's checksum list.
|
|||||||
## The window (each system)
|
## The window (each system)
|
||||||
|
|
||||||
- [ ] The dashboard shows in the frame and the terminal panel is visible beneath it
|
- [ ] The dashboard shows in the frame and the terminal panel is visible beneath it
|
||||||
|
- [ ] macOS: the frame signs in by itself (WebKit gives it no cookie, so the console moves it under
|
||||||
|
its own `/f/<key>/` path on `127.0.0.1`); a blank frame or a sign-in page in it is a failure
|
||||||
- [ ] Resizing the window keeps both usable; dragging the handle resizes the panel
|
- [ ] Resizing the window keeps both usable; dragging the handle resizes the panel
|
||||||
- [ ] The bar shows the project folder; the permission note appears only while an agent started
|
- [ ] The bar shows the project folder; the permission note appears only while an agent started
|
||||||
with checks off is running, never otherwise
|
with checks off is running, never otherwise
|
||||||
@@ -92,8 +109,9 @@ file directly after checking it against the release's checksum list.
|
|||||||
- [ ] **Change project** in the top bar's project menu, with an agent running: it asks first, then the folder
|
- [ ] **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
|
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
|
- [ ] 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
|
- [ ] Change project, pick a different folder: the old agent and console stop, and the same agent starts in the new folder
|
||||||
on the launch card (or the checklist, if its own first run has not passed yet)
|
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
|
- [ ] 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
|
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
|
- [ ] When the app and the installed skills differ in version, the bar's right end offers **Update
|
||||||
@@ -111,7 +129,9 @@ Do each of Claude Code, Devin and Codex for a few minutes:
|
|||||||
- [ ] Pasting several lines
|
- [ ] Pasting several lines
|
||||||
- [ ] A line with Unicode and emoji
|
- [ ] A line with Unicode and emoji
|
||||||
- [ ] Select text in the terminal: it copies on its own; Ctrl+Shift+C (Windows, Linux) or Cmd+C
|
- [ ] Select text in the terminal: it copies on its own; Ctrl+Shift+C (Windows, Linux) or Cmd+C
|
||||||
(macOS) copies the selection too; Ctrl+V / Cmd+V pastes
|
(macOS) copies the selection too; Ctrl+V (Windows, Linux) or Cmd+V (macOS) pastes
|
||||||
|
- [ ] macOS: Cmd+V pastes the text once, at once, with no **Paste** menu popping up first
|
||||||
|
- [ ] macOS: Ctrl+V reaches the agent instead of pasting (Claude Code pastes a copied image with it)
|
||||||
- [ ] Exiting the agent: the agent menu reads "ended" with the reason beside it, and New Session stays
|
- [ ] Exiting the agent: the agent menu reads "ended" with the reason beside it, and New Session stays
|
||||||
just left of it
|
just left of it
|
||||||
|
|
||||||
@@ -120,10 +140,22 @@ Do each of Claude Code, Devin and Codex for a few minutes:
|
|||||||
- [ ] Start, then **New Session**: it confirms once, with Planny on a coffee break and no claim about unsaved
|
- [ ] Start, then **New Session**: it confirms once, with Planny on a coffee break and no claim about unsaved
|
||||||
work, then a fresh agent starts on the same agent, model, effort and permission mode, and the
|
work, then a fresh agent starts on the same agent, model, effort and permission mode, and the
|
||||||
dashboard shows the pick-up chip with a brief that matches the session
|
dashboard shows the pick-up chip with a brief that matches the session
|
||||||
|
- [ ] macOS and Linux: once New Session's dashboard shows, `ps -Ao pid,command | grep server.mjs` lists
|
||||||
|
the new console only; the old one stopped when the window moved on from it
|
||||||
- [ ] An agent that ends by itself leaves the app asking nothing until New Session or **Change agent**
|
- [ ] An agent that ends by itself leaves the app asking nothing until New Session or **Change agent**
|
||||||
(in the agent menu) is pressed; Change agent reopens the launch card with a real choice to make again
|
(in the agent menu) is pressed; Change agent reopens the launch card with a real choice to make again
|
||||||
- [ ] Closing the window while an agent runs asks first, and "no" keeps the window open
|
- [ ] Closing the window while an agent runs asks first, and "no" keeps the window open
|
||||||
- [ ] Cmd+Q on macOS asks the same
|
- [ ] macOS: Cmd+Q and the app menu's Quit ask the same while an agent works, in the window; Quit
|
||||||
|
from the Dock's menu quits at once with no question, and its cleanup still runs
|
||||||
|
- [ ] macOS: with another app in front, the window's close button asks in front of it, and one
|
||||||
|
click on Quit quits; Cmd+Q with the window minimized brings the window back with the question
|
||||||
|
- [ ] macOS and Linux: after each way of quitting (Cmd+Q, the app menu's Quit, closing the window,
|
||||||
|
a plain `kill` of the app, Ctrl+C or closing the terminal when the app's program was run from
|
||||||
|
one, and on macOS Quit from the Dock), with an agent running, nothing is left:
|
||||||
|
`ps -Ao pid,pgid,command | grep -E 'plan2code-app|server.mjs'` shows no app, no agent or
|
||||||
|
process of its group, and no console the agent opened. After an agent that ended by itself,
|
||||||
|
the same shows no app and no console it opened, while a process it left running in its
|
||||||
|
group on purpose (a backgrounded dev server) is still there
|
||||||
- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then New Session; check Task
|
- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then New Session; check Task
|
||||||
Manager and confirm no leftover `node.exe` (or the CLI's own process) is left running
|
Manager and confirm no leftover `node.exe` (or the CLI's own process) is left running
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "fake-agent"
|
name = "fake-agent"
|
||||||
version = "3.2.3"
|
version = "3.2.7"
|
||||||
description = "A stand-in agent program for the Plan2Code app's tests"
|
description = "A stand-in agent program for the Plan2Code app's tests"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
publish = false
|
publish = false
|
||||||
|
|||||||
@@ -19,6 +19,9 @@
|
|||||||
//! leaves the folder)
|
//! leaves the folder)
|
||||||
//! ENV <name> print the variable as `ENV <name>=<value>`
|
//! ENV <name> print the variable as `ENV <name>=<value>`
|
||||||
//! HANG say `HANGING`, then go silent for good (no more lines read)
|
//! HANG say `HANGING`, then go silent for good (no more lines read)
|
||||||
|
//! STRAY (macOS and Linux) start a child that ignores hangup and is never
|
||||||
|
//! waited for, and print its process id as `STRAY <n>`; elsewhere
|
||||||
|
//! say `STRAY unavailable`
|
||||||
//! <other> echoed back as `echo: <line>`
|
//! <other> echoed back as `echo: <line>`
|
||||||
//!
|
//!
|
||||||
//! A change in terminal size is reported on its own as `SIZE <cols>x<rows>`.
|
//! A change in terminal size is reported on its own as `SIZE <cols>x<rows>`.
|
||||||
@@ -56,6 +59,8 @@ pub enum Command {
|
|||||||
File(String, String),
|
File(String, String),
|
||||||
/// `HANG`: go silent, to model an agent that stops answering.
|
/// `HANG`: go silent, to model an agent that stops answering.
|
||||||
Hang,
|
Hang,
|
||||||
|
/// `STRAY`: leave a hangup-ignoring child behind in the agent's process group.
|
||||||
|
Stray,
|
||||||
Echo(String),
|
Echo(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +139,24 @@ fn update_state(
|
|||||||
std::fs::write(&temp, text).is_ok() && std::fs::rename(&temp, &file).is_ok()
|
std::fs::write(&temp, text).is_ok() && std::fs::rename(&temp, &file).is_ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A child that ignores hangup, in this process's group, never waited for.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn start_stray() -> Option<u32> {
|
||||||
|
std::process::Command::new("/bin/sh")
|
||||||
|
.args(["-c", "trap '' HUP; exec sleep 300"])
|
||||||
|
.stdin(std::process::Stdio::null())
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.ok()
|
||||||
|
.map(|child| child.id())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
fn start_stray() -> Option<u32> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
pub fn parse(line: &str) -> Command {
|
pub fn parse(line: &str) -> Command {
|
||||||
let line = line.trim();
|
let line = line.trim();
|
||||||
if let Some(rest) = line.strip_prefix("STEP ") {
|
if let Some(rest) = line.strip_prefix("STEP ") {
|
||||||
@@ -176,6 +199,9 @@ pub fn parse(line: &str) -> Command {
|
|||||||
if line == "HANG" {
|
if line == "HANG" {
|
||||||
return Command::Hang;
|
return Command::Hang;
|
||||||
}
|
}
|
||||||
|
if line == "STRAY" {
|
||||||
|
return Command::Stray;
|
||||||
|
}
|
||||||
Command::Echo(line.to_string())
|
Command::Echo(line.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -274,6 +300,10 @@ fn main() {
|
|||||||
thread::sleep(Duration::from_secs(3600));
|
thread::sleep(Duration::from_secs(3600));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Command::Stray => match start_stray() {
|
||||||
|
Some(pid) => say(&format!("STRAY {pid}")),
|
||||||
|
None => say("STRAY unavailable"),
|
||||||
|
},
|
||||||
Command::Echo(text) => say(&format!("echo: {text}")),
|
Command::Echo(text) => say(&format!("echo: {text}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -303,6 +333,7 @@ mod tests {
|
|||||||
Command::Report("{\"phase\":2}".into())
|
Command::Report("{\"phase\":2}".into())
|
||||||
);
|
);
|
||||||
assert_eq!(parse("HANG\r\n"), Command::Hang);
|
assert_eq!(parse("HANG\r\n"), Command::Hang);
|
||||||
|
assert_eq!(parse("STRAY"), Command::Stray);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "plan2code-app",
|
"name": "plan2code-app",
|
||||||
"version": "3.2.3",
|
"version": "3.2.7",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "plan2code-app",
|
"name": "plan2code-app",
|
||||||
"version": "3.2.3",
|
"version": "3.2.7",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tauri-apps/api": "2.12.4",
|
"@tauri-apps/api": "2.12.4",
|
||||||
"@xterm/addon-fit": "0.11.0",
|
"@xterm/addon-fit": "0.11.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "plan2code-app",
|
"name": "plan2code-app",
|
||||||
"version": "3.2.3",
|
"version": "3.2.7",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Plan2Code desktop app (Tauri). Separate from the repo root so the root and the web console stay dependency-free.",
|
"description": "Plan2Code desktop app (Tauri). Separate from the repo root so the root and the web console stay dependency-free.",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
Executable
+32
@@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// A stand-in agent for CI's smoke run of the built app (.github/workflows/app.yml).
|
||||||
|
// Point PLAN2CODE_APP_AGENT_BIN at this file. Like a real agent, it opens a web
|
||||||
|
// console dashboard, with the environment the app gave it, so the console
|
||||||
|
// announces itself to the window and the dashboard frame has something to
|
||||||
|
// connect to (smoke-frame.mjs then checks it did). The repo's fake-agent opens
|
||||||
|
// no console, so it cannot stand in for this.
|
||||||
|
//
|
||||||
|
// It needs PLAN2CODE_CONSOLE_DIR (the folder holding console.mjs), ignores the
|
||||||
|
// arguments the app passes a real agent, and then waits on its input until it
|
||||||
|
// closes. It starts nothing else: the console server is detached, and the
|
||||||
|
// smoke run stops it with `console.mjs stop --all`.
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
const consoleDir = process.env.PLAN2CODE_CONSOLE_DIR;
|
||||||
|
if (!consoleDir) {
|
||||||
|
console.error('smoke-agent: PLAN2CODE_CONSOLE_DIR is not set; it names the folder holding console.mjs');
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
const open = spawnSync(process.execPath, [join(consoleDir, 'console.mjs'), 'open', '--workflow', 'dashboard'], {
|
||||||
|
stdio: ['ignore', 'inherit', 'inherit'],
|
||||||
|
});
|
||||||
|
if (open.error || open.status !== 0) {
|
||||||
|
console.error(`smoke-agent: console.mjs open failed (${open.error ? open.error.message : `exit ${open.status}`})`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('smoke-agent: dashboard open; waiting on input');
|
||||||
|
process.stdin.resume();
|
||||||
|
process.stdin.on('end', () => process.exit(0));
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
// Checks the app's dashboard frame connected to its console, for CI's macOS smoke
|
||||||
|
// run (.github/workflows/app.yml). A window that comes up but never signs its
|
||||||
|
// frame in looks alive to a process check; the console's own browser count
|
||||||
|
// does not lie.
|
||||||
|
//
|
||||||
|
// node smoke-frame.mjs [<console home>] [--timeout-ms N]
|
||||||
|
//
|
||||||
|
// The console home defaults to PLAN2CODE_CONSOLE_HOME. Waits for a session
|
||||||
|
// handle there (runtime/<project hash>/<sid>.json), then polls that session's
|
||||||
|
// open GET /health until it counts a browser. Exit 0 once one connects; exit 1
|
||||||
|
// when the time (60 s by default, for both waits together) runs out, with the
|
||||||
|
// last answer printed; exit 2 for a usage error.
|
||||||
|
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { parseArgs } from 'node:util';
|
||||||
|
|
||||||
|
const POLL_MS = 500;
|
||||||
|
const REQUEST_MS = 2000;
|
||||||
|
|
||||||
|
let parsed;
|
||||||
|
try {
|
||||||
|
parsed = parseArgs({ allowPositionals: true, options: { 'timeout-ms': { type: 'string' } } });
|
||||||
|
} catch (err) {
|
||||||
|
usage(err.message);
|
||||||
|
}
|
||||||
|
const home = parsed.positionals[0] || process.env.PLAN2CODE_CONSOLE_HOME;
|
||||||
|
if (!home) usage('no console home: pass one, or set PLAN2CODE_CONSOLE_HOME');
|
||||||
|
const timeoutMs = Number(parsed.values['timeout-ms'] ?? 60000);
|
||||||
|
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) usage('--timeout-ms takes a positive number');
|
||||||
|
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
let last = null;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
// Read again each round: a reconnect can resume the session on a new port.
|
||||||
|
const handle = newestHandle(home);
|
||||||
|
if (handle) {
|
||||||
|
last = await health(handle);
|
||||||
|
if (last.body && last.body.sid === handle.sid && last.body.browsers >= 1) {
|
||||||
|
console.log(`smoke-frame: the dashboard frame connected (browsers ${last.body.browsers}, port ${handle.port})`);
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
|
||||||
|
}
|
||||||
|
if (!last) {
|
||||||
|
console.error(`smoke-frame: no session appeared under ${home} within ${timeoutMs} ms`);
|
||||||
|
} else {
|
||||||
|
console.error(`smoke-frame: no browser connected within ${timeoutMs} ms; last /health answer from port ${last.port}: ${last.text}`);
|
||||||
|
}
|
||||||
|
process.exit(1);
|
||||||
|
|
||||||
|
function usage(message) {
|
||||||
|
console.error(`smoke-frame: ${message}\nusage: node smoke-frame.mjs [<console home>] [--timeout-ms N]`);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The most recently written session handle under the home, or null.
|
||||||
|
function newestHandle(consoleHome) {
|
||||||
|
const runtime = join(consoleHome, 'runtime');
|
||||||
|
let newest = null;
|
||||||
|
for (const hash of safeList(runtime)) {
|
||||||
|
for (const name of safeList(join(runtime, hash))) {
|
||||||
|
if (!name.endsWith('.json')) continue;
|
||||||
|
const file = join(runtime, hash, name);
|
||||||
|
try {
|
||||||
|
const handle = JSON.parse(readFileSync(file, 'utf8'));
|
||||||
|
const mtime = statSync(file).mtimeMs;
|
||||||
|
if (Number.isInteger(handle.port) && handle.sid && (!newest || mtime > newest.mtime)) newest = { ...handle, mtime };
|
||||||
|
} catch {
|
||||||
|
// Half written or removed between the listing and the read: the next round sees it whole.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return newest;
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeList(dir) {
|
||||||
|
try {
|
||||||
|
return readdirSync(dir);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One /health answer: the raw text for the failure message, and the body when it parsed.
|
||||||
|
async function health(handle) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`http://127.0.0.1:${handle.port}/health`, { signal: AbortSignal.timeout(REQUEST_MS) });
|
||||||
|
const text = await res.text();
|
||||||
|
let body = null;
|
||||||
|
try {
|
||||||
|
body = JSON.parse(text);
|
||||||
|
} catch {
|
||||||
|
// Not JSON: kept as text for the message.
|
||||||
|
}
|
||||||
|
return { port: handle.port, text: `${res.status} ${text}`, body };
|
||||||
|
} catch (err) {
|
||||||
|
return { port: handle.port, text: `no answer (${err.message})`, body: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "plan2code-app"
|
name = "plan2code-app"
|
||||||
version = "3.2.3"
|
version = "3.2.7"
|
||||||
description = "Plan2Code desktop app"
|
description = "Plan2Code desktop app"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
publish = false
|
publish = false
|
||||||
@@ -28,6 +28,13 @@ reqwest = { version = "0.13", default-features = false, features = ["blocking",
|
|||||||
[target.'cfg(unix)'.dependencies]
|
[target.'cfg(unix)'.dependencies]
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
|
# Already pulled in by tauri itself; named directly here only to set the Dock
|
||||||
|
# icon (`set_app_icon` in main.rs), which tauri does for dev builds alone.
|
||||||
|
objc2 = "0.6"
|
||||||
|
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSImage", "NSResponder"] }
|
||||||
|
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSData", "NSGeometry"] }
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
# Already pulled in by portable-pty itself; named directly here only for the
|
# Already pulled in by portable-pty itself; named directly here only for the
|
||||||
# Job Object APIs it does not expose (ending a `cmd /c` npm shim's whole
|
# Job Object APIs it does not expose (ending a `cmd /c` npm shim's whole
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ use std::thread;
|
|||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
use crate::agents::{agent_launch_spec, Agent, PermissionMode};
|
use crate::agents::{agent_launch_spec, Agent, PermissionMode};
|
||||||
|
use crate::log;
|
||||||
use crate::pty_host::{PtyHost, StartOptions};
|
use crate::pty_host::{PtyHost, StartOptions};
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
@@ -35,6 +36,12 @@ pub type BeforeFresh = Arc<dyn Fn() -> Option<String> + Send + Sync>;
|
|||||||
/// the manager.
|
/// the manager.
|
||||||
pub type ForgetSession = Arc<dyn Fn() + Send + Sync>;
|
pub type ForgetSession = Arc<dyn Fn() + Send + Sync>;
|
||||||
|
|
||||||
|
/// Runs once for each agent that ends, however it ends: by itself, by a stop,
|
||||||
|
/// or replaced by Restart or a loop phase's fresh start. It can run with the
|
||||||
|
/// manager's state locked, so it must return quickly and must not call back
|
||||||
|
/// into the manager.
|
||||||
|
pub type Ended = Arc<dyn Fn() + Send + Sync>;
|
||||||
|
|
||||||
/// What the page needs to draw the bar. `generation` counts the agents started
|
/// What the page needs to draw the bar. `generation` counts the agents started
|
||||||
/// so far: a new number means a fresh agent, so the terminal clears.
|
/// so far: a new number means a fresh agent, so the terminal clears.
|
||||||
#[derive(Clone, Debug, Serialize)]
|
#[derive(Clone, Debug, Serialize)]
|
||||||
@@ -116,12 +123,17 @@ struct Shared {
|
|||||||
sink: Sink,
|
sink: Sink,
|
||||||
before_fresh: Mutex<Option<BeforeFresh>>,
|
before_fresh: Mutex<Option<BeforeFresh>>,
|
||||||
forget_session: Mutex<Option<ForgetSession>>,
|
forget_session: Mutex<Option<ForgetSession>>,
|
||||||
|
ended: Mutex<Option<Ended>>,
|
||||||
/// Environment every agent this manager starts gets, on top of its own:
|
/// Environment every agent this manager starts gets, on top of its own:
|
||||||
/// the in-app signal that sends the agent's console pages to this window.
|
/// the in-app signal that sends the agent's console pages to this window.
|
||||||
extra_env: Mutex<Vec<(String, String)>>,
|
extra_env: Mutex<Vec<(String, String)>>,
|
||||||
/// Bumped for every agent started. Output and exits from an older agent
|
/// Bumped for every agent started. Output and exits from an older agent
|
||||||
/// compare against it and are dropped.
|
/// compare against it and are dropped.
|
||||||
generation: AtomicU64,
|
generation: AtomicU64,
|
||||||
|
/// The threads that wait for each agent's end and finish the process group
|
||||||
|
/// of one the app replaced, so a stop can wait for them.
|
||||||
|
#[cfg(unix)]
|
||||||
|
ends: Mutex<Vec<thread::JoinHandle<()>>>,
|
||||||
inner: Mutex<Inner>,
|
inner: Mutex<Inner>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,8 +156,11 @@ impl AgentManager {
|
|||||||
sink,
|
sink,
|
||||||
before_fresh: Mutex::new(None),
|
before_fresh: Mutex::new(None),
|
||||||
forget_session: Mutex::new(None),
|
forget_session: Mutex::new(None),
|
||||||
|
ended: Mutex::new(None),
|
||||||
extra_env: Mutex::new(Vec::new()),
|
extra_env: Mutex::new(Vec::new()),
|
||||||
generation: AtomicU64::new(0),
|
generation: AtomicU64::new(0),
|
||||||
|
#[cfg(unix)]
|
||||||
|
ends: Mutex::new(Vec::new()),
|
||||||
inner: Mutex::new(Inner {
|
inner: Mutex::new(Inner {
|
||||||
state: AgentState::Idle,
|
state: AgentState::Idle,
|
||||||
running: None,
|
running: None,
|
||||||
@@ -177,6 +192,13 @@ impl AgentManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Run `hook` once for every agent that ends (see `Ended`).
|
||||||
|
pub fn set_ended(&self, hook: Ended) {
|
||||||
|
if let Ok(mut slot) = self.shared.ended.lock() {
|
||||||
|
*slot = Some(hook);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Make the app forget the console session it follows, so the next agent's
|
/// Make the app forget the console session it follows, so the next agent's
|
||||||
/// `open` starts a new one.
|
/// `open` starts a new one.
|
||||||
pub fn forget_session(&self) {
|
pub fn forget_session(&self) {
|
||||||
@@ -366,6 +388,7 @@ impl AgentManager {
|
|||||||
self.shared.generation.fetch_add(1, Ordering::SeqCst);
|
self.shared.generation.fetch_add(1, Ordering::SeqCst);
|
||||||
if let Some(old) = inner.running.take() {
|
if let Some(old) = inner.running.take() {
|
||||||
let _ = old.host.kill();
|
let _ = old.host.kill();
|
||||||
|
self.shared.ended();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
match self.shared.spawn(&mut inner, prompt, choice, extra_env) {
|
match self.shared.spawn(&mut inner, prompt, choice, extra_env) {
|
||||||
@@ -455,7 +478,9 @@ impl AgentManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// End the agent for good (quitting). Nothing starts afterwards, and the
|
/// End the agent for good (quitting). Nothing starts afterwards, and the
|
||||||
/// agent's process is gone when this returns.
|
/// agent's process, with what is left of its process group on macOS and
|
||||||
|
/// Linux, is gone when this returns. So is the group of an agent replaced
|
||||||
|
/// a moment before, whose grace may still be running.
|
||||||
pub fn stop(&self) {
|
pub fn stop(&self) {
|
||||||
let host = {
|
let host = {
|
||||||
let mut inner = lock(&self.shared.inner);
|
let mut inner = lock(&self.shared.inner);
|
||||||
@@ -470,7 +495,12 @@ impl AgentManager {
|
|||||||
if let Some(host) = host {
|
if let Some(host) = host {
|
||||||
let _ = host.kill();
|
let _ = host.kill();
|
||||||
let _ = host.wait();
|
let _ = host.wait();
|
||||||
|
// The app may exit right after, before `kill`'s own grace runs out.
|
||||||
|
host.end_group();
|
||||||
|
self.shared.ended();
|
||||||
}
|
}
|
||||||
|
#[cfg(unix)]
|
||||||
|
self.shared.finish_ends();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -513,6 +543,42 @@ impl Shared {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An agent ended: run the `ended` hook, if one is set.
|
||||||
|
fn ended(&self) {
|
||||||
|
let hook = self.ended.lock().ok().and_then(|slot| slot.clone());
|
||||||
|
if let Some(run) = hook {
|
||||||
|
run();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep an agent's end thread, so `finish_ends` can wait for it; threads
|
||||||
|
/// already done are let go.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn keep_end(&self, end: thread::JoinHandle<()>) {
|
||||||
|
let mut ends = self
|
||||||
|
.ends
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||||
|
ends.retain(|kept| !kept.is_finished());
|
||||||
|
ends.push(end);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait until every agent started here has ended and the process group of
|
||||||
|
/// each one the app stopped or replaced is gone: the app may exit straight
|
||||||
|
/// after, which would cut a replaced agent's grace short.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn finish_ends(&self) {
|
||||||
|
let ends = std::mem::take(
|
||||||
|
&mut *self
|
||||||
|
.ends
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner()),
|
||||||
|
);
|
||||||
|
for end in ends {
|
||||||
|
let _ = end.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn emit(&self, inner: &Inner) {
|
fn emit(&self, inner: &Inner) {
|
||||||
(self.sink)(AgentEvent::State(self.snapshot(inner)));
|
(self.sink)(AgentEvent::State(self.snapshot(inner)));
|
||||||
}
|
}
|
||||||
@@ -602,14 +668,25 @@ impl Shared {
|
|||||||
self.emit(inner);
|
self.emit(inner);
|
||||||
|
|
||||||
let shared = Arc::clone(self);
|
let shared = Arc::clone(self);
|
||||||
thread::spawn(move || {
|
let end = thread::spawn(move || {
|
||||||
let reason = match host.wait_described() {
|
let reason = match host.wait_described() {
|
||||||
Ok((_, Some(signal))) => format!("was ended by a signal ({signal})"),
|
Ok((_, Some(signal))) => format!("{SIGNAL_REASON} ({signal})"),
|
||||||
Ok((code, None)) => format!("exited with code {code}"),
|
Ok((code, None)) => format!("exited with code {code}"),
|
||||||
Err(e) => format!("stopped: {e}"),
|
Err(e) => format!("stopped: {e}"),
|
||||||
};
|
};
|
||||||
shared.on_exit(generation, reason);
|
// Only an agent the app stopped or replaced takes its process
|
||||||
|
// group with it: after a Restart or New Session this finishes
|
||||||
|
// what `kill`'s grace thread started (after a stop it finds the
|
||||||
|
// group gone). An agent that ended by itself leaves its group
|
||||||
|
// alone, so work the person asked it to leave running survives.
|
||||||
|
if !shared.on_exit(generation, reason) {
|
||||||
|
host.end_group();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
#[cfg(unix)]
|
||||||
|
self.keep_end(end);
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
drop(end);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -620,6 +697,7 @@ impl Shared {
|
|||||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||||
if let Some(old) = inner.running.take() {
|
if let Some(old) = inner.running.take() {
|
||||||
let _ = old.host.kill();
|
let _ = old.host.kill();
|
||||||
|
self.ended();
|
||||||
}
|
}
|
||||||
let hook = self.before_fresh.lock().ok().and_then(|slot| slot.clone());
|
let hook = self.before_fresh.lock().ok().and_then(|slot| slot.clone());
|
||||||
inner.brief_note = hook.and_then(|run| run());
|
inner.brief_note = hook.and_then(|run| run());
|
||||||
@@ -644,19 +722,42 @@ impl Shared {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The agent's process ended. Stale if a newer agent has replaced it.
|
/// The agent's process ended. Stale if a newer agent has replaced it, or
|
||||||
fn on_exit(self: &Arc<Self>, generation: u64, reason: String) {
|
/// the app stopped it. True when it ended by itself (not stale).
|
||||||
|
fn on_exit(self: &Arc<Self>, generation: u64, reason: String) -> bool {
|
||||||
let mut inner = lock(&self.inner);
|
let mut inner = lock(&self.inner);
|
||||||
if self.generation.load(Ordering::SeqCst) != generation {
|
if self.generation.load(Ordering::SeqCst) != generation {
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
inner.running = None;
|
inner.running = None;
|
||||||
// Ended on its own: say why and start nothing.
|
// Ended on its own: say why and start nothing. A signal nobody here
|
||||||
|
// sent (stop and Restart move the generation on first) also goes to
|
||||||
|
// the log, since the bar's reason is gone once a new agent starts.
|
||||||
|
if let Some((choice, _)) = &inner.last_start {
|
||||||
|
if let Some(line) = exit_log_line(choice.kind.id(), &reason) {
|
||||||
|
log::line(&line);
|
||||||
|
}
|
||||||
|
}
|
||||||
inner.state = AgentState::Ended { reason };
|
inner.state = AgentState::Ended { reason };
|
||||||
self.emit(&inner);
|
self.emit(&inner);
|
||||||
|
// Still locked: no fresh agent can start, and announce, before the
|
||||||
|
// hook has taken what this one left.
|
||||||
|
self.ended();
|
||||||
|
true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How the bar's reason starts for an agent a signal ended.
|
||||||
|
const SIGNAL_REASON: &str = "was ended by a signal";
|
||||||
|
|
||||||
|
/// The log line for an agent's end, from its id and the bar's reason: only
|
||||||
|
/// an end by a signal gets one, since an exit code is the agent's own word.
|
||||||
|
fn exit_log_line(agent: &str, reason: &str) -> Option<String> {
|
||||||
|
reason
|
||||||
|
.starts_with(SIGNAL_REASON)
|
||||||
|
.then(|| format!("plan2code: the agent {agent} {reason}"))
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod replay_tests {
|
mod replay_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -684,3 +785,24 @@ mod replay_tests {
|
|||||||
assert_eq!(replay, b"6789");
|
assert_eq!(replay, b"6789");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod exit_log_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_signal_gives_a_line_naming_the_agent_and_the_signal() {
|
||||||
|
let reason = format!("{SIGNAL_REASON} (Killed: 9)");
|
||||||
|
let line = exit_log_line("claude", &reason).expect("a signal is logged");
|
||||||
|
assert!(line.contains("claude"), "{line}");
|
||||||
|
assert!(line.contains("Killed: 9"), "{line}");
|
||||||
|
assert!(line.starts_with("plan2code: "), "{line}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_exit_code_or_a_failed_wait_gives_no_line() {
|
||||||
|
assert_eq!(exit_log_line("claude", "exited with code 0"), None);
|
||||||
|
assert_eq!(exit_log_line("claude", "exited with code 1"), None);
|
||||||
|
assert_eq!(exit_log_line("claude", "stopped: wait failed"), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1150,6 +1150,34 @@ pub fn custom_agents() -> (Vec<CustomAgent>, Vec<String>) {
|
|||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The command of every built-in and custom agent that the lookup searches
|
||||||
|
/// PATH for by name, each once, in list order. A command with a folder in it
|
||||||
|
/// runs from there, whatever PATH holds, so it is left out. The PATH lookup at
|
||||||
|
/// start (`node_check::login_shell_path`) reads the shell's interactive config
|
||||||
|
/// when none of these is on the login PATH.
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub fn path_agent_commands() -> Vec<String> {
|
||||||
|
let (custom, _) = custom_agents();
|
||||||
|
path_commands(
|
||||||
|
builtin_entries()
|
||||||
|
.iter()
|
||||||
|
.map(|entry| entry.command.as_str())
|
||||||
|
.chain(custom.iter().map(|agent| agent.command.as_str())),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `path_agent_commands` over the given commands.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn path_commands<'a>(commands: impl Iterator<Item = &'a str>) -> Vec<String> {
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
commands
|
||||||
|
.map(clean_command)
|
||||||
|
.filter(|command| !command.is_empty() && !has_separator(command, false))
|
||||||
|
.filter(|command| seen.insert(*command))
|
||||||
|
.map(str::to_string)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
fn clean_command(command: &str) -> &str {
|
fn clean_command(command: &str) -> &str {
|
||||||
let command = command.trim();
|
let command = command.trim();
|
||||||
command
|
command
|
||||||
@@ -1656,6 +1684,31 @@ mod tests {
|
|||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn the_path_agent_commands_are_the_bare_names_each_once() {
|
||||||
|
// The baked built-ins, then a custom list with a repeat, a quoted
|
||||||
|
// name, a command with a folder in it and an empty one.
|
||||||
|
let builtins = parse_agent_list(BAKED_AGENTS).expect("the baked list parses");
|
||||||
|
let custom = [
|
||||||
|
"codex",
|
||||||
|
"\"opencode\"",
|
||||||
|
"/opt/tools/bin/gemini",
|
||||||
|
"./agent",
|
||||||
|
" ",
|
||||||
|
];
|
||||||
|
assert_eq!(
|
||||||
|
path_commands(
|
||||||
|
builtins
|
||||||
|
.builtins
|
||||||
|
.iter()
|
||||||
|
.map(|entry| entry.command.as_str())
|
||||||
|
.chain(custom)
|
||||||
|
),
|
||||||
|
["claude", "devin", "codex", "opencode"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_baked_list_matches_the_shipped_agents_json() {
|
fn the_baked_list_matches_the_shipped_agents_json() {
|
||||||
// include_str! means the baked copy IS src/launcher/agents.json; this
|
// include_str! means the baked copy IS src/launcher/agents.json; this
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ use std::io::{Read, Write};
|
|||||||
use std::net::{TcpStream, ToSocketAddrs};
|
use std::net::{TcpStream, ToSocketAddrs};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
use std::sync::{Arc, Mutex, MutexGuard};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
@@ -119,6 +120,13 @@ fn node_command(console_dir: &Path) -> Command {
|
|||||||
use std::os::windows::process::CommandExt;
|
use std::os::windows::process::CommandExt;
|
||||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||||
}
|
}
|
||||||
|
// Ctrl+C and a closing terminal signal the app's whole process group: a stop running there
|
||||||
|
// would end before it stopped its console.
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::process::CommandExt;
|
||||||
|
command.process_group(0);
|
||||||
|
}
|
||||||
command
|
command
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -403,22 +411,237 @@ impl ConsoleSupervisor {
|
|||||||
if self.stopped {
|
if self.stopped {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let output = node_command(&self.console_dir)
|
let result = run_stop(&self.console_dir, &self.project_dir, &self.session.sid);
|
||||||
.args(stop_args(&self.session.sid))
|
// Only a stop that could not run at all leaves the flag clear, as before.
|
||||||
.current_dir(&self.project_dir)
|
if !matches!(result, Err(StopError::NotRun(_))) {
|
||||||
.output()
|
self.stopped = true;
|
||||||
.map_err(err)?;
|
|
||||||
self.stopped = true;
|
|
||||||
if !output.status.success() {
|
|
||||||
return Err(format!(
|
|
||||||
"console stop failed: {}",
|
|
||||||
String::from_utf8_lossy(&output.stderr).trim()
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
Ok(())
|
result.map_err(StopError::into_message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `console.mjs stop --session <sid> --force` for any session, run in the
|
||||||
|
/// project folder: the same stop `ConsoleSupervisor::stop` runs, for a console
|
||||||
|
/// this app does not supervise (one an agent announced and the window has
|
||||||
|
/// since moved on from).
|
||||||
|
pub fn stop_console_session(
|
||||||
|
console_dir: &Path,
|
||||||
|
project_dir: &Path,
|
||||||
|
sid: &str,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
run_stop(console_dir, project_dir, sid).map_err(StopError::into_message)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One console an agent announced. `left` once that agent has ended while the
|
||||||
|
/// window still showed the console: nothing needs it after the window moves on.
|
||||||
|
struct Announced {
|
||||||
|
sid: String,
|
||||||
|
left: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The console sessions this app's agents announced on macOS and Linux, by
|
||||||
|
/// sid, in the order they came: the ones to stop when the agent that opened
|
||||||
|
/// them ends, when the window moves on from one an ended agent left, or when
|
||||||
|
/// the app quits. Consoles the app started itself are never recorded here, and
|
||||||
|
/// one the app stopped for good is forgotten; the bar's stop, which keeps the
|
||||||
|
/// session to start it again, leaves it recorded. Also holds the threads still
|
||||||
|
/// stopping consoles after an agent's end or a new page, so a quit can wait for
|
||||||
|
/// them.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct AnnouncedConsoles {
|
||||||
|
consoles: Mutex<Vec<Announced>>,
|
||||||
|
stops: Mutex<Vec<std::thread::JoinHandle<()>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AnnouncedConsoles {
|
||||||
|
fn lock(&self) -> MutexGuard<'_, Vec<Announced>> {
|
||||||
|
self.consoles
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remember `sid`, announced by a running agent; one already recorded is
|
||||||
|
/// kept once, and is no longer left: the new agent joined it.
|
||||||
|
pub fn record(&self, sid: &str) {
|
||||||
|
let mut consoles = self.lock();
|
||||||
|
match consoles.iter_mut().find(|known| known.sid == sid) {
|
||||||
|
Some(known) => known.left = false,
|
||||||
|
None => consoles.push(Announced {
|
||||||
|
sid: sid.to_string(),
|
||||||
|
left: false,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remember `sid` as left by an agent that has ended; one a new agent
|
||||||
|
/// announced in the meantime stays that agent's.
|
||||||
|
fn leave(&self, sid: &str) {
|
||||||
|
let mut consoles = self.lock();
|
||||||
|
if !consoles.iter().any(|known| known.sid == sid) {
|
||||||
|
consoles.push(Announced {
|
||||||
|
sid: sid.to_string(),
|
||||||
|
left: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drop `sid` from the record: the app stopped that console itself.
|
||||||
|
pub fn forget(&self, sid: &str) {
|
||||||
|
self.lock().retain(|known| known.sid != sid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every recorded sid, in record order, and an empty record after.
|
||||||
|
pub fn take_all(&self) -> Vec<String> {
|
||||||
|
std::mem::take(&mut *self.lock())
|
||||||
|
.into_iter()
|
||||||
|
.map(|known| known.sid)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every console left by an agent that has ended, but for the one the
|
||||||
|
/// window follows, no longer recorded after.
|
||||||
|
fn take_left(&self, followed: Option<&str>) -> Vec<String> {
|
||||||
|
let mut consoles = self.lock();
|
||||||
|
let (left, kept) = std::mem::take(&mut *consoles)
|
||||||
|
.into_iter()
|
||||||
|
.partition(|known| known.left && followed != Some(known.sid.as_str()));
|
||||||
|
*consoles = kept;
|
||||||
|
left.into_iter().map(|known| known.sid).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The window follows `followed` now: stop each console an agent that has
|
||||||
|
/// ended left under it, with `stop` on a thread of its own, since a stop
|
||||||
|
/// runs `node`. A console of an agent still running is never touched.
|
||||||
|
pub fn stop_left<F>(&self, followed: &str, stop: F)
|
||||||
|
where
|
||||||
|
F: Fn(&str) + Send + 'static,
|
||||||
|
{
|
||||||
|
let sids = self.take_left(Some(followed));
|
||||||
|
if sids.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.keep_stop(std::thread::spawn(move || {
|
||||||
|
for sid in sids {
|
||||||
|
stop(&sid);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep a thread that is stopping consoles, so `finish_stops` can wait
|
||||||
|
/// for it; threads already done are let go.
|
||||||
|
fn keep_stop(&self, stop: std::thread::JoinHandle<()>) {
|
||||||
|
let mut stops = self
|
||||||
|
.stops
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||||
|
stops.retain(|kept| !kept.is_finished());
|
||||||
|
stops.push(stop);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait for every console stop still running on a thread, after an agent's
|
||||||
|
/// end or a new page: the app may exit straight after, which would cut it
|
||||||
|
/// short.
|
||||||
|
pub fn finish_stops(&self) {
|
||||||
|
let stops = std::mem::take(
|
||||||
|
&mut *self
|
||||||
|
.stops
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner()),
|
||||||
|
);
|
||||||
|
for stop in stops {
|
||||||
|
let _ = stop.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The hook an agent manager runs when an agent ends (`AgentManager::set_ended`):
|
||||||
|
/// it takes every console `announced` holds at once, inside the hook, so a
|
||||||
|
/// console the next agent announces later is never taken by mistake, then
|
||||||
|
/// stops each with `stop` on a thread of its own, since a stop runs `node` and
|
||||||
|
/// the hook must return quickly. The console the window follows (`followed`)
|
||||||
|
/// is left to the supervisor and recorded again, as left: stopped under the
|
||||||
|
/// window, the bar's health poll would only start it again as a server no one
|
||||||
|
/// tracks. It is stopped once the window moves on (`stop_left`), here if that
|
||||||
|
/// happened while this thread was deciding, or at the quit. `followed` is asked
|
||||||
|
/// on that thread too: it takes the console lock, held across `node` runs,
|
||||||
|
/// while the hook runs with the agent manager locked. A caller about to stop
|
||||||
|
/// the followed console waits for the thread first (`finish_stops`), so it is
|
||||||
|
/// never recorded again after that stop.
|
||||||
|
/// The macOS and Linux stand-in for Windows' Job Object, which ends every
|
||||||
|
/// console an agent opened along with it.
|
||||||
|
pub fn stop_announced_on_end<K, F>(
|
||||||
|
announced: Arc<AnnouncedConsoles>,
|
||||||
|
followed: K,
|
||||||
|
stop: F,
|
||||||
|
) -> Arc<dyn Fn() + Send + Sync>
|
||||||
|
where
|
||||||
|
K: Fn() -> Option<String> + Send + Sync + 'static,
|
||||||
|
F: Fn(&str) + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
let followed = Arc::new(followed);
|
||||||
|
let stop = Arc::new(stop);
|
||||||
|
Arc::new(move || {
|
||||||
|
let sids = announced.take_all();
|
||||||
|
if sids.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let (followed, stop, record) = (
|
||||||
|
Arc::clone(&followed),
|
||||||
|
Arc::clone(&stop),
|
||||||
|
Arc::clone(&announced),
|
||||||
|
);
|
||||||
|
announced.keep_stop(std::thread::spawn(move || {
|
||||||
|
let shown = followed();
|
||||||
|
let mut left = false;
|
||||||
|
for sid in sids {
|
||||||
|
if shown.as_deref() == Some(sid.as_str()) {
|
||||||
|
record.leave(&sid);
|
||||||
|
left = true;
|
||||||
|
} else {
|
||||||
|
stop(&sid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if left {
|
||||||
|
// A page that took the window since the question above found
|
||||||
|
// nothing left to stop yet.
|
||||||
|
for sid in record.take_left(followed().as_deref()) {
|
||||||
|
stop(&sid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a stop failed: it never ran (`node` could not be started), or it ran
|
||||||
|
/// and the console said no.
|
||||||
|
enum StopError {
|
||||||
|
NotRun(String),
|
||||||
|
Failed(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StopError {
|
||||||
|
fn into_message(self) -> String {
|
||||||
|
match self {
|
||||||
|
StopError::NotRun(message) | StopError::Failed(message) => message,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_stop(console_dir: &Path, project_dir: &Path, sid: &str) -> Result<(), StopError> {
|
||||||
|
let output = node_command(console_dir)
|
||||||
|
.args(stop_args(sid))
|
||||||
|
.current_dir(project_dir)
|
||||||
|
.output()
|
||||||
|
.map_err(|e| StopError::NotRun(err(e)))?;
|
||||||
|
if !output.status.success() {
|
||||||
|
return Err(StopError::Failed(format!(
|
||||||
|
"console stop failed: {}",
|
||||||
|
String::from_utf8_lossy(&output.stderr).trim()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Is the session's folder still in the console's home. Unknown (no home
|
/// Is the session's folder still in the console's home. Unknown (no home
|
||||||
/// directory) counts as there, so the answer never throws a session away. A
|
/// directory) counts as there, so the answer never throws a session away. A
|
||||||
/// sid that is not a plain folder name (empty, `..`, a path) is never there.
|
/// sid that is not a plain folder name (empty, `..`, a path) is never there.
|
||||||
@@ -463,6 +686,241 @@ fn stop_args(sid: &str) -> [&str; 4] {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn announced_consoles_are_taken_once_in_order_without_duplicates() {
|
||||||
|
let announced = AnnouncedConsoles::default();
|
||||||
|
announced.record("s1");
|
||||||
|
announced.record("s2");
|
||||||
|
announced.record("s1");
|
||||||
|
assert_eq!(announced.take_all(), vec!["s1", "s2"]);
|
||||||
|
assert!(announced.take_all().is_empty(), "taking clears the record");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn forget_drops_one_console_and_keeps_the_rest() {
|
||||||
|
let announced = AnnouncedConsoles::default();
|
||||||
|
announced.record("s1");
|
||||||
|
announced.record("s2");
|
||||||
|
announced.forget("s1");
|
||||||
|
announced.forget("never-recorded");
|
||||||
|
assert_eq!(announced.take_all(), vec!["s2"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_agents_end_asks_which_console_the_window_follows_off_its_own_thread() {
|
||||||
|
// The hook runs with the agent manager locked, and the followed check
|
||||||
|
// takes the console lock, which is held across `node` runs: asked
|
||||||
|
// there, typing into the terminal stalled behind a console stop.
|
||||||
|
let announced = Arc::new(AnnouncedConsoles::default());
|
||||||
|
let asked_on = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
let log = Arc::clone(&asked_on);
|
||||||
|
let hook = stop_announced_on_end(
|
||||||
|
Arc::clone(&announced),
|
||||||
|
move || {
|
||||||
|
log.lock().unwrap().push(std::thread::current().id());
|
||||||
|
None
|
||||||
|
},
|
||||||
|
|_| {},
|
||||||
|
);
|
||||||
|
announced.record("s1");
|
||||||
|
|
||||||
|
hook();
|
||||||
|
announced.finish_stops();
|
||||||
|
|
||||||
|
let asked_on = asked_on.lock().unwrap();
|
||||||
|
assert_eq!(asked_on.len(), 1, "asked once");
|
||||||
|
assert_ne!(asked_on[0], std::thread::current().id());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_agents_end_leaves_the_console_the_window_follows_and_keeps_it_recorded() {
|
||||||
|
// New Session ends the old agent while the window still shows its
|
||||||
|
// console: stopping it there only had the bar's poll bring it back as
|
||||||
|
// a server nobody tracked, which then outlived the quit.
|
||||||
|
let announced = Arc::new(AnnouncedConsoles::default());
|
||||||
|
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||||
|
let log = Arc::clone(&stopped);
|
||||||
|
let hook = stop_announced_on_end(
|
||||||
|
Arc::clone(&announced),
|
||||||
|
|| Some("followed".to_string()),
|
||||||
|
move |sid| log.lock().unwrap().push(sid.to_string()),
|
||||||
|
);
|
||||||
|
announced.record("followed");
|
||||||
|
announced.record("other");
|
||||||
|
|
||||||
|
hook();
|
||||||
|
announced.finish_stops();
|
||||||
|
|
||||||
|
assert_eq!(*stopped.lock().unwrap(), vec!["other"]);
|
||||||
|
assert_eq!(
|
||||||
|
announced.take_all(),
|
||||||
|
vec!["followed"],
|
||||||
|
"kept for the quit, or until the window moves on"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An agent that ended while the window showed its console `sid`.
|
||||||
|
fn left_under_the_window(sid: &'static str) -> Arc<AnnouncedConsoles> {
|
||||||
|
let announced = Arc::new(AnnouncedConsoles::default());
|
||||||
|
announced.record(sid);
|
||||||
|
let hook = stop_announced_on_end(
|
||||||
|
Arc::clone(&announced),
|
||||||
|
move || Some(sid.to_string()),
|
||||||
|
|sid| panic!("{sid} was stopped under the window"),
|
||||||
|
);
|
||||||
|
hook();
|
||||||
|
announced.finish_stops();
|
||||||
|
announced
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What `stop_left` stops once the window follows `followed`.
|
||||||
|
fn stopped_by_moving_to(announced: &AnnouncedConsoles, followed: &str) -> Vec<String> {
|
||||||
|
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||||
|
let log = Arc::clone(&stopped);
|
||||||
|
announced.stop_left(followed, move |sid| log.lock().unwrap().push(sid.into()));
|
||||||
|
announced.finish_stops();
|
||||||
|
let stopped = stopped.lock().unwrap().clone();
|
||||||
|
stopped
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_window_moving_on_stops_the_console_an_ended_agent_left_once() {
|
||||||
|
let announced = left_under_the_window("old");
|
||||||
|
announced.record("new");
|
||||||
|
assert!(stopped_by_moving_to(&announced, "old").is_empty(), "shown");
|
||||||
|
assert_eq!(stopped_by_moving_to(&announced, "new"), vec!["old"]);
|
||||||
|
assert!(stopped_by_moving_to(&announced, "new").is_empty(), "once");
|
||||||
|
assert_eq!(announced.take_all(), vec!["new"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_window_moving_on_never_stops_a_running_agents_console() {
|
||||||
|
// One agent may open a second session and still use the first.
|
||||||
|
let announced = AnnouncedConsoles::default();
|
||||||
|
announced.record("first");
|
||||||
|
announced.record("second");
|
||||||
|
assert!(stopped_by_moving_to(&announced, "second").is_empty());
|
||||||
|
|
||||||
|
// A new agent that joins the console an ended one left makes it its own.
|
||||||
|
let announced = left_under_the_window("joined");
|
||||||
|
announced.record("joined");
|
||||||
|
announced.record("second");
|
||||||
|
assert!(stopped_by_moving_to(&announced, "second").is_empty());
|
||||||
|
assert_eq!(announced.take_all(), vec!["joined", "second"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An agent's end whose console `old` the window shows, where `meanwhile`
|
||||||
|
/// runs right after the hook asked which console that is: what it stopped.
|
||||||
|
fn stopped_by_an_end_while<M>(meanwhile: M) -> (Vec<String>, Vec<String>)
|
||||||
|
where
|
||||||
|
M: Fn(&AnnouncedConsoles) -> &'static str + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
let announced = Arc::new(AnnouncedConsoles::default());
|
||||||
|
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||||
|
let (log, record) = (Arc::clone(&stopped), Arc::clone(&announced));
|
||||||
|
let shown = Mutex::new("old");
|
||||||
|
let hook = stop_announced_on_end(
|
||||||
|
Arc::clone(&announced),
|
||||||
|
move || {
|
||||||
|
let mut shown = shown.lock().unwrap();
|
||||||
|
let answer = shown.to_string();
|
||||||
|
if answer == "old" {
|
||||||
|
*shown = meanwhile(&record);
|
||||||
|
}
|
||||||
|
Some(answer)
|
||||||
|
},
|
||||||
|
move |sid| log.lock().unwrap().push(sid.to_string()),
|
||||||
|
);
|
||||||
|
announced.record("old");
|
||||||
|
hook();
|
||||||
|
announced.finish_stops();
|
||||||
|
let stopped = stopped.lock().unwrap().clone();
|
||||||
|
(stopped, announced.take_all())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_page_that_takes_the_window_while_an_agents_end_decides_still_stops_the_old_console() {
|
||||||
|
let (stopped, recorded) = stopped_by_an_end_while(|announced| {
|
||||||
|
announced.record("new");
|
||||||
|
announced.stop_left("new", |sid| panic!("{sid} is not left yet"));
|
||||||
|
"new"
|
||||||
|
});
|
||||||
|
assert_eq!(stopped, vec!["old"]);
|
||||||
|
assert_eq!(recorded, vec!["new"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_new_agent_that_joins_the_console_while_an_agents_end_decides_keeps_it() {
|
||||||
|
let (stopped, recorded) = stopped_by_an_end_while(|announced| {
|
||||||
|
announced.record("old");
|
||||||
|
announced.record("new");
|
||||||
|
"new"
|
||||||
|
});
|
||||||
|
assert!(stopped.is_empty(), "{stopped:?}");
|
||||||
|
assert_eq!(recorded, vec!["old", "new"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn finish_stops_waits_for_the_stop_a_new_page_started() {
|
||||||
|
// Quitting right after New Session: the exit must not cut it short.
|
||||||
|
let announced = left_under_the_window("old");
|
||||||
|
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||||
|
let log = Arc::clone(&stopped);
|
||||||
|
announced.stop_left("new", move |sid| {
|
||||||
|
std::thread::sleep(Duration::from_millis(300));
|
||||||
|
log.lock().unwrap().push(sid.to_string());
|
||||||
|
});
|
||||||
|
assert!(stopped.lock().unwrap().is_empty(), "it runs on a thread");
|
||||||
|
announced.finish_stops();
|
||||||
|
assert_eq!(*stopped.lock().unwrap(), vec!["old"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn finish_stops_waits_for_the_stops_an_agents_end_still_has_running() {
|
||||||
|
// Quitting right after an agent ended: the exit must not cut its
|
||||||
|
// consoles' stops short.
|
||||||
|
let announced = Arc::new(AnnouncedConsoles::default());
|
||||||
|
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||||
|
let log = Arc::clone(&stopped);
|
||||||
|
let hook = stop_announced_on_end(
|
||||||
|
Arc::clone(&announced),
|
||||||
|
|| None,
|
||||||
|
move |sid| {
|
||||||
|
std::thread::sleep(Duration::from_millis(300));
|
||||||
|
log.lock().unwrap().push(sid.to_string());
|
||||||
|
},
|
||||||
|
);
|
||||||
|
announced.record("s1");
|
||||||
|
|
||||||
|
hook();
|
||||||
|
assert!(
|
||||||
|
stopped.lock().unwrap().is_empty(),
|
||||||
|
"the stop runs on a thread"
|
||||||
|
);
|
||||||
|
announced.finish_stops();
|
||||||
|
|
||||||
|
assert_eq!(*stopped.lock().unwrap(), vec!["s1"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_console_call_runs_in_a_process_group_of_its_own() {
|
||||||
|
// Ctrl+C and a closing terminal signal the app's whole group: a stop
|
||||||
|
// already running there ended before it stopped its console.
|
||||||
|
let console = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console");
|
||||||
|
let mut child = node_command(&console)
|
||||||
|
.arg("help")
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.expect("node starts");
|
||||||
|
let pid = child.id() as i32;
|
||||||
|
// SAFETY: getpgid only reads; the child is not waited for yet, so its id is its own.
|
||||||
|
let group = unsafe { libc::getpgid(pid) };
|
||||||
|
let _ = child.wait();
|
||||||
|
assert_eq!(group, pid);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_apps_stop_calls_pass_force() {
|
fn the_apps_stop_calls_pass_force() {
|
||||||
let args = stop_args("20261101-120000-abcdef");
|
let args = stop_args("20261101-120000-abcdef");
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ pub mod attention;
|
|||||||
pub mod brief;
|
pub mod brief;
|
||||||
pub mod console_supervisor;
|
pub mod console_supervisor;
|
||||||
pub mod handoff;
|
pub mod handoff;
|
||||||
|
pub mod log;
|
||||||
pub mod loop_commit;
|
pub mod loop_commit;
|
||||||
pub mod loop_driver;
|
pub mod loop_driver;
|
||||||
pub mod loop_notify;
|
pub mod loop_notify;
|
||||||
@@ -28,5 +29,7 @@ pub mod session_reader;
|
|||||||
pub mod settings;
|
pub mod settings;
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
pub mod task_dialog;
|
pub mod task_dialog;
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub mod term_signal;
|
||||||
pub mod ui_confirm;
|
pub mod ui_confirm;
|
||||||
pub mod versions;
|
pub mod versions;
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
//! Lines for the app's log, its stderr, on the paths a quit takes. `eprintln!` panics when the
|
||||||
|
//! write fails, as it does once the terminal the app was started from has closed: the quit's
|
||||||
|
//! cleanup would end at its first line, with the app still open.
|
||||||
|
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
/// Writes one line, or nothing when the log cannot be written to.
|
||||||
|
pub fn line(text: &str) {
|
||||||
|
let _ = writeln!(std::io::stderr(), "{text}");
|
||||||
|
}
|
||||||
@@ -10,8 +10,13 @@ use plan2code_app_lib::agents::{self, Agent, PermissionMode};
|
|||||||
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
|
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
|
||||||
use plan2code_app_lib::attention::{self, Badge, Signal};
|
use plan2code_app_lib::attention::{self, Badge, Signal};
|
||||||
use plan2code_app_lib::console_supervisor::{
|
use plan2code_app_lib::console_supervisor::{
|
||||||
app_origin, origin_of, session_on_disk, ConsoleSupervisor,
|
app_origin, origin_of, session_on_disk, AnnouncedConsoles, ConsoleSupervisor,
|
||||||
};
|
};
|
||||||
|
#[cfg(unix)]
|
||||||
|
use plan2code_app_lib::console_supervisor::{
|
||||||
|
find_console_dir, stop_announced_on_end, stop_console_session,
|
||||||
|
};
|
||||||
|
use plan2code_app_lib::log;
|
||||||
use plan2code_app_lib::loop_driver::{self, Hooks, LastLoop, LoopFacts, LoopSlot};
|
use plan2code_app_lib::loop_driver::{self, Hooks, LastLoop, LoopFacts, LoopSlot};
|
||||||
use plan2code_app_lib::models;
|
use plan2code_app_lib::models;
|
||||||
use plan2code_app_lib::node_check;
|
use plan2code_app_lib::node_check;
|
||||||
@@ -44,6 +49,11 @@ struct AppState {
|
|||||||
page: PageChannel,
|
page: PageChannel,
|
||||||
// This window's endpoint for pages the agent's `console.mjs open` wants shown here.
|
// This window's endpoint for pages the agent's `console.mjs open` wants shown here.
|
||||||
announce: Arc<Mutex<Option<AnnounceServer>>>,
|
announce: Arc<Mutex<Option<AnnounceServer>>>,
|
||||||
|
// Every console session an agent announced and the window took, to stop
|
||||||
|
// when that agent ends or the app quits (macOS and Linux). On Windows the
|
||||||
|
// agent's Job Object ends them, so nothing there records or reads this.
|
||||||
|
#[cfg_attr(not(unix), allow(dead_code))]
|
||||||
|
announced: Arc<AnnouncedConsoles>,
|
||||||
// The Node check's result: it runs on a background thread after the
|
// The Node check's result: it runs on a background thread after the
|
||||||
// window opens (Task 9.10), so this is unchecked until it reports.
|
// window opens (Task 9.10), so this is unchecked until it reports.
|
||||||
node: Mutex<NodeReport>,
|
node: Mutex<NodeReport>,
|
||||||
@@ -152,13 +162,23 @@ fn platform_info() -> serde_json::Value {
|
|||||||
|
|
||||||
// What the launch card offers per agent: whether its CLI is on PATH (else how
|
// What the launch card offers per agent: whether its CLI is on PATH (else how
|
||||||
// to install it), and whether it takes its own reasoning effort; plus the
|
// to install it), and whether it takes its own reasoning effort; plus the
|
||||||
// warnings about agents.json.
|
// warnings about agents.json. A refresh runs the person's login shell, which
|
||||||
|
// can take seconds with a slow profile, so the work runs on a blocking thread:
|
||||||
|
// a sync command would run on the main thread and freeze the window meanwhile.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn agent_availability(refresh: Option<bool>) -> serde_json::Value {
|
async fn agent_availability(refresh: Option<bool>) -> Result<serde_json::Value, String> {
|
||||||
|
let refresh = refresh == Some(true);
|
||||||
|
tauri::async_runtime::spawn_blocking(move || agent_list(refresh))
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
// The agent list `agent_availability` answers with.
|
||||||
|
fn agent_list(refresh: bool) -> serde_json::Value {
|
||||||
// "Check again" also works the PATH out again and re-reads the shipped
|
// "Check again" also works the PATH out again and re-reads the shipped
|
||||||
// agent list, so a CLI whose installer added a new folder to PATH, or a
|
// agent list, so a CLI whose installer added a new folder to PATH, or a
|
||||||
// list an update rewrote, is seen without restarting the app.
|
// list an update rewrote, is seen without restarting the app.
|
||||||
if refresh == Some(true) {
|
if refresh {
|
||||||
node_check::refresh_path();
|
node_check::refresh_path();
|
||||||
agents::refresh_agent_list();
|
agents::refresh_agent_list();
|
||||||
}
|
}
|
||||||
@@ -318,16 +338,62 @@ fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
|
|||||||
let agent = Arc::new(AgentManager::new(dir, sink));
|
let agent = Arc::new(AgentManager::new(dir, sink));
|
||||||
agent.set_before_fresh(before_fresh_hook(state));
|
agent.set_before_fresh(before_fresh_hook(state));
|
||||||
agent.set_forget_session(forget_session_hook(state));
|
agent.set_forget_session(forget_session_hook(state));
|
||||||
|
// On Windows the agent's Job Object already ends every console it opened.
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
let project_dir = agent.folder().clone();
|
||||||
|
let console = Arc::clone(&state.console);
|
||||||
|
agent.set_ended(stop_announced_on_end(
|
||||||
|
Arc::clone(&state.announced),
|
||||||
|
move || followed_sid(&console),
|
||||||
|
move |sid| stop_announced_console(&project_dir, sid),
|
||||||
|
));
|
||||||
|
}
|
||||||
*guard = Some(Arc::clone(&agent));
|
*guard = Some(Arc::clone(&agent));
|
||||||
Ok(agent)
|
Ok(agent)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The session the window's console supervisor follows, if any.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn followed_sid(console: &Mutex<Option<ConsoleSupervisor>>) -> Option<String> {
|
||||||
|
console
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||||
|
.as_ref()
|
||||||
|
.map(|sup| sup.session().sid.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
// The project's folder, or the current one with none chosen.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn project_folder(state: &AppState) -> std::path::PathBuf {
|
||||||
|
state
|
||||||
|
.project
|
||||||
|
.lock()
|
||||||
|
.ok()
|
||||||
|
.and_then(|p| p.as_ref().map(|p| p.dir.clone()))
|
||||||
|
.unwrap_or_else(|| std::path::PathBuf::from("."))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stops one console an agent announced, from that agent's project folder; a
|
||||||
|
// failure is only logged, since nothing is left to tell.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn stop_announced_console(project_dir: &std::path::Path, sid: &str) {
|
||||||
|
let stopped = find_console_dir()
|
||||||
|
.and_then(|console_dir| stop_console_session(&console_dir, project_dir, sid));
|
||||||
|
if let Err(error) = stopped {
|
||||||
|
log::line(&format!(
|
||||||
|
"plan2code: could not stop the console {sid}: {error}"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// What New Session does before the fresh agent starts. It leaves the brief for
|
// What New Session does before the fresh agent starts. It leaves the brief for
|
||||||
// the dashboard, from the console session running now, then forgets that
|
// the dashboard, from the console session running now, then forgets that
|
||||||
// session, so the fresh agent's `open` starts one of its own: a session that
|
// session, so the fresh agent's `open` starts one of its own: a session that
|
||||||
// joined the old one would carry its meter along, still red after the very
|
// joined the old one would carry its meter along, still red after the very
|
||||||
// press the red meter asks for. The old console is left to shut itself down
|
// press the red meter asks for. The old console is left running under the
|
||||||
// once the frame moves on to the new page.
|
// window until the new page takes over: on macOS and Linux the app stops it
|
||||||
|
// then (`take_announced`); elsewhere it shuts itself down once its page is gone.
|
||||||
fn before_fresh_hook(state: &AppState) -> BeforeFresh {
|
fn before_fresh_hook(state: &AppState) -> BeforeFresh {
|
||||||
let console = Arc::clone(&state.console);
|
let console = Arc::clone(&state.console);
|
||||||
let announce = Arc::clone(&state.announce);
|
let announce = Arc::clone(&state.announce);
|
||||||
@@ -371,11 +437,13 @@ fn current_agent(state: &AppState) -> Option<Arc<AgentManager>> {
|
|||||||
// page from a loopback dev server, so the window is asked for its real URL.
|
// page from a loopback dev server, so the window is asked for its real URL.
|
||||||
/// A page the agent's `open` announced: the supervisor follows it, or adopts
|
/// A page the agent's `open` announced: the supervisor follows it, or adopts
|
||||||
/// it when the agent started the console (the app owns its stop from there).
|
/// it when the agent started the console (the app owns its stop from there).
|
||||||
/// Says whether the window should show it. A session outside this app's
|
/// Says whether the window should show it. The console an ended agent left
|
||||||
/// console store is refused: `cargo test` run by the agent inside the app
|
/// under the window stops here, since the window has moved on from it (macOS
|
||||||
/// once announced a test's throwaway console, the window followed it, and
|
/// and Linux). A session outside this app's console store is refused: `cargo
|
||||||
/// when the test shut it down the reconnect opened an empty dashboard, so the
|
/// test` run by the agent inside the app once announced a test's throwaway
|
||||||
/// build's own page was never seen again.
|
/// console, the window followed it, and when the test shut it down the
|
||||||
|
/// reconnect opened an empty dashboard, so the build's own page was never seen
|
||||||
|
/// again.
|
||||||
fn take_announced(
|
fn take_announced(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
notice: &PageNotice,
|
notice: &PageNotice,
|
||||||
@@ -392,6 +460,10 @@ fn take_announced(
|
|||||||
if notice.workflow == "setup" {
|
if notice.workflow == "setup" {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
// The agent opened it: it ends with that agent, or with the app (on
|
||||||
|
// Windows the agent's Job Object ends it).
|
||||||
|
#[cfg(unix)]
|
||||||
|
state.announced.record(¬ice.sid);
|
||||||
if let Ok(mut guard) = state.console.lock() {
|
if let Ok(mut guard) = state.console.lock() {
|
||||||
match guard.as_mut() {
|
match guard.as_mut() {
|
||||||
Some(sup) => sup.follow(¬ice.url, ¬ice.sid),
|
Some(sup) => sup.follow(¬ice.url, ¬ice.sid),
|
||||||
@@ -410,6 +482,13 @@ fn take_announced(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
let project_dir = project_folder(state);
|
||||||
|
state.announced.stop_left(¬ice.sid, move |sid| {
|
||||||
|
stop_announced_console(&project_dir, sid)
|
||||||
|
});
|
||||||
|
}
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -687,6 +766,17 @@ fn confirm_quit(app: &tauri::AppHandle) {
|
|||||||
QuitCase::Waiting => MessageDialogKind::Info,
|
QuitCase::Waiting => MessageDialogKind::Info,
|
||||||
QuitCase::Working => MessageDialogKind::Warning,
|
QuitCase::Working => MessageDialogKind::Warning,
|
||||||
};
|
};
|
||||||
|
// A close button pressed on a window in the background leaves the app inactive, and the
|
||||||
|
// window's web view does not take the first click on an inactive window, so the question
|
||||||
|
// would need a click to activate the window before Quit or Stay is heard. A minimized window
|
||||||
|
// would show it to nobody. So the window comes forward, as the key window, before it asks.
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
if let Some(window) = app.get_webview_window("main") {
|
||||||
|
if window.is_minimized().unwrap_or(false) {
|
||||||
|
let _ = window.unminimize();
|
||||||
|
}
|
||||||
|
let _ = window.set_focus();
|
||||||
|
}
|
||||||
// Off Windows the shell's own modal asks, with Stay first and focused, so Stay is the default
|
// Off Windows the shell's own modal asks, with Stay first and focused, so Stay is the default
|
||||||
// answer everywhere (the plugin's box makes Quit the default). The OS box is the fallback for a
|
// answer everywhere (the plugin's box makes Quit the default). The OS box is the fallback for a
|
||||||
// page that cannot show it. Both wait off the event loop.
|
// page that cannot show it. Both wait off the event loop.
|
||||||
@@ -737,22 +827,10 @@ fn agent_is_active(app: &tauri::AppHandle) -> bool {
|
|||||||
|| current_agent(&state).is_some_and(|agent| agent.is_active())
|
|| current_agent(&state).is_some_and(|agent| agent.is_active())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stops the loop, the agent, then the console, then exits. The loop goes first:
|
// Stops everything this app's work left running, then exits.
|
||||||
// its record is dropped without a word to the page, so its watch thread never
|
|
||||||
// takes the ended agent for a crash.
|
|
||||||
fn quit_app(app: &tauri::AppHandle) {
|
fn quit_app(app: &tauri::AppHandle) {
|
||||||
let restart = RESTART_ON_QUIT.lock().ok().and_then(|mut plan| plan.take());
|
let restart = RESTART_ON_QUIT.lock().ok().and_then(|mut plan| plan.take());
|
||||||
let state = app.state::<AppState>();
|
shutdown(app);
|
||||||
loop_driver::abandon(&state.loop_run);
|
|
||||||
review_loop::abandon(&state.review_run);
|
|
||||||
if let Some(agent) = current_agent(&state) {
|
|
||||||
agent.stop();
|
|
||||||
}
|
|
||||||
if let Ok(mut guard) = state.console.lock() {
|
|
||||||
if let Some(mut console) = guard.take() {
|
|
||||||
let _ = console.stop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(plan) = restart {
|
if let Some(plan) = restart {
|
||||||
if let Err(error) = spawn_restart(&plan) {
|
if let Err(error) = spawn_restart(&plan) {
|
||||||
eprintln!("plan2code: restart failed: {error}");
|
eprintln!("plan2code: restart failed: {error}");
|
||||||
@@ -761,6 +839,76 @@ fn quit_app(app: &tauri::AppHandle) {
|
|||||||
app.exit(0);
|
app.exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The one cleanup every quit runs: from `quit_app`, and on macOS and Linux
|
||||||
|
// from `RunEvent::Exit` too, for the routes that never pass through
|
||||||
|
// `quit_app`. A second call finds nothing left to stop.
|
||||||
|
fn shutdown(app: &tauri::AppHandle) {
|
||||||
|
let state = app.state::<AppState>();
|
||||||
|
shutdown_with(&state);
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
let project_dir = project_folder(&state);
|
||||||
|
stop_other_announced(&state, |sid| stop_announced_console(&project_dir, sid));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stops the loops, the agent, then the console, each before returning: the app
|
||||||
|
// may exit straight after, and a stop left to a thread would lose that race.
|
||||||
|
// The loops go first: their records are dropped without a word to the page, so
|
||||||
|
// their watch threads never take the ended agent for a crash.
|
||||||
|
fn shutdown_with(state: &AppState) {
|
||||||
|
loop_driver::abandon(&state.loop_run);
|
||||||
|
review_loop::abandon(&state.review_run);
|
||||||
|
if let Some(agent) = current_agent(state) {
|
||||||
|
agent.stop();
|
||||||
|
}
|
||||||
|
settle_agent_ends(state);
|
||||||
|
if let Ok(mut guard) = state.console.lock() {
|
||||||
|
if let Some(mut console) = guard.take() {
|
||||||
|
if let Err(error) = stop_supervised(state, &mut console) {
|
||||||
|
let sid = &console.session().sid;
|
||||||
|
log::line(&format!(
|
||||||
|
"plan2code: could not stop the console {sid}: {error}"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// macOS and Linux, after `shutdown_with`: stops every console an agent
|
||||||
|
// announced that is still recorded, each before returning. On Windows the
|
||||||
|
// agent's Job Object ends those consoles.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn stop_other_announced(state: &AppState, stop_sid: impl Fn(&str)) {
|
||||||
|
for sid in state.announced.take_all() {
|
||||||
|
stop_sid(&sid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Waits for what an agent's end or a new page still has running on a thread
|
||||||
|
// (macOS and Linux): stopping consoles, and, after an end, deciding whether to
|
||||||
|
// keep the one the window follows recorded. Called before taking the console
|
||||||
|
// lock to stop that console, since the end's thread takes the lock too, and a
|
||||||
|
// decision made after the stop would record it again.
|
||||||
|
fn settle_agent_ends(state: &AppState) {
|
||||||
|
#[cfg(unix)]
|
||||||
|
state.announced.finish_stops();
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
let _ = state;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stops the console the window follows and, on macOS and Linux, forgets it as
|
||||||
|
// an announced one, so no later agent's end or quit stops it again. Call
|
||||||
|
// `settle_agent_ends` before taking the console lock.
|
||||||
|
fn stop_supervised(state: &AppState, sup: &mut ConsoleSupervisor) -> Result<(), String> {
|
||||||
|
let stopped = sup.stop();
|
||||||
|
#[cfg(unix)]
|
||||||
|
state.announced.forget(&sup.session().sid);
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
let _ = state;
|
||||||
|
stopped
|
||||||
|
}
|
||||||
|
|
||||||
// The console page's state, told on every change (`attention` from the page):
|
// The console page's state, told on every change (`attention` from the page):
|
||||||
// the taskbar's dot for this system, and one flash on a change into the
|
// the taskbar's dot for this system, and one flash on a change into the
|
||||||
// person's move or needs attention while the window is not focused. An
|
// person's move or needs attention while the window is not focused. An
|
||||||
@@ -1140,9 +1288,10 @@ fn teardown_project(state: &AppState) -> Result<(), String> {
|
|||||||
agent.stop();
|
agent.stop();
|
||||||
}
|
}
|
||||||
*state.agent.lock().map_err(|e| e.to_string())? = None;
|
*state.agent.lock().map_err(|e| e.to_string())? = None;
|
||||||
|
settle_agent_ends(state);
|
||||||
if let Ok(mut guard) = state.console.lock() {
|
if let Ok(mut guard) = state.console.lock() {
|
||||||
if let Some(mut sup) = guard.take() {
|
if let Some(mut sup) = guard.take() {
|
||||||
let _ = sup.stop();
|
let _ = stop_supervised(state, &mut sup);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// The new project's agent asks the window which session is current and
|
// The new project's agent asks the window which session is current and
|
||||||
@@ -1310,8 +1459,13 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Stop the console but keep its supervisor, so a start after a stop opens
|
/// Stop the console but keep its supervisor, so a start after a stop opens
|
||||||
/// the same session again instead of finding nothing to start.
|
/// the same session again instead of finding nothing to start. Unlike the
|
||||||
|
/// other stops, this one leaves an announced console recorded: the supervisor
|
||||||
|
/// keeps its session to start it again, and from then on it stops as any
|
||||||
|
/// announced console does, with its agent, once the window moves on from one
|
||||||
|
/// an ended agent left, or at the quit.
|
||||||
fn console_stop_impl(state: &AppState) -> Result<(), String> {
|
fn console_stop_impl(state: &AppState) -> Result<(), String> {
|
||||||
|
settle_agent_ends(state);
|
||||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||||
if let Some(sup) = guard.as_mut() {
|
if let Some(sup) = guard.as_mut() {
|
||||||
sup.stop()?;
|
sup.stop()?;
|
||||||
@@ -1348,9 +1502,10 @@ fn console_setup_start_impl(state: &AppState, origin: &str) -> Result<serde_json
|
|||||||
// The setup console starts before the old one is stopped: a failed open
|
// The setup console starts before the old one is stopped: a failed open
|
||||||
// (a missing console.mjs, a dead session store) leaves what was showing.
|
// (a missing console.mjs, a dead session store) leaves what was showing.
|
||||||
let sup = ConsoleSupervisor::start_with_workflow(dir, origin.to_string(), "setup")?;
|
let sup = ConsoleSupervisor::start_with_workflow(dir, origin.to_string(), "setup")?;
|
||||||
|
settle_agent_ends(state);
|
||||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||||
if let Some(mut old) = guard.take() {
|
if let Some(mut old) = guard.take() {
|
||||||
let _ = old.stop();
|
let _ = stop_supervised(state, &mut old);
|
||||||
}
|
}
|
||||||
let session = serde_json::to_value(sup.session()).map_err(|e| e.to_string())?;
|
let session = serde_json::to_value(sup.session()).map_err(|e| e.to_string())?;
|
||||||
*guard = Some(sup);
|
*guard = Some(sup);
|
||||||
@@ -1591,7 +1746,7 @@ fn loop_stop_after_phase(
|
|||||||
// once. The page asked the person first ("End the agent now? This phase's
|
// once. The page asked the person first ("End the agent now? This phase's
|
||||||
// changes stay uncommitted."); the strip says Stopping, and the driver tells
|
// changes stay uncommitted."); the strip says Stopping, and the driver tells
|
||||||
// the stop screen on its next look.
|
// the stop screen on its next look.
|
||||||
#[tauri::command]
|
#[tauri::command(async)]
|
||||||
fn loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
fn loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||||
let agent = current_agent(&state);
|
let agent = current_agent(&state);
|
||||||
// The event goes out before the agent is ended (which can take a while), so
|
// The event goes out before the agent is ended (which can take a while), so
|
||||||
@@ -1696,7 +1851,7 @@ fn review_loop_stop_after(
|
|||||||
|
|
||||||
// Stop now: the flag first, then the agent ends at once. Nothing more is
|
// Stop now: the flag first, then the agent ends at once. Nothing more is
|
||||||
// committed; the stop screen offers Keep or Discard for the partial changes.
|
// committed; the stop screen offers Keep or Discard for the partial changes.
|
||||||
#[tauri::command]
|
#[tauri::command(async)]
|
||||||
fn review_loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
fn review_loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||||
let agent = current_agent(&state);
|
let agent = current_agent(&state);
|
||||||
review_loop::request_stop_now(&state.review_run, agent.as_deref(), |event| {
|
review_loop::request_stop_now(&state.review_run, agent.as_deref(), |event| {
|
||||||
@@ -1882,9 +2037,10 @@ fn loop_dashboard(state: State<'_, AppState>) -> Result<serde_json::Value, Strin
|
|||||||
if let Some(agent) = current_agent(&state) {
|
if let Some(agent) = current_agent(&state) {
|
||||||
agent.stop();
|
agent.stop();
|
||||||
}
|
}
|
||||||
|
settle_agent_ends(&state);
|
||||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||||
if let Some(mut sup) = guard.take() {
|
if let Some(mut sup) = guard.take() {
|
||||||
let _ = sup.stop();
|
let _ = stop_supervised(&state, &mut sup);
|
||||||
}
|
}
|
||||||
let sup = ConsoleSupervisor::start(dir, origin)?;
|
let sup = ConsoleSupervisor::start(dir, origin)?;
|
||||||
let session = serde_json::to_value(sup.session()).map_err(|e| e.to_string())?;
|
let session = serde_json::to_value(sup.session()).map_err(|e| e.to_string())?;
|
||||||
@@ -1903,21 +2059,25 @@ fn first_launch(app: &tauri::AppHandle) -> bool {
|
|||||||
|
|
||||||
// macOS gets a real menu bar: Plan2Code (About, Check for Updates, Help, Quit) and the standard Edit
|
// macOS gets a real menu bar: Plan2Code (About, Check for Updates, Help, Quit) and the standard Edit
|
||||||
// menu, so Copy, Paste and Select All work in the page's fields. The three custom items tell the
|
// menu, so Copy, Paste and Select All work in the page's fields. The three custom items tell the
|
||||||
// page (the same actions as the bar's "..." menu); Quit is the predefined one, and the exit it asks
|
// page (the same actions as the bar's "..." menu). Quit is the app's own item, id `quit` on Cmd+Q,
|
||||||
// for goes through the quit check in the run loop below.
|
// not the predefined one: that sends `terminate:`, which never raises `ExitRequested`, so it would
|
||||||
|
// quit with no prompt while an agent works.
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> {
|
fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> {
|
||||||
use tauri::menu::{MenuBuilder, MenuItemBuilder, SubmenuBuilder};
|
use tauri::menu::{MenuBuilder, MenuItemBuilder, SubmenuBuilder};
|
||||||
let about = MenuItemBuilder::with_id("about", "About Plan2Code").build(app)?;
|
let about = MenuItemBuilder::with_id("about", "About Plan2Code").build(app)?;
|
||||||
let check = MenuItemBuilder::with_id("check-updates", "Check for Updates...").build(app)?;
|
let check = MenuItemBuilder::with_id("check-updates", "Check for Updates...").build(app)?;
|
||||||
let help = MenuItemBuilder::with_id("help", "Plan2Code Help").build(app)?;
|
let help = MenuItemBuilder::with_id("help", "Plan2Code Help").build(app)?;
|
||||||
|
let quit = MenuItemBuilder::with_id("quit", "Quit Plan2Code")
|
||||||
|
.accelerator("CmdOrCtrl+Q")
|
||||||
|
.build(app)?;
|
||||||
let app_menu = SubmenuBuilder::new(app, "Plan2Code")
|
let app_menu = SubmenuBuilder::new(app, "Plan2Code")
|
||||||
.item(&about)
|
.item(&about)
|
||||||
.item(&check)
|
.item(&check)
|
||||||
.separator()
|
.separator()
|
||||||
.item(&help)
|
.item(&help)
|
||||||
.separator()
|
.separator()
|
||||||
.quit()
|
.item(&quit)
|
||||||
.build()?;
|
.build()?;
|
||||||
let edit = SubmenuBuilder::new(app, "Edit")
|
let edit = SubmenuBuilder::new(app, "Edit")
|
||||||
.undo()
|
.undo()
|
||||||
@@ -1934,11 +2094,56 @@ fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> {
|
|||||||
let id = event.id().as_ref();
|
let id = event.id().as_ref();
|
||||||
if matches!(id, "about" | "check-updates" | "help") {
|
if matches!(id, "about" | "check-updates" | "help") {
|
||||||
let _ = app.emit("app-menu", id);
|
let _ = app.emit("app-menu", id);
|
||||||
|
} else if id == "quit" {
|
||||||
|
request_quit(app.clone());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// macOS takes an app's Dock and Cmd+Tab icon from its `.app` bundle, but the app ships as a bare
|
||||||
|
// program (`tauri build --no-bundle`), so without this the Dock shows the generic "exec" icon.
|
||||||
|
// Tauri sets the icon this way in dev builds only; this does the same in every build.
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
const APP_ICON_ICNS: &[u8] = include_bytes!("../icons/icon.icns");
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
fn app_icon_image() -> Option<objc2::rc::Retained<objc2_app_kit::NSImage>> {
|
||||||
|
use objc2::AllocAnyThread;
|
||||||
|
let data = objc2_foundation::NSData::with_bytes(APP_ICON_ICNS);
|
||||||
|
objc2_app_kit::NSImage::initWithData(objc2_app_kit::NSImage::alloc(), &data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Runs from `setup`, on the main thread AppKit requires; anywhere else it only logs.
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
fn set_app_icon() {
|
||||||
|
let Some(mtm) = objc2::MainThreadMarker::new() else {
|
||||||
|
eprintln!("plan2code: the Dock icon can only be set on the main thread");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(icon) = app_icon_image() else {
|
||||||
|
eprintln!("plan2code: the app icon could not be read, so the Dock keeps the default one");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
|
||||||
|
// SAFETY: called on the main thread (checked above) with a valid image, as AppKit requires.
|
||||||
|
unsafe { app.setApplicationIconImage(Some(&icon)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// A bare program the launcher starts from a terminal is not made the active app, so its window
|
||||||
|
// opened behind that terminal. Once, at start: later shows of the window leave the active app
|
||||||
|
// alone.
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
fn activate_app() {
|
||||||
|
let Some(mtm) = objc2::MainThreadMarker::new() else {
|
||||||
|
eprintln!("plan2code: the app can only be activated on the main thread");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// `activate` needs macOS 14; this one works on every macOS the app runs on.
|
||||||
|
#[allow(deprecated)]
|
||||||
|
objc2_app_kit::NSApplication::sharedApplication(mtm).activateIgnoringOtherApps(true);
|
||||||
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let args = std::env::args().collect::<Vec<_>>();
|
let args = std::env::args().collect::<Vec<_>>();
|
||||||
tauri::Builder::default()
|
tauri::Builder::default()
|
||||||
@@ -2083,14 +2288,41 @@ fn main() {
|
|||||||
}
|
}
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
build_mac_menu(app)?;
|
build_mac_menu(app)?;
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
set_app_icon();
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
activate_app();
|
||||||
|
// A plain `kill`, Ctrl+C or a closed terminal runs the quit cleanup, then exits,
|
||||||
|
// instead of ending the app with its consoles still running. `shutdown`, not
|
||||||
|
// `quit_app`: a signal never starts a pending update's restart.
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
let handle = app.handle().clone();
|
||||||
|
if let Err(error) = plan2code_app_lib::term_signal::on_terminate(move || {
|
||||||
|
shutdown(&handle);
|
||||||
|
handle.exit(0);
|
||||||
|
}) {
|
||||||
|
eprintln!("plan2code: a signal may skip the quit cleanup: {error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
spawn_node_check(app.handle().clone());
|
spawn_node_check(app.handle().clone());
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.build(tauri::generate_context!())
|
.build(tauri::generate_context!())
|
||||||
.expect("error while building the Plan2Code app")
|
.expect("error while building the Plan2Code app")
|
||||||
.run(|app, event| {
|
.run(|app, event| {
|
||||||
// Cmd+Q and the app menu's Quit on macOS end the app without closing the
|
// The app is going, by whatever route: clean up here too. On macOS,
|
||||||
// window first. An exit asked for in code (`code` is set) is `quit_app`'s own.
|
// Dock Quit sends `terminate:`, which raises only this and never asks
|
||||||
|
// first, and a quit with no agent active still stops the console this
|
||||||
|
// way. After `quit_app` this finds nothing left.
|
||||||
|
#[cfg(unix)]
|
||||||
|
if let tauri::RunEvent::Exit = event {
|
||||||
|
shutdown(app);
|
||||||
|
}
|
||||||
|
// An exit nobody asked for in code (`code: None`) asks first while an
|
||||||
|
// agent works; one with `code` set is `quit_app`'s own. On macOS,
|
||||||
|
// Cmd+Q and the app menu's Quit go through the app's own Quit item
|
||||||
|
// (`build_mac_menu`), and Dock Quit never reaches here.
|
||||||
if let tauri::RunEvent::ExitRequested {
|
if let tauri::RunEvent::ExitRequested {
|
||||||
api, code: None, ..
|
api, code: None, ..
|
||||||
} = event
|
} = event
|
||||||
@@ -2186,6 +2418,202 @@ mod tests {
|
|||||||
let_go(&state);
|
let_go(&state);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Windows' Job Object ends an agent's consoles with it: nothing is recorded there.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn only_an_accepted_announce_is_recorded_for_the_agents_end() {
|
||||||
|
let state = state_for("project-a");
|
||||||
|
// Refused: outside the console store.
|
||||||
|
assert!(!take_announced(
|
||||||
|
&state,
|
||||||
|
¬ice("outside"),
|
||||||
|
app_origin().to_string(),
|
||||||
|
|_| false
|
||||||
|
));
|
||||||
|
// Refused: an announced setup page.
|
||||||
|
let mut setup = notice("setup-console");
|
||||||
|
setup.workflow = "setup".into();
|
||||||
|
assert!(!take_announced(
|
||||||
|
&state,
|
||||||
|
&setup,
|
||||||
|
app_origin().to_string(),
|
||||||
|
|_| true
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
state.announced.take_all().is_empty(),
|
||||||
|
"nothing refused is recorded"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Accepted while following a console, then while following none.
|
||||||
|
*state.console.lock().unwrap() = Some(following_the_build());
|
||||||
|
assert!(take_announced(
|
||||||
|
&state,
|
||||||
|
¬ice("followed"),
|
||||||
|
app_origin().to_string(),
|
||||||
|
|_| true
|
||||||
|
));
|
||||||
|
let_go(&state);
|
||||||
|
assert!(take_announced(
|
||||||
|
&state,
|
||||||
|
¬ice("adopted"),
|
||||||
|
app_origin().to_string(),
|
||||||
|
|_| true
|
||||||
|
));
|
||||||
|
let_go(&state);
|
||||||
|
assert_eq!(state.announced.take_all(), vec!["followed", "adopted"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn shutdown_stops_every_announced_console_once_and_is_safe_twice() {
|
||||||
|
let state = state_for("project-a");
|
||||||
|
state.announced.record("s1");
|
||||||
|
state.announced.record("s2");
|
||||||
|
let stopped = Mutex::new(Vec::<String>::new());
|
||||||
|
let stop = |sid: &str| stopped.lock().unwrap().push(sid.to_string());
|
||||||
|
|
||||||
|
shutdown_with(&state);
|
||||||
|
stop_other_announced(&state, stop);
|
||||||
|
assert_eq!(
|
||||||
|
*stopped.lock().unwrap(),
|
||||||
|
vec!["s1", "s2"],
|
||||||
|
"both, before returning"
|
||||||
|
);
|
||||||
|
|
||||||
|
shutdown_with(&state);
|
||||||
|
stop_other_announced(&state, stop);
|
||||||
|
assert_eq!(
|
||||||
|
stopped.lock().unwrap().len(),
|
||||||
|
2,
|
||||||
|
"a second shutdown stops nothing"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn shutdown_never_stops_the_followed_console_a_second_time() {
|
||||||
|
// The window follows the build's console, which the agent announced:
|
||||||
|
// the supervisor stops it, so the announced list must skip it.
|
||||||
|
let state = state_for("project-a");
|
||||||
|
*state.console.lock().unwrap() = Some(following_the_build());
|
||||||
|
state.announced.record("build");
|
||||||
|
state.announced.record("other");
|
||||||
|
let stopped = Mutex::new(Vec::<String>::new());
|
||||||
|
|
||||||
|
shutdown_with(&state);
|
||||||
|
stop_other_announced(&state, |sid| stopped.lock().unwrap().push(sid.to_string()));
|
||||||
|
|
||||||
|
assert_eq!(*stopped.lock().unwrap(), vec!["other"]);
|
||||||
|
assert!(
|
||||||
|
state.console.lock().unwrap().is_none(),
|
||||||
|
"the supervisor was taken"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn shutdown_waits_for_the_stops_an_agents_end_left_running() {
|
||||||
|
// The agent ended a moment before the quit: its hook is still
|
||||||
|
// stopping that agent's consoles on a thread the exit would cut short.
|
||||||
|
let state = state_for("project-a");
|
||||||
|
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||||
|
let log = Arc::clone(&stopped);
|
||||||
|
let ended = stop_announced_on_end(
|
||||||
|
Arc::clone(&state.announced),
|
||||||
|
|| None,
|
||||||
|
move |sid| {
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||||
|
log.lock().unwrap().push(sid.to_string());
|
||||||
|
},
|
||||||
|
);
|
||||||
|
state.announced.record("s1");
|
||||||
|
ended();
|
||||||
|
|
||||||
|
shutdown_with(&state);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
*stopped.lock().unwrap(),
|
||||||
|
vec!["s1"],
|
||||||
|
"done before returning"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_new_page_stops_the_console_an_ended_agent_left_under_the_window() {
|
||||||
|
// New Session: the old agent's console stayed up with no page in it,
|
||||||
|
// until the next agent's end, the quit or its own idle limit.
|
||||||
|
let state = state_for("project-a");
|
||||||
|
*state.console.lock().unwrap() = Some(following_the_build());
|
||||||
|
state.announced.record("build");
|
||||||
|
let console = Arc::clone(&state.console);
|
||||||
|
let ended = stop_announced_on_end(
|
||||||
|
Arc::clone(&state.announced),
|
||||||
|
move || followed_sid(&console),
|
||||||
|
|_| {},
|
||||||
|
);
|
||||||
|
ended();
|
||||||
|
state.announced.finish_stops();
|
||||||
|
|
||||||
|
assert!(take_announced(
|
||||||
|
&state,
|
||||||
|
¬ice("next"),
|
||||||
|
app_origin().to_string(),
|
||||||
|
|_| true
|
||||||
|
));
|
||||||
|
state.announced.finish_stops();
|
||||||
|
|
||||||
|
assert_eq!(state.announced.take_all(), vec!["next"]);
|
||||||
|
let_go(&state);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_console_the_app_stopped_is_forgotten_so_no_later_end_stops_it_again() {
|
||||||
|
// A project switch stops the console the window follows, which its
|
||||||
|
// agent announced: still recorded, the next project's agent's end and
|
||||||
|
// the quit each ran `console.mjs stop` on it again.
|
||||||
|
let state = state_for("project-a");
|
||||||
|
*state.console.lock().unwrap() = Some(following_the_build());
|
||||||
|
state.announced.record("build");
|
||||||
|
state.announced.record("other");
|
||||||
|
|
||||||
|
teardown_project(&state).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(state.announced.take_all(), vec!["other"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
#[test]
|
||||||
|
fn the_dock_icon_is_the_apps_own_icon_set_and_macos_can_read_it() {
|
||||||
|
let icon = app_icon_image().expect("NSImage reads the bundled icon.icns");
|
||||||
|
let size = icon.size();
|
||||||
|
assert!(
|
||||||
|
size.width > 0.0 && size.height > 0.0,
|
||||||
|
"a drawable image, not an empty one: {size:?}"
|
||||||
|
);
|
||||||
|
// The same artwork the bundle lists for macOS (`bundle.icon` in
|
||||||
|
// tauri.conf.json), not a copy: a renamed bundle icon fails here
|
||||||
|
// instead of leaving the Dock and the bundle apart.
|
||||||
|
let config: serde_json::Value = serde_json::from_slice(
|
||||||
|
&std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tauri.conf.json")).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
config["bundle"]["icon"]
|
||||||
|
.as_array()
|
||||||
|
.is_some_and(|icons| icons
|
||||||
|
.iter()
|
||||||
|
.any(|icon| icon.as_str() == Some("icons/icon.icns"))),
|
||||||
|
"the bundle lists icons/icon.icns: {}",
|
||||||
|
config["bundle"]["icon"]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
APP_ICON_ICNS,
|
||||||
|
std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/icons/icon.icns")).unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_page_from_the_console_store_is_followed() {
|
fn a_page_from_the_console_store_is_followed() {
|
||||||
let state = state_for("project-a");
|
let state = state_for("project-a");
|
||||||
@@ -2429,7 +2857,7 @@ mod tests {
|
|||||||
// Every entry carries the shared lookup's state: found (on PATH),
|
// Every entry carries the shared lookup's state: found (on PATH),
|
||||||
// outside (needing setup, not missing) or missing, with `folder` for
|
// outside (needing setup, not missing) or missing, with `folder` for
|
||||||
// where an outside hit lives.
|
// where an outside hit lives.
|
||||||
let json = agent_availability(None);
|
let json = agent_list(false);
|
||||||
let entries = json["agents"].as_array().unwrap();
|
let entries = json["agents"].as_array().unwrap();
|
||||||
assert!(!entries.is_empty());
|
assert!(!entries.is_empty());
|
||||||
let mut builtins = 0;
|
let mut builtins = 0;
|
||||||
@@ -2448,6 +2876,17 @@ mod tests {
|
|||||||
assert!(builtins >= 3, "claude, devin and codex are listed");
|
assert!(builtins >= 3, "claude, devin and codex are listed");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_availability_command_is_awaited_not_run_on_the_ui_thread() {
|
||||||
|
// Check again re-runs the login shell, then the interactive config
|
||||||
|
// (up to 5 s with slow ones). A sync command runs on the main thread and freezes the
|
||||||
|
// window that long, so the command is a future that hands the work
|
||||||
|
// to a blocking thread; awaiting it gives the same list.
|
||||||
|
let json = tauri::async_runtime::block_on(agent_availability(None))
|
||||||
|
.expect("the blocking task finished");
|
||||||
|
assert_eq!(json, agent_list(false));
|
||||||
|
}
|
||||||
|
|
||||||
/// A real console, the same way `tests/console_supervisor.rs` sets one
|
/// A real console, the same way `tests/console_supervisor.rs` sets one
|
||||||
/// up (see `console_test_env`). Keep the guard until the test ends: the
|
/// up (see `console_test_env`). Keep the guard until the test ends: the
|
||||||
/// console's variables must not change while its session is in use.
|
/// console's variables must not change while its session is in use.
|
||||||
@@ -2534,6 +2973,50 @@ mod tests {
|
|||||||
let _ = state.console.lock().unwrap().take().unwrap().stop();
|
let _ = state.console.lock().unwrap().take().unwrap().stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_console_the_bar_stopped_and_started_again_still_stops_at_the_quit() {
|
||||||
|
// The bar's Reconnect (or a skills update) stops the console its
|
||||||
|
// agent announced and starts it again on the same session. When the
|
||||||
|
// window then follows the next agent's page, the quit must still stop
|
||||||
|
// that console: once forgotten at the stop, it outlived the app.
|
||||||
|
let Some((_env, sup)) = real_console() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let state = state_for("project-a");
|
||||||
|
let sid = sup.session().sid.clone();
|
||||||
|
*state.console.lock().unwrap() = Some(sup);
|
||||||
|
state.announced.record(&sid);
|
||||||
|
|
||||||
|
console_stop_impl(&state).unwrap();
|
||||||
|
console_start_impl(&state).expect("a start after a stop works");
|
||||||
|
assert!(take_announced(
|
||||||
|
&state,
|
||||||
|
¬ice("next"),
|
||||||
|
app_origin().to_string(),
|
||||||
|
|_| true
|
||||||
|
));
|
||||||
|
let stopped_at_quit = Mutex::new(Vec::new());
|
||||||
|
stop_other_announced(&state, |sid| {
|
||||||
|
stopped_at_quit.lock().unwrap().push(sid.to_string())
|
||||||
|
});
|
||||||
|
|
||||||
|
// Stop the real console before asserting, so a failure leaves nothing running.
|
||||||
|
let console_dir = PathBuf::from(std::env::var("PLAN2CODE_CONSOLE_DIR").unwrap());
|
||||||
|
let project =
|
||||||
|
std::env::temp_dir().join(format!("p2c-main-test-project-{}", std::process::id()));
|
||||||
|
let _ = plan2code_app_lib::console_supervisor::stop_console_session(
|
||||||
|
&console_dir,
|
||||||
|
&project,
|
||||||
|
&sid,
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
stopped_at_quit.lock().unwrap().contains(&sid),
|
||||||
|
"the quit stops the console the bar started again: {:?}",
|
||||||
|
stopped_at_quit.lock().unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_slow_health_check_never_holds_the_console_lock() {
|
fn a_slow_health_check_never_holds_the_console_lock() {
|
||||||
// A server that takes the connection and never answers: the check
|
// A server that takes the connection and never answers: the check
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -19,7 +19,7 @@ pub const BATCH_INTERVAL: Duration = Duration::from_millis(16);
|
|||||||
/// On macOS and Linux the kill is a hang-up signal, which a program can ignore.
|
/// On macOS and Linux the kill is a hang-up signal, which a program can ignore.
|
||||||
/// This long after it, a command that is still running is killed outright.
|
/// This long after it, a command that is still running is killed outright.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
const HANGUP_GRACE: Duration = Duration::from_secs(2);
|
pub const HANGUP_GRACE: Duration = Duration::from_secs(2);
|
||||||
|
|
||||||
/// What to run, where, and how big the terminal starts.
|
/// What to run, where, and how big the terminal starts.
|
||||||
pub struct StartOptions {
|
pub struct StartOptions {
|
||||||
@@ -43,6 +43,11 @@ pub struct PtyHost {
|
|||||||
/// a process id that may have been given to something else.
|
/// a process id that may have been given to something else.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
exited: Arc<AtomicBool>,
|
exited: Arc<AtomicBool>,
|
||||||
|
/// Set once `end_group` has seen the process group empty (or killed what
|
||||||
|
/// was left of it), so `kill`'s late group kill never signals a group id
|
||||||
|
/// that may since have been given to something else.
|
||||||
|
#[cfg(unix)]
|
||||||
|
group_done: Arc<AtomicBool>,
|
||||||
/// A Windows Job Object the spawned process was assigned to, so ending
|
/// A Windows Job Object the spawned process was assigned to, so ending
|
||||||
/// it (`kill`, or this host simply being dropped) ends every process
|
/// it (`kill`, or this host simply being dropped) ends every process
|
||||||
/// still in it, not just the one directly spawned: a `cmd /c` npm shim's
|
/// still in it, not just the one directly spawned: a `cmd /c` npm shim's
|
||||||
@@ -150,6 +155,8 @@ impl PtyHost {
|
|||||||
pid,
|
pid,
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
exited: Arc::new(AtomicBool::new(false)),
|
exited: Arc::new(AtomicBool::new(false)),
|
||||||
|
#[cfg(unix)]
|
||||||
|
group_done: Arc::new(AtomicBool::new(false)),
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
job,
|
job,
|
||||||
})
|
})
|
||||||
@@ -171,7 +178,9 @@ impl PtyHost {
|
|||||||
.map_err(err)
|
.map_err(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// End the command. Safe to call while `wait` is blocked in another thread.
|
/// End the command and everything it started that is still in its process
|
||||||
|
/// group (on Windows, its Job Object). Safe to call while `wait` is
|
||||||
|
/// blocked in another thread.
|
||||||
pub fn kill(&self) -> Result<(), String> {
|
pub fn kill(&self) -> Result<(), String> {
|
||||||
let result = self.killer.lock().map_err(err)?.kill().map_err(err);
|
let result = self.killer.lock().map_err(err)?.kill().map_err(err);
|
||||||
// The job object, when there is one, ends the whole process tree:
|
// The job object, when there is one, ends the whole process tree:
|
||||||
@@ -187,22 +196,60 @@ impl PtyHost {
|
|||||||
if cfg!(windows) {
|
if cfg!(windows) {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
// portable-pty only sends SIGHUP on macOS and Linux; follow it with
|
// portable-pty only sends SIGHUP on macOS and Linux, and only to the
|
||||||
// SIGKILL if the command is still there after the grace period.
|
// command itself. It starts the command under `setsid`, so the
|
||||||
|
// command's pid is also its process group's id: hang up the whole
|
||||||
|
// group too, then, after the grace period, kill whatever of the group
|
||||||
|
// is still there. A process that left the group (`setsid`, a detached
|
||||||
|
// child) is out of reach here.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
if let Some(pid) = self.pid {
|
if let Some(pid) = self.pid {
|
||||||
|
// SAFETY: plain signal to the command's own process group.
|
||||||
|
unsafe { libc::kill(-(pid as i32), libc::SIGHUP) };
|
||||||
let exited = Arc::clone(&self.exited);
|
let exited = Arc::clone(&self.exited);
|
||||||
|
let group_done = Arc::clone(&self.group_done);
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
thread::sleep(HANGUP_GRACE);
|
thread::sleep(HANGUP_GRACE);
|
||||||
if !exited.load(Ordering::SeqCst) {
|
if !exited.load(Ordering::SeqCst) {
|
||||||
// SAFETY: plain signal to a process id the command still holds.
|
// SAFETY: plain signal to a process id the command still holds.
|
||||||
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
|
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
|
||||||
}
|
}
|
||||||
|
// The group outlives its leader while any member is left; signal 0
|
||||||
|
// only asks whether one is. Once `end_group` saw it gone, its id
|
||||||
|
// may belong to another group by now: leave it alone.
|
||||||
|
// SAFETY: plain signals to the command's own process group.
|
||||||
|
if !group_done.load(Ordering::SeqCst)
|
||||||
|
&& unsafe { libc::kill(-(pid as i32), 0) } == 0
|
||||||
|
{
|
||||||
|
unsafe { libc::kill(-(pid as i32), libc::SIGKILL) };
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// For after `kill` and `wait` when the app is about to exit: `kill`'s
|
||||||
|
/// grace thread dies with the app, so this blocks until nothing of the
|
||||||
|
/// command's process group is left, killing what is still there after
|
||||||
|
/// `HANGUP_GRACE`. A no-op on Windows, where `kill` ended the Job Object.
|
||||||
|
pub fn end_group(&self) {
|
||||||
|
#[cfg(unix)]
|
||||||
|
if let Some(pid) = self.pid {
|
||||||
|
let group = -(pid as i32);
|
||||||
|
let deadline = Instant::now() + HANGUP_GRACE;
|
||||||
|
// SAFETY: signal 0 only asks whether the group still has members.
|
||||||
|
while unsafe { libc::kill(group, 0) } == 0 {
|
||||||
|
if Instant::now() >= deadline {
|
||||||
|
// SAFETY: plain signal to the command's own process group.
|
||||||
|
unsafe { libc::kill(group, libc::SIGKILL) };
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
thread::sleep(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
self.group_done.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Block until the command ends and return its exit code. A command ended by
|
/// Block until the command ends and return its exit code. A command ended by
|
||||||
/// a signal reports 1.
|
/// a signal reports 1.
|
||||||
pub fn wait(&self) -> Result<u32, String> {
|
pub fn wait(&self) -> Result<u32, String> {
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
//! SIGTERM (a plain `kill`), SIGINT (Ctrl+C) and SIGHUP (the terminal closed) end a process at
|
||||||
|
//! once by default, so the app's quit cleanup never ran and the consoles its agents had opened
|
||||||
|
//! kept running. Here they are caught instead and handed to a thread of its own, which runs the
|
||||||
|
//! cleanup it was given, once. The handler only writes one byte to a pipe, which a signal handler
|
||||||
|
//! may safely do; the thread does the work.
|
||||||
|
//! A second SIGTERM or SIGINT ends the process at once, so a cleanup that stalls never leaves a
|
||||||
|
//! plain `kill` unable to end the app. A repeated SIGHUP does not: closing a terminal can send it
|
||||||
|
//! twice at once, from the shell and from the terminal itself, and the commands the cleanup runs
|
||||||
|
//! ignore it too.
|
||||||
|
//! Unix only: Windows has none of these to catch.
|
||||||
|
|
||||||
|
use std::io;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
|
||||||
|
|
||||||
|
/// The signals that run the cleanup.
|
||||||
|
const SIGNALS: [libc::c_int; 3] = [libc::SIGTERM, libc::SIGINT, libc::SIGHUP];
|
||||||
|
|
||||||
|
static INSTALLED: AtomicBool = AtomicBool::new(false);
|
||||||
|
static CAUGHT: AtomicBool = AtomicBool::new(false);
|
||||||
|
static WRITE_END: AtomicI32 = AtomicI32::new(-1);
|
||||||
|
|
||||||
|
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
|
||||||
|
unsafe fn errno() -> *mut libc::c_int {
|
||||||
|
libc::__error()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||||
|
unsafe fn errno() -> *mut libc::c_int {
|
||||||
|
libc::__errno_location()
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" fn on_signal(signal: libc::c_int) {
|
||||||
|
if CAUGHT.swap(true, Ordering::SeqCst) {
|
||||||
|
if signal != libc::SIGHUP {
|
||||||
|
// SAFETY: raise is async-signal-safe. SA_RESETHAND has put this signal's default
|
||||||
|
// action back, so it ends the process as the handler returns.
|
||||||
|
unsafe { libc::raise(signal) };
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let fd = WRITE_END.load(Ordering::Relaxed);
|
||||||
|
if fd < 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let byte = 1u8;
|
||||||
|
// SAFETY: write is async-signal-safe, and the end is non-blocking, so it never hangs the
|
||||||
|
// handler. errno is put back, since the code the signal interrupted may be about to read it.
|
||||||
|
unsafe {
|
||||||
|
let saved = *errno();
|
||||||
|
libc::write(fd, (&byte as *const u8).cast(), 1);
|
||||||
|
*errno() = saved;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn last_error(what: &str) -> io::Error {
|
||||||
|
let error = io::Error::last_os_error();
|
||||||
|
io::Error::new(error.kind(), format!("{what}: {error}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `cleanup` on a thread of its own the first time the process gets SIGTERM, SIGINT or
|
||||||
|
/// SIGHUP, instead of the process ending there; a second SIGTERM or SIGINT ends it. A signal the
|
||||||
|
/// process was started with ignored (`nohup` ignores SIGHUP) stays ignored. Once per process: a
|
||||||
|
/// second call is an error and changes nothing.
|
||||||
|
pub fn on_terminate(cleanup: impl FnOnce() + Send + 'static) -> io::Result<()> {
|
||||||
|
if INSTALLED.swap(true, Ordering::SeqCst) {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::AlreadyExists,
|
||||||
|
"the signal handler is already installed",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut ends = [0; 2];
|
||||||
|
// SAFETY: pipe fills the two-element array it is given.
|
||||||
|
if unsafe { libc::pipe(ends.as_mut_ptr()) } != 0 {
|
||||||
|
return Err(last_error("pipe"));
|
||||||
|
}
|
||||||
|
let [read_end, write_end] = ends;
|
||||||
|
// SAFETY: fcntl on the two descriptors just made. Close-on-exec keeps them out of the
|
||||||
|
// agents and consoles the app starts.
|
||||||
|
unsafe {
|
||||||
|
libc::fcntl(read_end, libc::F_SETFD, libc::FD_CLOEXEC);
|
||||||
|
libc::fcntl(write_end, libc::F_SETFD, libc::FD_CLOEXEC);
|
||||||
|
let flags = libc::fcntl(write_end, libc::F_GETFL);
|
||||||
|
libc::fcntl(write_end, libc::F_SETFL, flags | libc::O_NONBLOCK);
|
||||||
|
}
|
||||||
|
WRITE_END.store(write_end, Ordering::SeqCst);
|
||||||
|
std::thread::Builder::new()
|
||||||
|
.name("quit-signal".into())
|
||||||
|
.spawn(move || {
|
||||||
|
let mut byte = 0u8;
|
||||||
|
loop {
|
||||||
|
// SAFETY: a one-byte read into a local; it blocks until the handler writes.
|
||||||
|
let read = unsafe { libc::read(read_end, (&mut byte as *mut u8).cast(), 1) };
|
||||||
|
if read == 1 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if read < 0 && io::Error::last_os_error().kind() == io::ErrorKind::Interrupted {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// The pipe failed: no cleanup can be signalled any more, so none runs.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// For the commands the cleanup runs, which start with this process's ignored signals:
|
||||||
|
// a repeated SIGHUP would end one before it has done its work.
|
||||||
|
// SAFETY: ignoring a signal installs no handler.
|
||||||
|
unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) };
|
||||||
|
cleanup();
|
||||||
|
})?;
|
||||||
|
for signal in SIGNALS {
|
||||||
|
// SAFETY: a zeroed sigaction is a valid one to read the current action into, and, with the
|
||||||
|
// handler set and an empty mask, to install. SA_RESTART resumes the calls the signal
|
||||||
|
// interrupts elsewhere in the app, and SA_RESETHAND puts the default action back once the
|
||||||
|
// handler has run, so a second one ends the app; SIGHUP goes without it.
|
||||||
|
unsafe {
|
||||||
|
let mut action: libc::sigaction = std::mem::zeroed();
|
||||||
|
if libc::sigaction(signal, std::ptr::null(), &mut action) != 0 {
|
||||||
|
return Err(last_error("sigaction"));
|
||||||
|
}
|
||||||
|
if action.sa_sigaction == libc::SIG_IGN {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
action = std::mem::zeroed();
|
||||||
|
action.sa_sigaction = on_signal as extern "C" fn(libc::c_int) as libc::sighandler_t;
|
||||||
|
action.sa_flags = libc::SA_RESTART;
|
||||||
|
if signal != libc::SIGHUP {
|
||||||
|
action.sa_flags |= libc::SA_RESETHAND;
|
||||||
|
}
|
||||||
|
libc::sigemptyset(&mut action.sa_mask);
|
||||||
|
if libc::sigaction(signal, &action, std::ptr::null_mut()) != 0 {
|
||||||
|
return Err(last_error("sigaction"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "Plan2Code",
|
"productName": "Plan2Code",
|
||||||
"version": "3.2.3",
|
"version": "3.2.7",
|
||||||
"identifier": "com.plan2code.desktop",
|
"identifier": "com.plan2code.desktop",
|
||||||
"build": {
|
"build": {
|
||||||
"frontendDist": "../ui",
|
"frontendDist": "../ui",
|
||||||
|
|||||||
@@ -521,6 +521,197 @@ fn a_phase_start_runs_on_its_model_and_env_and_leaves_the_launch_choice_alone()
|
|||||||
h.manager.stop();
|
h.manager.stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Counts the manager's `ended` calls.
|
||||||
|
fn count_ends(h: &Harness) -> Arc<Mutex<usize>> {
|
||||||
|
let ends = Arc::new(Mutex::new(0));
|
||||||
|
let counter = Arc::clone(&ends);
|
||||||
|
h.manager.set_ended(Arc::new(move || {
|
||||||
|
*counter.lock().unwrap() += 1;
|
||||||
|
}));
|
||||||
|
ends
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait (briefly) for `ends` to reach `want`, then make sure it stays there.
|
||||||
|
fn expect_ends(h: &mut Harness, ends: &Arc<Mutex<usize>>, want: usize, what: &str) {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while *ends.lock().unwrap() < want && Instant::now() < deadline {
|
||||||
|
h.pump_for(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
// A late exit of an agent already counted must not count again.
|
||||||
|
h.pump_for(Duration::from_millis(500));
|
||||||
|
assert_eq!(*ends.lock().unwrap(), want, "{what}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ended_runs_once_for_an_agent_that_exits_by_itself() {
|
||||||
|
let mut h = Harness::new();
|
||||||
|
let ends = count_ends(&h);
|
||||||
|
h.start_and_wait_ready();
|
||||||
|
h.type_line("EXIT 7");
|
||||||
|
h.wait_state("Ended", |s| matches!(s.state, AgentState::Ended { .. }));
|
||||||
|
expect_ends(&mut h, &ends, 1, "one natural end");
|
||||||
|
// Nothing is running now: a stop ends nothing more.
|
||||||
|
h.manager.stop();
|
||||||
|
expect_ends(&mut h, &ends, 1, "a stop with no running agent");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ended_runs_once_for_a_stopped_agent_and_never_for_a_stop_of_none() {
|
||||||
|
let mut h = Harness::new();
|
||||||
|
let ends = count_ends(&h);
|
||||||
|
h.manager.stop();
|
||||||
|
expect_ends(&mut h, &ends, 0, "a stop before any start");
|
||||||
|
h.start_and_wait_ready();
|
||||||
|
h.manager.stop();
|
||||||
|
expect_ends(&mut h, &ends, 1, "one stop of a running agent");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ended_runs_once_for_the_old_agent_on_restart_and_on_a_fresh_start() {
|
||||||
|
let mut h = Harness::new();
|
||||||
|
let ends = count_ends(&h);
|
||||||
|
h.start_and_wait_ready();
|
||||||
|
h.manager.restart().unwrap();
|
||||||
|
h.wait_for_output(READY, 2);
|
||||||
|
expect_ends(&mut h, &ends, 1, "the restarted agent's old one");
|
||||||
|
h.manager
|
||||||
|
.start_fresh("/plan2code next".to_string())
|
||||||
|
.unwrap();
|
||||||
|
h.wait_for_output(READY, 3);
|
||||||
|
expect_ends(&mut h, &ends, 2, "the old agent a fresh start replaced");
|
||||||
|
h.manager.stop();
|
||||||
|
expect_ends(&mut h, &ends, 3, "the last agent, stopped");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_ended_agent_takes_the_consoles_it_announced_and_only_those() {
|
||||||
|
use plan2code_app_lib::console_supervisor::{stop_announced_on_end, AnnouncedConsoles};
|
||||||
|
|
||||||
|
let mut h = Harness::new();
|
||||||
|
let announced = Arc::new(AnnouncedConsoles::default());
|
||||||
|
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||||
|
let log = Arc::clone(&stopped);
|
||||||
|
h.manager.set_ended(stop_announced_on_end(
|
||||||
|
Arc::clone(&announced),
|
||||||
|
|| None,
|
||||||
|
move |sid| {
|
||||||
|
log.lock().unwrap().push(sid.to_string());
|
||||||
|
},
|
||||||
|
));
|
||||||
|
h.start_and_wait_ready();
|
||||||
|
announced.record("s1");
|
||||||
|
h.manager.stop();
|
||||||
|
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while stopped.lock().unwrap().is_empty() && Instant::now() < deadline {
|
||||||
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
// Recorded after the end: it belongs to whatever comes next.
|
||||||
|
announced.record("s2");
|
||||||
|
std::thread::sleep(Duration::from_millis(300));
|
||||||
|
assert_eq!(*stopped.lock().unwrap(), vec!["s1"]);
|
||||||
|
assert_eq!(announced.take_all(), vec!["s2"], "s2 was never taken");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts the harness's agent, has it leave a child that ignores the
|
||||||
|
/// terminal's hangup in its process group, and returns that child's pid.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn start_with_stray(h: &mut Harness) -> u32 {
|
||||||
|
h.start_and_wait_ready();
|
||||||
|
h.type_line("STRAY");
|
||||||
|
h.wait_for_output("STRAY ", 1);
|
||||||
|
let stray: u32 = h
|
||||||
|
.seen
|
||||||
|
.rsplit("STRAY ")
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.split(|c: char| !c.is_ascii_digit())
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.parse()
|
||||||
|
.expect("the stray child's pid");
|
||||||
|
assert!(process_alive(stray), "the stray child should be running");
|
||||||
|
stray
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Waits out the hangup grace for `stray` to go, then kills it if it is
|
||||||
|
/// still there, so a failing test leaves nothing running. True if it went.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn stray_gone(stray: u32) -> bool {
|
||||||
|
use plan2code_app_lib::pty_host::HANGUP_GRACE;
|
||||||
|
|
||||||
|
let deadline = Instant::now() + HANGUP_GRACE + Duration::from_secs(2);
|
||||||
|
while process_alive(stray) && Instant::now() < deadline {
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
let gone = !process_alive(stray);
|
||||||
|
if !gone {
|
||||||
|
let _ = std::process::Command::new("kill")
|
||||||
|
.args(["-9", &stray.to_string()])
|
||||||
|
.status();
|
||||||
|
}
|
||||||
|
gone
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An agent that ends by itself leaves its process group alone: work the
|
||||||
|
/// person asked it to leave running (a dev server it backgrounded) stays up,
|
||||||
|
/// as it did before the app ended process groups at all.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn an_agent_that_exits_by_itself_leaves_its_process_group_running() {
|
||||||
|
let mut h = Harness::new();
|
||||||
|
let stray = start_with_stray(&mut h);
|
||||||
|
h.type_line("EXIT 0");
|
||||||
|
h.wait_state("Ended", |s| matches!(s.state, AgentState::Ended { .. }));
|
||||||
|
assert!(
|
||||||
|
!stray_gone(stray),
|
||||||
|
"the stray child was ended with an agent that exited by itself"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An agent the app stops (quit, a project switch) takes its process group
|
||||||
|
/// with it, a child that ignores the terminal's hangup included.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_stopped_agent_takes_its_process_group_with_it() {
|
||||||
|
let mut h = Harness::new();
|
||||||
|
let stray = start_with_stray(&mut h);
|
||||||
|
h.manager.stop();
|
||||||
|
assert!(
|
||||||
|
stray_gone(stray),
|
||||||
|
"the stray child outlived its stopped agent"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Restart or New Session replaces the agent, and its process group goes
|
||||||
|
/// with the old one.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_replaced_agent_takes_its_process_group_with_it() {
|
||||||
|
let mut h = Harness::new();
|
||||||
|
let stray = start_with_stray(&mut h);
|
||||||
|
h.manager.restart().unwrap();
|
||||||
|
assert!(
|
||||||
|
stray_gone(stray),
|
||||||
|
"the stray child outlived its replaced agent"
|
||||||
|
);
|
||||||
|
h.manager.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Quitting right after New Session: the replaced agent's grace is still
|
||||||
|
/// running on a thread that would end with the app.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_stop_right_after_a_restart_waits_for_the_replaced_agents_process_group() {
|
||||||
|
let mut h = Harness::new();
|
||||||
|
let stray = start_with_stray(&mut h);
|
||||||
|
h.manager.restart().expect("restart");
|
||||||
|
h.manager.stop();
|
||||||
|
let left = process_alive(stray);
|
||||||
|
assert!(stray_gone(stray), "the stray child outlived its grace");
|
||||||
|
assert!(!left, "the stray child was still there when stop returned");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_phase_start_with_no_launch_choice_is_refused() {
|
fn a_phase_start_with_no_launch_choice_is_refused() {
|
||||||
let h = Harness::new();
|
let h = Harness::new();
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use std::path::PathBuf;
|
|||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use plan2code_app_lib::console_supervisor::{app_origin, ConsoleSupervisor};
|
use plan2code_app_lib::console_supervisor::{app_origin, stop_console_session, ConsoleSupervisor};
|
||||||
|
|
||||||
fn have_node() -> bool {
|
fn have_node() -> bool {
|
||||||
Command::new("node")
|
Command::new("node")
|
||||||
@@ -120,6 +120,38 @@ fn a_killed_console_is_dead_and_restarts() {
|
|||||||
sup.stop().expect("stop");
|
sup.stop().expect("stop");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stopping_a_session_by_id_never_panics() {
|
||||||
|
let Some(project) = setup() else { return };
|
||||||
|
// The console has nothing to stop for a session it does not know: that is
|
||||||
|
// not a failure.
|
||||||
|
assert_eq!(
|
||||||
|
stop_console_session(&repo_console_dir(), &project, "no-such-session"),
|
||||||
|
Ok(())
|
||||||
|
);
|
||||||
|
// A folder with no console in it is.
|
||||||
|
let empty = temp_dir("no-console");
|
||||||
|
let error = stop_console_session(&empty, &project, "no-such-session")
|
||||||
|
.expect_err("no console.mjs to run");
|
||||||
|
assert!(error.starts_with("console stop failed"), "{error}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_session_stopped_by_id_stops_answering() {
|
||||||
|
let Some(project) = setup() else { return };
|
||||||
|
let mut sup =
|
||||||
|
ConsoleSupervisor::start(project.clone(), app_origin().to_string()).expect("start");
|
||||||
|
assert!(until_health(&sup, true), "the console URL never answered");
|
||||||
|
let sid = sup.session().sid.clone();
|
||||||
|
|
||||||
|
stop_console_session(&repo_console_dir(), &project, &sid).expect("stop by id");
|
||||||
|
assert!(
|
||||||
|
until_health(&sup, false),
|
||||||
|
"the console still answered after stop_console_session()"
|
||||||
|
);
|
||||||
|
sup.stop().expect("a second stop is harmless");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_live_console_is_not_restarted() {
|
fn a_live_console_is_not_restarted() {
|
||||||
let Some(project) = setup() else { return };
|
let Some(project) = setup() else { return };
|
||||||
|
|||||||
@@ -103,6 +103,102 @@ fn kill_ends_a_running_step() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A grandchild that ignores hangup is still in the agent's process group
|
||||||
|
/// (portable-pty starts the agent under `setsid`), so `kill` must reach it
|
||||||
|
/// through the group once the grace is up. An ordinary grandchild already dies
|
||||||
|
/// with its shell, when the kernel hangs up the terminal, so it cannot show this.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn kill_ends_a_hangup_ignoring_grandchild_after_the_grace() {
|
||||||
|
use plan2code_app_lib::pty_host::HANGUP_GRACE;
|
||||||
|
|
||||||
|
let (host, pid) =
|
||||||
|
start_sh_with_grandchild("trap '' HUP; sleep 300 & echo GRANDCHILD=$! END; wait");
|
||||||
|
assert!(alive(pid), "the grandchild should be running before kill");
|
||||||
|
|
||||||
|
host.kill().unwrap();
|
||||||
|
host.wait().unwrap();
|
||||||
|
assert!(
|
||||||
|
gone_within(pid, HANGUP_GRACE + Duration::from_secs(2)),
|
||||||
|
"the hangup-ignoring grandchild outlived kill()"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An agent that ended by itself was never killed, so no grace thread of
|
||||||
|
/// `kill`'s is there to finish its group: only `end_group` can end the
|
||||||
|
/// grandchild that ignored the terminal's hangup.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn end_group_ends_what_a_command_that_exited_by_itself_left() {
|
||||||
|
let (host, pid) = start_sh_with_grandchild(
|
||||||
|
"(trap '' HUP; exec sleep 300) & echo GRANDCHILD=$! END; sleep 0.2; exit 0",
|
||||||
|
);
|
||||||
|
host.wait().unwrap();
|
||||||
|
assert!(alive(pid), "the grandchild outlived its shell, as set up");
|
||||||
|
|
||||||
|
host.end_group();
|
||||||
|
// Only the moment it takes the reaper to collect it.
|
||||||
|
assert!(
|
||||||
|
gone_within(pid, Duration::from_secs(1)),
|
||||||
|
"the grandchild outlived end_group()"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `script` under `/bin/sh -c` on a pty; it must print `GRANDCHILD=<pid> END`.
|
||||||
|
/// Returns the host and that pid.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn start_sh_with_grandchild(script: &str) -> (PtyHost, i32) {
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
let host = PtyHost::start(
|
||||||
|
StartOptions {
|
||||||
|
program: "/bin/sh".to_string(),
|
||||||
|
args: vec!["-c".to_string(), script.to_string()],
|
||||||
|
env: vec![],
|
||||||
|
cwd: None,
|
||||||
|
cols: 80,
|
||||||
|
rows: 24,
|
||||||
|
},
|
||||||
|
move |bytes| {
|
||||||
|
let _ = tx.send(bytes);
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("start the shell");
|
||||||
|
let mut seen = String::new();
|
||||||
|
wait_for(&host, &rx, &mut seen, " END");
|
||||||
|
let pid = seen
|
||||||
|
.rsplit("GRANDCHILD=")
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.split(|c: char| !c.is_ascii_digit())
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.parse()
|
||||||
|
.expect("the grandchild's pid");
|
||||||
|
(host, pid)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn alive(pid: i32) -> bool {
|
||||||
|
// SAFETY: signal 0 only asks whether the process exists.
|
||||||
|
unsafe { libc::kill(pid, 0) == 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `pid` is gone within `within`; killed on the way out either way,
|
||||||
|
/// so a failing test leaves nothing behind.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn gone_within(pid: i32, within: Duration) -> bool {
|
||||||
|
let deadline = Instant::now() + within;
|
||||||
|
while alive(pid) && Instant::now() < deadline {
|
||||||
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
let gone = !alive(pid);
|
||||||
|
if !gone {
|
||||||
|
// SAFETY: a process this test started.
|
||||||
|
unsafe { libc::kill(pid, libc::SIGKILL) };
|
||||||
|
}
|
||||||
|
gone
|
||||||
|
}
|
||||||
|
|
||||||
/// An npm `.cmd` shim: `cmd.exe` is the directly spawned process, the real
|
/// An npm `.cmd` shim: `cmd.exe` is the directly spawned process, the real
|
||||||
/// program (here, the fake agent) its grandchild. `kill` must end both, not
|
/// program (here, the fake agent) its grandchild. `kill` must end both, not
|
||||||
/// just `cmd.exe` (Task 9.8).
|
/// just `cmd.exe` (Task 9.8).
|
||||||
|
|||||||
@@ -0,0 +1,263 @@
|
|||||||
|
//! The signals that end the app against the handler that turns them into its quit cleanup. A
|
||||||
|
//! file of its own, so the handler lives in a test process of its own: without it, a signal below
|
||||||
|
//! ends the whole process and the run fails. The handler installs once per process, so every
|
||||||
|
//! other case runs in a child: this test binary again, running only `signal_child`.
|
||||||
|
#![cfg(unix)]
|
||||||
|
|
||||||
|
use std::io::{BufRead, BufReader, IsTerminal, Write};
|
||||||
|
use std::os::fd::{FromRawFd, OwnedFd};
|
||||||
|
use std::os::unix::process::ExitStatusExt;
|
||||||
|
use std::process::{Child, Command, ExitStatus, Stdio};
|
||||||
|
use std::sync::mpsc::channel;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use plan2code_app_lib::{log, term_signal};
|
||||||
|
|
||||||
|
/// Names the case, and is set only in the child process a test starts.
|
||||||
|
const CHILD: &str = "P2C_TERM_SIGNAL_CHILD";
|
||||||
|
|
||||||
|
/// The child's exit codes: its cleanup ran to the end, or it did not when it should have.
|
||||||
|
const CLEANED: i32 = 0;
|
||||||
|
const NOT_CLEANED: i32 = 3;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_sigterm_runs_the_cleanup_instead_of_ending_the_process() {
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
term_signal::on_terminate(move || {
|
||||||
|
let _ = tx.send(());
|
||||||
|
})
|
||||||
|
.expect("the handler installs");
|
||||||
|
raise(libc::SIGTERM);
|
||||||
|
rx.recv_timeout(Duration::from_secs(5))
|
||||||
|
.expect("the cleanup ran after SIGTERM");
|
||||||
|
// A second install is refused: one signal, one cleanup.
|
||||||
|
assert!(term_signal::on_terminate(|| {}).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ctrl_c_and_a_closed_terminal_run_the_cleanup_too() {
|
||||||
|
for case in ["sigint", "sighup"] {
|
||||||
|
let status = outcome(child(case).spawn().expect("the child starts"));
|
||||||
|
assert_eq!(status.code(), Some(CLEANED), "{case}: {status:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_second_signal_ends_the_app_while_its_cleanup_still_runs() {
|
||||||
|
// A cleanup that stalls must not leave a plain `kill` or Ctrl+C unable to
|
||||||
|
// end the app, whichever signal started it.
|
||||||
|
for (case, ends_by) in [
|
||||||
|
("sigterm twice", libc::SIGTERM),
|
||||||
|
("sigint twice", libc::SIGINT),
|
||||||
|
("sighup then sigterm", libc::SIGTERM),
|
||||||
|
] {
|
||||||
|
let status = outcome(child(case).spawn().expect("the child starts"));
|
||||||
|
assert_eq!(status.signal(), Some(ends_by), "{case}: {status:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_repeated_sighup_lets_the_cleanup_finish() {
|
||||||
|
// Closing a terminal can send it twice at once: zsh passes it on to the
|
||||||
|
// program in front, and the terminal's own hangup sends it again.
|
||||||
|
let status = outcome(child("sighup twice").spawn().expect("the child starts"));
|
||||||
|
assert_eq!(status.code(), Some(CLEANED), "{status:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_signal_the_app_was_started_with_ignored_stays_ignored() {
|
||||||
|
// `nohup` starts a program with SIGHUP ignored, to outlive its terminal.
|
||||||
|
let status = outcome(child("ignored sighup").spawn().expect("the child starts"));
|
||||||
|
assert_eq!(status.code(), Some(CLEANED), "{status:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_command_the_cleanup_runs_outlives_a_repeated_sighup() {
|
||||||
|
// The cleanup stops consoles by running `node`, which the second SIGHUP of
|
||||||
|
// a closed terminal would end before it stopped anything.
|
||||||
|
let status = outcome(child("command").spawn().expect("the child starts"));
|
||||||
|
assert_eq!(status.code(), Some(CLEANED), "{status:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cleanup_that_logs_after_its_terminal_is_gone_still_finishes() {
|
||||||
|
for case in ["sighup, closed terminal", "sigterm, closed terminal"] {
|
||||||
|
logs_to_a_closed_terminal(case);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs the child on a terminal of its own, and closes that terminal once the
|
||||||
|
/// child has its handler.
|
||||||
|
fn logs_to_a_closed_terminal(case: &str) {
|
||||||
|
let (mut master, mut slave) = (-1, -1);
|
||||||
|
// SAFETY: openpty fills the two descriptors; the name and settings are optional.
|
||||||
|
let opened = unsafe {
|
||||||
|
libc::openpty(
|
||||||
|
&mut master,
|
||||||
|
&mut slave,
|
||||||
|
std::ptr::null_mut(),
|
||||||
|
std::ptr::null_mut(),
|
||||||
|
std::ptr::null_mut(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
assert_eq!(opened, 0, "openpty: {}", std::io::Error::last_os_error());
|
||||||
|
// SAFETY: both descriptors were just opened, and nothing else owns them. Close-on-exec keeps
|
||||||
|
// the terminal's other end out of the child, which would hold it open.
|
||||||
|
let (master, slave) = unsafe {
|
||||||
|
libc::fcntl(master, libc::F_SETFD, libc::FD_CLOEXEC);
|
||||||
|
(OwnedFd::from_raw_fd(master), OwnedFd::from_raw_fd(slave))
|
||||||
|
};
|
||||||
|
let mut child = child(case)
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::from(slave))
|
||||||
|
.spawn()
|
||||||
|
.expect("the child starts");
|
||||||
|
let stdout = child.stdout.take().expect("the child's stdout is piped");
|
||||||
|
let ready = BufReader::new(stdout)
|
||||||
|
.lines()
|
||||||
|
.map_while(Result::ok)
|
||||||
|
.any(|line| line.ends_with("ready"));
|
||||||
|
assert!(ready, "the child installed the handler");
|
||||||
|
drop(master);
|
||||||
|
let status = outcome(child);
|
||||||
|
assert_eq!(status.code(), Some(CLEANED), "{case}: {status:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn raise(signal: libc::c_int) {
|
||||||
|
// SAFETY: raise only sends this process a signal.
|
||||||
|
assert_eq!(unsafe { libc::raise(signal) }, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This test binary again, running only `signal_child` on `case`.
|
||||||
|
fn child(case: &str) -> Command {
|
||||||
|
let mut command = Command::new(std::env::current_exe().expect("the test binary"));
|
||||||
|
command
|
||||||
|
.args(["--exact", "signal_child", "--test-threads=1", "--nocapture"])
|
||||||
|
.env(CHILD, case)
|
||||||
|
.stdout(Stdio::null())
|
||||||
|
.stderr(Stdio::null());
|
||||||
|
command
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the child ended, within 30 s.
|
||||||
|
fn outcome(mut child: Child) -> ExitStatus {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(30);
|
||||||
|
loop {
|
||||||
|
if let Some(status) = child.try_wait().expect("the child can be waited on") {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
if Instant::now() > deadline {
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
panic!("the child neither ended nor exited within 30 s");
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Not a check on its own: the child process of the tests above. Run any other
|
||||||
|
/// way, it returns at once.
|
||||||
|
#[test]
|
||||||
|
fn signal_child() {
|
||||||
|
let Some(case) = std::env::var_os(CHILD) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// A signal this run was started with ignored (`nohup`, a script's `&`)
|
||||||
|
// would stay ignored, and no case below means that one.
|
||||||
|
for signal in [libc::SIGTERM, libc::SIGINT, libc::SIGHUP] {
|
||||||
|
// SAFETY: putting a signal's default action back installs no handler.
|
||||||
|
unsafe { libc::signal(signal, libc::SIG_DFL) };
|
||||||
|
}
|
||||||
|
match case.to_str().expect("a case name") {
|
||||||
|
"sigint" => cleans_up_after(&[libc::SIGINT]),
|
||||||
|
"sighup" => cleans_up_after(&[libc::SIGHUP]),
|
||||||
|
"sighup twice" => cleans_up_after(&[libc::SIGHUP, libc::SIGHUP]),
|
||||||
|
"sigterm twice" => ends_during_the_cleanup(libc::SIGTERM, libc::SIGTERM),
|
||||||
|
"sigint twice" => ends_during_the_cleanup(libc::SIGINT, libc::SIGINT),
|
||||||
|
"sighup then sigterm" => ends_during_the_cleanup(libc::SIGHUP, libc::SIGTERM),
|
||||||
|
"ignored sighup" => ignores_sighup(),
|
||||||
|
"command" => runs_a_command_through_a_sighup(),
|
||||||
|
"sighup, closed terminal" => logs_after_its_terminal_closed(libc::SIGHUP),
|
||||||
|
"sigterm, closed terminal" => logs_after_its_terminal_closed(libc::SIGTERM),
|
||||||
|
other => panic!("no such case: {other}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cleanup takes a moment, so a signal that ends the app would cut it short.
|
||||||
|
fn cleans_up_after(signals: &[libc::c_int]) {
|
||||||
|
term_signal::on_terminate(|| {
|
||||||
|
std::thread::sleep(Duration::from_millis(300));
|
||||||
|
std::process::exit(CLEANED);
|
||||||
|
})
|
||||||
|
.expect("the handler installs");
|
||||||
|
for signal in signals {
|
||||||
|
raise(*signal);
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_secs(5));
|
||||||
|
std::process::exit(NOT_CLEANED);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ends_during_the_cleanup(first: libc::c_int, second: libc::c_int) {
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
term_signal::on_terminate(move || {
|
||||||
|
let _ = tx.send(());
|
||||||
|
// A cleanup that never finishes.
|
||||||
|
loop {
|
||||||
|
std::thread::sleep(Duration::from_secs(60));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.expect("the handler installs");
|
||||||
|
raise(first);
|
||||||
|
rx.recv_timeout(Duration::from_secs(5))
|
||||||
|
.expect("the first signal started the cleanup");
|
||||||
|
raise(second);
|
||||||
|
// Still running: the second signal was swallowed.
|
||||||
|
std::thread::sleep(Duration::from_secs(2));
|
||||||
|
std::process::exit(NOT_CLEANED);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ignores_sighup() {
|
||||||
|
// SAFETY: ignoring a signal installs no handler.
|
||||||
|
unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) };
|
||||||
|
term_signal::on_terminate(|| std::process::exit(NOT_CLEANED)).expect("the handler installs");
|
||||||
|
raise(libc::SIGHUP);
|
||||||
|
std::thread::sleep(Duration::from_secs(1));
|
||||||
|
std::process::exit(CLEANED);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn runs_a_command_through_a_sighup() {
|
||||||
|
term_signal::on_terminate(|| {
|
||||||
|
let status = Command::new("/bin/sh")
|
||||||
|
.args(["-c", "kill -HUP $$; exit 0"])
|
||||||
|
.status()
|
||||||
|
.expect("sh runs");
|
||||||
|
std::process::exit(if status.success() {
|
||||||
|
CLEANED
|
||||||
|
} else {
|
||||||
|
NOT_CLEANED
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.expect("the handler installs");
|
||||||
|
raise(libc::SIGHUP);
|
||||||
|
std::thread::sleep(Duration::from_secs(5));
|
||||||
|
std::process::exit(NOT_CLEANED);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn logs_after_its_terminal_closed(signal: libc::c_int) {
|
||||||
|
assert!(std::io::stderr().is_terminal(), "stderr is a terminal");
|
||||||
|
term_signal::on_terminate(|| {
|
||||||
|
log::line("a line from the cleanup");
|
||||||
|
std::process::exit(CLEANED);
|
||||||
|
})
|
||||||
|
.expect("the handler installs");
|
||||||
|
println!("ready");
|
||||||
|
// Closed once a write fails: macOS reports neither a hangup nor a lost terminal here.
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(10);
|
||||||
|
while std::io::stderr().write_all(b".").is_ok() {
|
||||||
|
assert!(Instant::now() < deadline, "the terminal never closed");
|
||||||
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
|
}
|
||||||
|
raise(signal);
|
||||||
|
std::thread::sleep(Duration::from_secs(5));
|
||||||
|
std::process::exit(NOT_CLEANED);
|
||||||
|
}
|
||||||
+67
-6
@@ -972,6 +972,29 @@ let helloTimer = null;
|
|||||||
// Nothing has shown here yet: no agent has opened the dashboard. No polling,
|
// Nothing has shown here yet: no agent has opened the dashboard. No polling,
|
||||||
// no "reconnect" button makes sense until that first page lands.
|
// no "reconnect" button makes sense until that first page lands.
|
||||||
let consoleKnown = false;
|
let consoleKnown = false;
|
||||||
|
// Which console the checks below ask about. A project switch moves it on, so
|
||||||
|
// an answer that comes back afterward is about a console that is gone.
|
||||||
|
let consoleEpoch = 0;
|
||||||
|
|
||||||
|
// The project moved on, and its console was stopped on purpose: nothing is
|
||||||
|
// known here again until the new agent opens a page. Left known, the next
|
||||||
|
// poll found no console and put "The console stopped" over the new agent's
|
||||||
|
// start, or the launch card; left in the frame, the old page showed its "Lost
|
||||||
|
// contact" around it.
|
||||||
|
function forgetConsole() {
|
||||||
|
consoleEpoch += 1;
|
||||||
|
consoleKnown = false;
|
||||||
|
clearInterval(pollTimer);
|
||||||
|
pollTimer = null;
|
||||||
|
clearTimeout(helloTimer);
|
||||||
|
currentUrl = null;
|
||||||
|
frameReady = false;
|
||||||
|
// As for any page going away (loadFrame): its taskbar dot and its game go too.
|
||||||
|
clearAttention();
|
||||||
|
setGameFull(false);
|
||||||
|
frame.src = 'about:blank';
|
||||||
|
markConsoleAlive();
|
||||||
|
}
|
||||||
|
|
||||||
function loadFrame(url) {
|
function loadFrame(url) {
|
||||||
currentUrl = url;
|
currentUrl = url;
|
||||||
@@ -1252,6 +1275,7 @@ setWindowTheme(document.documentElement.getAttribute('data-theme') === 'light' ?
|
|||||||
// No hello in time: ask the console why, and say so with a way forward.
|
// No hello in time: ask the console why, and say so with a way forward.
|
||||||
async function onNoHello() {
|
async function onNoHello() {
|
||||||
if (frameReady || !consoleKnown || restarting) return;
|
if (frameReady || !consoleKnown || restarting) return;
|
||||||
|
const epoch = consoleEpoch;
|
||||||
// A page that does not answer cannot say it is done needing the person.
|
// A page that does not answer cannot say it is done needing the person.
|
||||||
clearAttention();
|
clearAttention();
|
||||||
// The next phase's console is on its way; the poll says so instead. Look
|
// The next phase's console is on its way; the poll says so instead. Look
|
||||||
@@ -1267,6 +1291,7 @@ async function onNoHello() {
|
|||||||
} catch {
|
} catch {
|
||||||
// The status check itself failed; treat it as a console that is not answering.
|
// The status check itself failed; treat it as a console that is not answering.
|
||||||
}
|
}
|
||||||
|
if (epoch !== consoleEpoch) return;
|
||||||
if (!status || status.state !== 'running') {
|
if (!status || status.state !== 'running') {
|
||||||
showState('The console stopped, so the page could not show.', 'Reconnect the console', reconnectConsole);
|
showState('The console stopped, so the page could not show.', 'Reconnect the console', reconnectConsole);
|
||||||
} else {
|
} else {
|
||||||
@@ -1434,12 +1459,15 @@ let pollTimer = null;
|
|||||||
// on its own session. The app never opens a dashboard on its own (the agent
|
// on its own session. The app never opens a dashboard on its own (the agent
|
||||||
// does, by running the skill), so there is nothing to start before that.
|
// does, by running the skill), so there is nothing to start before that.
|
||||||
async function reconnectConsole() {
|
async function reconnectConsole() {
|
||||||
|
const epoch = consoleEpoch;
|
||||||
markConsoleAlive();
|
markConsoleAlive();
|
||||||
showState('Reconnecting to the console...');
|
showState('Reconnecting to the console...');
|
||||||
try {
|
try {
|
||||||
const info = await invoke('console_start');
|
const info = await invoke('console_start');
|
||||||
|
if (epoch !== consoleEpoch) return;
|
||||||
loadFrame(info.url);
|
loadFrame(info.url);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (epoch !== consoleEpoch) return;
|
||||||
showErrorState(error, 'reach the console', 'Retry', reconnectConsole);
|
showErrorState(error, 'reach the console', 'Retry', reconnectConsole);
|
||||||
// An old console cannot be framed: the fix is the skills update, so offer it.
|
// An old console cannot be framed: the fix is the skills update, so offer it.
|
||||||
if (String(error).includes('too old')) setVersionState({ kind: 'too-old' });
|
if (String(error).includes('too old')) setVersionState({ kind: 'too-old' });
|
||||||
@@ -1453,8 +1481,10 @@ const RECONNECT_LIMIT = 3;
|
|||||||
let reconnects = 0;
|
let reconnects = 0;
|
||||||
|
|
||||||
async function pollConsole() {
|
async function pollConsole() {
|
||||||
|
const epoch = consoleEpoch;
|
||||||
try {
|
try {
|
||||||
const status = await invoke('console_status');
|
const status = await invoke('console_status');
|
||||||
|
if (epoch !== consoleEpoch) return;
|
||||||
if (status.state === 'running') {
|
if (status.state === 'running') {
|
||||||
markConsoleAlive();
|
markConsoleAlive();
|
||||||
return;
|
return;
|
||||||
@@ -2101,7 +2131,7 @@ function afterProjectKnown() {
|
|||||||
// tears the old project's agent and console down before the new one is
|
// 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
|
// remembered, so nothing from it carries over. Cancel (or Escape) leaves
|
||||||
// the current project as it was; the folder already open is not listed.
|
// the current project as it was; the folder already open is not listed.
|
||||||
async function doChangeProject() {
|
async function doChangeProject(prior = null) {
|
||||||
try {
|
try {
|
||||||
const dir = await showFolderPicker({ dialog: true });
|
const dir = await showFolderPicker({ dialog: true });
|
||||||
if (!dir) {
|
if (!dir) {
|
||||||
@@ -2115,15 +2145,46 @@ async function doChangeProject() {
|
|||||||
setProjectDir(dir);
|
setProjectDir(dir);
|
||||||
if (appState) appState.projectDir = dir;
|
if (appState) appState.projectDir = dir;
|
||||||
restarting = false;
|
restarting = false;
|
||||||
currentUrl = null;
|
forgetConsole();
|
||||||
frameReady = false;
|
// An agent was in use: start the same one (agent, model, effort and
|
||||||
afterProjectKnown();
|
// 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) {
|
} 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() {
|
async function changeProject() {
|
||||||
|
const prior = priorAgentSettings();
|
||||||
if (agentActive()) {
|
if (agentActive()) {
|
||||||
const yes = await confirmModal({
|
const yes = await confirmModal({
|
||||||
title: 'Stop the running agent and switch to a different project?',
|
title: 'Stop the running agent and switch to a different project?',
|
||||||
@@ -2133,7 +2194,7 @@ async function changeProject() {
|
|||||||
});
|
});
|
||||||
if (!yes) return;
|
if (!yes) return;
|
||||||
}
|
}
|
||||||
doChangeProject();
|
doChangeProject(prior);
|
||||||
}
|
}
|
||||||
|
|
||||||
changeProjectBtn.onclick = () => {
|
changeProjectBtn.onclick = () => {
|
||||||
|
|||||||
@@ -110,6 +110,12 @@ export function lastAgentNotice(list, remembered) {
|
|||||||
export function barNextSteps({ consoleDead = false, version = null, newRelease = null, updatedTo = null, notReplaced = null } = {}) {
|
export function barNextSteps({ consoleDead = false, version = null, newRelease = null, updatedTo = null, notReplaced = null } = {}) {
|
||||||
const v = version || {};
|
const v = version || {};
|
||||||
const steps = [];
|
const steps = [];
|
||||||
|
const rel = newRelease || {};
|
||||||
|
const notes = rel.latest ? { label: "What's new", url: releaseNotesUrl(rel.latest) } : null;
|
||||||
|
// A release that is merely out, with no update under way: while skills are ahead of the app,
|
||||||
|
// the lead step below offers it, so the same button is not shown twice.
|
||||||
|
const releasePlain = Boolean(rel.latest) && !rel.restartNeeded && rel.updating === undefined && !rel.failed;
|
||||||
|
let aheadOffersUpdate = false;
|
||||||
if (v.kind === 'updated') {
|
if (v.kind === 'updated') {
|
||||||
steps.push({ id: 'updated', text: 'Skills updated', title: 'Updated. Reconnect the console to use the new version.', tone: 'ok', action: 'restart-console' });
|
steps.push({ id: 'updated', text: 'Skills updated', title: 'Updated. Reconnect the console to use the new version.', tone: 'ok', action: 'restart-console' });
|
||||||
} else if (consoleDead) {
|
} else if (consoleDead) {
|
||||||
@@ -134,7 +140,15 @@ export function barNextSteps({ consoleDead = false, version = null, newRelease =
|
|||||||
steps.push({ id: 'failed', text: 'Update failed', title: String(v.error || 'The update did not finish.'), tone: 'err', action: 'update' });
|
steps.push({ id: 'failed', text: 'Update failed', title: String(v.error || 'The update did not finish.'), tone: 'err', action: 'update' });
|
||||||
break;
|
break;
|
||||||
case 'ahead':
|
case 'ahead':
|
||||||
steps.push({ id: 'ahead', text: `Skills v${v.skills} are newer than this app`, title: `The installed skills are v${v.skills}, newer than this app (v${v.app}). Get the new app.`, tone: 'warn', action: null });
|
// The skills are ahead of the app, so another Update skills run cannot help: the release's
|
||||||
|
// Update and restart replaces the app file. While that is under way, failed or waiting for
|
||||||
|
// a restart, its own step below says so instead.
|
||||||
|
if (releasePlain) {
|
||||||
|
steps.push({ id: 'ahead', text: `Update to latest: v${rel.latest}`, title: `The installed skills are v${v.skills}, newer than this app (v${v.app}). Update and restart installs v${rel.latest}; nothing needs a terminal.`, tone: 'warn', action: 'update-restart', link: notes });
|
||||||
|
aheadOffersUpdate = true;
|
||||||
|
} else if (!rel.latest) {
|
||||||
|
steps.push({ id: 'ahead', text: `App v${v.app} is older than the skills (v${v.skills})`, title: `The installed skills are v${v.skills}, newer than this app (v${v.app}). Get the new app.`, tone: 'warn', action: null });
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
@@ -144,8 +158,6 @@ export function barNextSteps({ consoleDead = false, version = null, newRelease =
|
|||||||
// `{ latest, failed: reason }`, `{ latest, restartNeeded: true }` (installed, waiting for the
|
// `{ latest, failed: reason }`, `{ latest, restartNeeded: true }` (installed, waiting for the
|
||||||
// restart) or `{ problem }` (the check could not run); `updatedTo` is the version the app
|
// restart) or `{ problem }` (the check could not run); `updatedTo` is the version the app
|
||||||
// restarted into, shown once.
|
// restarted into, shown once.
|
||||||
const rel = newRelease || {};
|
|
||||||
const notes = rel.latest ? { label: "What's new", url: releaseNotesUrl(rel.latest) } : null;
|
|
||||||
if (rel.latest) {
|
if (rel.latest) {
|
||||||
const latest = rel.latest;
|
const latest = rel.latest;
|
||||||
if (rel.restartNeeded) {
|
if (rel.restartNeeded) {
|
||||||
@@ -155,7 +167,7 @@ export function barNextSteps({ consoleDead = false, version = null, newRelease =
|
|||||||
steps.push({ id: 'new-release', text: line, title: line, tone: 'warn', busy: true, action: null });
|
steps.push({ id: 'new-release', text: line, title: line, tone: 'warn', busy: true, action: null });
|
||||||
} else if (rel.failed) {
|
} else if (rel.failed) {
|
||||||
steps.push({ id: 'new-release', text: 'Update failed', title: `${rel.failed} Plan2Code is still running as it was. You can try again, or run \`${NEW_RELEASE_COMMAND}\` in a terminal.`, tone: 'err', action: 'update-restart', link: notes });
|
steps.push({ id: 'new-release', text: 'Update failed', title: `${rel.failed} Plan2Code is still running as it was. You can try again, or run \`${NEW_RELEASE_COMMAND}\` in a terminal.`, tone: 'err', action: 'update-restart', link: notes });
|
||||||
} else {
|
} else if (!aheadOffersUpdate) {
|
||||||
steps.push({ id: 'new-release', text: `Update available: v${latest}`, title: `Plan2Code v${latest} is out. Update and restart installs it; nothing needs a terminal.`, tone: 'warn', action: 'update-restart', link: notes });
|
steps.push({ id: 'new-release', text: `Update available: v${latest}`, title: `Plan2Code v${latest} is out. Update and restart installs it; nothing needs a terminal.`, tone: 'warn', action: 'update-restart', link: notes });
|
||||||
}
|
}
|
||||||
} else if (rel.problem) {
|
} else if (rel.problem) {
|
||||||
@@ -762,7 +774,10 @@ export function shortcutFromMessage(data) {
|
|||||||
* What a key press does in the terminal's clipboard handling: "copy" (Ctrl+Shift+C, Cmd+C, and
|
* What a key press does in the terminal's clipboard handling: "copy" (Ctrl+Shift+C, Cmd+C, and
|
||||||
* Ctrl+C while text is selected, the Windows Terminal rule: with nothing selected Ctrl+C is the
|
* Ctrl+C while text is selected, the Windows Terminal rule: with nothing selected Ctrl+C is the
|
||||||
* interrupt and returns null), "paste" (Ctrl+V, Ctrl+Shift+V, Cmd+V), or null. With `mac`, a plain
|
* interrupt and returns null), "paste" (Ctrl+V, Ctrl+Shift+V, Cmd+V), or null. With `mac`, a plain
|
||||||
* Ctrl+C is always the interrupt, as in every macOS terminal: copy there is Cmd+C.
|
* Ctrl+C is always the interrupt, as in every macOS terminal: copy there is Cmd+C. Ctrl+V belongs to
|
||||||
|
* the agent there too (Claude Code pastes an image with it), and Cmd+V returns null as well: it is
|
||||||
|
* left to the webview's own paste event, which xterm takes as one paste, because reading the
|
||||||
|
* clipboard from script makes WebKit ask with a Paste menu before the text arrives.
|
||||||
*/
|
*/
|
||||||
export function clipboardAction(event, hasSelection, { mac = false } = {}) {
|
export function clipboardAction(event, hasSelection, { mac = false } = {}) {
|
||||||
if (!event || event.altKey) return null;
|
if (!event || event.altKey) return null;
|
||||||
@@ -772,7 +787,7 @@ export function clipboardAction(event, hasSelection, { mac = false } = {}) {
|
|||||||
if (event.ctrlKey && !event.metaKey) return event.shiftKey || (hasSelection && !mac) ? 'copy' : null;
|
if (event.ctrlKey && !event.metaKey) return event.shiftKey || (hasSelection && !mac) ? 'copy' : null;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (key === 'v' && (event.ctrlKey || event.metaKey)) return 'paste';
|
if (key === 'v' && !mac && (event.ctrlKey || event.metaKey)) return 'paste';
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -139,7 +139,7 @@ export async function mountTerminal(container, { onInput, onResize, onFontSize,
|
|||||||
// Ctrl+C copies while text is selected and is the interrupt otherwise (the Windows Terminal
|
// Ctrl+C copies while text is selected and is the interrupt otherwise (the Windows Terminal
|
||||||
// rule; on a Mac it is always the interrupt); Ctrl+Shift+C and Cmd+C always copy.
|
// rule; on a Mac it is always the interrupt); Ctrl+Shift+C and Cmd+C always copy.
|
||||||
// preventDefault on the paste keys: the browser's own paste event would otherwise reach the
|
// preventDefault on the paste keys: the browser's own paste event would otherwise reach the
|
||||||
// terminal a second time.
|
// terminal a second time. On a Mac no key is a paste key here: Cmd+V is that own paste event.
|
||||||
const action = clipboardAction(event, term.hasSelection(), { mac: IS_MAC });
|
const action = clipboardAction(event, term.hasSelection(), { mac: IS_MAC });
|
||||||
if (action === 'copy') {
|
if (action === 'copy') {
|
||||||
copySelection();
|
copySelection();
|
||||||
|
|||||||
@@ -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,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 };
|
||||||
|
}
|
||||||
@@ -124,6 +124,25 @@ export async function openSession(browser, { t, workflow, payload: first, projec
|
|||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Stands a real window in for the desktop app that frames the page, listening
|
||||||
|
// to what the page tells it (kept in window.__told); the returned function
|
||||||
|
// replies the way the app's window does.
|
||||||
|
export async function frameInFakeApp(s) {
|
||||||
|
await s.page.evaluate(() => {
|
||||||
|
const frame = document.createElement("iframe");
|
||||||
|
frame.hidden = true;
|
||||||
|
document.body.appendChild(frame);
|
||||||
|
const app = frame.contentWindow;
|
||||||
|
window.__told = [];
|
||||||
|
app.postMessage = (message) => window.__told.push(message);
|
||||||
|
Object.defineProperty(window, "parent", { value: app, configurable: true });
|
||||||
|
});
|
||||||
|
return (data) =>
|
||||||
|
s.page.evaluate((message) => {
|
||||||
|
window.dispatchEvent(new MessageEvent("message", { source: window.parent, data: message }));
|
||||||
|
}, data);
|
||||||
|
}
|
||||||
|
|
||||||
// Waits until the document has not changed for `quietMs`, or `maxMs` at most (a page that never
|
// Waits until the document has not changed for `quietMs`, or `maxMs` at most (a page that never
|
||||||
// goes quiet must not block a test). Counts mutations in the page and polls the count from
|
// goes quiet must not block a test). Counts mutations in the page and polls the count from
|
||||||
// here, so it needs no timer in the page.
|
// here, so it needs no timer in the page.
|
||||||
|
|||||||
@@ -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));
|
||||||
|
}
|
||||||
@@ -119,6 +119,16 @@ test("each version state reads and acts as the old version bar did", () => {
|
|||||||
const [ahead] = barNextSteps({ version: { kind: "ahead", skills: "3.2.0", app: "3.1.0" } });
|
const [ahead] = barNextSteps({ version: { kind: "ahead", skills: "3.2.0", app: "3.1.0" } });
|
||||||
assert.equal(ahead.action, null, "another Update skills run cannot help when the skills are ahead");
|
assert.equal(ahead.action, null, "another Update skills run cannot help when the skills are ahead");
|
||||||
assert.match(ahead.title, /newer than this app \(v3\.1\.0\)\. Get the new app\./);
|
assert.match(ahead.title, /newer than this app \(v3\.1\.0\)\. Get the new app\./);
|
||||||
|
assert.equal(ahead.text, "App v3.1.0 is older than the skills (v3.2.0)", "no release known: the plain facts, never 'Skills ... are newer'");
|
||||||
|
// A release is out: the same step offers Update and restart, and the release step is not shown twice.
|
||||||
|
const leadSteps = barNextSteps({ version: { kind: "ahead", skills: "3.2.5", app: "3.2.4" }, newRelease: { latest: "3.2.5" } });
|
||||||
|
assert.deepEqual(leadSteps.map((step) => [step.id, step.text, step.action]), [["ahead", "Update to latest: v3.2.5", "update-restart"]]);
|
||||||
|
assert.match(leadSteps[0].title, /Update and restart installs v3\.2\.5/);
|
||||||
|
assert.equal(leadSteps[0].link.label, "What's new");
|
||||||
|
// While it runs, fails or waits for the restart, the release's own step says so, with no second button.
|
||||||
|
for (const newRelease of [{ latest: "3.2.5", updating: "Downloading" }, { latest: "3.2.5", failed: "No." }, { latest: "3.2.5", restartNeeded: true }]) {
|
||||||
|
assert.deepEqual(barNextSteps({ version: { kind: "ahead", skills: "3.2.5", app: "3.2.4" }, newRelease }).map((step) => step.id), ["new-release"]);
|
||||||
|
}
|
||||||
const [updating] = barNextSteps({ version: { kind: "updating", line: "Installing skills (4 of 9)" } });
|
const [updating] = barNextSteps({ version: { kind: "updating", line: "Installing skills (4 of 9)" } });
|
||||||
assert.deepEqual([updating.text, updating.busy, updating.action], ["Installing skills (4 of 9)", true, null], "no button while it runs");
|
assert.deepEqual([updating.text, updating.busy, updating.action], ["Installing skills (4 of 9)", true, null], "no button while it runs");
|
||||||
const [remains] = barNextSteps({ version: { kind: "remains", skills: "3.0.0", app: "3.1.0" } });
|
const [remains] = barNextSteps({ version: { kind: "remains", skills: "3.0.0", app: "3.1.0" } });
|
||||||
@@ -530,6 +540,31 @@ test("app.js refills the reconnect budget on a new page and brings the page back
|
|||||||
assert.match(app.slice(app.indexOf("async function showLoopEnd"), app.indexOf("function applyLoopState")), /reconnectConsole\(\)/);
|
assert.match(app.slice(app.indexOf("async function showLoopEnd"), app.indexOf("function applyLoopState")), /reconnectConsole\(\)/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("app.js forgets the old project's console on a project switch, so no check of it covers the new agent's start or the launch card", () => {
|
||||||
|
const app = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "app.js"), "utf8");
|
||||||
|
const at = app.indexOf("function forgetConsole");
|
||||||
|
assert.ok(at > 0, "left known, the old console's poll put \"The console stopped\" over the new agent's start, or the launch card, five seconds after a switch");
|
||||||
|
const forget = app.slice(at, app.indexOf("\n}\n", at));
|
||||||
|
assert.match(forget, /consoleKnown = false/, "nothing is known again until the new agent opens a page");
|
||||||
|
assert.match(forget, /clearInterval\(pollTimer\);\s*pollTimer = null/, "the poll stops, and showAnnounced can start it again");
|
||||||
|
assert.match(forget, /clearTimeout\(helloTimer\)/, "a hello still awaited from the old page is not waited for");
|
||||||
|
assert.match(forget, /markConsoleAlive\(\)/, "the bar drops a Console stopped it was showing");
|
||||||
|
assert.match(forget, /frame\.src = 'about:blank'/, "the stopped console's page leaves the frame, or its Lost contact shows around the launch card");
|
||||||
|
assert.match(forget, /clearAttention\(\);\s*setGameFull\(false\)/, "and takes its taskbar dot and its full-screen game with it, as loadFrame does");
|
||||||
|
assert.match(forget, /consoleEpoch \+= 1/, "a check already under way can tell the project moved on");
|
||||||
|
const change = app.slice(app.indexOf("async function doChangeProject"), app.indexOf("function changeProject"));
|
||||||
|
assert.match(change, /forgetConsole\(\);[^}]*if \(prior\) await startPriorAgent\(prior\);\s*else afterProjectKnown\(\)/s, "forgotten before the new agent starts or the launch card shows");
|
||||||
|
// Each check that waits on the app answers for the console it asked about.
|
||||||
|
for (const name of ["onNoHello", "reconnectConsole", "pollConsole"]) {
|
||||||
|
const from = app.indexOf(`async function ${name}`);
|
||||||
|
const body = app.slice(from, app.indexOf("\n}\n", from));
|
||||||
|
assert.match(body, /const epoch = consoleEpoch;/, `${name} notes which console it asks about`);
|
||||||
|
const awaits = body.split("await invoke(").length - 1;
|
||||||
|
const guards = body.split("if (epoch !== consoleEpoch) return;").length - 1;
|
||||||
|
assert.ok(guards >= awaits, `${name} drops an answer that comes back after a switch (${guards} checks for ${awaits} waits)`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("the window title says a loop is running, and when it needs the person", () => {
|
test("the window title says a loop is running, and when it needs the person", () => {
|
||||||
assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Build" }), "Loop: Phase 2 of 7 - lunch");
|
assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Build" }), "Loop: Phase 2 of 7 - lunch");
|
||||||
assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Waiting on you" }), "Loop needs you: Phase 2 - lunch");
|
assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Waiting on you" }), "Loop needs you: Phase 2 - lunch");
|
||||||
@@ -1373,6 +1408,36 @@ test("clipboardAction: Ctrl+C copies only with a selection (else it is the inter
|
|||||||
assert.equal(clipboardAction(null, true), null);
|
assert.equal(clipboardAction(null, true), null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("clipboardAction on a Mac: Ctrl+V goes to the agent, Cmd+V is left to the webview's own paste", () => {
|
||||||
|
const ev = (key, mods = {}) => ({ key, ctrlKey: false, metaKey: false, shiftKey: false, altKey: false, ...mods });
|
||||||
|
assert.equal(clipboardAction(ev("v", { ctrlKey: true }), false, { mac: true }), null, "xterm sends \\x16 to the agent (Claude Code's image paste)");
|
||||||
|
assert.equal(clipboardAction(ev("V", { ctrlKey: true, shiftKey: true }), false, { mac: true }), null);
|
||||||
|
assert.equal(clipboardAction(ev("v", { metaKey: true }), false, { mac: true }), null, "a script clipboard read makes WebKit ask with a Paste menu first");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("clipboardAction off a Mac: every key decides exactly as before the Mac rule", () => {
|
||||||
|
// The rule as it was before Ctrl+V was left to the agent on a Mac.
|
||||||
|
const before = (event, hasSelection) => {
|
||||||
|
if (event.altKey) return null;
|
||||||
|
const key = event.key.toLowerCase();
|
||||||
|
if (key === "c") {
|
||||||
|
if (event.metaKey && !event.ctrlKey) return "copy";
|
||||||
|
if (event.ctrlKey && !event.metaKey) return event.shiftKey || hasSelection ? "copy" : null;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (key === "v" && (event.ctrlKey || event.metaKey)) return "paste";
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
for (const key of ["c", "C", "v", "V", "x"]) {
|
||||||
|
for (let bits = 0; bits < 16; bits++) {
|
||||||
|
const event = { key, ctrlKey: Boolean(bits & 1), metaKey: Boolean(bits & 2), shiftKey: Boolean(bits & 4), altKey: Boolean(bits & 8) };
|
||||||
|
for (const sel of [true, false]) {
|
||||||
|
assert.equal(clipboardAction(event, sel), before(event, sel), `${key} ${JSON.stringify(event)} selection ${sel}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("the terminal pastes once and in brackets, copies on select only by preference, and has a Copy / Paste / Clear menu", () => {
|
test("the terminal pastes once and in brackets, copies on select only by preference, and has a Copy / Paste / Clear menu", () => {
|
||||||
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
|
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
|
||||||
assert.match(term, /term\.paste\(text\)/, "bracketed paste, not onInput(text)");
|
assert.match(term, /term\.paste\(text\)/, "bracketed paste, not onInput(text)");
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
// Tests for plan2code-app/scripts/smoke-agent.mjs, the stand-in agent CI's
|
||||||
|
// macOS smoke run starts in place of a real agent CLI. Run with:
|
||||||
|
// node --test scripts/test-app-smoke-agent.mjs
|
||||||
|
//
|
||||||
|
// The stand-in has one job: open a real web console the way an agent would,
|
||||||
|
// so the app's dashboard frame has something to connect to. This runs it
|
||||||
|
// outside the app, under a throwaway console home, and checks a live session
|
||||||
|
// appears and the stand-in ends when its input closes.
|
||||||
|
|
||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import { spawn, spawnSync } from "node:child_process";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const AGENT = path.join(HERE, "../plan2code-app/scripts/smoke-agent.mjs");
|
||||||
|
const CONSOLE_DIR = path.join(HERE, "../src/web-console");
|
||||||
|
|
||||||
|
// The desktop app's own variables would have the console announce itself to
|
||||||
|
// a live window. Deleted from the spawned environment, never inherited.
|
||||||
|
const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_APP_VERSION", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_CONSOLE_SID"];
|
||||||
|
|
||||||
|
function outsideAppEnv(extra) {
|
||||||
|
const env = { ...process.env, ...extra };
|
||||||
|
for (const name of APP_VARS) delete env[name];
|
||||||
|
return env;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every session handle under a console home: runtime/<project hash>/<sid>.json.
|
||||||
|
function handles(consoleHome) {
|
||||||
|
const runtime = path.join(consoleHome, "runtime");
|
||||||
|
if (!fs.existsSync(runtime)) return [];
|
||||||
|
return fs.readdirSync(runtime).flatMap((hash) =>
|
||||||
|
fs
|
||||||
|
.readdirSync(path.join(runtime, hash))
|
||||||
|
.filter((name) => name.endsWith(".json"))
|
||||||
|
.map((name) => JSON.parse(fs.readFileSync(path.join(runtime, hash, name), "utf8")))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitFor(check, ms) {
|
||||||
|
const end = Date.now() + ms;
|
||||||
|
while (Date.now() < end) {
|
||||||
|
const value = check();
|
||||||
|
if (value) return value;
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
|
}
|
||||||
|
return check();
|
||||||
|
}
|
||||||
|
|
||||||
|
function pidAlive(pid) {
|
||||||
|
try {
|
||||||
|
process.kill(pid, 0);
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
return err.code === "EPERM";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test("smoke agent: is an executable Node script with no dependencies", { skip: process.platform === "win32" }, () => {
|
||||||
|
const source = fs.readFileSync(AGENT, "utf8");
|
||||||
|
assert.ok(source.startsWith("#!/usr/bin/env node\n"), "starts with a node shebang");
|
||||||
|
assert.ok((fs.statSync(AGENT).mode & 0o111) !== 0, "has its executable bits set");
|
||||||
|
for (const [, name] of source.matchAll(/from\s+["']([^"']+)["']/g)) {
|
||||||
|
assert.ok(name.startsWith("node:"), `imports only Node built-ins, not ${name}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("smoke agent: opens a live dashboard session, then ends when its input closes", async (t) => {
|
||||||
|
const consoleHome = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-agent-home-"));
|
||||||
|
const project = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-agent-project-"));
|
||||||
|
const env = outsideAppEnv({ PLAN2CODE_CONSOLE_HOME: consoleHome, PLAN2CODE_NO_BROWSER: "1", PLAN2CODE_CONSOLE_DIR: CONSOLE_DIR });
|
||||||
|
let agent;
|
||||||
|
t.after(() => {
|
||||||
|
if (agent && agent.exitCode === null) agent.kill("SIGKILL");
|
||||||
|
// --all stops this folder's sessions, so it runs from the project, under the same home.
|
||||||
|
spawnSync(process.execPath, [path.join(CONSOLE_DIR, "console.mjs"), "stop", "--all"], { cwd: project, env, timeout: 15000 });
|
||||||
|
fs.rmSync(consoleHome, { recursive: true, force: true });
|
||||||
|
fs.rmSync(project, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
agent = spawn(process.execPath, [AGENT, "--some-agent-flag"], { cwd: project, env, stdio: ["pipe", "pipe", "pipe"] });
|
||||||
|
let output = "";
|
||||||
|
agent.stdout.on("data", (chunk) => (output += chunk));
|
||||||
|
agent.stderr.on("data", (chunk) => (output += chunk));
|
||||||
|
const exited = new Promise((resolve) => agent.on("exit", (code) => resolve(code)));
|
||||||
|
|
||||||
|
const handle = await waitFor(() => handles(consoleHome)[0], 20000);
|
||||||
|
assert.ok(handle, `a session appeared under the console home; agent said: ${output}`);
|
||||||
|
const health = await (await fetch(`http://127.0.0.1:${handle.port}/health`)).json();
|
||||||
|
assert.equal(health.ok, true);
|
||||||
|
assert.equal(health.sid, handle.sid, "the port answers for this session");
|
||||||
|
const state = JSON.parse(fs.readFileSync(path.join(consoleHome, "sessions", handle.sid, "state.json"), "utf8"));
|
||||||
|
assert.equal(state.workflow, "dashboard");
|
||||||
|
|
||||||
|
// Still running until its input closes, like an agent waiting for the person.
|
||||||
|
assert.equal(agent.exitCode, null, "the stand-in waits on its input");
|
||||||
|
agent.stdin.end();
|
||||||
|
const code = await Promise.race([exited, new Promise((resolve) => setTimeout(() => resolve("timeout"), 10000))]);
|
||||||
|
assert.equal(code, 0, `the stand-in exits cleanly once its input closes; agent said: ${output}`);
|
||||||
|
|
||||||
|
// The console outlives the agent (it is detached), so the stop below is what ends it.
|
||||||
|
const stop = spawnSync(process.execPath, [path.join(CONSOLE_DIR, "console.mjs"), "stop", "--all"], { cwd: project, env, encoding: "utf8", timeout: 15000 });
|
||||||
|
assert.equal(stop.status, 0, stop.stderr);
|
||||||
|
assert.equal(await waitFor(() => !pidAlive(handle.pid), 10000), true, "the console server is gone after stop --all");
|
||||||
|
});
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
// Tests for plan2code-app/scripts/smoke-frame.mjs, the check CI's macOS smoke
|
||||||
|
// run uses to prove the app's dashboard frame connected to the console. Run with:
|
||||||
|
// node --test scripts/test-app-smoke-frame.mjs
|
||||||
|
//
|
||||||
|
// No app and no real console: a session handle under a throwaway console home
|
||||||
|
// points at a tiny local server whose /health answers with a browser count the
|
||||||
|
// test controls.
|
||||||
|
|
||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import http from "node:http";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import { spawn } from "node:child_process";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const SCRIPT = path.join(HERE, "../plan2code-app/scripts/smoke-frame.mjs");
|
||||||
|
const SID = "20261108-000000-abcdef";
|
||||||
|
|
||||||
|
// A /health server answering with `browsers()` for this session.
|
||||||
|
async function healthServer(browsers) {
|
||||||
|
const server = http.createServer((req, res) => {
|
||||||
|
if (req.url !== "/health") return res.writeHead(404).end();
|
||||||
|
res.writeHead(200, { "content-type": "application/json" });
|
||||||
|
res.end(JSON.stringify({ ok: true, sid: SID, browsers: browsers(), rev: 1, phase: "unknown" }));
|
||||||
|
});
|
||||||
|
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A console home holding one session handle, the way server.mjs writes it.
|
||||||
|
function consoleHomeFor(port) {
|
||||||
|
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-frame-home-"));
|
||||||
|
const dir = path.join(home, "runtime", "0123456789abcdef");
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(dir, `${SID}.json`), JSON.stringify({ v: 1, sid: SID, pid: process.pid, port, url: `http://127.0.0.1:${port}/` }));
|
||||||
|
return home;
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(args, env = {}) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const child = spawn(process.execPath, [SCRIPT, ...args], { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] });
|
||||||
|
let output = "";
|
||||||
|
child.stdout.on("data", (chunk) => (output += chunk));
|
||||||
|
child.stderr.on("data", (chunk) => (output += chunk));
|
||||||
|
child.on("exit", (code) => resolve({ code, output }));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test("smoke frame: passes once /health counts a browser", async (t) => {
|
||||||
|
let asked = 0;
|
||||||
|
const server = await healthServer(() => (++asked < 3 ? 0 : 1));
|
||||||
|
const home = consoleHomeFor(server.address().port);
|
||||||
|
t.after(() => {
|
||||||
|
server.close();
|
||||||
|
fs.rmSync(home, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const { code, output } = await run([home, "--timeout-ms", "10000"]);
|
||||||
|
assert.equal(code, 0, output);
|
||||||
|
assert.ok(asked >= 3, "it kept polling while no browser was connected");
|
||||||
|
assert.match(output, /connected/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("smoke frame: fails with the last answer printed when no browser ever connects", async (t) => {
|
||||||
|
const server = await healthServer(() => 0);
|
||||||
|
const home = consoleHomeFor(server.address().port);
|
||||||
|
t.after(() => {
|
||||||
|
server.close();
|
||||||
|
fs.rmSync(home, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const { code, output } = await run([home, "--timeout-ms", "1500"]);
|
||||||
|
assert.equal(code, 1, output);
|
||||||
|
assert.match(output, /"browsers":0/, "the last /health answer is printed");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("smoke frame: fails when no session ever appears, and reads the home from PLAN2CODE_CONSOLE_HOME", async (t) => {
|
||||||
|
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-frame-empty-"));
|
||||||
|
t.after(() => fs.rmSync(home, { recursive: true, force: true }));
|
||||||
|
|
||||||
|
const { code, output } = await run(["--timeout-ms", "1000"], { PLAN2CODE_CONSOLE_HOME: home });
|
||||||
|
assert.equal(code, 1, output);
|
||||||
|
assert.match(output, /no session/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("smoke frame: refuses to run with no console home", async () => {
|
||||||
|
const env = { ...process.env };
|
||||||
|
delete env.PLAN2CODE_CONSOLE_HOME;
|
||||||
|
const result = await new Promise((resolve) => {
|
||||||
|
const child = spawn(process.execPath, [SCRIPT], { env, stdio: ["ignore", "pipe", "pipe"] });
|
||||||
|
let output = "";
|
||||||
|
child.stderr.on("data", (chunk) => (output += chunk));
|
||||||
|
child.on("exit", (code) => resolve({ code, output }));
|
||||||
|
});
|
||||||
|
assert.equal(result.code, 2, result.output);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("smoke frame: the CI step keeps the console from opening a browser, so only the frame can count", () => {
|
||||||
|
// Inside the app the console opens no browser of its own. If the app's signal
|
||||||
|
// to it were lost, `open` would start the runner's browser, which signs in by
|
||||||
|
// cookie and would pass this check with the frame dead.
|
||||||
|
const workflow = fs.readFileSync(path.join(HERE, "../.github/workflows/app.yml"), "utf8");
|
||||||
|
const start = workflow.indexOf("- name: Smoke-test the dashboard frame connects (macOS)");
|
||||||
|
assert.ok(start >= 0, "the frame step is there");
|
||||||
|
// The step runs to the blank line that ends it.
|
||||||
|
const end = workflow.indexOf("\n\n", start);
|
||||||
|
const step = workflow.slice(start, end === -1 ? undefined : end);
|
||||||
|
assert.match(step, /\n\s+export PLAN2CODE_NO_BROWSER=1\n/, step);
|
||||||
|
assert.ok(step.indexOf("PLAN2CODE_NO_BROWSER") < step.indexOf("target/release/plan2code-app"), "set before the app starts");
|
||||||
|
});
|
||||||
@@ -25,7 +25,7 @@ const OUTSIDE_APP = Object.fromEntries(
|
|||||||
|
|
||||||
export const BUDGETS = {
|
export const BUDGETS = {
|
||||||
// The card an agent reads once per session.
|
// The card an agent reads once per session.
|
||||||
card: { "console.md": 9700 },
|
card: { "console.md": 9800 },
|
||||||
// Each topic file under notes/, read when its workflow starts.
|
// Each topic file under notes/, read when its workflow starts.
|
||||||
notes: {
|
notes: {
|
||||||
"changelog.md": 1400,
|
"changelog.md": 1400,
|
||||||
@@ -42,7 +42,7 @@ export const BUDGETS = {
|
|||||||
"pathfinder.md": 2622, // raised by the UI prototype line's bytes only
|
"pathfinder.md": 2622, // raised by the UI prototype line's bytes only
|
||||||
"plan.md": 1023, // raised by the UI prototype line's bytes only
|
"plan.md": 1023, // raised by the UI prototype line's bytes only
|
||||||
"pr-prep.md": 4500,
|
"pr-prep.md": 4500,
|
||||||
"quick-task.md": 5194, // raised by the UI prototype line's, the prototype recap line's, the prototype archive wording's, the lessons card line's and the Changes tab lines' bytes only
|
"quick-task.md": 5238, // raised by the UI prototype line's, the prototype recap line's, the prototype archive wording's, the lessons card line's, the Changes tab lines' and the post-build cards' nothingYet bytes only
|
||||||
"review-loop.md": 4000, // its written size (3,564 bytes) plus 10 percent, rounded up to the next 100
|
"review-loop.md": 4000, // its written size (3,564 bytes) plus 10 percent, rounded up to the next 100
|
||||||
"review.md": 1190, // raised by the lessons card line's bytes, then the Review Loop pointer line's bytes only
|
"review.md": 1190, // raised by the lessons card line's bytes, then the Review Loop pointer line's bytes only
|
||||||
"revise-plan.md": 1422, // raised by the UI prototype line's bytes only
|
"revise-plan.md": 1422, // raised by the UI prototype line's bytes only
|
||||||
|
|||||||
@@ -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 },
|
||||||
|
]);
|
||||||
|
});
|
||||||
+1563
-32
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,7 @@
|
|||||||
"test-agent-lookup.mjs",
|
"test-agent-lookup.mjs",
|
||||||
"test-agents-file.mjs",
|
"test-agents-file.mjs",
|
||||||
"test-app-meter.mjs",
|
"test-app-meter.mjs",
|
||||||
|
"test-app-smoke-frame.mjs",
|
||||||
"test-browser-helper.mjs",
|
"test-browser-helper.mjs",
|
||||||
"test-check-console-openings.mjs",
|
"test-check-console-openings.mjs",
|
||||||
"test-check-doc-size.mjs",
|
"test-check-doc-size.mjs",
|
||||||
@@ -11,8 +12,11 @@
|
|||||||
"test-check-versions.mjs",
|
"test-check-versions.mjs",
|
||||||
"test-getting-started.mjs",
|
"test-getting-started.mjs",
|
||||||
"test-git-repo.mjs",
|
"test-git-repo.mjs",
|
||||||
|
"test-install-bench.mjs",
|
||||||
|
"test-install-refs.mjs",
|
||||||
"test-install-update.mjs",
|
"test-install-update.mjs",
|
||||||
"test-line-endings.mjs",
|
"test-line-endings.mjs",
|
||||||
|
"test-publish-install-refs.mjs",
|
||||||
"test-script-changelog.mjs",
|
"test-script-changelog.mjs",
|
||||||
"test-script-changes.mjs",
|
"test-script-changes.mjs",
|
||||||
"test-script-coverage.mjs",
|
"test-script-coverage.mjs",
|
||||||
@@ -40,6 +44,7 @@
|
|||||||
"test-web-console-diff-parse.mjs",
|
"test-web-console-diff-parse.mjs",
|
||||||
"test-web-console-git-board.mjs",
|
"test-web-console-git-board.mjs",
|
||||||
"test-web-console-prototypes.mjs",
|
"test-web-console-prototypes.mjs",
|
||||||
|
"test-web-console-relative-urls.mjs",
|
||||||
"test-web-console-send-state.mjs",
|
"test-web-console-send-state.mjs",
|
||||||
"test-web-console-shape.mjs",
|
"test-web-console-shape.mjs",
|
||||||
"test-web-console-skills.mjs",
|
"test-web-console-skills.mjs",
|
||||||
@@ -49,9 +54,11 @@
|
|||||||
"test-web-console-tones.mjs"
|
"test-web-console-tones.mjs"
|
||||||
],
|
],
|
||||||
"skipFast": [
|
"skipFast": [
|
||||||
|
"test-app-smoke-agent.mjs",
|
||||||
"test-console-stub.mjs",
|
"test-console-stub.mjs",
|
||||||
"test-console-wire-budgets.mjs",
|
"test-console-wire-budgets.mjs",
|
||||||
"test-fast.mjs",
|
"test-fast.mjs",
|
||||||
|
"test-install-e2e.mjs",
|
||||||
"test-launcher.mjs",
|
"test-launcher.mjs",
|
||||||
"test-standalone-check.mjs",
|
"test-standalone-check.mjs",
|
||||||
"test-ui-prototype-page.mjs",
|
"test-ui-prototype-page.mjs",
|
||||||
@@ -115,6 +122,7 @@
|
|||||||
"test-web-console-page-cards.mjs",
|
"test-web-console-page-cards.mjs",
|
||||||
"test-web-console-page-changes.mjs",
|
"test-web-console-page-changes.mjs",
|
||||||
"test-web-console-page-dashboard.mjs",
|
"test-web-console-page-dashboard.mjs",
|
||||||
|
"test-web-console-page-frame.mjs",
|
||||||
"test-web-console-page-layout.mjs",
|
"test-web-console-page-layout.mjs",
|
||||||
"test-web-console-page-git.mjs",
|
"test-web-console-page-git.mjs",
|
||||||
"test-web-console-page-help.mjs",
|
"test-web-console-page-help.mjs",
|
||||||
|
|||||||
+158
-2
@@ -14,6 +14,11 @@ import { spawn, spawnSync } from "node:child_process";
|
|||||||
import { createRequire } from "node:module";
|
import { createRequire } from "node:module";
|
||||||
import { fileURLToPath } from "node:url";
|
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 require = createRequire(import.meta.url);
|
||||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||||
const LAUNCHER = path.join(ROOT, "src", "launcher", "plan2code.js");
|
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' +
|
'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.
|
// 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' +
|
'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"
|
"process.exitCode = Number(process.env.P2C_TEST_EXIT || 0);\n"
|
||||||
);
|
);
|
||||||
for (const cli of clis) {
|
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(" "));
|
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"]);
|
const box = sandbox(["npx"]);
|
||||||
t.after(box.cleanup);
|
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") });
|
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.equal(result.status, 0, result.stderr);
|
||||||
assert.match(result.stdout, /Updating Plan2Code to v3\.0\.2\.\.\./);
|
assert.match(result.stdout, /Updating Plan2Code to v3\.0\.2\.\.\./);
|
||||||
assert.ok(box.argsOf("npx").includes(`${REPO}#v3.0.2`), box.argsOf("npx").join(" "));
|
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) => {
|
test("launcher: update --force reaches the installer", (t) => {
|
||||||
const box = sandbox(["npx"]);
|
const box = sandbox(["npx"]);
|
||||||
t.after(box.cleanup);
|
t.after(box.cleanup);
|
||||||
@@ -820,6 +948,34 @@ test("launcher app: modelFrom reads --model, --model= and Codex's -m", () => {
|
|||||||
assert.equal(modelFrom(["--verbose"], "claude"), null);
|
assert.equal(modelFrom(["--verbose"], "claude"), null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// osascript exits 1 both on a cancel and on a failure; only the cancel has -128.
|
||||||
|
test("launcher picker: on macOS an exit 1 is a cancel only with osascript's (-128); elsewhere an exit 1 with nothing picked stays a cancel", () => {
|
||||||
|
const { pickerCancelled } = require(LAUNCHER);
|
||||||
|
const cancel = "0:17: execution error: User canceled. (-128)\n";
|
||||||
|
const failure = "0:4: execution error: The variable this is not defined. (-2753)\n";
|
||||||
|
assert.equal(pickerCancelled(1, "", cancel, "darwin"), true);
|
||||||
|
assert.equal(pickerCancelled(1, "", failure, "darwin"), false, "a failure falls through to the typed prompt");
|
||||||
|
assert.equal(pickerCancelled(1, "", "", "darwin"), false);
|
||||||
|
assert.equal(pickerCancelled(1, null, null, "darwin"), false);
|
||||||
|
for (const platform of ["linux", "win32"]) {
|
||||||
|
assert.equal(pickerCancelled(1, "", "", platform), true, platform);
|
||||||
|
assert.equal(pickerCancelled(1, "", "Gtk-WARNING\n", platform), true, platform);
|
||||||
|
assert.equal(pickerCancelled(3, "", "", platform), false, platform);
|
||||||
|
}
|
||||||
|
for (const platform of ["darwin", "linux", "win32"]) {
|
||||||
|
assert.equal(pickerCancelled(0, "", "", platform), true, `${platform}: exit 0 with nothing picked`);
|
||||||
|
assert.equal(pickerCancelled(0, "/some/folder\n", "", platform), false, `${platform}: a pick`);
|
||||||
|
assert.equal(pickerCancelled(1, "/some/folder\n", cancel, platform), false, `${platform}: something printed is no cancel`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("launcher picker: pickFolder decides a cancel through pickerCancelled", () => {
|
||||||
|
const source = fs.readFileSync(require.resolve(LAUNCHER), "utf8");
|
||||||
|
const body = source.slice(source.indexOf("async function pickFolder"), source.indexOf("async function projectCwd"));
|
||||||
|
assert.match(body, /pickerCancelled\(result\.status, result\.stdout, result\.stderr\)/);
|
||||||
|
assert.doesNotMatch(body, /result\.status === 1/, "no cancel rule left beside it");
|
||||||
|
});
|
||||||
|
|
||||||
test("launcher app: an app that starts and then exits with a failure falls back to the terminal flow", (t) => {
|
test("launcher app: an app that starts and then exits with a failure falls back to the terminal flow", (t) => {
|
||||||
const box = sandbox(["claude"]);
|
const box = sandbox(["claude"]);
|
||||||
t.after(box.cleanup);
|
t.after(box.cleanup);
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
@@ -14,12 +14,18 @@ const skillNames = () => fs.readdirSync(SKILLS).filter((name) => !name.startsWit
|
|||||||
|
|
||||||
/* ================================================================ install */
|
/* ================================================================ install */
|
||||||
|
|
||||||
test("npm test runs every scripts/test-*.mjs file, and names none that is missing", () => {
|
test("npm test and npm run test:games together run every scripts/test-*.mjs file once, games only in test:games", () => {
|
||||||
const command = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).scripts.test;
|
const scripts = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).scripts;
|
||||||
const listed = [...command.matchAll(/scripts\/(test-[\w-]+\.mjs)/g)].map((m) => m[1]).sort();
|
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.
|
// 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();
|
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", () => {
|
test("every skill with scripts ships common.mjs and version.json; the dashboard ships only Learning's", () => {
|
||||||
|
|||||||
@@ -52,6 +52,6 @@ test("it asks once per page", async () => {
|
|||||||
await load();
|
await load();
|
||||||
await load();
|
await load();
|
||||||
assert.equal(calls.length, 1);
|
assert.equal(calls.length, 1);
|
||||||
assert.deepEqual(calls[0], ["/spec-carry", "POST"]);
|
assert.deepEqual(calls[0], ["spec-carry", "POST"]);
|
||||||
assert.equal(typeof loadSpecCarry, "function");
|
assert.equal(typeof loadSpecCarry, "function");
|
||||||
});
|
});
|
||||||
@@ -280,7 +280,7 @@ test("the list names Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Sta
|
|||||||
assert.equal(ACTIVITIES[12].title, "Flock Dash");
|
assert.equal(ACTIVITIES[12].title, "Flock Dash");
|
||||||
for (const a of ACTIVITIES) {
|
for (const a of ACTIVITIES) {
|
||||||
assert.ok(Object.isFrozen(a), `${a.id} is frozen`);
|
assert.ok(Object.isFrozen(a), `${a.id} is frozen`);
|
||||||
assert.equal(a.module, a.id === "ghoul" ? "/activities/ghoul-rush/ghoul.js" : `/activities/${a.id}.js`);
|
assert.equal(a.module, a.id === "ghoul" ? "activities/ghoul-rush/ghoul.js" : `activities/${a.id}.js`);
|
||||||
assert.equal(typeof a.title, "string");
|
assert.equal(typeof a.title, "string");
|
||||||
assert.ok(typeof a.blurb === "string" && a.blurb.length > 10, `${a.id} has a line for its picker card`);
|
assert.ok(typeof a.blurb === "string" && a.blurb.length > 10, `${a.id} has a line for its picker card`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -97,6 +97,19 @@ test("wait's existing outcomes are pinned: submit, images, waiting, cancel, carr
|
|||||||
|
|
||||||
/* --------------------------------------------- quick question: the channel */
|
/* --------------------------------------------- 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 () => {
|
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();
|
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 () => {
|
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();
|
const s = openSession();
|
||||||
try {
|
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 s.send("/submit", EXPORT_A)).status, 200);
|
||||||
assert.equal((await ask(s, "Mid-build question")).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");
|
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.status, 0);
|
||||||
assert.equal(got.json.chat.length, 1);
|
assert.equal(got.json.chat.length, 1);
|
||||||
assert.match(got.json.reply, /Quick question \(\d+\): Mid-build question/);
|
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(onDisk.consumedAt, undefined, "the card send is still waiting for wait");
|
||||||
assert.equal((await (await s.send("/ping", {})).json()).pendingChat, 0);
|
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.equal(none.status, 10);
|
||||||
assert.deepEqual(none.json, {});
|
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() });
|
const line = JSON.stringify({ kind: "message", conversation: 1, text: "torn in two", seq, at: new Date().toISOString() });
|
||||||
fs.appendFileSync(file, line.slice(0, 20));
|
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(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");
|
fs.appendFileSync(file, line.slice(20) + "\n");
|
||||||
assert.ok(readChat(s.session).some((e) => e.seq === seq));
|
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.equal(got.status, 0);
|
||||||
assert.match(got.json.reply, /Quick question \(\d+\): torn in two/);
|
assert.match(got.json.reply, /Quick question \(\d+\): torn in two/);
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -386,17 +386,19 @@ test("only an installed console's open leaves the console-dir pointer; status, h
|
|||||||
assert.match(usage.stderr, /keep/, "the usage line names every command");
|
assert.match(usage.stderr, /keep/, "the usage line names every command");
|
||||||
assert.equal(fs.existsSync(pointer), false);
|
assert.equal(fs.existsSync(pointer), false);
|
||||||
// A source checkout never points every skill stub at itself.
|
// A source checkout never points every skill stub at itself.
|
||||||
|
// Each console is stopped before its assert, so a failing assert leaves no server running.
|
||||||
const fromSource = cli(["open", "--no-open"], { env });
|
const fromSource = cli(["open", "--no-open"], { env });
|
||||||
assert.equal(fs.existsSync(pointer), false, "a source checkout leaves no pointer");
|
const sourcePointer = fs.existsSync(pointer);
|
||||||
cli(["stop", "--session", fromSource.json.sid, "--force"], { env });
|
cli(["stop", "--session", fromSource.json.sid, "--force"], { env });
|
||||||
|
assert.equal(sourcePointer, false, "a source checkout leaves no pointer");
|
||||||
// An installed console (a version folder) does.
|
// An installed console (a version folder) does.
|
||||||
const installed = path.join(home, "9.9.9");
|
const installed = path.join(home, "9.9.9");
|
||||||
fs.cpSync(path.join(ROOT, "src", "web-console"), installed, { recursive: true });
|
fs.cpSync(path.join(ROOT, "src", "web-console"), installed, { recursive: true });
|
||||||
const res = spawnSync(process.execPath, [path.join(installed, "console.mjs"), "open", "--no-open"], { env: { ...ENV, ...env }, encoding: "utf8", cwd: ROOT });
|
const res = spawnSync(process.execPath, [path.join(installed, "console.mjs"), "open", "--no-open"], { env: { ...ENV, ...env }, encoding: "utf8", cwd: ROOT });
|
||||||
assert.equal(res.status, 0, res.stderr);
|
assert.equal(res.status, 0, res.stderr);
|
||||||
assert.equal(fs.readFileSync(pointer, "utf8").trim(), installed);
|
|
||||||
const sid = JSON.parse(res.stdout.trim().split(/\r?\n/)[0]).sid;
|
const sid = JSON.parse(res.stdout.trim().split(/\r?\n/)[0]).sid;
|
||||||
spawnSync(process.execPath, [path.join(installed, "console.mjs"), "stop", "--session", sid, "--force"], { env: { ...ENV, ...env }, encoding: "utf8", cwd: ROOT });
|
spawnSync(process.execPath, [path.join(installed, "console.mjs"), "stop", "--session", sid, "--force"], { env: { ...ENV, ...env }, encoding: "utf8", cwd: ROOT });
|
||||||
|
assert.equal(fs.readFileSync(pointer, "utf8").trim(), installed);
|
||||||
} finally {
|
} finally {
|
||||||
fs.rmSync(home, { recursive: true, force: true });
|
fs.rmSync(home, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,27 +2,37 @@
|
|||||||
// variable unset the page's CSP keeps frame-ancestors 'none'; set to exactly
|
// variable unset the page's CSP keeps frame-ancestors 'none'; set to exactly
|
||||||
// one allowed origin it names that origin; set to anything else it is ignored
|
// one allowed origin it names that origin; set to anything else it is ignored
|
||||||
// and 'none' stands. Each case boots its own server with the variable in its
|
// and 'none' stands. Each case boots its own server with the variable in its
|
||||||
// environment. Shared setup: ./web-console-test-helpers.mjs.
|
// environment. Inside the macOS app the frame signs in by a path prefix on
|
||||||
|
// 127.0.0.1 instead of by cookie, and only there. Shared setup:
|
||||||
|
// ./web-console-test-helpers.mjs.
|
||||||
|
|
||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
|
import crypto from "node:crypto";
|
||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
|
import http from "node:http";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { spawn } from "node:child_process";
|
import { spawn } from "node:child_process";
|
||||||
import { cookieFor, ENV, HOME, ROOT } from "./web-console-test-helpers.mjs";
|
import { cookieFor, ENV, HOME, JPEG, ROOT } from "./web-console-test-helpers.mjs";
|
||||||
|
|
||||||
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
|
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
|
||||||
|
|
||||||
// Boot a session server whose environment carries PLAN2CODE_EMBED_ORIGIN set
|
// Boot a session server whose environment carries PLAN2CODE_EMBED_ORIGIN set
|
||||||
// to `origin` (or does not carry it at all when origin is undefined). Returns
|
// to `origin` (or does not carry it at all when origin is undefined). Returns
|
||||||
// the child and its base URL; the caller always kills the child.
|
// the child and its base URL; the caller always kills the child. `platform`
|
||||||
async function bootServer(origin) {
|
// fakes process.platform in the server before it loads (the whole server
|
||||||
|
// sees it, not only frameKey()), so the macOS-only frame sign-in is tested on
|
||||||
|
// every OS. `state` adds fields to state.json.
|
||||||
|
async function bootServer(origin, { platform, token = "t", state = {} } = {}) {
|
||||||
const dir = fs.mkdtempSync(path.join(HOME, "embed-"));
|
const dir = fs.mkdtempSync(path.join(HOME, "embed-"));
|
||||||
fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting" }));
|
fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting", ...state }));
|
||||||
const env = { ...ENV };
|
const env = { ...ENV };
|
||||||
if (origin === undefined) delete env.PLAN2CODE_EMBED_ORIGIN;
|
if (origin === undefined) delete env.PLAN2CODE_EMBED_ORIGIN;
|
||||||
else env.PLAN2CODE_EMBED_ORIGIN = origin;
|
else env.PLAN2CODE_EMBED_ORIGIN = origin;
|
||||||
const child = spawn(process.execPath, [SERVER_JS, `--session=${dir}`, "--token=t", `--project=${dir}`], {
|
const fake = platform
|
||||||
|
? ["--import", `data:text/javascript,Object.defineProperty(process,"platform",{value:${JSON.stringify(platform)}})`]
|
||||||
|
: [];
|
||||||
|
const child = spawn(process.execPath, [...fake, SERVER_JS, `--session=${dir}`, `--token=${token}`, `--project=${dir}`], {
|
||||||
env,
|
env,
|
||||||
stdio: ["ignore", "pipe", "ignore"],
|
stdio: ["ignore", "pipe", "ignore"],
|
||||||
windowsHide: true,
|
windowsHide: true,
|
||||||
@@ -36,7 +46,7 @@ async function bootServer(origin) {
|
|||||||
});
|
});
|
||||||
child.on("exit", () => reject(new Error("server exited before it was ready")));
|
child.on("exit", () => reject(new Error("server exited before it was ready")));
|
||||||
});
|
});
|
||||||
return { child, base: `http://127.0.0.1:${ready.port}` };
|
return { child, dir, base: `http://127.0.0.1:${ready.port}`, port: ready.port };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch the session page with its token cookie and resolve to the page's
|
// Fetch the session page with its token cookie and resolve to the page's
|
||||||
@@ -54,8 +64,8 @@ async function cspWith(origin) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fetch the sign-in redirect and resolve to its set-cookie header.
|
// Fetch the sign-in redirect and resolve to its set-cookie header.
|
||||||
async function cookieWith(origin) {
|
async function cookieWith(origin, options) {
|
||||||
const { child, base } = await bootServer(origin);
|
const { child, base } = await bootServer(origin, options);
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${base}/s/t/`, { redirect: "manual" });
|
const res = await fetch(`${base}/s/t/`, { redirect: "manual" });
|
||||||
assert.equal(res.status, 302);
|
assert.equal(res.status, 302);
|
||||||
@@ -89,7 +99,9 @@ test("the session cookie is Strict standalone and None; Secure under embed", asy
|
|||||||
// WebKit (the app on Linux and macOS) drops a Secure cookie sent over plain
|
// WebKit (the app on Linux and macOS) drops a Secure cookie sent over plain
|
||||||
// http, so the page in the app's frame got a 403 after the sign-in.
|
// http, so the page in the app's frame got a 403 after the sign-in.
|
||||||
test("the session cookie is Lax and never Secure under the tauri://localhost embed", async () => {
|
test("the session cookie is Lax and never Secure under the tauri://localhost embed", async () => {
|
||||||
const embedded = await cookieWith("tauri://localhost");
|
// Linux, where this frame signs in by cookie: on macOS it signs in by its
|
||||||
|
// path prefix instead (the frame tests below).
|
||||||
|
const embedded = await cookieWith("tauri://localhost", { platform: "linux" });
|
||||||
assert.match(embedded, /SameSite=Lax/);
|
assert.match(embedded, /SameSite=Lax/);
|
||||||
assert.doesNotMatch(embedded, /Secure/);
|
assert.doesNotMatch(embedded, /Secure/);
|
||||||
assert.match(embedded, /HttpOnly/);
|
assert.match(embedded, /HttpOnly/);
|
||||||
@@ -112,3 +124,214 @@ test("anything but exactly one allowed origin keeps frame-ancestors 'none'", asy
|
|||||||
assert.match(csp, /frame-ancestors 'none'$/, `${JSON.stringify(origin)}: ${csp}`);
|
assert.match(csp, /frame-ancestors 'none'$/, `${JSON.stringify(origin)}: ${csp}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/* ------------------------------------------- the macOS app's frame sign-in */
|
||||||
|
|
||||||
|
// fetch() will not send a Host header of the caller's choosing, and some of
|
||||||
|
// these requests must, so they go through node:http. Resolves to status,
|
||||||
|
// headers and body text; with `head` it resolves on the headers and drops
|
||||||
|
// the connection (the event stream never ends).
|
||||||
|
function raw(port, urlPath, { method = "GET", headers = {}, body, head = false } = {}) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const req = http.request({ host: "127.0.0.1", port, path: urlPath, method, headers: { connection: "close", ...headers } }, (res) => {
|
||||||
|
if (head) {
|
||||||
|
resolve({ status: res.statusCode, headers: res.headers, body: "" });
|
||||||
|
return req.destroy();
|
||||||
|
}
|
||||||
|
let text = "";
|
||||||
|
res.setEncoding("utf8");
|
||||||
|
res.on("data", (c) => (text += c));
|
||||||
|
res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body: text }));
|
||||||
|
});
|
||||||
|
req.on("error", (e) => (head && e.code === "ECONNRESET" ? undefined : reject(e)));
|
||||||
|
req.end(body);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// The frame's key: a hash of the token, so the token the terminal prints
|
||||||
|
// never sits in the frame's address, and still 128 bits.
|
||||||
|
const frameKey = (token) => crypto.createHash("sha256").update(token).digest("hex").slice(0, 32);
|
||||||
|
|
||||||
|
// A real token's shape: 16 random bytes in base64url, uppercase included.
|
||||||
|
const MIXED_TOKEN = "aB3xZ9-Qk_T7mN2pLw8RvY";
|
||||||
|
|
||||||
|
// A server in the macOS app's frame mode, its prefix, and the same-origin
|
||||||
|
// headers the frame's page sends with an origin-checked POST.
|
||||||
|
async function macFrame(options = {}) {
|
||||||
|
const server = await bootServer("tauri://localhost", { platform: "darwin", token: MIXED_TOKEN, ...options });
|
||||||
|
return { ...server, prefix: `/f/${frameKey(MIXED_TOKEN)}`, own: { origin: `http://127.0.0.1:${server.port}` } };
|
||||||
|
}
|
||||||
|
|
||||||
|
test("the macOS app's frame signs in by a path prefix on 127.0.0.1, with no cookie", async () => {
|
||||||
|
const { child, port, prefix, own } = await macFrame();
|
||||||
|
try {
|
||||||
|
const signIn = await raw(port, `/s/${MIXED_TOKEN}/`, { headers: { "sec-fetch-dest": "iframe" } });
|
||||||
|
assert.equal(signIn.status, 302);
|
||||||
|
assert.equal(signIn.headers.location, `${prefix}/`, "the same host, a path, never a host name");
|
||||||
|
assert.equal(signIn.headers["set-cookie"], undefined);
|
||||||
|
|
||||||
|
const page = await raw(port, `${prefix}/`);
|
||||||
|
assert.equal(page.status, 200);
|
||||||
|
assert.match(page.headers["content-security-policy"], /frame-ancestors tauri:\/\/localhost$/);
|
||||||
|
assert.equal((await raw(port, `${prefix}/state`)).status, 200);
|
||||||
|
assert.equal((await raw(port, `${prefix}/app.js`)).status, 200);
|
||||||
|
const events = await raw(port, `${prefix}/events`, { head: true });
|
||||||
|
assert.equal(events.status, 200);
|
||||||
|
assert.match(String(events.headers["content-type"]), /^text\/event-stream/);
|
||||||
|
|
||||||
|
// An origin-checked route takes the page's own origin under the prefix.
|
||||||
|
assert.equal((await raw(port, `${prefix}/bye`, { method: "POST", headers: own })).status, 200);
|
||||||
|
} finally {
|
||||||
|
child.kill();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("under the frame's prefix the routes that read the raw request line answer, and still refuse `..`", async () => {
|
||||||
|
const project = fs.mkdtempSync(path.join(HOME, "embed-project-"));
|
||||||
|
const kept = "shot-1a2b3c4d.jpg";
|
||||||
|
fs.mkdirSync(path.join(project, "spec", "attachments"), { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(project, "spec", "attachments", kept), JSON.stringify("not read as text"));
|
||||||
|
const { child, dir, port, prefix, own } = await macFrame({ state: { worktree: project, specDir: "spec" } });
|
||||||
|
try {
|
||||||
|
const jpeg = { ...own, "content-type": "image/jpeg" };
|
||||||
|
const upload = JSON.parse((await raw(port, `${prefix}/upload`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
||||||
|
assert.equal((await raw(port, `${prefix}/uploads/${upload.id}.jpg`)).status, 200, "an upload");
|
||||||
|
assert.equal((await raw(port, `${prefix}/uploads/../uploads/${upload.id}.jpg`)).status, 404, "`..` is still refused");
|
||||||
|
|
||||||
|
const note = JSON.parse((await raw(port, `${prefix}/notepad/image`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
||||||
|
assert.ok(note.ok, JSON.stringify(note));
|
||||||
|
const tab = /images\/([0-9a-f]{12})\//.exec(note.url)[1];
|
||||||
|
assert.equal((await raw(port, `${prefix}/notepad/images/${tab}/${note.id}.jpg`)).status, 200, "a notepad picture");
|
||||||
|
|
||||||
|
fs.mkdirSync(path.join(dir, "shots"));
|
||||||
|
fs.writeFileSync(path.join(dir, "shots", "run.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0]));
|
||||||
|
assert.equal((await raw(port, `${prefix}/shots/run.png`)).status, 200, "a shot");
|
||||||
|
assert.equal((await raw(port, `${prefix}/shots/../shots/run.png`)).status, 404, "`..` is still refused");
|
||||||
|
|
||||||
|
assert.equal((await raw(port, `${prefix}/attachments/${kept}`)).status, 200, "a kept attachment");
|
||||||
|
} finally {
|
||||||
|
child.kill();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the links the server hands the page are page-relative", async () => {
|
||||||
|
const { child, port, prefix, own } = await macFrame();
|
||||||
|
try {
|
||||||
|
const jpeg = { ...own, "content-type": "image/jpeg" };
|
||||||
|
const upload = JSON.parse((await raw(port, `${prefix}/upload`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
||||||
|
assert.equal(upload.url, `uploads/${upload.id}.jpg`);
|
||||||
|
const note = JSON.parse((await raw(port, `${prefix}/notepad/image`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
||||||
|
assert.match(note.url, /^notepad\/images\/[0-9a-f]{12}\/[0-9a-f-]{36}\.jpg$/);
|
||||||
|
const pad = JSON.parse((await raw(port, `${prefix}/notepad`)).body);
|
||||||
|
assert.equal(pad.images.length, 1);
|
||||||
|
for (const img of pad.images) {
|
||||||
|
assert.doesNotMatch(img.url, /^\//, img.url);
|
||||||
|
assert.doesNotMatch(String(img.thumb ?? ""), /^\//, img.thumb);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
child.kill();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a wrong or missing frame key is refused exactly as a request with no cookie is", async () => {
|
||||||
|
const { child, port, prefix } = await macFrame();
|
||||||
|
try {
|
||||||
|
const key = frameKey(MIXED_TOKEN);
|
||||||
|
const plain = await raw(port, "/state");
|
||||||
|
assert.equal(plain.status, 403);
|
||||||
|
const wrong = [
|
||||||
|
`/f/${frameKey("someone-else")}/state`,
|
||||||
|
`/f/${key.toUpperCase()}/state`,
|
||||||
|
`/f/${key.slice(0, -1)}/state`,
|
||||||
|
`/f/${key}x/state`,
|
||||||
|
`/f//state`,
|
||||||
|
`/f/state`,
|
||||||
|
`/f/${key}`,
|
||||||
|
`/F/${key}/state`,
|
||||||
|
`/f/%${key.charCodeAt(0).toString(16)}${key.slice(1)}/state`,
|
||||||
|
`/x/f/${key}/state`,
|
||||||
|
];
|
||||||
|
for (const p of wrong) {
|
||||||
|
const res = await raw(port, p);
|
||||||
|
assert.equal(res.status, plain.status, p);
|
||||||
|
assert.equal(res.body, plain.body, `${p} says no more than a request with no cookie`);
|
||||||
|
}
|
||||||
|
// The prefix comes off once: a second one is just a path, and nothing serves it.
|
||||||
|
assert.equal((await raw(port, `${prefix}${prefix}/state`)).status, 404);
|
||||||
|
assert.equal((await raw(port, `/s/${MIXED_TOKEN}x/`, { headers: { "sec-fetch-dest": "iframe" } })).status, 403);
|
||||||
|
} finally {
|
||||||
|
child.kill();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a .localhost host name neither signs in nor passes the origin check", async () => {
|
||||||
|
const { child, port, prefix } = await macFrame();
|
||||||
|
try {
|
||||||
|
const key = frameKey(MIXED_TOKEN);
|
||||||
|
for (const host of [`${key}.localhost:${port}`, `x.localhost:${port}`, `${key}.localhost`]) {
|
||||||
|
assert.equal((await raw(port, "/state", { headers: { host } })).status, 403, host);
|
||||||
|
assert.equal((await raw(port, `${prefix}/state`, { headers: { host } })).status, 403, `${host} under the prefix`);
|
||||||
|
}
|
||||||
|
const foreign = await raw(port, `${prefix}/bye`, { method: "POST", headers: { origin: `http://${key}.localhost:${port}` } });
|
||||||
|
assert.equal(foreign.status, 403);
|
||||||
|
assert.equal((await raw(port, `${prefix}/bye`, { method: "POST", headers: { origin: "http://evil.localhost:80" } })).status, 403);
|
||||||
|
} finally {
|
||||||
|
child.kill();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a browser tab on the macOS app's console keeps the cookie and `/`", async () => {
|
||||||
|
const { child, port, prefix } = await macFrame();
|
||||||
|
try {
|
||||||
|
const signIn = await raw(port, `/s/${MIXED_TOKEN}/`, { headers: { "sec-fetch-dest": "document" } });
|
||||||
|
assert.equal(signIn.status, 302);
|
||||||
|
assert.equal(signIn.headers.location, "/");
|
||||||
|
// The tauri://localhost cookie (cookieSameSite): Lax, never Secure,
|
||||||
|
// since Safari drops a Secure cookie on plain http.
|
||||||
|
assert.match(String(signIn.headers["set-cookie"]), /HttpOnly; SameSite=Lax;/);
|
||||||
|
assert.doesNotMatch(String(signIn.headers["set-cookie"]), /Secure/);
|
||||||
|
const cookie = cookieFor(`http://127.0.0.1:${port}`, MIXED_TOKEN);
|
||||||
|
assert.equal((await raw(port, "/state", { headers: { cookie } })).status, 200);
|
||||||
|
assert.ok(!String(signIn.headers.location).includes(prefix));
|
||||||
|
} finally {
|
||||||
|
child.kill();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the frame prefix is off everywhere but the macOS app, where `/f/` is just a path", async () => {
|
||||||
|
const cases = [
|
||||||
|
{ origin: "tauri://localhost", platform: "win32" },
|
||||||
|
{ origin: "tauri://localhost", platform: "linux" },
|
||||||
|
{ origin: "http://tauri.localhost", platform: "darwin" },
|
||||||
|
{ origin: "http://127.0.0.1:5173", platform: "darwin" },
|
||||||
|
{ origin: undefined, platform: "darwin" },
|
||||||
|
];
|
||||||
|
for (const { origin, platform } of cases) {
|
||||||
|
const label = `${origin} on ${platform}`;
|
||||||
|
const { child, port } = await bootServer(origin, { platform, token: MIXED_TOKEN });
|
||||||
|
try {
|
||||||
|
const signIn = await raw(port, `/s/${MIXED_TOKEN}/`, { headers: { "sec-fetch-dest": "iframe" } });
|
||||||
|
assert.equal(signIn.headers.location, "/", label);
|
||||||
|
assert.match(String(signIn.headers["set-cookie"]), /HttpOnly/, label);
|
||||||
|
const prefixed = `/f/${frameKey(MIXED_TOKEN)}/state`;
|
||||||
|
assert.equal((await raw(port, prefixed)).status, 403, `${label}: no sign-in by path`);
|
||||||
|
const cookie = cookieFor(`http://127.0.0.1:${port}`, MIXED_TOKEN);
|
||||||
|
assert.equal((await raw(port, prefixed, { headers: { cookie } })).status, 404, `${label}: never stripped`);
|
||||||
|
assert.equal((await raw(port, "/state", { headers: { cookie } })).status, 200, `${label}: the cookie route as before`);
|
||||||
|
} finally {
|
||||||
|
child.kill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the page-closed signal is a keepalive fetch, which carries the page's origin, not a beacon", () => {
|
||||||
|
// A body-less sendBeacon is a no-cors POST: under the console's
|
||||||
|
// `referrer-policy: no-referrer` it goes out with `Origin: null`, which /bye's
|
||||||
|
// origin check refuses (WebKit showed it; the Fetch standard says every engine
|
||||||
|
// does the same). A keepalive fetch is a cors request and sends the real origin.
|
||||||
|
const core = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "core.js"), "utf8");
|
||||||
|
const wire = core.slice(core.indexOf("export function wireChrome()"));
|
||||||
|
const pagehide = wire.slice(0, wire.indexOf("});"));
|
||||||
|
assert.match(pagehide, /fetch\("bye", \{ method: "POST", keepalive: true \}\)/, pagehide);
|
||||||
|
assert.doesNotMatch(core, /navigator\.sendBeacon\(/, "no beacon call left anywhere in the page's core");
|
||||||
|
});
|
||||||
@@ -589,7 +589,7 @@ test("git board: the page draws it from git-board.js, with no inline styles", ()
|
|||||||
const dir = path.join(path.dirname(CONSOLE_CLI), "public");
|
const dir = path.join(path.dirname(CONSOLE_CLI), "public");
|
||||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||||
const view = fs.readFileSync(path.join(dir, "git-board-view.js"), "utf8");
|
const view = fs.readFileSync(path.join(dir, "git-board-view.js"), "utf8");
|
||||||
for (const m of ["git-board.js", "git-board-view.js", "pr-url.js"]) assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
for (const m of ["git-board.js", "git-board-view.js", "pr-url.js"]) assert.ok(html.includes(`rel="modulepreload" href="${m}"`), `the page preloads ${m}`);
|
||||||
const selectors = fs.readFileSync(path.join(dir, "selectors.js"), "utf8");
|
const selectors = fs.readFileSync(path.join(dir, "selectors.js"), "utf8");
|
||||||
assert.match(selectors, /const isGitBoard = \(\) => page\.S && page\.S\.workflow === "git" && page\.S\.git;/);
|
assert.match(selectors, /const isGitBoard = \(\) => page\.S && page\.S\.workflow === "git" && page\.S\.git;/);
|
||||||
assert.match(view, /a\.rel = "noopener"/, "the PR link opens with rel=noopener");
|
assert.match(view, /a\.rel = "noopener"/, "the PR link opens with rel=noopener");
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ import assert from "node:assert/strict";
|
|||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { execFileSync, spawnSync } from "node:child_process";
|
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
||||||
|
import { createRequire } from "node:module";
|
||||||
import { EventEmitter } from "node:events";
|
import { EventEmitter } from "node:events";
|
||||||
import { PassThrough } from "node:stream";
|
import { PassThrough } from "node:stream";
|
||||||
// The page's pure answer-shaping logic. app.js itself cannot be imported here
|
// The page's pure answer-shaping logic. app.js itself cannot be imported here
|
||||||
@@ -166,6 +167,7 @@ import {
|
|||||||
import { applyMention, matchNames, mentionAt } from "../src/web-console/public/mentions.js";
|
import { applyMention, matchNames, mentionAt } from "../src/web-console/public/mentions.js";
|
||||||
import {
|
import {
|
||||||
pickerCommand,
|
pickerCommand,
|
||||||
|
pickerOutcome,
|
||||||
pickFolder,
|
pickFolder,
|
||||||
WINDOWS_PICKER_SOURCE,
|
WINDOWS_PICKER_SOURCE,
|
||||||
WORKSPACE_PICKER_PROMPT,
|
WORKSPACE_PICKER_PROMPT,
|
||||||
@@ -187,6 +189,7 @@ import { chatReplyLines } from "../src/web-console/inbox.mjs";
|
|||||||
import {
|
import {
|
||||||
initialWorkspace,
|
initialWorkspace,
|
||||||
pendingWorkspaceChanges,
|
pendingWorkspaceChanges,
|
||||||
|
pickerStart,
|
||||||
readWorkspaceCursor,
|
readWorkspaceCursor,
|
||||||
WORKSPACE_FILE,
|
WORKSPACE_FILE,
|
||||||
writeWorkspaceCursor,
|
writeWorkspaceCursor,
|
||||||
@@ -2297,7 +2300,7 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
|
|||||||
assert.ok(pill, "the pill sits in .ident");
|
assert.ok(pill, "the pill sits in .ident");
|
||||||
assert.ok(pill[0].includes('class="meter-track"') && pill[0].includes('class="meter-fill"'));
|
assert.ok(pill[0].includes('class="meter-track"') && pill[0].includes('class="meter-fill"'));
|
||||||
for (const m of ["workspace.js", "meter.js", "mentions.js", "favicon.js"]) {
|
for (const m of ["workspace.js", "meter.js", "mentions.js", "favicon.js"]) {
|
||||||
assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
assert.ok(html.includes(`rel="modulepreload" href="${m}"`), `the page preloads ${m}`);
|
||||||
}
|
}
|
||||||
// The CSP refuses style attributes and inline script: the new markup has neither.
|
// The CSP refuses style attributes and inline script: the new markup has neither.
|
||||||
const added = [
|
const added = [
|
||||||
@@ -2351,31 +2354,106 @@ test("picker: the workspace picker cannot drift from the launcher's", () => {
|
|||||||
assert.equal(WORKSPACE_PICKER_PROMPT, "Choose a folder to add to the workspace");
|
assert.equal(WORKSPACE_PICKER_PROMPT, "Choose a folder to add to the workspace");
|
||||||
});
|
});
|
||||||
|
|
||||||
function fakeSpawn(code, output) {
|
test("picker: the launcher and the workspace read a picker's exit the same way", () => {
|
||||||
|
// Two copies of one rule (macOS: only osascript's (-128) is a cancel), each
|
||||||
|
// with its own tests: this keeps an edit to one from leaving the other behind.
|
||||||
|
const { pickerCancelled } = createRequire(import.meta.url)(path.join(ROOT, "src", "launcher", "plan2code.js"));
|
||||||
|
const errors = ["", "0:17: execution error: User canceled. (-128)", "execution error: Not authorized to send Apple events. (-1743)", "(-1280)", "Gtk-WARNING\n"];
|
||||||
|
for (const platform of ["darwin", "linux", "win32"]) {
|
||||||
|
for (const code of [0, 1, 2]) {
|
||||||
|
for (const stdout of ["", "/some/folder\n"]) {
|
||||||
|
for (const stderr of errors) {
|
||||||
|
const workspace = "cancelled" in pickerOutcome(code, stdout, stderr, platform);
|
||||||
|
assert.equal(pickerCancelled(code, stdout, stderr, platform), workspace, JSON.stringify({ platform, code, stdout, stderr }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("picker: stderr is read only on macOS, where it tells a cancel from a failure", { skip: process.platform === "win32" ? "pickerCommand needs a POSIX picker here" : false }, async () => {
|
||||||
|
for (const [platform, expected] of [["darwin", "pipe"], ["linux", "ignore"], ["win32", "ignore"]]) {
|
||||||
|
// Linux's picker is zenity or kdialog, found on PATH: none on this machine, nothing to start.
|
||||||
|
if (!pickerCommand(os.tmpdir(), "p", { platform })) continue;
|
||||||
|
let stdio = null;
|
||||||
|
const spy = (command, args, options) => {
|
||||||
|
stdio = options.stdio;
|
||||||
|
return fakeSpawn(0, "", "", platform)(command, args, options);
|
||||||
|
};
|
||||||
|
await pickFolder(os.tmpdir(), "p", { platform, spawnImpl: spy });
|
||||||
|
assert.ok(stdio, `${platform}: the picker was started`);
|
||||||
|
assert.equal(stdio[2], expected, platform);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function fakeSpawn(code, output, errorText = "", platform = process.platform) {
|
||||||
return (command, args, options) => {
|
return (command, args, options) => {
|
||||||
assert.equal(options.windowsHide, true);
|
assert.equal(options.windowsHide, true);
|
||||||
|
assert.equal(options.stdio[2], platform === "darwin" ? "pipe" : "ignore", "stderr is piped on macOS only, where a cancel is told from a failure");
|
||||||
const child = new EventEmitter();
|
const child = new EventEmitter();
|
||||||
child.stdout = new PassThrough();
|
child.stdout = new PassThrough();
|
||||||
|
child.stderr = new PassThrough();
|
||||||
setImmediate(() => {
|
setImmediate(() => {
|
||||||
if (output) child.stdout.write(output);
|
if (output) child.stdout.write(output);
|
||||||
|
if (errorText) child.stderr.write(errorText);
|
||||||
child.stdout.end();
|
child.stdout.end();
|
||||||
|
child.stderr.end();
|
||||||
setImmediate(() => child.emit("close", code));
|
setImmediate(() => child.emit("close", code));
|
||||||
});
|
});
|
||||||
return child;
|
return child;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// What osascript prints on a cancel, and on a failure (a bad script here; a
|
||||||
|
// missing default folder or a refused permission end the same way, exit 1).
|
||||||
|
const MAC_CANCEL = "0:17: execution error: User canceled. (-128)\n";
|
||||||
|
const MAC_FAILURE = "0:4: execution error: The variable this is not defined. (-2753)\n";
|
||||||
|
|
||||||
test(
|
test(
|
||||||
"picker: pickFolder reads a pick, a cancel and a failure off the picker's exit",
|
"picker: pickFolder reads a pick, a cancel and a failure off the picker's exit",
|
||||||
{ skip: pickerCommand(os.tmpdir(), WORKSPACE_PICKER_PROMPT) ? false : "no folder picker on this machine" },
|
{ skip: pickerCommand(os.tmpdir(), WORKSPACE_PICKER_PROMPT) ? false : "no folder picker on this machine" },
|
||||||
async () => {
|
async () => {
|
||||||
const picked = path.join(os.tmpdir(), "picked");
|
const picked = path.join(os.tmpdir(), "picked");
|
||||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(0, picked + "\n") }), { path: path.resolve(picked) });
|
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(0, picked + "\n") }), { path: path.resolve(picked) });
|
||||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(1, "") }), { cancelled: true });
|
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(1, "", MAC_CANCEL) }), { cancelled: true });
|
||||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(2, "") }), { error: "picker-failed" });
|
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(2, "") }), { error: "picker-failed" });
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
test("picker: on macOS only osascript's (-128) makes an exit 1 a cancel; any other exit 1 with no folder is a failure", async () => {
|
||||||
|
const pick = (code, output, errorText) => pickFolder(os.tmpdir(), "p", { platform: "darwin", spawnImpl: fakeSpawn(code, output, errorText, "darwin") });
|
||||||
|
assert.equal(pickerCommand(os.tmpdir(), "p", { platform: "darwin" }).command, "osascript");
|
||||||
|
assert.deepEqual(await pick(1, "", MAC_CANCEL), { cancelled: true });
|
||||||
|
assert.deepEqual(await pick(1, "", MAC_FAILURE), { error: "picker-failed" });
|
||||||
|
assert.deepEqual(await pick(1, "", ""), { error: "picker-failed" }, "no stderr at all is no proof of a cancel");
|
||||||
|
const picked = path.join(os.tmpdir(), "picked");
|
||||||
|
assert.deepEqual(await pick(0, picked + "\n", ""), { path: path.resolve(picked) });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("picker: on Windows and Linux an exit 1 with no folder stays a cancel, whatever stderr says", async () => {
|
||||||
|
assert.equal(pickerCommand(os.tmpdir(), "p", { platform: "win32" }).command, "powershell.exe");
|
||||||
|
for (const errorText of ["", "Gtk-WARNING: some noise\n"]) {
|
||||||
|
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { platform: "win32", spawnImpl: fakeSpawn(1, "", errorText, "win32") }), { cancelled: true });
|
||||||
|
}
|
||||||
|
// Linux's picker needs a display and zenity or kdialog on this host, so its
|
||||||
|
// rule is checked on the outcome itself.
|
||||||
|
for (const platform of ["linux", "win32"]) {
|
||||||
|
assert.deepEqual(pickerOutcome(1, "", "", platform), { cancelled: true }, platform);
|
||||||
|
assert.deepEqual(pickerOutcome(1, "", "(-2753)", platform), { cancelled: true }, platform);
|
||||||
|
assert.deepEqual(pickerOutcome(0, "", "", platform), { cancelled: true }, platform);
|
||||||
|
assert.deepEqual(pickerOutcome(3, "", "", platform), { error: "picker-failed" }, platform);
|
||||||
|
}
|
||||||
|
assert.deepEqual(pickerOutcome(1, "", MAC_CANCEL, "darwin"), { cancelled: true });
|
||||||
|
assert.deepEqual(pickerOutcome(1, "", MAC_FAILURE, "darwin"), { error: "picker-failed" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("picker: a picker that writes a lot to stderr still finishes, and its last words decide", async () => {
|
||||||
|
// A real child writing far past a pipe's buffer: unread, it would block before exiting.
|
||||||
|
const chatty = (command, args, options) =>
|
||||||
|
spawn(process.execPath, ["-e", "process.stderr.write('Gtk-WARNING\\n'.repeat(100000)); process.stderr.write('User canceled. (-128)'); process.exitCode = 1"], options);
|
||||||
|
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { platform: "darwin", spawnImpl: chatty }), { cancelled: true });
|
||||||
|
});
|
||||||
|
|
||||||
test("ledger: a torn trailing line is skipped, then read once completed; an append after a fragment starts a new line", () => {
|
test("ledger: a torn trailing line is skipped, then read once completed; an append after a fragment starts a new line", () => {
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-ledger-"));
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-ledger-"));
|
||||||
try {
|
try {
|
||||||
@@ -2708,6 +2786,26 @@ test("initialWorkspace names the original folder after itself and marks it origi
|
|||||||
assert.deepEqual([ws.missing, ws.changes, ws.remote], [[], [], ""]);
|
assert.deepEqual([ws.missing, ws.changes, ws.remote], [[], [], ""]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Browse... opens beside the last folder added. When that folder is gone, a missing
|
||||||
|
// start must not read as "Browse is not available here".
|
||||||
|
test("pickerStart opens beside the last folder added, or at its nearest folder still on disk", () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-picker-start-"));
|
||||||
|
try {
|
||||||
|
const project = path.join(root, "project");
|
||||||
|
const kept = path.join(root, "kept");
|
||||||
|
fs.mkdirSync(project);
|
||||||
|
fs.mkdirSync(path.join(kept, "inner"), { recursive: true });
|
||||||
|
assert.equal(pickerStart(initialWorkspace(project), project), project, "the original folder when nothing was added");
|
||||||
|
const ws = initialWorkspace(project);
|
||||||
|
ws.folders.push({ id: "f1", path: path.join(kept, "inner"), name: "inner", description: "" });
|
||||||
|
assert.equal(pickerStart(ws, project), kept, "beside the last folder added");
|
||||||
|
fs.rmSync(kept, { recursive: true, force: true });
|
||||||
|
assert.equal(pickerStart(ws, project), root, "the nearest folder still on disk");
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(root, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// The meter's tables are built from skills.js plus the events that are not a
|
// The meter's tables are built from skills.js plus the events that are not a
|
||||||
// skill's own. Held to their values when they were written by hand.
|
// skill's own. Held to their values when they were written by hand.
|
||||||
test("meter: the weights and labels built from the skill list are the ones written by hand before", () => {
|
test("meter: the weights and labels built from the skill list are the ones written by hand before", () => {
|
||||||
|
|||||||
@@ -144,14 +144,14 @@ test("pictures: JPEG only, listed oldest first, with thumbnails when sent", () =
|
|||||||
const first = addImage(folder, tab, JPEG);
|
const first = addImage(folder, tab, JPEG);
|
||||||
const second = addImage(folder, tab, JPEG);
|
const second = addImage(folder, tab, JPEG);
|
||||||
assert.match(first.id, IMAGE_ID_RE);
|
assert.match(first.id, IMAGE_ID_RE);
|
||||||
assert.equal(first.url, `/notepad/images/${tab}/${first.id}.jpg`);
|
assert.equal(first.url, `notepad/images/${tab}/${first.id}.jpg`);
|
||||||
// Make the order unambiguous: the first is older.
|
// Make the order unambiguous: the first is older.
|
||||||
const older = new Date(Date.now() - 60_000);
|
const older = new Date(Date.now() - 60_000);
|
||||||
fs.utimesSync(path.join(tabDir(folder, tab), "images", first.id + ".jpg"), older, older);
|
fs.utimesSync(path.join(tabDir(folder, tab), "images", first.id + ".jpg"), older, older);
|
||||||
addThumb(folder, tab, second.id, JPEG);
|
addThumb(folder, tab, second.id, JPEG);
|
||||||
assert.deepEqual(readNotepad(folder).images, [
|
assert.deepEqual(readNotepad(folder).images, [
|
||||||
{ id: first.id, url: first.url, thumb: null },
|
{ id: first.id, url: first.url, thumb: null },
|
||||||
{ id: second.id, url: second.url, thumb: `/notepad/images/${tab}/${second.id}.thumb.jpg` },
|
{ id: second.id, url: second.url, thumb: `notepad/images/${tab}/${second.id}.thumb.jpg` },
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -509,8 +509,8 @@ test("the first shape reads as one Notes tab, and the read writes nothing", () =
|
|||||||
[U1, U2],
|
[U1, U2],
|
||||||
"oldest first",
|
"oldest first",
|
||||||
);
|
);
|
||||||
assert.equal(read.images[0].url, `/notepad/images/${LEGACY_TAB_ID}/${U1}.jpg`);
|
assert.equal(read.images[0].url, `notepad/images/${LEGACY_TAB_ID}/${U1}.jpg`);
|
||||||
assert.equal(read.images[0].thumb, `/notepad/images/${LEGACY_TAB_ID}/${U1}.thumb.jpg`);
|
assert.equal(read.images[0].thumb, `notepad/images/${LEGACY_TAB_ID}/${U1}.thumb.jpg`);
|
||||||
assert.equal(read.images[1].thumb, null);
|
assert.equal(read.images[1].thumb, null);
|
||||||
assert.deepEqual(listTabs(folder), { tabs: [{ id: LEGACY_TAB_ID, name: "Notes" }], last: LEGACY_TAB_ID });
|
assert.deepEqual(listTabs(folder), { tabs: [{ id: LEGACY_TAB_ID, name: "Notes" }], last: LEGACY_TAB_ID });
|
||||||
assert.equal(readNotepad(folder, LEGACY_TAB_ID).text, "old note\n");
|
assert.equal(readNotepad(folder, LEGACY_TAB_ID).text, "old note\n");
|
||||||
@@ -564,7 +564,7 @@ test("any first write migrates: a picture, a new tab, and an old picture can be
|
|||||||
const f2 = freshFolder("legacy");
|
const f2 = freshFolder("legacy");
|
||||||
legacyNotepad(f2);
|
legacyNotepad(f2);
|
||||||
const added = addImage(f2, LEGACY_TAB_ID, JPEG);
|
const added = addImage(f2, LEGACY_TAB_ID, JPEG);
|
||||||
assert.equal(added.url, `/notepad/images/${LEGACY_TAB_ID}/${added.id}.jpg`);
|
assert.equal(added.url, `notepad/images/${LEGACY_TAB_ID}/${added.id}.jpg`);
|
||||||
assert.equal(readNotepad(f2).images.length, 3);
|
assert.equal(readNotepad(f2).images.length, 3);
|
||||||
// A first-shape notepad with a picture and no note still migrates.
|
// A first-shape notepad with a picture and no note still migrates.
|
||||||
const f3 = freshFolder("legacy");
|
const f3 = freshFolder("legacy");
|
||||||
@@ -718,7 +718,10 @@ test("pictures through the routes: upload, thumb, fetch, delete and every refusa
|
|||||||
|
|
||||||
const up = await postJpeg(s, "/notepad/image", JPEG);
|
const up = await postJpeg(s, "/notepad/image", JPEG);
|
||||||
assert.equal(up.status, 200);
|
assert.equal(up.status, 200);
|
||||||
const { id, url } = await up.json();
|
const { id, url: link } = await up.json();
|
||||||
|
assert.doesNotMatch(link, /^\//, "page-relative");
|
||||||
|
// The page at / asks for it here.
|
||||||
|
const url = `/${link}`;
|
||||||
assert.match(id, IMAGE_ID_RE);
|
assert.match(id, IMAGE_ID_RE);
|
||||||
|
|
||||||
const unknownThumb = await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG);
|
const unknownThumb = await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG);
|
||||||
@@ -853,7 +856,7 @@ test("GET /notepad answers a notepad still in the first shape as a Notes tab, an
|
|||||||
assert.equal(res.body.text, "old note\n");
|
assert.equal(res.body.text, "old note\n");
|
||||||
assert.equal(res.body.images.length, 2);
|
assert.equal(res.body.images.length, 2);
|
||||||
assert.deepEqual(treeOf(dir), before, "the read wrote nothing");
|
assert.deepEqual(treeOf(dir), before, "the read wrote nothing");
|
||||||
const img = await fetch(`${s.base}${res.body.images[0].url}`, { headers: { cookie: s.cookie, connection: "close" } });
|
const img = await fetch(`${s.base}/${res.body.images[0].url}`, { headers: { cookie: s.cookie, connection: "close" } });
|
||||||
assert.equal(img.status, 200, "the picture is served from where it still is");
|
assert.equal(img.status, 200, "the picture is served from where it still is");
|
||||||
// The unchanged page's save, with no tab named, lands in Notes and migrates.
|
// The unchanged page's save, with no tab named, lands in Notes and migrates.
|
||||||
assert.equal((await s.send("/notepad/text", { text: "page save" })).status, 200);
|
assert.equal((await s.send("/notepad/text", { text: "page save" })).status, 200);
|
||||||
@@ -1004,16 +1007,18 @@ test("pictures through ?tab=: upload, thumb, fetch and delete, each under the ta
|
|||||||
const up = await postJpeg(s, `/notepad/image?tab=${a}`, JPEG);
|
const up = await postJpeg(s, `/notepad/image?tab=${a}`, JPEG);
|
||||||
assert.equal(up.status, 200);
|
assert.equal(up.status, 200);
|
||||||
const { id, url } = await up.json();
|
const { id, url } = await up.json();
|
||||||
assert.equal(url, `/notepad/images/${a}/${id}.jpg`);
|
assert.equal(url, `notepad/images/${a}/${id}.jpg`);
|
||||||
|
// Page-relative: the page at / asks for it here.
|
||||||
|
const served = `/${url}`;
|
||||||
assert.equal((await postJpeg(s, `/notepad/thumb?tab=${a}&id=${id}`, JPEG)).status, 200);
|
assert.equal((await postJpeg(s, `/notepad/thumb?tab=${a}&id=${id}`, JPEG)).status, 200);
|
||||||
assert.equal((await get(url)).status, 200);
|
assert.equal((await get(served)).status, 200);
|
||||||
assert.equal((await get(`/notepad/images/${a}/${id}.thumb.jpg`)).status, 200);
|
assert.equal((await get(`/notepad/images/${a}/${id}.thumb.jpg`)).status, 200);
|
||||||
// Not under another tab, not in the old shape, not under a tab that is not there.
|
// Not under another tab, not in the old shape, not under a tab that is not there.
|
||||||
assert.equal((await get(`/notepad/images/${b}/${id}.jpg`)).status, 404);
|
assert.equal((await get(`/notepad/images/${b}/${id}.jpg`)).status, 404);
|
||||||
assert.equal((await get(`/notepad/images/${id}.jpg`)).status, 404);
|
assert.equal((await get(`/notepad/images/${id}.jpg`)).status, 404);
|
||||||
assert.equal((await get(`/notepad/images/ffffffffffff/${id}.jpg`)).status, 404);
|
assert.equal((await get(`/notepad/images/ffffffffffff/${id}.jpg`)).status, 404);
|
||||||
assert.deepEqual((await getJson(s, `/notepad?tab=${b}`)).body.images, []);
|
assert.deepEqual((await getJson(s, `/notepad?tab=${b}`)).body.images, []);
|
||||||
assert.equal((await getJson(s, `/notepad?tab=${a}`)).body.images[0].thumb, `/notepad/images/${a}/${id}.thumb.jpg`);
|
assert.equal((await getJson(s, `/notepad?tab=${a}`)).body.images[0].thumb, `notepad/images/${a}/${id}.thumb.jpg`);
|
||||||
// A picture or thumb for a tab that is not there, and a delete from the wrong tab.
|
// A picture or thumb for a tab that is not there, and a delete from the wrong tab.
|
||||||
const stray = await postJpeg(s, "/notepad/image?tab=ffffffffffff", JPEG);
|
const stray = await postJpeg(s, "/notepad/image?tab=ffffffffffff", JPEG);
|
||||||
assert.equal(stray.status, 404);
|
assert.equal(stray.status, 404);
|
||||||
@@ -1022,12 +1027,12 @@ test("pictures through ?tab=: upload, thumb, fetch and delete, each under the ta
|
|||||||
assert.equal((await postJpeg(s, `/notepad/image?tab=nope`, JPEG)).status, 404);
|
assert.equal((await postJpeg(s, `/notepad/image?tab=nope`, JPEG)).status, 404);
|
||||||
assert.equal((await s.send(`/notepad/image/delete?tab=${b}`, { id })).status, 404, "tab B does not hold it");
|
assert.equal((await s.send(`/notepad/image/delete?tab=${b}`, { id })).status, 404, "tab B does not hold it");
|
||||||
assert.equal((await s.send(`/notepad/image/delete?tab=ffffffffffff`, { id })).status, 404);
|
assert.equal((await s.send(`/notepad/image/delete?tab=ffffffffffff`, { id })).status, 404);
|
||||||
assert.equal((await get(url)).status, 200, "still there");
|
assert.equal((await get(served)).status, 200, "still there");
|
||||||
assert.equal((await s.send(`/notepad/image/delete?tab=${a}`, { id })).status, 200);
|
assert.equal((await s.send(`/notepad/image/delete?tab=${a}`, { id })).status, 200);
|
||||||
assert.equal((await get(url)).status, 404);
|
assert.equal((await get(served)).status, 404);
|
||||||
// With no tab named, the picture goes to the last tab used.
|
// With no tab named, the picture goes to the last tab used.
|
||||||
const unnamed = await (await postJpeg(s, "/notepad/image", JPEG)).json();
|
const unnamed = await (await postJpeg(s, "/notepad/image", JPEG)).json();
|
||||||
assert.equal(unnamed.url.split("/")[3], b);
|
assert.equal(unnamed.url.split("/")[2], b);
|
||||||
assert.equal((await s.send("/notepad/image/delete", { id: unnamed.id })).status, 200);
|
assert.equal((await s.send("/notepad/image/delete", { id: unnamed.id })).status, 200);
|
||||||
assert.deepEqual(await (await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG)).json(), { error: "not-found" });
|
assert.deepEqual(await (await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG)).json(), { error: "not-found" });
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import fs from "node:fs";
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { pageSuite, openSession, tempProject, textOf, styleOf } from "./page-test-helpers.mjs";
|
import { pageSuite, openSession, tempProject, textOf, styleOf, frameInFakeApp } from "./page-test-helpers.mjs";
|
||||||
import { cli, until, CONSOLE_CLI, HOME, JPEG } from "./web-console-test-helpers.mjs";
|
import { cli, until, CONSOLE_CLI, HOME, JPEG } from "./web-console-test-helpers.mjs";
|
||||||
import { addImage, createTab, deleteTab, markTabSent, saveNote } from "../src/web-console/notepads.mjs";
|
import { addImage, createTab, deleteTab, markTabSent, saveNote } from "../src/web-console/notepads.mjs";
|
||||||
import { steadyColumns } from "../src/web-console/public/card-rows.js";
|
import { steadyColumns } from "../src/web-console/public/card-rows.js";
|
||||||
@@ -922,3 +922,183 @@ test("with the flag set the dashboard shows the quiet extras line", async (t) =>
|
|||||||
await line.waitFor();
|
await line.waitFor();
|
||||||
assert.match(await textOf(line), /Two optional extras: set your role, switch on Learning\./);
|
assert.match(await textOf(line), /Two optional extras: set your role, switch on Learning\./);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// The Loop box: Implement's and Review's confirm panes carry a Loop checkbox
|
||||||
|
// that opens the desktop app's matching loop setup screen in place of a
|
||||||
|
// launch. NOTE_PROJECT's documented spec (ready) is the only one here, so the
|
||||||
|
// picker opens on it and Implement's card is lit.
|
||||||
|
const LOOP_PROJECT = {
|
||||||
|
"AGENTS.md": DRAFT_PROJECT["AGENTS.md"],
|
||||||
|
"specs/ready/overview.md": NOTE_PROJECT["specs/ready/overview.md"],
|
||||||
|
"specs/ready/phase-1.md": NOTE_PROJECT["specs/ready/phase-1.md"],
|
||||||
|
};
|
||||||
|
|
||||||
|
const IMPLEMENT_LOOP_BOX = "Build every phase unattended (Implementation Loop)";
|
||||||
|
const REVIEW_LOOP_BOX = "Review and fix in rounds (Review Loop)";
|
||||||
|
const REVIEW_BOX = "Review each phase with a fresh agent before sign-off";
|
||||||
|
|
||||||
|
|
||||||
|
// The dashboard on LOOP_PROJECT, under the app (PLAN2CODE_IN_APP=1, framed
|
||||||
|
// by a fake app) or in a plain browser, with the picker on `ready`.
|
||||||
|
async function openLoopMenu(t, { inApp }) {
|
||||||
|
const s = await openSession(await suite.browser(), {
|
||||||
|
t,
|
||||||
|
workflow: "dashboard",
|
||||||
|
payload: MENU,
|
||||||
|
project: tempProject(LOOP_PROJECT),
|
||||||
|
...(inApp ? { env: { PLAN2CODE_IN_APP: "1" } } : {}),
|
||||||
|
});
|
||||||
|
const main = await toTheMenu(s);
|
||||||
|
if (inApp) await frameInFakeApp(s);
|
||||||
|
await pickedChip(main, "ready").waitFor();
|
||||||
|
return { s, main };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Opens `command`'s card on the menu, landing on its confirm pane.
|
||||||
|
async function openPane(main, command) {
|
||||||
|
await lightOf(main, command).click();
|
||||||
|
await main.getByRole("button", { name: "Back" }).waitFor();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function backToMenu(main) {
|
||||||
|
await main.getByRole("button", { name: "Back" }).click();
|
||||||
|
await main.getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||||
|
}
|
||||||
|
|
||||||
|
// A checkbox's own `disabled`, read in the page: Playwright's isDisabled()
|
||||||
|
// also counts aria-disabled.
|
||||||
|
const disabledOf = (box) => box.evaluate((input) => input.disabled);
|
||||||
|
|
||||||
|
// What the page holds in `page.<key>`, read through its own state module.
|
||||||
|
const pageField = (s, key) =>
|
||||||
|
s.page.evaluate(async (name) => {
|
||||||
|
const { page } = await import(new URL("state.js", document.baseURI).href);
|
||||||
|
return JSON.parse(JSON.stringify(page[name] ?? null));
|
||||||
|
}, key);
|
||||||
|
|
||||||
|
// Sets `loop` on the page's copy of the session state and redraws, the way a
|
||||||
|
// state frame from a loop-driven session would. The server only locks
|
||||||
|
// implement, implement-review and review sessions with `open --loop`, so the
|
||||||
|
// dashboard's pane is driven from the page.
|
||||||
|
async function setLoop(s, loop) {
|
||||||
|
await s.page.evaluate(async (value) => {
|
||||||
|
const { page, redraw } = await import(new URL("state.js", document.baseURI).href);
|
||||||
|
page.S = { ...page.S, loop: value };
|
||||||
|
redraw();
|
||||||
|
}, loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
test("under the app, Implement's Loop box is enabled, grays the Review box and swaps the command and Start while ticked", async (t) => {
|
||||||
|
const { main } = await openLoopMenu(t, { inApp: true });
|
||||||
|
await openPane(main, "/plan2code-3-implement");
|
||||||
|
|
||||||
|
const loop = main.getByRole("checkbox", { name: IMPLEMENT_LOOP_BOX });
|
||||||
|
const review = main.getByRole("checkbox", { name: REVIEW_BOX });
|
||||||
|
const cmd = main.locator(".confirm-cmd code");
|
||||||
|
assert.equal(await disabledOf(loop), false, "the Loop box is enabled in the app");
|
||||||
|
assert.equal(await loop.isChecked(), false, "the Loop box starts unticked");
|
||||||
|
assert.equal(await main.locator(".confirm-loop-off").count(), 0, "no reason line while it is enabled");
|
||||||
|
const command = await textOf(cmd);
|
||||||
|
assert.match(command, /^\/plan2code-3-implement/);
|
||||||
|
await main.getByRole("button", { name: "Start Implement" }).waitFor();
|
||||||
|
|
||||||
|
await loop.check();
|
||||||
|
assert.equal(await disabledOf(review), true, "ticking Loop grays the Review box");
|
||||||
|
assert.equal(await textOf(cmd), "Desktop app only");
|
||||||
|
await main.getByRole("button", { name: "Set up Implementation Loop" }).waitFor();
|
||||||
|
assert.equal(await main.getByRole("button", { name: "Start Implement" }).count(), 0, "Start names the loop");
|
||||||
|
|
||||||
|
await loop.uncheck();
|
||||||
|
assert.equal(await disabledOf(review), false, "unticking Loop gives the Review box back");
|
||||||
|
assert.equal(await textOf(cmd), command, "the command line comes back");
|
||||||
|
await main.getByRole("button", { name: "Start Implement" }).waitFor();
|
||||||
|
assert.equal(await main.getByRole("button", { name: "Set up Implementation Loop" }).count(), 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("under the app, Start on Implement with Loop ticked opens the Implementation Loop setup for the picked spec", async (t) => {
|
||||||
|
const { s, main } = await openLoopMenu(t, { inApp: true });
|
||||||
|
await openPane(main, "/plan2code-3-implement");
|
||||||
|
await main.getByRole("checkbox", { name: IMPLEMENT_LOOP_BOX }).check();
|
||||||
|
await main.getByRole("button", { name: "Set up Implementation Loop" }).click();
|
||||||
|
|
||||||
|
await s.page.locator("#loop-start").waitFor();
|
||||||
|
assert.equal((await pageField(s, "loopSetup"))?.spec, "specs/ready");
|
||||||
|
assert.equal(await textOf(main.locator(".confirm-spec code")), "specs/ready", "the setup screen names the picker's spec");
|
||||||
|
assert.equal(s.wait(1).code, 10, "nothing was launched");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("under the app, Review's Loop box is enabled and Start opens the Review Loop setup with the spec filled in", async (t) => {
|
||||||
|
const { s, main } = await openLoopMenu(t, { inApp: true });
|
||||||
|
await openPane(main, "/plan2code-review");
|
||||||
|
|
||||||
|
const loop = main.getByRole("checkbox", { name: REVIEW_LOOP_BOX });
|
||||||
|
assert.equal(await disabledOf(loop), false, "the Loop box is enabled in the app");
|
||||||
|
await main.getByRole("button", { name: "Start Review" }).waitFor();
|
||||||
|
await loop.check();
|
||||||
|
await main.getByRole("button", { name: "Set up Review Loop" }).click();
|
||||||
|
|
||||||
|
await s.page.locator("#review-loop-start").waitFor();
|
||||||
|
const setup = await pageField(s, "reviewLoopSetup");
|
||||||
|
assert.equal(setup?.spec, "specs/ready", "the setup opened for the picker's spec");
|
||||||
|
assert.equal(setup?.form?.spec, "specs/ready", "the picker's spec fills the setup's spec");
|
||||||
|
assert.equal(s.wait(1).code, 10, "nothing was launched");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("outside the app, both Loop boxes are grayed with the desktop-app line, and Start still launches", async (t) => {
|
||||||
|
// A launch ends the menu, so each pane gets a session of its own.
|
||||||
|
// Review's card takes no spec, so its launch carries none.
|
||||||
|
for (const [command, name, title, skill, spec] of [
|
||||||
|
["/plan2code-3-implement", IMPLEMENT_LOOP_BOX, "Implement", "plan2code-3-implement-review", "specs/ready"],
|
||||||
|
["/plan2code-review", REVIEW_LOOP_BOX, "Review", "plan2code-review", undefined],
|
||||||
|
]) {
|
||||||
|
const { s, main } = await openLoopMenu(t, { inApp: false });
|
||||||
|
await openPane(main, command);
|
||||||
|
const loop = main.getByRole("checkbox", { name });
|
||||||
|
assert.equal(await disabledOf(loop), true, `${title}'s Loop box is grayed outside the app`);
|
||||||
|
await loop.click({ force: true });
|
||||||
|
assert.equal(await loop.isChecked(), false, "a press on the grayed box ticks nothing");
|
||||||
|
assert.equal(await textOf(main.locator(".confirm-loop-off")), "Runs only in the Plan2Code desktop app.");
|
||||||
|
if (title === "Implement") assert.equal(await disabledOf(main.getByRole("checkbox", { name: REVIEW_BOX })), false, "the Review box stays usable");
|
||||||
|
await main.getByRole("button", { name: `Start ${title}` }).click();
|
||||||
|
|
||||||
|
const launch = collect(s).actions.find((a) => a.i === "__launch");
|
||||||
|
assert.ok(launch, `Start launched ${title}`);
|
||||||
|
assert.deepEqual({ skill: launch.skill, spec: launch.spec }, { skill, spec });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("no Implementation Loop or Review Loop card is drawn, in the app or outside it", async (t) => {
|
||||||
|
for (const inApp of [true, false]) {
|
||||||
|
const { main } = await openLoopMenu(t, { inApp });
|
||||||
|
await hideUnavailable(main, false);
|
||||||
|
const titles = (await main.locator(".dash-card .dash-card-title").allInnerTexts()).map((title) => title.trim());
|
||||||
|
assert.ok(titles.includes("Implement") && titles.includes("Review"), `the cards the boxes ride on are drawn: ${titles.join(", ")}`);
|
||||||
|
for (const gone of ["Implementation Loop", "Review Loop"]) {
|
||||||
|
assert.equal(titles.includes(gone), false, `no ${gone} card ${inApp ? "in the app" : "outside it"}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("while a loop runs, both Loop boxes are grayed with the running line", async (t) => {
|
||||||
|
const { s, main } = await openLoopMenu(t, { inApp: true });
|
||||||
|
for (const [command, name] of [
|
||||||
|
["/plan2code-3-implement", IMPLEMENT_LOOP_BOX],
|
||||||
|
["/plan2code-review", REVIEW_LOOP_BOX],
|
||||||
|
]) {
|
||||||
|
await openPane(main, command);
|
||||||
|
const loop = main.getByRole("checkbox", { name });
|
||||||
|
assert.equal(await disabledOf(loop), false, `${command}'s box is enabled before the loop starts`);
|
||||||
|
|
||||||
|
await setLoop(s, { driving: true });
|
||||||
|
const reason = main.locator(".confirm-loop-off");
|
||||||
|
await reason.waitFor();
|
||||||
|
assert.equal(await textOf(reason), "A loop is running. Stop it from the banner at the top of the window first.");
|
||||||
|
assert.equal(await disabledOf(loop), true, `${command}'s box is grayed while a loop runs`);
|
||||||
|
await loop.click({ force: true });
|
||||||
|
assert.equal(await loop.isChecked(), false, "a press on the grayed box ticks nothing");
|
||||||
|
|
||||||
|
await setLoop(s, null);
|
||||||
|
await reason.waitFor({ state: "detached" });
|
||||||
|
await backToMenu(main);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
// Web console page tests: the page as the macOS app's frame has it. WebKit
|
||||||
|
// gives that frame no cookie, so the console signs it in by a path prefix
|
||||||
|
// (`/f/<key>/`, routes.mjs) and the page runs under it. Every request the page
|
||||||
|
// makes there must stay under the prefix: one that leaves it gets a 403, and
|
||||||
|
// only in the macOS app. This file opens the page that way in a browser
|
||||||
|
// context with no cookie, uses the parts that fetch, and fails on any request
|
||||||
|
// that left the prefix or was refused. Run with:
|
||||||
|
// node --test scripts/test-web-console-page-frame.mjs
|
||||||
|
|
||||||
|
import crypto from "node:crypto";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { pageSuite, openSession, drawn } from "./page-test-helpers.mjs";
|
||||||
|
import { until, HOME } from "./web-console-test-helpers.mjs";
|
||||||
|
import { createTab, listTabs } from "../src/web-console/notepads.mjs";
|
||||||
|
|
||||||
|
const suite = pageSuite(test);
|
||||||
|
|
||||||
|
const LOOKS_FILE = path.join(HOME, "looks.json");
|
||||||
|
|
||||||
|
// The server takes the app's frame mode only on macOS, with the app's page as
|
||||||
|
// the embed ancestor. On any other OS this makes the server alone believe it
|
||||||
|
// runs on macOS (the CLI that starts it is left as it is), so CI's Linux run
|
||||||
|
// checks the same thing. The whole server sees darwin, not only frameKey():
|
||||||
|
// every macOS branch in it runs here too.
|
||||||
|
const FAKE_MAC =
|
||||||
|
"data:text/javascript," +
|
||||||
|
encodeURIComponent('if (/server\\.mjs$/.test(process.argv[1] || "")) Object.defineProperty(process, "platform", { value: "darwin" });');
|
||||||
|
const FRAME_ENV = { PLAN2CODE_EMBED_ORIGIN: "tauri://localhost", NODE_OPTIONS: `--import=${FAKE_MAC}` };
|
||||||
|
|
||||||
|
// The frame's key, as routes.mjs makes it from the session token.
|
||||||
|
const frameKey = (token) => crypto.createHash("sha256").update(token).digest("hex").slice(0, 32);
|
||||||
|
|
||||||
|
test("under the frame's prefix, with no cookie, the dashboard draws, its stream connects, and nothing it asks for leaves the prefix", async (t) => {
|
||||||
|
fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { welcomeSeen: true, hideActivities: false } }));
|
||||||
|
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
|
||||||
|
const browser = await suite.browser();
|
||||||
|
const s = await openSession(browser, { t, workflow: "dashboard", env: FRAME_ENV });
|
||||||
|
if (!listTabs(s.project).tabs.length) createTab(s.project, "Notes");
|
||||||
|
|
||||||
|
const signIn = new URL(s.url);
|
||||||
|
const token = /^\/s\/([^/]+)\/$/.exec(signIn.pathname)[1];
|
||||||
|
const prefix = `/f/${frameKey(token)}/`;
|
||||||
|
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||||
|
t.after(() => context.close().catch(() => {}));
|
||||||
|
const page = await context.newPage();
|
||||||
|
page.setDefaultTimeout(60000);
|
||||||
|
|
||||||
|
const left = [];
|
||||||
|
const refused = [];
|
||||||
|
const errors = [];
|
||||||
|
let streamed = false;
|
||||||
|
page.on("pageerror", (e) => errors.push(e.message));
|
||||||
|
page.on("request", (r) => {
|
||||||
|
const u = new URL(r.url());
|
||||||
|
if (u.origin === signIn.origin && !u.pathname.startsWith(prefix)) left.push(`${r.method()} ${u.pathname}`);
|
||||||
|
});
|
||||||
|
page.on("response", (r) => {
|
||||||
|
const u = new URL(r.url());
|
||||||
|
if (u.origin !== signIn.origin) return;
|
||||||
|
if (r.status() === 403 || r.status() === 404) refused.push(`${r.status()} ${u.pathname}`);
|
||||||
|
if (u.pathname === `${prefix}events` && r.status() === 200) streamed = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await page.goto(signIn.origin + prefix, { waitUntil: "domcontentloaded" });
|
||||||
|
assert.equal(res.status(), 200, "the page itself, under the prefix");
|
||||||
|
await drawn(page);
|
||||||
|
// Past Planny's wake-up, to the menu.
|
||||||
|
const skip = page.getByRole("button", { name: "Skip the intro" });
|
||||||
|
await skip.click();
|
||||||
|
await skip.waitFor({ state: "hidden" });
|
||||||
|
await page.locator("#main section.dash-group").first().waitFor();
|
||||||
|
assert.deepEqual(await context.cookies(), [], "the frame signs in with no cookie");
|
||||||
|
await until(() => streamed, 10000);
|
||||||
|
assert.ok(streamed, "the event stream connected under the prefix");
|
||||||
|
|
||||||
|
// A step that waits on a request the server refused times out; the
|
||||||
|
// requests that left the prefix or were refused are the reason, so they
|
||||||
|
// are reported first.
|
||||||
|
try {
|
||||||
|
// The Notebook: its tab list and note come from the server.
|
||||||
|
await page.click("#btn-notepad");
|
||||||
|
await page.locator("#notepad-modal[open]").waitFor({ timeout: 15000 });
|
||||||
|
await page.waitForFunction(
|
||||||
|
() => {
|
||||||
|
const c = document.querySelector(".notepad-cm-host")?.shadowRoot?.querySelector(".cm-content");
|
||||||
|
return Boolean(c) && c.getAttribute("aria-readonly") !== "true";
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
{ timeout: 15000 }
|
||||||
|
);
|
||||||
|
await page.click("#notepad-close");
|
||||||
|
|
||||||
|
// User Preferences: a change of theme is saved to the server.
|
||||||
|
await page.click("#btn-looks");
|
||||||
|
await page.locator("#looks-modal[open]").waitFor({ timeout: 15000 });
|
||||||
|
const saved = page.waitForResponse((r) => r.url().endsWith(`${prefix}looks`) && r.request().method() === "POST", { timeout: 15000 });
|
||||||
|
await page.locator('input[name="looks-theme"][value="dark"]').check();
|
||||||
|
assert.equal((await saved).status(), 200, "the looks were saved");
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
|
||||||
|
// Activities: a game's module, loaded the first time it opens.
|
||||||
|
await page.click("#btn-activities");
|
||||||
|
await page.locator("#activities-modal[open]").waitFor({ timeout: 15000 });
|
||||||
|
await page.locator('#activities-picker .activities-row[data-activity="snake"]').click();
|
||||||
|
await page.locator("#activities-board").waitFor({ timeout: 15000 });
|
||||||
|
} finally {
|
||||||
|
await until(async () => {
|
||||||
|
const n = refused.length + left.length;
|
||||||
|
await new Promise((r) => setTimeout(r, 300));
|
||||||
|
return n === refused.length + left.length;
|
||||||
|
}, 5000);
|
||||||
|
assert.deepEqual(left, [], "every request stays under the prefix");
|
||||||
|
assert.deepEqual(refused, [], "no request is refused or missing");
|
||||||
|
}
|
||||||
|
assert.deepEqual(errors, [], "no error on the page");
|
||||||
|
});
|
||||||
@@ -51,3 +51,44 @@ test("the one-column layout (900px and narrower) keeps its page scroll", async (
|
|||||||
const narrow = await s.page.evaluate(() => getComputedStyle(document.documentElement).overflowY);
|
const narrow = await s.page.evaluate(() => getComputedStyle(document.documentElement).overflowY);
|
||||||
assert.equal(narrow, "visible", "its content sits under the first screen, so the lock must not apply");
|
assert.equal(narrow, "visible", "its content sits under the first screen, so the lock must not apply");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a stacked Notes panel has a handle that drags its height, keeps it and resets on double-click", async (t) => {
|
||||||
|
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||||
|
await s.page.setViewportSize({ width: 1000, height: 700 });
|
||||||
|
await s.page.locator("#main [data-item=\"q1\"]").first().waitFor();
|
||||||
|
const grip = s.page.locator("#aside .aside-grip");
|
||||||
|
await grip.waitFor();
|
||||||
|
const asideHeight = async () => Math.round((await s.page.locator("#aside").boundingBox()).height);
|
||||||
|
const auto = await asideHeight();
|
||||||
|
|
||||||
|
const drag = async (dy) => {
|
||||||
|
const box = await grip.boundingBox();
|
||||||
|
const x = box.x + box.width / 2;
|
||||||
|
const y = box.y + box.height / 2;
|
||||||
|
await s.page.mouse.move(x, y);
|
||||||
|
await s.page.mouse.down();
|
||||||
|
await s.page.mouse.move(x, y + dy / 2, { steps: 4 });
|
||||||
|
await s.page.mouse.move(x, y + dy, { steps: 4 });
|
||||||
|
await s.page.mouse.up();
|
||||||
|
};
|
||||||
|
|
||||||
|
await drag(-120);
|
||||||
|
const taller = await asideHeight();
|
||||||
|
assert.ok(taller >= auto + 100, `dragging the handle up makes the panel taller (${auto} -> ${taller})`);
|
||||||
|
await s.page.waitForFunction((h) => Number(document.querySelector("#aside .aside-grip").getAttribute("aria-valuenow")) === h, taller);
|
||||||
|
await drag(60);
|
||||||
|
const shorter = await asideHeight();
|
||||||
|
assert.ok(shorter <= taller - 40 && shorter >= 96, `dragging it down makes the panel shorter (${taller} -> ${shorter})`);
|
||||||
|
|
||||||
|
// Kept with the saved looks, so the next session opens at this height.
|
||||||
|
const saved = async () => s.page.evaluate(async () => (await (await fetch("/looks")).json()).looks?.asideHeight);
|
||||||
|
await s.page.waitForFunction(async (h) => (await (await fetch("/looks")).json()).looks?.asideHeight === h, shorter);
|
||||||
|
assert.equal(await saved(), shorter, "the height is kept in the saved looks");
|
||||||
|
|
||||||
|
await grip.dblclick();
|
||||||
|
assert.equal(await asideHeight(), auto, "a double-click goes back to the automatic height");
|
||||||
|
assert.equal(await s.page.evaluate(() => document.documentElement.hasAttribute("data-aside-h")), false);
|
||||||
|
|
||||||
|
await s.page.setViewportSize({ width: 1400, height: 700 });
|
||||||
|
assert.equal(await grip.isVisible(), false, "side by side, the panel has no handle");
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// Page tests for the Implementation Loop's setup screen. The dashboard card
|
// Page tests for the Implementation Loop's setup screen. Its Loop box only
|
||||||
// that opens it only shows inside the desktop app, so these open the screen
|
// enables inside the desktop app, so these open the screen through its own
|
||||||
// through its own module, then drive the real page. Run with:
|
// module, then drive the real page. Run with:
|
||||||
// node --test scripts/test-web-console-page-loop.mjs
|
// node --test scripts/test-web-console-page-loop.mjs
|
||||||
|
|
||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
@@ -8,7 +8,7 @@ import assert from "node:assert/strict";
|
|||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs";
|
import { pageSuite, openSession, tempProject, textOf, frameInFakeApp } from "./page-test-helpers.mjs";
|
||||||
import { MODELS_DIR } from "./web-console-test-helpers.mjs";
|
import { MODELS_DIR } from "./web-console-test-helpers.mjs";
|
||||||
|
|
||||||
const suite = pageSuite(test);
|
const suite = pageSuite(test);
|
||||||
@@ -112,23 +112,6 @@ test("the web address field shows the name only beside an address, warns while t
|
|||||||
assert.equal(reread.remembered, true);
|
assert.equal(reread.remembered, true);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Stands a real window in for the app that frames the page, listening to what
|
|
||||||
// the page tells it; `answer` then replies the way the app's window does.
|
|
||||||
async function frameInFakeApp(s) {
|
|
||||||
await s.page.evaluate(() => {
|
|
||||||
const frame = document.createElement("iframe");
|
|
||||||
frame.hidden = true;
|
|
||||||
document.body.appendChild(frame);
|
|
||||||
const app = frame.contentWindow;
|
|
||||||
window.__told = [];
|
|
||||||
app.postMessage = (message) => window.__told.push(message);
|
|
||||||
Object.defineProperty(window, "parent", { value: app, configurable: true });
|
|
||||||
});
|
|
||||||
return (data) =>
|
|
||||||
s.page.evaluate((message) => {
|
|
||||||
window.dispatchEvent(new MessageEvent("message", { source: window.parent, data: message }));
|
|
||||||
}, data);
|
|
||||||
}
|
|
||||||
|
|
||||||
test("Cancel in the app's confirm leaves Start ready to press again; a real start locks it", async (t) => {
|
test("Cancel in the app's confirm leaves Start ready to press again; a real start locks it", async (t) => {
|
||||||
const s = await openSetup(t);
|
const s = await openSetup(t);
|
||||||
@@ -459,6 +442,51 @@ test("after Continue building replaces the Ask agent, the same stop again offers
|
|||||||
assert.deepEqual(seen.told, ["loop-ask", "loop-resume"]);
|
assert.deepEqual(seen.told, ["loop-ask", "loop-resume"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const FINISHED = { kind: "finished", line: "All 1 phases built", phases: [{ n: 1, name: "API", commit: "abc1234" }], uncommitted: [], can: ["finalize", "dashboard"] };
|
||||||
|
|
||||||
|
test("a pressed Finalize shows a spinner and stays busy after the app's ok answer, and an error frees it", async (t) => {
|
||||||
|
const s = await openSetup(t);
|
||||||
|
await frameInFakeApp(s);
|
||||||
|
const seen = await s.page.evaluate(async (end) => {
|
||||||
|
const m = await import(new URL("screens/ending.js", document.baseURI).href);
|
||||||
|
const { page } = await import(new URL("state.js", document.baseURI).href);
|
||||||
|
const read = () => {
|
||||||
|
const card = m.renderLoopEnd(end);
|
||||||
|
const choices = [...card.querySelectorAll(".loop-end-choice")];
|
||||||
|
const of = (text) => choices.find((c) => c.querySelector("button").textContent.includes(text));
|
||||||
|
const fin = of("Finalize") || of("Starting Finalize");
|
||||||
|
const home = of("dashboard");
|
||||||
|
const b = fin.querySelector("button");
|
||||||
|
return {
|
||||||
|
busy: b.classList.contains("is-busy"),
|
||||||
|
disabled: b.disabled,
|
||||||
|
spinner: Boolean(b.querySelector(".spinner")),
|
||||||
|
label: b.textContent,
|
||||||
|
hint: fin.querySelector(".loop-end-hint").textContent,
|
||||||
|
otherDisabled: home.querySelector("button").disabled,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const before = read();
|
||||||
|
m.renderLoopEnd(end).querySelector(".loop-end-actions button").click();
|
||||||
|
const waiting = read();
|
||||||
|
page.loopAction = { kind: "loop-finalize-result", ok: true, error: null };
|
||||||
|
const started = read();
|
||||||
|
page.loopAction = { kind: "loop-finalize-result", ok: false, error: "no" };
|
||||||
|
const failed = read();
|
||||||
|
m.forgetLoopEnd();
|
||||||
|
page.loopAction = null;
|
||||||
|
return { before, waiting, started, failed, told: window.__told.map((x) => x.plan2code) };
|
||||||
|
}, FINISHED);
|
||||||
|
assert.deepEqual([seen.before.busy, seen.before.disabled], [false, false]);
|
||||||
|
for (const phase of [seen.waiting, seen.started]) {
|
||||||
|
assert.deepEqual([phase.busy, phase.disabled, phase.spinner, phase.otherDisabled], [true, true, true, true]);
|
||||||
|
assert.equal(phase.label, "Starting Finalize…");
|
||||||
|
assert.match(phase.hint, /starting in the terminal/);
|
||||||
|
}
|
||||||
|
assert.deepEqual([seen.failed.busy, seen.failed.disabled, seen.failed.label], [false, false, "Finalize"], "an error gives the button back");
|
||||||
|
assert.deepEqual(seen.told, ["loop-finalize"]);
|
||||||
|
});
|
||||||
|
|
||||||
// A real loop session: `open --loop` under the app's signal stamps the lock.
|
// A real loop session: `open --loop` under the app's signal stamps the lock.
|
||||||
async function openLoopPage(t) {
|
async function openLoopPage(t) {
|
||||||
return openSession(await suite.browser(), {
|
return openSession(await suite.browser(), {
|
||||||
|
|||||||
@@ -579,7 +579,7 @@ test("each tab keeps its own text and pictures, and switching never saves into t
|
|||||||
await tabNamed(s, "Ideas").click();
|
await tabNamed(s, "Ideas").click();
|
||||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li.is-ready").length === 1);
|
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li.is-ready").length === 1);
|
||||||
const src = await s.page.locator("#notepad-strip img").getAttribute("src");
|
const src = await s.page.locator("#notepad-strip img").getAttribute("src");
|
||||||
assert.match(src, new RegExp(`^/notepad/images/${ideas}/`), "the picture's address names its tab");
|
assert.match(src, new RegExp(`^notepad/images/${ideas}/`), "the picture's address names its tab");
|
||||||
|
|
||||||
// A save that cannot reach the server keeps you on the tab, with why.
|
// A save that cannot reach the server keeps you on the tab, with why.
|
||||||
await s.page.route("**/notepad/text*", (route) => route.abort());
|
await s.page.route("**/notepad/text*", (route) => route.abort());
|
||||||
@@ -1009,7 +1009,8 @@ test("the preview opens at the clicked picture, steps and wraps, and Esc closes
|
|||||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||||
await openNotepad(s);
|
await openNotepad(s);
|
||||||
for (const color of ["#c33", "#3c3", "#33c"]) await addViaButton(s, color);
|
for (const color of ["#c33", "#3c3", "#33c"]) await addViaButton(s, color);
|
||||||
const urls = stored(s).map((img) => img.url);
|
// Page-relative: the page at / shows each one here.
|
||||||
|
const urls = stored(s).map((img) => `/${img.url}`);
|
||||||
const shown = () =>
|
const shown = () =>
|
||||||
s.page.evaluate(() => ({
|
s.page.evaluate(() => ({
|
||||||
src: new URL(document.getElementById("picview-img").src).pathname,
|
src: new URL(document.getElementById("picview-img").src).pathname,
|
||||||
|
|||||||
@@ -897,6 +897,48 @@ test("below 720 px the side list is a horizontal strip with no hints", async (t)
|
|||||||
await s.page.waitForFunction(() => document.getElementById("prefs-tabs").getAttribute("aria-orientation") === "vertical");
|
await s.page.waitForFunction(() => document.getElementById("prefs-tabs").getAttribute("aria-orientation") === "vertical");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Every choice box in a looks row whose label overflows it, or that runs into the next box on its line.
|
||||||
|
async function crampedChoices(s) {
|
||||||
|
return s.page.evaluate(() => {
|
||||||
|
const bad = [];
|
||||||
|
for (const row of document.querySelectorAll("#prefs-panel-appearance .looks-row")) {
|
||||||
|
const boxes = [...row.querySelectorAll(":scope > label")];
|
||||||
|
boxes.forEach((box, i) => {
|
||||||
|
const name = box.textContent.trim();
|
||||||
|
if (box.scrollWidth > box.clientWidth + 1) bad.push(`${name}: its label overflows the box`);
|
||||||
|
const next = boxes[i + 1];
|
||||||
|
if (!next) return;
|
||||||
|
const a = box.getBoundingClientRect();
|
||||||
|
const b = next.getBoundingClientRect();
|
||||||
|
if (Math.abs(a.top - b.top) < 2 && a.right > b.left + 1) bad.push(`${name}: runs into ${next.textContent.trim()}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return bad;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test("with the Narrow card width in a wide window, no Appearance choice overflows or overlaps its neighbor", async (t) => {
|
||||||
|
noSavedLooks(t);
|
||||||
|
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||||
|
// Wide enough that no window-width rule applies: only the dialog is narrow.
|
||||||
|
await s.page.setViewportSize({ width: 1400, height: 900 });
|
||||||
|
await s.page.click("#btn-looks");
|
||||||
|
await s.page.locator("#looks-modal[open]").waitFor();
|
||||||
|
await s.page.locator('input[name="looks-width"][value="narrow"]').check();
|
||||||
|
await s.page.waitForFunction(() => document.documentElement.getAttribute("data-width") === "narrow");
|
||||||
|
assert.deepEqual(await crampedChoices(s), []);
|
||||||
|
// The other widths stay clean too.
|
||||||
|
for (const width of ["comfortable", "wide", "ultrawide"]) {
|
||||||
|
await s.page.locator(`input[name="looks-width"][value="${width}"]`).check();
|
||||||
|
// The default width leaves no attribute on the page.
|
||||||
|
await s.page.waitForFunction((w) => (document.documentElement.getAttribute("data-width") ?? "comfortable") === w, width);
|
||||||
|
assert.deepEqual(await crampedChoices(s), [], width);
|
||||||
|
}
|
||||||
|
// A small window still stacks the choices in one column, as before.
|
||||||
|
await s.page.setViewportSize({ width: 600, height: 800 });
|
||||||
|
await s.page.waitForFunction(() => getComputedStyle(document.querySelector("#prefs-panel-appearance .looks-row.four")).gridTemplateColumns.split(" ").length === 1);
|
||||||
|
});
|
||||||
|
|
||||||
test("Set your role on the dashboard opens on Appearance with agents and models loaded", async (t) => {
|
test("Set your role on the dashboard opens on Appearance with agents and models loaded", async (t) => {
|
||||||
fs.mkdirSync(HOME, { recursive: true });
|
fs.mkdirSync(HOME, { recursive: true });
|
||||||
fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { welcomeSeen: true, skillLaunched: true } }));
|
fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { welcomeSeen: true, skillLaunched: true } }));
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// Page tests for the Review Loop's setup screen. The dashboard card that opens
|
// Page tests for the Review Loop's setup screen. Its Loop box only enables
|
||||||
// it only shows inside the desktop app, so these open the screen through its
|
// inside the desktop app, so these open the screen through its own module,
|
||||||
// own module, then drive the real page, the way test-web-console-page-loop.mjs
|
// then drive the real page, the way test-web-console-page-loop.mjs does for
|
||||||
// does for the Implementation Loop's. Run with:
|
// the Implementation Loop's. Run with:
|
||||||
// node --test scripts/test-web-console-page-review-loop.mjs
|
// node --test scripts/test-web-console-page-review-loop.mjs
|
||||||
|
|
||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
@@ -9,7 +9,7 @@ import assert from "node:assert/strict";
|
|||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs";
|
import { pageSuite, openSession, tempProject, textOf, frameInFakeApp } from "./page-test-helpers.mjs";
|
||||||
import { MODELS_DIR } from "./web-console-test-helpers.mjs";
|
import { MODELS_DIR } from "./web-console-test-helpers.mjs";
|
||||||
|
|
||||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||||
@@ -26,23 +26,6 @@ const MENU = { menu: { note: "Ready when you are." }, agent: { status: "waiting"
|
|||||||
|
|
||||||
const FACTS = { agent: "claude", agentLabel: "Claude Code", helpers: true, strengthsMapped: true, running: false, promptSupport: true, notifyKind: "query", notifyUrl: "", notifyParam: "message" };
|
const FACTS = { agent: "claude", agentLabel: "Claude Code", helpers: true, strengthsMapped: true, running: false, promptSupport: true, notifyKind: "query", notifyUrl: "", notifyParam: "message" };
|
||||||
|
|
||||||
// Stands a real window in for the app that frames the page, listening to what
|
|
||||||
// the page tells it; the returned function replies the way the app does.
|
|
||||||
async function frameInFakeApp(s) {
|
|
||||||
await s.page.evaluate(() => {
|
|
||||||
const frame = document.createElement("iframe");
|
|
||||||
frame.hidden = true;
|
|
||||||
document.body.appendChild(frame);
|
|
||||||
const app = frame.contentWindow;
|
|
||||||
window.__told = [];
|
|
||||||
app.postMessage = (message) => window.__told.push(message);
|
|
||||||
Object.defineProperty(window, "parent", { value: app, configurable: true });
|
|
||||||
});
|
|
||||||
return (data) =>
|
|
||||||
s.page.evaluate((message) => {
|
|
||||||
window.dispatchEvent(new MessageEvent("message", { source: window.parent, data: message }));
|
|
||||||
}, data);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The installed copy of the shipped model menu, with its strengths, as install.js drops it.
|
// The installed copy of the shipped model menu, with its strengths, as install.js drops it.
|
||||||
function installShippedModels() {
|
function installShippedModels() {
|
||||||
|
|||||||
@@ -432,7 +432,7 @@ test("kept attachments are served read-only from the session's spec, by their ex
|
|||||||
assert.match(kept, /realpathSync/);
|
assert.match(kept, /realpathSync/);
|
||||||
assert.match(kept, /path\.dirname\(real\)\.toLowerCase\(\) !== realDir\.toLowerCase\(\)/, "only files directly in attachments/");
|
assert.match(kept, /path\.dirname\(real\)\.toLowerCase\(\) !== realDir\.toLowerCase\(\)/, "only files directly in attachments/");
|
||||||
const render = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "render.js"), "utf8");
|
const render = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "render.js"), "utf8");
|
||||||
assert.match(render, /return "\/attachments\/" \+ kept\[1\]\.toLowerCase\(\)/);
|
assert.match(render, /return "attachments\/" \+ kept\[1\]\.toLowerCase\(\)/);
|
||||||
assert.match(render, /function isComment\(t\)/, "HTML comments are not shown");
|
assert.match(render, /function isComment\(t\)/, "HTML comments are not shown");
|
||||||
assert.match(render, /"!": \{ mark: "!", label: "blocked"/, "a blocked task gets its marker");
|
assert.match(render, /"!": \{ mark: "!", label: "blocked"/, "a blocked task gets its marker");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
// Web console tests, the page's URLs: every URL the page uses is page-relative.
|
||||||
|
// The macOS app's frame gets no cookie, so it signs in by a path prefix
|
||||||
|
// (`/f/<key>/`, routes.mjs) and the page is served under it there, while a
|
||||||
|
// browser tab has it at `/`. A relative `state` reaches the server either
|
||||||
|
// way; a slash-leading `/state` drops the prefix and gets a 403, in the macOS
|
||||||
|
// app only, so no other test would notice. This guard reads the page's source
|
||||||
|
// (and the links the server hands it) and names each slash-leading one.
|
||||||
|
// Run with: node --test scripts/test-web-console-relative-urls.mjs
|
||||||
|
|
||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { ROOT } from "./web-console-test-helpers.mjs";
|
||||||
|
|
||||||
|
const CONSOLE_DIR = path.join(ROOT, "src", "web-console");
|
||||||
|
const PUBLIC_DIR = path.join(CONSOLE_DIR, "public");
|
||||||
|
|
||||||
|
const WHY = "the macOS app serves the page under /f/<key>/, so a slash-leading URL misses the prefix and gets a 403 there; drop the leading slash";
|
||||||
|
|
||||||
|
// Slash-leading text that is not a URL. Any literal opening `/plan2code` is a
|
||||||
|
// slash command (no route starts so); anything else is named here, by file
|
||||||
|
// and exact literal, with its reason.
|
||||||
|
const SLASH_COMMAND = /^.\/plan2code(?![\w/])|^.\/plan2code-/;
|
||||||
|
const TEXT = new Map([
|
||||||
|
["answers.js", new Set(["`/${offer.skill}`"])], // a skill offer's slash command
|
||||||
|
["diff-parse.js", new Set(['"/dev/null"'])], // git's name for no file in a diff header, compared, never fetched
|
||||||
|
["loop-parts.js", new Set(['"/api/webhooks/"'])], // a path test on a Discord address the person typed
|
||||||
|
["skills.js", new Set(['"/"'])], // `"/" + entry.skill`, a skill's slash command
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Every page file the rule reads: scripts, the page and stylesheets under
|
||||||
|
// public/, vendored code aside, as paths relative to it with forward slashes.
|
||||||
|
function pageFiles(rel = "") {
|
||||||
|
const out = [];
|
||||||
|
for (const e of fs.readdirSync(path.join(PUBLIC_DIR, rel), { withFileTypes: true })) {
|
||||||
|
const p = rel ? `${rel}/${e.name}` : e.name;
|
||||||
|
if (e.isDirectory()) {
|
||||||
|
if (p !== "vendor") out.push(...pageFiles(p));
|
||||||
|
} else if (/\.(js|html|css)$/.test(e.name)) out.push(p);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Each string literal in `text` (double quotes, single quotes or backticks)
|
||||||
|
* that makes a slash-leading URL, as `{ line, literal }`, in three shapes:
|
||||||
|
* text opening with `/` and a path character (a letter, digit, `_`, `.`, `-`
|
||||||
|
* or `${`); a lone `"/"` that starts an expression joined on with `+`
|
||||||
|
* (`fetch("/" + route)`; one joined in the middle of a path is fine); and
|
||||||
|
* markup in a string whose `src`, `href` or like attribute opens with `/`
|
||||||
|
* (`` `<img src="/x">` ``). A comment line and anything after a `//` outside
|
||||||
|
* a string are skipped; `//` opening a string is the protocol-relative case,
|
||||||
|
* which render.js blocks on its own. Quotes are tracked one line at a time, so
|
||||||
|
* a template literal that spans lines, or a regex literal holding a quote,
|
||||||
|
* can put the scan out of step for the rest of that line: a URL there goes
|
||||||
|
* unflagged, and only the frame page test, which loads the dashboard alone,
|
||||||
|
* would catch it at run time.
|
||||||
|
*/
|
||||||
|
function scriptUrls(text) {
|
||||||
|
const hits = [];
|
||||||
|
text.split("\n").forEach((line, i) => {
|
||||||
|
const t = line.trim();
|
||||||
|
if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) return;
|
||||||
|
for (let j = 0; j < line.length; j++) {
|
||||||
|
const c = line[j];
|
||||||
|
if (c === "/" && line[j + 1] === "/") break;
|
||||||
|
if (c !== '"' && c !== "'" && c !== "`") continue;
|
||||||
|
let k = j + 1;
|
||||||
|
while (k < line.length && line[k] !== c) k += line[k] === "\\" ? 2 : 1;
|
||||||
|
const body = line.slice(j + 1, k);
|
||||||
|
const opens = body[0] === "/" && /[A-Za-z0-9_.$-]/.test(body[1] || "");
|
||||||
|
const joined = body === "/" && /^\s*\+/.test(line.slice(k + 1)) && STARTS_EXPRESSION.test(line.slice(0, j));
|
||||||
|
if (opens || joined || ATTRIBUTE_URL.test(body)) hits.push({ line: i + 1, literal: line.slice(j, k + 1) });
|
||||||
|
j = k;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return hits;
|
||||||
|
}
|
||||||
|
|
||||||
|
// What may come right before an expression's first operand: nothing, an
|
||||||
|
// opening bracket, a separator, an operator or `return`.
|
||||||
|
const STARTS_EXPRESSION = /(?:^|[([{,=:?!&|>]|\breturn)\s*$/;
|
||||||
|
|
||||||
|
// An attribute that holds a URL, opening with `/` (but not `//`), in markup a
|
||||||
|
// script builds, quoted or not and with its quote escaped or not.
|
||||||
|
const ATTRIBUTE_URL = /\b(?:src|srcset|href|action|poster|data)=\\?["']?\/(?![/\\])/;
|
||||||
|
|
||||||
|
/** Each `src`, `srcset`, `href`, `action`, `poster` or `data` value opening with `/`, in either quotes. */
|
||||||
|
function htmlUrls(text) {
|
||||||
|
return text
|
||||||
|
.split("\n")
|
||||||
|
.flatMap((l, i) =>
|
||||||
|
[...l.matchAll(/\b(?:src|srcset|href|action|poster|data)=(?:"(\/[^"]*)"|'(\/[^']*)')/g)].map((m) => ({ line: i + 1, literal: m[1] ?? m[2] }))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Each `url(/...)` or `@import "/..."`. */
|
||||||
|
function cssUrls(text) {
|
||||||
|
return text
|
||||||
|
.split("\n")
|
||||||
|
.flatMap((l, i) => [...l.matchAll(/url\(\s*["']?(\/[^)"']*)|@import\s+["'](\/[^"']*)/g)].map((m) => ({ line: i + 1, literal: m[1] || m[2] })));
|
||||||
|
}
|
||||||
|
|
||||||
|
// A link the server builds for the page: a slash-leading literal given to a
|
||||||
|
// name holding `url`, `href` or `src` (`url: "/uploads/..."`, `imageUrl = (...) => "/..."`).
|
||||||
|
const SERVER_LINK = /\b\w*(?:url|href|src)\w*\s*[:=]\s*(?:\([^)]*\)\s*=>\s*)?["'`]\/(?!\/)/i;
|
||||||
|
|
||||||
|
function pageOffenders() {
|
||||||
|
const out = [];
|
||||||
|
for (const f of pageFiles()) {
|
||||||
|
const text = fs.readFileSync(path.join(PUBLIC_DIR, f), "utf8");
|
||||||
|
if (f.endsWith(".html")) {
|
||||||
|
out.push(...htmlUrls(text).map((h) => ({ file: f, ...h })));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (f.endsWith(".css")) {
|
||||||
|
out.push(...cssUrls(text).map((h) => ({ file: f, ...h })));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const h of scriptUrls(text)) {
|
||||||
|
if (SLASH_COMMAND.test(h.literal) || TEXT.get(f)?.has(h.literal)) continue;
|
||||||
|
out.push({ file: f, ...h });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.map((h) => `public/${h.file}:${h.line} ${h.literal}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
test("the scanner finds slash-leading literals and leaves comments, other schemes and slash commands alone", () => {
|
||||||
|
const found = (src) => scriptUrls(src).map((h) => h.literal);
|
||||||
|
assert.deepEqual(found('fetch("/state");'), ['"/state"']);
|
||||||
|
assert.deepEqual(found("x('/looks', `/${a}.mp3`)"), ["'/looks'", "`/${a}.mp3`"]);
|
||||||
|
assert.deepEqual(found('a("state"); b("https://x/y"); c("//cdn"); d("/");'), []);
|
||||||
|
assert.deepEqual(found('// fetch("/state")'), []);
|
||||||
|
assert.deepEqual(found(' * see "/state"'), []);
|
||||||
|
assert.deepEqual(found('go(); // then "/state"'), []);
|
||||||
|
assert.deepEqual(found('q("a\\"/b", "/c")'), ['"/c"']);
|
||||||
|
// A slash joined on at the start of an expression, and markup holding one.
|
||||||
|
assert.deepEqual(found('fetch("/" + route); x = "/" + y; return "/" + z;'), ['"/"', '"/"', '"/"']);
|
||||||
|
assert.deepEqual(found('a("notepad/images/" + tab + "/" + id); b(sep ? "/" : "")'), []);
|
||||||
|
assert.deepEqual(found('box.innerHTML = `<img src="/uploads/${id}.jpg">`;'), ['`<img src="/uploads/${id}.jpg">`']);
|
||||||
|
assert.deepEqual(found("h = '<a href=\\'/state\\'>'; s = \"<img src=\\\"/x.png\\\">\";").length, 2);
|
||||||
|
assert.deepEqual(found('h = `<img src="uploads/${id}.jpg"><a href="//cdn/x">`'), []);
|
||||||
|
assert.ok(SLASH_COMMAND.test('"/plan2code"') && SLASH_COMMAND.test('"/plan2code-review"'));
|
||||||
|
assert.ok(!SLASH_COMMAND.test('"/plan2codex"') && !SLASH_COMMAND.test('"/plan2code/x"'));
|
||||||
|
assert.deepEqual(htmlUrls('<link href="/app.css" /><script src="app.js"></script>'), [{ line: 1, literal: "/app.css" }]);
|
||||||
|
assert.deepEqual(htmlUrls("<img src='/x.png' srcset=\"/y.png 2x\">"), [
|
||||||
|
{ line: 1, literal: "/x.png" },
|
||||||
|
{ line: 1, literal: "/y.png 2x" },
|
||||||
|
]);
|
||||||
|
assert.deepEqual(cssUrls("a { background: url(/x.png) } @import \"/y.css\";"), [
|
||||||
|
{ line: 1, literal: "/x.png" },
|
||||||
|
{ line: 1, literal: "/y.css" },
|
||||||
|
]);
|
||||||
|
assert.ok(SERVER_LINK.test('url: "/uploads/" + id'));
|
||||||
|
assert.ok(SERVER_LINK.test('const imageUrl = (tab, id) => "/notepad/images/" + tab'));
|
||||||
|
assert.ok(!SERVER_LINK.test('url: "uploads/" + id') && !SERVER_LINK.test('{ path: "/state", run }'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("every URL in the page is page-relative", () => {
|
||||||
|
const offenders = pageOffenders();
|
||||||
|
assert.deepEqual(offenders, [], `${offenders.length} slash-leading URL(s) in the page (${WHY}):\n${offenders.join("\n")}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("every link the server hands the page is page-relative", () => {
|
||||||
|
const offenders = [];
|
||||||
|
for (const f of fs.readdirSync(CONSOLE_DIR).filter((n) => n.endsWith(".mjs"))) {
|
||||||
|
fs.readFileSync(path.join(CONSOLE_DIR, f), "utf8")
|
||||||
|
.split("\n")
|
||||||
|
.forEach((l, i) => {
|
||||||
|
if (!l.trim().startsWith("//") && SERVER_LINK.test(l)) offenders.push(`${f}:${i + 1} ${l.trim()}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
assert.deepEqual(offenders, [], `slash-leading link(s) the server builds for the page (${WHY}):\n${offenders.join("\n")}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("every name the rule lets through is still in its file", () => {
|
||||||
|
for (const [file, literals] of TEXT) {
|
||||||
|
const found = new Set(scriptUrls(fs.readFileSync(path.join(PUBLIC_DIR, file), "utf8")).map((h) => h.literal));
|
||||||
|
for (const literal of literals) assert.ok(found.has(literal), `${file} no longer has ${literal}: drop it from TEXT`);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -83,7 +83,7 @@ test("the page carries its first state, title and badge, so the first paint need
|
|||||||
assert.ok(html.includes(`<h1 id="title">Lunch </script><script>alert(1)</script> $& $' app</h1>`));
|
assert.ok(html.includes(`<h1 id="title">Lunch </script><script>alert(1)</script> $& $' app</h1>`));
|
||||||
assert.ok(html.includes('<span class="pill is-accent is-caps badge" id="badge">Building</span>'));
|
assert.ok(html.includes('<span class="pill is-accent is-caps badge" id="badge">Building</span>'));
|
||||||
assert.ok(html.includes("Starting Implement"), "the static starting screen names the skill");
|
assert.ok(html.includes("Starting Implement"), "the static starting screen names the skill");
|
||||||
assert.ok(html.includes('rel="modulepreload" href="/app.js"'));
|
assert.ok(html.includes('rel="modulepreload" href="app.js"'));
|
||||||
cli(["stop", "--session", res.json.sid, "--force"]);
|
cli(["stop", "--session", res.json.sid, "--force"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -948,6 +948,19 @@ test("notes/quick-task.md has the finished quick task offer Back to the dashboar
|
|||||||
assert.ok(bullet.includes("Review it now"));
|
assert.ok(bullet.includes("Review it now"));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// A review card says "Nothing has been changed yet" unless it sends nothingYet:false
|
||||||
|
// (screens/cards.js), and both of these come after the build is on disk.
|
||||||
|
test("notes/quick-task.md has its post-build review cards drop the nothing-changed-yet line", () => {
|
||||||
|
const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "quick-task.md"), "utf8");
|
||||||
|
const bullet = md.slice(md.indexOf("**See it running, before the finish:**"), md.indexOf("**Archive a finished folder:**"));
|
||||||
|
for (const title of ["See it running", "Does it look right?"]) {
|
||||||
|
const at = bullet.indexOf(`\`review\` "${title}" (`);
|
||||||
|
assert.ok(at >= 0, `the ${title} card is specified`);
|
||||||
|
const spec = bullet.slice(at, bullet.indexOf("with `--wait`", at));
|
||||||
|
assert.ok(spec.includes('"nothingYet":false'), `the ${title} card sends nothingYet:false`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Show me it working: a screenshot saved under <session>/shots/ posts as an
|
// Show me it working: a screenshot saved under <session>/shots/ posts as an
|
||||||
// image block and is served back; nothing else is reachable through /shots/.
|
// image block and is served back; nothing else is reachable through /shots/.
|
||||||
test("an image block under the session's shots folder round-trips, and /shots/ serves nothing else", async () => {
|
test("an image block under the session's shots folder round-trips, and /shots/ serves nothing else", async () => {
|
||||||
|
|||||||
@@ -685,8 +685,8 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at
|
|||||||
assert.deepEqual([...bytes.slice(0, 4)], [0x89, 0x50, 0x4e, 0x47]);
|
assert.deepEqual([...bytes.slice(0, 4)], [0x89, 0x50, 0x4e, 0x47]);
|
||||||
|
|
||||||
const html = await (await fetch(baseUrl + "/", { headers: { cookie: cookieFor(baseUrl, token) } })).text();
|
const html = await (await fetch(baseUrl + "/", { headers: { cookie: cookieFor(baseUrl, token) } })).text();
|
||||||
assert.ok(html.includes('href="/favicon.svg"'));
|
assert.ok(html.includes('href="favicon.svg"'));
|
||||||
assert.ok(html.includes('href="/favicon.png"'));
|
assert.ok(html.includes('href="favicon.png"'));
|
||||||
assert.doesNotMatch(html, /rel="icon"[^>]*href="data:/);
|
assert.doesNotMatch(html, /rel="icon"[^>]*href="data:/);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1006,7 +1006,7 @@ test("an upload is stored under a server-chosen name inside the session's upload
|
|||||||
const uploads = path.join(fs.realpathSync.native(session), "uploads");
|
const uploads = path.join(fs.realpathSync.native(session), "uploads");
|
||||||
assert.equal(path.dirname(file).toLowerCase(), uploads.toLowerCase());
|
assert.equal(path.dirname(file).toLowerCase(), uploads.toLowerCase());
|
||||||
assert.equal(path.basename(file), id + ".jpg");
|
assert.equal(path.basename(file), id + ".jpg");
|
||||||
assert.equal(url, `/uploads/${id}.jpg`);
|
assert.equal(url, `uploads/${id}.jpg`);
|
||||||
assert.equal(name, "../../evil name.png", "the name comes back as a label");
|
assert.equal(name, "../../evil name.png", "the name comes back as a label");
|
||||||
assert.equal(res.json.kind, "image");
|
assert.equal(res.json.kind, "image");
|
||||||
assert.equal(res.json.size, JPEG.length);
|
assert.equal(res.json.size, JPEG.length);
|
||||||
@@ -1035,7 +1035,8 @@ test("an upload that is not a JPEG, or is too large, is refused", async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("an upload is served back by its own url, and nothing else under /uploads/ is", async () => {
|
test("an upload is served back by its own url, and nothing else under /uploads/ is", async () => {
|
||||||
const { url } = (await uploadJpeg()).json;
|
// Page-relative: the page at / asks for it here.
|
||||||
|
const url = `/${(await uploadJpeg()).json.url}`;
|
||||||
const res = await raw("GET", url);
|
const res = await raw("GET", url);
|
||||||
assert.equal(res.status, 200);
|
assert.equal(res.status, 200);
|
||||||
assert.equal(res.headers["content-type"], "image/jpeg");
|
assert.equal(res.headers["content-type"], "image/jpeg");
|
||||||
@@ -1048,7 +1049,8 @@ test("an upload is served back by its own url, and nothing else under /uploads/
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("deleting an upload removes its file, once, and only from this origin", async () => {
|
test("deleting an upload removes its file, once, and only from this origin", async () => {
|
||||||
const { url, path: file } = (await uploadJpeg()).json;
|
const { url: link, path: file } = (await uploadJpeg()).json;
|
||||||
|
const url = `/${link}`;
|
||||||
assert.equal((await raw("DELETE", url, undefined, { origin: "http://evil.example.com" })).status, 403);
|
assert.equal((await raw("DELETE", url, undefined, { origin: "http://evil.example.com" })).status, 403);
|
||||||
assert.ok(fs.existsSync(file));
|
assert.ok(fs.existsSync(file));
|
||||||
assert.equal((await raw("DELETE", url)).status, 204);
|
assert.equal((await raw("DELETE", url)).status, 204);
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ import {
|
|||||||
isWorkflow,
|
isWorkflow,
|
||||||
isAgentless,
|
isAgentless,
|
||||||
} from "../src/web-console/public/skills.js";
|
} from "../src/web-console/public/skills.js";
|
||||||
import { APP_ONLY_ENTRIES, REVIEW_LOOP_ENTRY, cardAvailability, CONSOLE_WORKFLOWS, SKILL_CATALOG, catalogEntry, launchVariant, START_POSES, WORKFLOW_LABEL, dashNoteKind, onInitialPick, startPose, startingHint } from "../src/web-console/public/answers.js";
|
import * as ANSWERS from "../src/web-console/public/answers.js";
|
||||||
|
import { cardAvailability, CONSOLE_WORKFLOWS, loopBoxState, loopFor, OUTSIDE_APP_LINE, SKILL_CATALOG, catalogEntry, launchVariant, START_POSES, WORKFLOW_LABEL, dashNoteKind, onInitialPick, startPose, startingHint } from "../src/web-console/public/answers.js";
|
||||||
import { LAUNCH_COUNTED, PROGRESS_WORKFLOWS } from "../src/web-console/public/meter.js";
|
import { LAUNCH_COUNTED, PROGRESS_WORKFLOWS } from "../src/web-console/public/meter.js";
|
||||||
import { BUILD_WORKFLOWS } from "../src/web-console/public/labels.js";
|
import { BUILD_WORKFLOWS } from "../src/web-console/public/labels.js";
|
||||||
import { helpTabFor } from "../src/web-console/public/help.js";
|
import { helpTabFor } from "../src/web-console/public/help.js";
|
||||||
@@ -428,8 +429,9 @@ test("helper-strength.md ships in the eighteen skills that start helpers (the da
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
// The Implementation Loop and the Review Loop are cards the desktop app offers,
|
// The Implementation Loop and the Review Loop are features the desktop app
|
||||||
// not skills: neither has a workflow, so no list built from the workflows may hold them.
|
// offers, not skills: neither has a workflow, so no list built from the
|
||||||
|
// workflows may hold them, and neither draws a card of its own.
|
||||||
test("the app-only Implementation Loop and Review Loop entries stay out of every workflow list", () => {
|
test("the app-only Implementation Loop and Review Loop entries stay out of every workflow list", () => {
|
||||||
const apps = EVERY_ENTRY.filter((s) => s.appOnly);
|
const apps = EVERY_ENTRY.filter((s) => s.appOnly);
|
||||||
assert.deepEqual(apps.map((s) => s.skill), ["plan2code-loop", "plan2code-review-loop"], "both, the Implementation Loop first");
|
assert.deepEqual(apps.map((s) => s.skill), ["plan2code-loop", "plan2code-review-loop"], "both, the Implementation Loop first");
|
||||||
@@ -439,23 +441,38 @@ test("the app-only Implementation Loop and Review Loop entries stay out of every
|
|||||||
assert.ok(!isWorkflow(entry.skill));
|
assert.ok(!isWorkflow(entry.skill));
|
||||||
assert.equal(skillByName(entry.skill), null);
|
assert.equal(skillByName(entry.skill), null);
|
||||||
assert.ok(!CONSOLE_WORKFLOWS.includes(entry.command), "no console page is offered for it");
|
assert.ok(!CONSOLE_WORKFLOWS.includes(entry.command), "no console page is offered for it");
|
||||||
assert.ok(!SKILL_CATALOG.some((e) => e.skill === entry.skill), "the dashboard draws it apart from the catalog");
|
assert.ok(!SKILL_CATALOG.some((e) => e.skill === entry.skill), "the catalog leaves it out");
|
||||||
assert.equal(entry.subagents, null);
|
assert.equal(entry.subagents, null);
|
||||||
assert.equal(entry.card.group, "pipeline", "beside the Implementation Loop");
|
assert.equal(entry.card, null, "no card: its parent card's Loop box opens it");
|
||||||
}
|
}
|
||||||
assert.ok(!WORKFLOWS.includes(null) && !isWorkflow(null));
|
assert.ok(!WORKFLOWS.includes(null) && !isWorkflow(null));
|
||||||
assert.ok(!("null" in WORKFLOW_LABEL));
|
assert.ok(!("null" in WORKFLOW_LABEL));
|
||||||
assert.deepEqual([...apps[0].states], ["documented", "building"]);
|
assert.deepEqual([...apps[0].states], ["documented", "building"]);
|
||||||
assert.equal(apps[1].states, "any", "a Review Loop needs no spec");
|
assert.equal(apps[1].states, "any", "a Review Loop needs no spec");
|
||||||
assert.equal(apps[1].card.title, "Review Loop");
|
|
||||||
assert.equal(apps[1].card.blurb, "Review and fix in rounds on its own, each round checked by a fresh reviewer.");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("the Review card carries the app-only pointer line, and the app-only cards are the dashboard's extras", () => {
|
test("Implement's and Review's cards name the loop their Loop box opens, and no card carries an app-only line", () => {
|
||||||
|
const byId = (skill) => SKILL_CATALOG.find((e) => e.skill === skill);
|
||||||
|
assert.equal(byId("plan2code-3-implement").loop, "plan2code-loop");
|
||||||
|
assert.equal(byId("plan2code-review").loop, "plan2code-review-loop");
|
||||||
|
assert.deepEqual(SKILL_CATALOG.filter((e) => e.loop).map((e) => e.skill), ["plan2code-3-implement", "plan2code-review"], "no other card has a Loop box");
|
||||||
|
assert.equal(loopFor(byId("plan2code-3-implement")).name, "Implementation Loop");
|
||||||
|
assert.equal(loopFor(byId("plan2code-review")).name, "Review Loop");
|
||||||
|
assert.equal(loopFor(byId("plan2code-4-finalize")), null);
|
||||||
|
assert.deepEqual(EVERY_ENTRY.filter((s) => s.card && s.card.appNote).map((s) => s.skill), [], "no entry carries appNote");
|
||||||
|
assert.ok(!("APP_ONLY_ENTRIES" in ANSWERS) && !("REVIEW_LOOP_ENTRY" in ANSWERS) && !("LOOP_ENTRY" in ANSWERS), "the app-only card entries are gone");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the Loop box: grayed outside the app and while a loop runs, else the loop's own availability", () => {
|
||||||
|
const implement = SKILL_CATALOG.find((e) => e.skill === "plan2code-3-implement");
|
||||||
const review = SKILL_CATALOG.find((e) => e.skill === "plan2code-review");
|
const review = SKILL_CATALOG.find((e) => e.skill === "plan2code-review");
|
||||||
assert.equal(review.appNote, "In the app, the Review Loop runs review and fix rounds on its own.");
|
const scanned = { hasAgents: true };
|
||||||
assert.deepEqual(SKILL_CATALOG.filter((e) => e.appNote).map((e) => e.skill), ["plan2code-review"], "no other card has one");
|
const documented = { dir: "specs/x", state: "documented" };
|
||||||
assert.deepEqual(APP_ONLY_ENTRIES.map((e) => e.skill), ["plan2code-loop", "plan2code-review-loop"]);
|
assert.deepEqual(loopBoxState(implement, scanned, documented, { inApp: false, driving: false }), { on: false, reason: OUTSIDE_APP_LINE });
|
||||||
assert.equal(REVIEW_LOOP_ENTRY.command, "Desktop app only");
|
const running = loopBoxState(review, scanned, null, { inApp: true, driving: true });
|
||||||
assert.equal(cardAvailability(REVIEW_LOOP_ENTRY, { hasAgents: true }, null).on, true, "lit for any project state");
|
assert.equal(running.on, false);
|
||||||
|
assert.match(running.reason, /A loop is running/);
|
||||||
|
assert.equal(loopBoxState(implement, scanned, documented, { inApp: true, driving: false }).on, true);
|
||||||
|
assert.equal(loopBoxState(implement, scanned, null, { inApp: true, driving: false }).on, false, "the Implementation Loop needs a documented or building spec");
|
||||||
|
assert.equal(loopBoxState(review, scanned, null, { inApp: true, driving: false }).on, true, "the Review Loop is lit for any project state");
|
||||||
});
|
});
|
||||||
@@ -411,10 +411,6 @@ test("help: each loop's link opens its own Help topic", () => {
|
|||||||
const ids = HELP_TABS.map((t) => t.id);
|
const ids = HELP_TABS.map((t) => t.id);
|
||||||
assert.ok(ids.includes("review-loop"), "Help has a Review Loop topic");
|
assert.ok(ids.includes("review-loop"), "Help has a Review Loop topic");
|
||||||
assert.equal(HELP_TABS[ids.indexOf("review-loop")].label, "Review Loop");
|
assert.equal(HELP_TABS[ids.indexOf("review-loop")].label, "Review Loop");
|
||||||
const dash = publicSource("screens/dashboard.js");
|
|
||||||
const link = dash.match(/function loopHelpLink\(entry\) \{([\s\S]*?)\n\}/);
|
|
||||||
assert.ok(link, "dashboard.js has loopHelpLink");
|
|
||||||
assert.match(link[1], /openHelpOn\(review \? "review-loop" : "loop"\)/, "the dashboard's Review Loop link opens Review Loop, the other opens Implementation Loop");
|
|
||||||
const setup = publicSource("screens/review-loop-setup.js");
|
const setup = publicSource("screens/review-loop-setup.js");
|
||||||
assert.match(setup, /"How the Review Loop works"/, "the Review Loop setup screen names its own loop");
|
assert.match(setup, /"How the Review Loop works"/, "the Review Loop setup screen names its own loop");
|
||||||
assert.match(setup, /openHelpOn\("review-loop"\)/, "the Review Loop setup screen opens Review Loop");
|
assert.match(setup, /openHelpOn\("review-loop"\)/, "the Review Loop setup screen opens Review Loop");
|
||||||
@@ -520,7 +516,7 @@ test("prefs: the new modules are served and preloaded, and Preferences' styles l
|
|||||||
"screens/agents/agents-form.js",
|
"screens/agents/agents-form.js",
|
||||||
]) {
|
]) {
|
||||||
assert.ok(SERVABLE.has(m), `${m} is servable`);
|
assert.ok(SERVABLE.has(m), `${m} is servable`);
|
||||||
assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
assert.ok(html.includes(`rel="modulepreload" href="${m}"`), `the page preloads ${m}`);
|
||||||
}
|
}
|
||||||
for (const sheet of ["styles/prefs.css", "styles/agents.css"]) {
|
for (const sheet of ["styles/prefs.css", "styles/agents.css"]) {
|
||||||
const css = publicSource(sheet);
|
const css = publicSource(sheet);
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ test("state: the rest of the shared state starts as app.js always started it", (
|
|||||||
prototypes: { key: null, files: [], open: null, texts: {} },
|
prototypes: { key: null, files: [], open: null, texts: {} },
|
||||||
wake: null,
|
wake: null,
|
||||||
dashPick: null,
|
dashPick: null,
|
||||||
|
dashLoop: false,
|
||||||
mentionPop: null,
|
mentionPop: null,
|
||||||
heldPose: null,
|
heldPose: null,
|
||||||
newQuestions: new Set(),
|
newQuestions: new Set(),
|
||||||
|
|||||||
@@ -497,7 +497,7 @@ test("music: a song plays from its file, fades in toward its level, says when it
|
|||||||
withSongs(async () => {
|
withSongs(async () => {
|
||||||
const [name] = TRAILS_TRACKS;
|
const [name] = TRAILS_TRACKS;
|
||||||
assert.equal(music(name, 1, 1, { restart: true }), "playing");
|
assert.equal(music(name, 1, 1, { restart: true }), "playing");
|
||||||
const el = FakeAudio.made.find((a) => a.src === `/${trailsSfx.songs[name]}`);
|
const el = FakeAudio.made.find((a) => a.src === trailsSfx.songs[name]);
|
||||||
assert.ok(el, "an element for the song's file");
|
assert.ok(el, "an element for the song's file");
|
||||||
assert.ok(!el.paused && el.plays === 1, "it plays");
|
assert.ok(!el.paused && el.plays === 1, "it plays");
|
||||||
for (let i = 0; i < 20; i++) {
|
for (let i = 0; i < 20; i++) {
|
||||||
@@ -520,7 +520,7 @@ test("music: a song no longer asked for fades out and pauses where it was, and a
|
|||||||
withSongs(async () => {
|
withSongs(async () => {
|
||||||
const [first, second] = TRAILS_TRACKS;
|
const [first, second] = TRAILS_TRACKS;
|
||||||
music(first, 1, 0.5);
|
music(first, 1, 0.5);
|
||||||
const el = FakeAudio.made.findLast((a) => a.src === `/${trailsSfx.songs[first]}`);
|
const el = FakeAudio.made.findLast((a) => a.src === trailsSfx.songs[first]);
|
||||||
const loads = el.loads;
|
const loads = el.loads;
|
||||||
await sleep(800);
|
await sleep(800);
|
||||||
assert.ok(el.paused, "paused once it stops being asked for");
|
assert.ok(el.paused, "paused once it stops being asked for");
|
||||||
@@ -544,7 +544,7 @@ test("music: a song plays nothing while Play sounds is off, at a volume of 0, or
|
|||||||
assert.equal(music(name, 1, 0), undefined);
|
assert.equal(music(name, 1, 0), undefined);
|
||||||
globalThis.Audio = undefined;
|
globalThis.Audio = undefined;
|
||||||
assert.equal(music(name, 1, 1), undefined);
|
assert.equal(music(name, 1, 1), undefined);
|
||||||
assert.ok(FakeAudio.made.filter((a) => a.src === `/${trailsSfx.songs[name]}`).every((a) => a.paused), "nothing plays");
|
assert.ok(FakeAudio.made.filter((a) => a.src === trailsSfx.songs[name]).every((a) => a.paused), "nothing plays");
|
||||||
}));
|
}));
|
||||||
|
|
||||||
test("music: every Sunset Drive road has a song, and every song is a real track", () => {
|
test("music: every Sunset Drive road has a song, and every song is a real track", () => {
|
||||||
|
|||||||
@@ -75,6 +75,12 @@ const AMBIENT_ENV_KEYS = [
|
|||||||
"SSH_CONNECTION",
|
"SSH_CONNECTION",
|
||||||
"PLAN2CODE_PICKER_ECHO",
|
"PLAN2CODE_PICKER_ECHO",
|
||||||
"PLAN2CODE_NOW",
|
"PLAN2CODE_NOW",
|
||||||
|
// Set by the desktop app for its own terminal: a run from inside the app
|
||||||
|
// would otherwise frame every plain-browser test as in the app.
|
||||||
|
"PLAN2CODE_IN_APP",
|
||||||
|
"PLAN2CODE_CONSOLE_SID",
|
||||||
|
"PLAN2CODE_APP_ANNOUNCE",
|
||||||
|
"PLAN2CODE_APP_TOKEN",
|
||||||
];
|
];
|
||||||
const scrubbed = { ...process.env };
|
const scrubbed = { ...process.env };
|
||||||
for (const k of AMBIENT_ENV_KEYS) delete scrubbed[k];
|
for (const k of AMBIENT_ENV_KEYS) delete scrubbed[k];
|
||||||
|
|||||||
@@ -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 };
|
||||||
@@ -194,7 +194,7 @@
|
|||||||
"model": "swe-2-flash-high"
|
"model": "swe-2-flash-high"
|
||||||
},
|
},
|
||||||
"balanced": {
|
"balanced": {
|
||||||
"model": "swe-2-1-high"
|
"model": "claude-sonnet-5-5-medium"
|
||||||
},
|
},
|
||||||
"best": {
|
"best": {
|
||||||
"model": "claude-opus-5-5-medium"
|
"model": "claude-opus-5-5-medium"
|
||||||
|
|||||||
+102
-42
@@ -1559,6 +1559,17 @@ function isEmptyFolder(dir) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a finished picker means the person canceled. Pickers exit 0 or 1 with nothing printed
|
||||||
|
* when canceled, but osascript also exits 1 when it fails, so on macOS an exit 1 is a cancel
|
||||||
|
* only when stderr carries its "User canceled" number, -128.
|
||||||
|
*/
|
||||||
|
function pickerCancelled(status, stdout, stderr, platform = process.platform) {
|
||||||
|
if ((stdout || '').trim()) return false;
|
||||||
|
if (status === 0) return true;
|
||||||
|
return status === 1 && (platform !== 'darwin' || String(stderr || '').includes('(-128)'));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ask for the project folder: the native picker when there is one, a typed path otherwise.
|
* Ask for the project folder: the native picker when there is one, a typed path otherwise.
|
||||||
* Returns the folder, or null when the person canceled.
|
* Returns the folder, or null when the person canceled.
|
||||||
@@ -1577,10 +1588,10 @@ async function pickFolder() {
|
|||||||
windowsHide: true,
|
windowsHide: true,
|
||||||
});
|
});
|
||||||
const folder = (result.stdout || '').trim();
|
const folder = (result.stdout || '').trim();
|
||||||
// Pickers exit 0 or 1 with nothing printed when canceled; anything else means the picker
|
// Anything but a pick or a cancel means the picker itself failed, so fall through to the
|
||||||
// itself failed, so fall through to the typed prompt rather than giving up.
|
// typed prompt rather than giving up.
|
||||||
if (!result.error && folder && result.status === 0) return path.resolve(folder);
|
if (!result.error && folder && result.status === 0) return path.resolve(folder);
|
||||||
if (!result.error && !folder && (result.status === 0 || result.status === 1)) return null;
|
if (!result.error && pickerCancelled(result.status, result.stdout, result.stderr)) return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const answer = (await ask(`Project folder ${c.green(`[${start}]`)}: `)).trim().replace(/^["']|["']$/g, '');
|
const answer = (await ask(`Project folder ${c.green(`[${start}]`)}: `)).trim().replace(/^["']|["']$/g, '');
|
||||||
@@ -1678,48 +1689,75 @@ function spawnCommand(file, args, options) {
|
|||||||
* npx's exit code through. No agent starts. That one install updates the skills, this launcher
|
* 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.
|
* 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
|
* It installs the newest release, found in one `git ls-remote --tags --heads` snapshot read with
|
||||||
* the console's release check uses (update-check.mjs, copied beside this file), so a person is
|
* the rules of update-check.mjs (copied beside this file), so a person is never moved onto work a
|
||||||
* never moved onto work a published release does not have yet. `--main` is the old behavior (the
|
* published release does not have yet. A release is named by its logical `vX.Y.Z` everywhere the
|
||||||
* tip of `main`); `--tag <ref>` installs that tag or branch (the desktop app's Update skills
|
* person reads it, while npx fetches its slim immutable `install-vX.Y.Z` tag when the snapshot
|
||||||
* button pins the app's own tag this way, and it is how to go back to an earlier release);
|
* advertises one (the plain tag otherwise). `--main` is the old behavior (the tip of `main`);
|
||||||
* `--force` reinstalls even when the version is already current. `--main`, and a `--tag` naming a
|
* `--tag <ref>` installs that tag or branch (the desktop app's Update skills button pins the app's
|
||||||
* branch rather than a vX.Y.Z release, always reinstall: unreleased work keeps the last release's
|
* own tag this way, and it is how to go back to an earlier release: a `vX.Y.Z` there is mapped to
|
||||||
* version, so the installer's "Already on" check would otherwise install nothing.
|
* 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 } = {}) {
|
async function runUpdate({ tag, main, force, notice } = {}) {
|
||||||
let ref = tag;
|
if (notice) console.log(c.dim(notice));
|
||||||
if (ref === undefined && !main) {
|
const release = tag !== undefined && RELEASE_TAG.test(tag);
|
||||||
const latest = await newestReleaseTag();
|
let refs;
|
||||||
if (!latest) {
|
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(`${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).');
|
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);
|
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('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.'));
|
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));
|
const unreleased = main || (tag !== undefined && !release);
|
||||||
return runInstaller(['--update', ...(force || unreleased ? ['--force'] : [])], ref);
|
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
|
* The newest release as update-check.mjs's chooseReleaseRef() maps it, `{ releaseRef, fetchRef,
|
||||||
* update-check.mjs's own `git ls-remote --tags` run and its own pick, beside this file once
|
* synthetic, version }`, or null when it cannot be found.
|
||||||
* 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.
|
|
||||||
*/
|
*/
|
||||||
async function newestReleaseTag() {
|
async function newestRelease() {
|
||||||
try {
|
try {
|
||||||
const checker = [path.join(__dirname, 'update-check.mjs'), path.join(__dirname, '..', 'web-console', 'update-check.mjs')].find((file) => fs.existsSync(file));
|
const found = await readRefSnapshot();
|
||||||
if (!checker) return null;
|
return found ? found.checker.chooseReleaseRef(found.snapshot) : 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);
|
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -1734,21 +1772,28 @@ async function newestReleaseTag() {
|
|||||||
*/
|
*/
|
||||||
async function runUninstall(flags) {
|
async function runUninstall(flags) {
|
||||||
console.log('Uninstalling Plan2Code...');
|
console.log('Uninstalling Plan2Code...');
|
||||||
const latest = await newestReleaseTag();
|
return runInstaller(['--uninstall', ...flags], (await newestRelease()) || undefined);
|
||||||
return runInstaller(['--uninstall', ...flags], latest ? `v${latest}` : 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');
|
const npx = findOnPath('npx');
|
||||||
if (!npx) {
|
if (!npx) {
|
||||||
console.error(`${ce.red('plan2code:')} npx was not found on your PATH. It comes with Node.js 18+ (https://nodejs.org).`);
|
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);
|
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
|
// 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.
|
// launchers older than the release channel, must leave this run where it is. The logical
|
||||||
const env = { ...process.env, PLAN2CODE_INSTALL_REF: tag || 'main' };
|
// 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 });
|
const child = spawnCommand(npx, ['--yes', '--allow-git=all', spec, ...installerArgs], { stdio: 'inherit', env });
|
||||||
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
||||||
process.on(signal, () => {});
|
process.on(signal, () => {});
|
||||||
@@ -1802,7 +1847,19 @@ async function releaseNotice() {
|
|||||||
} catch {}
|
} 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) {
|
function parseUpdateArgs(args) {
|
||||||
const out = { main: false, force: false };
|
const out = { main: false, force: false };
|
||||||
for (let i = 0; i < args.length; i++) {
|
for (let i = 0; i < args.length; i++) {
|
||||||
@@ -1812,7 +1869,10 @@ function parseUpdateArgs(args) {
|
|||||||
else if (arg === '--tag') {
|
else if (arg === '--tag') {
|
||||||
const ref = args[i + 1];
|
const ref = args[i + 1];
|
||||||
if (!ref || ref.startsWith('--')) return { error: '--tag needs a release or branch, for example --tag v3.0.2' };
|
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++;
|
i++;
|
||||||
} else return { error: `unknown option for update: ${arg}` };
|
} else return { error: `unknown option for update: ${arg}` };
|
||||||
}
|
}
|
||||||
@@ -2024,4 +2084,4 @@ async function launch() {
|
|||||||
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
||||||
if (require.main === module) launch();
|
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, pickerCancelled };
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
# 🧭 PATHFINDER MODE
|
# 🧭 PATHFINDER MODE
|
||||||
|
|
||||||
|
**Language:** Write every reply, question, option and summary in US English, even when the person's messages or the project's files are in another language. Switch only when the person asks for a different language.
|
||||||
|
|
||||||
Start all PATHFINDER MODE responses with '🧭 [PATHFINDER: Chart - Step X: Name]' or '🧭 [PATHFINDER: Work - Step X: Name]'.
|
Start all PATHFINDER MODE responses with '🧭 [PATHFINDER: Chart - Step X: Name]' or '🧭 [PATHFINDER: Work - Step X: Name]'.
|
||||||
|
|
||||||
## Role
|
## Role
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
Start all PLANNING MODE responses with '🤔 [PLANNING PHASE X: Phase Name]'
|
Start all PLANNING MODE responses with '🤔 [PLANNING PHASE X: Phase Name]'
|
||||||
|
|
||||||
|
**Language:** Write every reply, question, option and summary in US English, even when the person's messages or the project's files are in another language. Switch only when the person asks for a different language.
|
||||||
|
|
||||||
## Role
|
## Role
|
||||||
|
|
||||||
Senior software architect and technical PM. Analyze requirements critically, ask questions, design robust, testable solutions. Output: SOW and Implementation Plan. Do NOT write code - plan and architect only.
|
Senior software architect and technical PM. Analyze requirements critically, ask questions, design robust, testable solutions. Output: SOW and Implementation Plan. Do NOT write code - plan and architect only.
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
Start all REVISION MODE responses with '🔄 [REVISION]'
|
Start all REVISION MODE responses with '🔄 [REVISION]'
|
||||||
|
|
||||||
|
**Language:** Write every reply, question, option and summary in US English, even when the person's messages or the project's files are in another language. Switch only when the person asks for a different language.
|
||||||
|
|
||||||
## Role
|
## Role
|
||||||
|
|
||||||
Senior software architect updating implementation specs when requirements change mid-project. **Output: spec-file edits only — never implementation.**
|
Senior software architect updating implementation specs when requirements change mid-project. **Output: spec-file edits only — never implementation.**
|
||||||
|
|||||||
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user