mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
Compare commits
8
Commits
faa5438db2
...
8459836d3b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8459836d3b | ||
|
|
2e2b3e1139 | ||
|
|
f61ef6e0a7 | ||
|
|
72ae44745f | ||
|
|
496bdf3e62 | ||
|
|
e80713742e | ||
|
|
7021ff9a48 | ||
|
|
cb64a8d15e |
No files matched your search
@@ -10,6 +10,8 @@ One row per file under `src/web-console/public/` (the games and their sound are
|
||||
| `public/md-field.css` | The frame a Markdown field wears inside its shadow root, linked beside `notepad-editor.css`. |
|
||||
| `public/app.js` | the page's entry and the only page file that starts anything: the start-up block. `index.html` loads it; it imports `screens/core.js` and the screens beside it |
|
||||
| `public/doc-files.js` | a document as the page shows it, and as a file: blocks, Markdown and HTML download |
|
||||
| `public/diff-parse.js` | the Changes tab's parser: the unified diff `changes.mjs diff` writes, read into files, hunks and numbered lines; never throws |
|
||||
| `public/diff-view.js` | the Changes tab: a `diff` doc block drawn as a file list and one unified diff, with its empty, loading and error states (Check again and Reload send `__changes`) |
|
||||
| `public/hops.js` | no imports: the hop rule, `startsClean(from, to)`, which says whether a hop from one workflow to another starts the new skill on a clean page (to or from the dashboard, into Git, or from one skill into another off a finished screen, but never out of Git or into Review); shared by `cmd-open.mjs`, `server.mjs` (its Ask reset) and `screens/core.js` |
|
||||
| `public/looks.js` | how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches |
|
||||
| `public/mention-box.js` | the @name suggestions popover under a text box |
|
||||
@@ -51,6 +53,7 @@ One row per file under `src/web-console/public/` (the games and their sound are
|
||||
| `public/styles/dashboard.css` | The dashboard: the menu, the spec picker, its confirm and the launching pane |
|
||||
| `public/styles/learning.css` | Learning's row (the paused amber tint, the sliding switch, the upward More menu) and the waiting banner, from the saved prototype on the page's tokens |
|
||||
| `public/styles/docs.css` | Documents and the doc tools |
|
||||
| `public/styles/diff.css` | The Changes tab: file list, unified diff and its states, on the page's tokens (added rows `--ok`, removed rows `--warn`) |
|
||||
| `public/styles/ending.css` | The end of a session: the hand-off and the stopping screen |
|
||||
| `public/styles/git.css` | The git board |
|
||||
| `public/styles/help.css` | The help dialog, its diagrams and its tabs |
|
||||
|
||||
@@ -27,7 +27,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `console-docs.md` | the topic file for `docs` in a patch (tabs of blocks), named by the console at the first patch that carries `docs`; not read up front. Byte-budgeted with the card and the notes in `scripts/test-console-wire-budgets.mjs` |
|
||||
| `pointers.mjs` | which topic file the console names and when: once per session per topic, remembered in the session folder (`pointers.json`), reset by a resume |
|
||||
| `metrics-pattern.json` | the PLAN-DRAFT scrape shapes the bait scanner in `patches.mjs` reads (`METRICS_BAIT`); one of three copies with the skill scripts' `SCRAPE` and `plan2code-metrics/src/metrics-pattern.json`, which `test-web-console-hardening.mjs` keeps in step |
|
||||
| `patches.mjs` | checking and merging an agent's patch into the session state: `validate()` (the house rules; allows `templates` only as `"idea"` on a `text` item, anything else exits 3; the `lessons` kind, the approval card `lessons.mjs list` prints, is checked by `lessonsProblems()` against `LESSON_ROW_TYPES`, only one may be open at a time, and it is the one card the dashboard accepts, drawn there in a dialog for Review from the Learning banner; its `rows` and its `firstAsk.lesson` are the project's own words, which Keep saves as noted, so the wording scan leaves them out and checks only the card's own title, body, opening and first-ask sentences), the patch merge, `resolveDocFiles()` and `applyPatch()` |
|
||||
| `patches.mjs` | checking and merging an agent's patch into the session state: `validate()` (the house rules; allows `templates` only as `"idea"` on a `text` item, anything else exits 3; the `lessons` kind, the approval card `lessons.mjs list` prints, is checked by `lessonsProblems()` against `LESSON_ROW_TYPES`, only one may be open at a time, and it is the one card the dashboard accepts, drawn there in a dialog for Review from the Learning banner; its `rows` and its `firstAsk.lesson` are the project's own words, which Keep saves as noted, so the wording scan leaves them out and checks only the card's own title, body, opening and first-ask sentences), the patch merge, `resolveDocFiles()` (`file` blocks and the refresh of `file` and `diff` blocks), `resolveDocImages()` (`image` blocks, and `diff` blocks: `{ id, diff: "changes.diff" }` names a `.diff` file directly in the session folder, read with `fs.realpathSync.native` confined to that folder and cut at `DOC_FILE_MAX` with the too-large line; stored as `diff` plus `text`, left out of the wording scan) and `applyPatch()` |
|
||||
| `routes.mjs` | every URL the page can call, in one ordered list (`ROUTES`, walked by `handle()`); `server.mjs` hands each request to it. Learning's three: `POST /learning/pause` (origin-checked; `{ paused: boolean }`, `400 bad-request` otherwise, `409 not-on` unless Learning is on or paused) writes the personal pause through `writePause()` (`pause.json` under `~/.plan2code/learning/<key>/`, the server's only write for Learning, never into the project), patches `scan.learning` in `state.json` in place and pushes it, so the row repaints with no agent; `GET /learning/state` returns `learningScan()` worked out now (`{}` when the settings format is unknown; the Loop's stop card, a page after a pause); `GET /learning/lessons` returns `{ files: [{ name, title, text }] }` for Open the lessons, read-only: `general.md` first, then every other `.md` directly in the project's `.plan2code/lessons/` in name order, plain files only (no link, no sub-folder, at most 100 files of 512 KB each). Both `GET`s send `cache-control: no-store` |
|
||||
| `scan.mjs` | what the dashboard knows about the repo: `scanProject()`, `classifySpec()` (a folder's files to a spec state; a `DIAGNOSIS-*.md` gives `diagnosed` or `fixed`, an `UPGRADE-*.md` brief from Update dependencies `upgrade` ("Upgrade ready") or, once its `**Status:**` reads `Done`, `upgraded` ("Upgrade done"), and a plan conversation or pathfinder map wins over either), `TASK_LINE_RE` (re-exported from `spec-files.mjs`) and `removeSpec()`. `open` (`cmd-open.mjs`) adds three fields that live outside the repo's specs, so `specs.mjs list` never sees them: `handoffs`, `handoffsDir` and `learning` (`learningScan()`: `{ state, pausedSince, waiting, oldestDays }`, `state` one of `not-set-up`, `off`, `on`, `paused`; left out when the settings format is unknown or the read fails, so the page draws no Learning row) |
|
||||
| `sessions.mjs` | a session's roots and handle files (`repoRoots()`, `healthOk()`, `attachmentName()`: the kept-file name `<slug>-<id8>.<ext>`, the same upload always gets the same name, `readOverview()`) and the console folder's housekeeping: the three sweeps `open` runs fire-and-forget after it prints (`sweepUploads()`, `staleSessions()` / `removeSessions()`, `staleScratch()` / `removeScratch()`) and `cleanupFindings()` / `removeCleanup()` for User Preferences → System → Cleanup. `KEPT_PLAN2CODE_ENTRIES` names the entries at the top of `~/.plan2code/` that Cleanup never offers (`console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`, `app`, `app.json`, `agents.json`, `prototypes`, `learning`); a new top-level entry joins it and the Cleanup test in `scripts/test-web-console-server.mjs` |
|
||||
|
||||
@@ -109,7 +109,7 @@ plan2code/
|
||||
| `version.json` | Version metadata (name, version, description) |
|
||||
| `QUICK-REFERENCE.md` | User quick-reference card |
|
||||
| `src/statusline-claude/` | Claude CLI status bar (see [the status line file](./AGENTS-architecture-statusline.md)) |
|
||||
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`). When the desktop app is installed (`~/.plan2code/app/plan2code-app[.exe]`, or the file `PLAN2CODE_APP` names) and a display exists (Windows and macOS always; Linux needs `DISPLAY` or `WAYLAND_DISPLAY`), it opens the app after the agent and model questions with `--project <folder> --agent <id> [--model <id>]` and exits; `--classic` (never forwarded to the CLI) and a failed spawn keep the terminal flow. The app reads all three (`project::launch_choice`): the picker starts on `--agent`, and `--model` applies to that agent on every start and Restart (`AgentManager::set_model`); a model never applies to another agent. Its menu, lookup and no-agent flow come from `agents.json` through `agent-lookup.mjs`, loaded by dynamic `import()` from `~/.plan2code/bin/` (the launcher's one stated exception to its Node-built-ins-only rule; a missing copy falls back to the plain printed install steps) |
|
||||
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`). When the desktop app is installed (`~/.plan2code/app/plan2code-app[.exe]`, or the file `PLAN2CODE_APP` names) and a display exists (Windows and macOS always; Linux needs `DISPLAY` or `WAYLAND_DISPLAY`), it opens the app after the agent and model questions with `--project <folder> --agent <id> [--model <id>]` and exits; `--classic` (never forwarded to the CLI) and a failed spawn keep the terminal flow. The app reads all three (`project::launch_choice`): the picker starts on `--agent`, and `--model` applies to that agent on every start and Restart (`AgentManager::set_model`); a model never applies to another agent. The folder comes from `--project` alone: with none (a bare start of the app) the app shows its own picker, Choose a folder first and focused with the recent folders under it (`project::recent_folders`, the `recent_folders` and `open_recent_folder` commands), and Change project opens the same picker. The list is `recentFolders` in `~/.plan2code/launcher.json`, one rule written twice (`readRecent`, `pushRecent`, `listRecent` in the launcher, their twins in `project.rs`) and held to `scripts/fixtures/recent-folders-cases.json`. Its menu, lookup and no-agent flow come from `agents.json` through `agent-lookup.mjs`, loaded by dynamic `import()` from `~/.plan2code/bin/` (the launcher's one stated exception to its Node-built-ins-only rule; a missing copy falls back to the plain printed install steps) |
|
||||
| `plan2code-app/` | Tauri desktop app (Rust host, xterm panel, the console's dashboard in a frame; its own README). `RELEASE-CHECKLIST.md` lists the by-hand checks before each release. `src-tauri/src/versions.rs` compares the app's version (`tauri.conf.json`) with the installed skills' (`~/.plan2code/bin/version.json`) for the bar's **Update skills** line, which runs `node ~/.plan2code/bin/plan2code.js update` only when pressed |
|
||||
| `plan2code-app/src-tauri/src/attention.rs` | The taskbar signal's rules, pure and knowing nothing about Tauri: `Signal` (`busy`, `ready`, `attention`, `plain`), `badge_for(signal, os, enabled)` (Windows: green dot on `ready`, red on `attention`; macOS: red `!` on `attention` only; Linux: count 1 on `attention`), `should_flash(prev, next, focused, enabled)` (once, only on a change into `ready` or `attention` while unfocused) and `dot_rgba()` (the dot's pixels, in the favicon's colors, which a test checks against `public/favicon.js`). `main.rs` applies the result through `set_attention`, `set_taskbar_signal` and `clear_attention_cmd`; the page asks with the `attention` and `taskbar` messages (`public/app-bridge.js`) and the switch is `taskbarSignal` in the app's own `~/.plan2code/app.json`. |
|
||||
| `plan2code-app/src-tauri/src/quit_prompt.rs`, `task_dialog.rs` | The quit check shown while an agent runs. `quit_prompt(last_signal)` is pure: the page's last taskbar signal `ready` or `plain` is the waiting case ("Done for now?", Info icon), and `busy`, `attention` or none yet is the working case ("Leave while your agent is busy?", Warning icon). `task_dialog.rs` (Windows only) draws it with `TaskDialogIndirect` through `winapi`: a heading, Stay as the default, and the app's icon in the title bar, since the dialog plugin has no heading and Windows copies its icon into the title bar (the warning once showed twice). `confirm_quit` in `main.rs` runs it on its own thread; macOS and Linux use the plugin box with the same words, where Quit stays the default button (putting Stay first would make Esc quit). A page reload or an unanswered page clears the signal to none (`clear_attention`), so the box stays on the working words until the page reports again; `QUIT_OPEN` keeps a second box from stacking |
|
||||
@@ -155,7 +155,7 @@ plan2code/
|
||||
| `plan2code-pr-prep.md` | pr-prep | Get a branch ready for review: pick the checks its changes need from the project's `## Test map` (or its config files), let the person trim the plan, run it, give Ready, Ready with notes or Not ready, and write a PR description to copy (following the repo's template) with the create-a-PR link; offers to save `PR-READINESS-<date>.md` into the branch's spec folder; never commits, pushes or opens the PR |
|
||||
| `plan2code-test.md` | test | Write missing tests: ask where to look, find source files no test covers (matching, plus real coverage when the project already has a coverage tool, offered first), show a plan opening with how this project writes tests, then write and run unit and integration tests; escalates past 8 source files, 8 new test files or 2 runners to a PLAN-DRAFT for Plan, hands a real bug to Diagnose, never changes source code |
|
||||
| `plan2code-dead-code.md` | dead-code | Find unused code and dead code: use the project's own dead-code tools, one per language that has files (Knip, vulture, cargo check and others), or search by itself, check every item for callers across the project (`references/caller-search.md`), label each Safe to remove, Check first or Warning, remove only what the person picks, then run the tests and build and put back anything that breaks them, then offer a final review of the removals in the same session (Step 7.5, recommended yes; ships `review.md`, `review-in-build.md`, `test-runs.md` and the review references, as Finalize does); never commits, never installs a tool. Scripts: `dead-code.mjs` (own), `test-map.mjs`, `glob.mjs`, `test-commands.mjs`, `run-check.mjs`, `specs.mjs`, `commit-msg.mjs`, `review-scope.mjs`, `lessons.mjs` |
|
||||
| `plan2code-deps.md` | deps | Update dependencies: scan every manifest (the npm family, Cargo, pip and uv, Go, .NET), label each available update Safe, Check first or Warning with a reason, show a pick list, apply the picks in batches, run the project's install and checks after each batch and put back whatever breaks (narrowing a failed batch to the breaking pick); a ticked Warning writes `specs/<package>-upgrade/UPGRADE-<YYYYMMDD>.md` instead. The dashboard scan reports such a folder as spec state `upgrade` ("Upgrade ready"), which lights Quick Task (suggested) and Plan; once Quick Task applies it and marks the brief `Done` the state is `upgraded` ("Upgrade done"), finished like `fixed`. Never commits, installs a tool, edits source code or updates anything not picked. Scripts: `deps.mjs` (own), `test-map.mjs`, `glob.mjs`, `test-commands.mjs`, `run-check.mjs` |
|
||||
| `plan2code-deps.md` | deps | Update dependencies: scan every manifest (the npm family, Cargo, pip and uv, Go, .NET), label each available update Safe, Check first or Warning with a reason, show a pick list, apply the picks in batches, run the project's install and checks after each batch and put back whatever breaks (narrowing a failed batch to the breaking pick); a ticked Warning writes `specs/<package>-upgrade/UPGRADE-<YYYYMMDD>.md` instead. The dashboard scan reports such a folder as spec state `upgrade` ("Upgrade ready"), which lights Quick Task (suggested) and Plan; once Quick Task applies it and marks the brief `Done` the state is `upgraded` ("Upgrade done"), finished like `fixed`. Never commits or updates anything not picked; installs a scanner or fixes a small break in project code only after the person approves that exact change, and puts the fix back if it fails. Scripts: `deps.mjs` (own), `test-map.mjs`, `glob.mjs`, `test-commands.mjs`, `run-check.mjs` |
|
||||
| `plan2code-ui-prototype.md` | ui-prototype | Draw several versions of a screen or flow on one page with live dials (drafts under `~/.plan2code/prototypes/`), bring the pick back by Copy and paste for the next round, and save the pair into `specs/<spec>/prototypes/` only on a yes; never changes code |
|
||||
| `plan2code-changelog.md` | changelog | Check the CHANGELOG version against the default branch, suggest editable entries for new work, keep `package.json` aligned, offer to commit the result through Git |
|
||||
| `plan2code-git.md` | git | Branches, pull (with conflict help), push, publish and commits (clear message, suggested splits) on the web console's git board, or plain instructions in the terminal (`switch to main`, `commit and push`); asks before every push, publish and delete |
|
||||
@@ -209,7 +209,7 @@ Typing `plan2code` in any directory opens the dashboard skill against the curren
|
||||
|
||||
The bracketed flags (each entry's `bypassArgs`; a custom agent's own `bypassArgs`) go in only when permission prompts are off. Right after the agent is chosen, and only when it has such a flag, `chooseBypass()` asks `Turn <CLI>'s permission prompts off?` (Codex: `approval prompts and its sandbox`, worded by `bypassQuestion()`) on every launch, with Yes as the default and no answer remembered; `--keep-permissions` answers no and `--bypass-permissions` answers yes (neither is forwarded; keep wins when both are given), and with no TTY on stdin the prompts stay on unless `--bypass-permissions` is given. When the desktop app will take over, the question is skipped (its launch card has its own tick) and asked only if the app fails to start. The installer prints no warning about it.
|
||||
|
||||
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it runs the setup flow when a person can see a page (`hasDisplay()` and a TTY or the shortcut; the desktop app first when it is installed, else the console's agent-less `setup` page in the browser) and otherwise prints the install steps (`printNoAgentGuidance()`: each built-in's install command and page, how to add another agent in `~/.plan2code/agents.json`, and to run `plan2code` again) and exits 127. An uninstalled `--cli` pick goes to the same setup flow on that agent when a page can open, else prints that CLI's own steps after its error. `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. `plan2code update` and `plan2code uninstall [--yes] [--purge]` are the two subcommands: neither is forwarded and neither opens an agent. Update runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists; uninstall runs the same npx line with `--uninstall` (an unknown flag exits 2 before npx runs), and `install.js` confirms, removes everything the menu's U option does, then asks about `~/.plan2code` (see `--uninstall` in Development Commands). On every other start, before spawning the CLI, it prints one line when a newer release is out (`Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`), compared against `~/.plan2code/bin/version.json` and read from the console's cached release check (`~/.plan2code/console/update-check.json`); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
|
||||
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it runs the setup flow when a person can see a page (`hasDisplay()` and a TTY or the shortcut; the desktop app first when it is installed, else the console's agent-less `setup` page in the browser) and otherwise prints the install steps (`printNoAgentGuidance()`: each built-in's install command and page, how to add another agent in `~/.plan2code/agents.json`, and to run `plan2code` again) and exits 127. An uninstalled `--cli` pick goes to the same setup flow on that agent when a page can open, else prints that CLI's own steps after its error. `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`, `recentFolders` and `lastModels`. Then, at a terminal with recent folders to offer, it asks `Which project folder?` as a numbered menu in the style of the model menu: the current folder first (Enter keeps it), the recent folders (at most 5, newest first), then `Choose another folder...` for the native picker. With no recent folders other than the current one (the typed command leaves the current folder out of the list), or no TTY on stdin, there is no menu and it opens the current folder as before. The folder is recorded as `recentFolders` (with `lastFolder` always its first entry) only after the project check passes (`recordFolder()`), on every path including the global command; declining the check records nothing. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. `plan2code update` and `plan2code uninstall [--yes] [--purge]` are the two subcommands: neither is forwarded and neither opens an agent. Update runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists; uninstall runs the same npx line with `--uninstall` (an unknown flag exits 2 before npx runs), and `install.js` confirms, removes everything the menu's U option does, then asks about `~/.plan2code` (see `--uninstall` in Development Commands). On every other start, before spawning the CLI, it prints one line when a newer release is out (`Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`), compared against `~/.plan2code/bin/version.json` and read from the console's cached release check (`~/.plan2code/console/update-check.json`); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
|
||||
|
||||
**Design constraints:**
|
||||
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. Beside it go `update-check.mjs` (the web console's release check, for the terminal notice), `agents.json` and `agent-lookup.mjs` (the shared agent list and lookup rule; `plan2code update` restores a missing copy) and a `version.json` (the installed version). (The metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||
@@ -218,7 +218,7 @@ On a terminal it first prints a Planny banner (`renderBanner()`). With more than
|
||||
- **Marker-based ownership** — every shim contains `plan2code-launcher`; `uninstallLauncher()` removes only files carrying it, leaving any other `plan2code` bin alone.
|
||||
- **Resolving the CLI** — `findAgent()` in the shared `agent-lookup.mjs` does the lookup: `PATH` (+ `PATHEXT` on Windows), the saved Windows PATH from the registry (`addSavedWindowsPath()`), npm's global bin and each entry's `installDirs`, giving `found` / `outside` / `missing` (the desktop app's `find_on_path` in `agents.rs` is its twin, held to `scripts/fixtures/agent-lookup-cases.json`). An `.exe` is spawned directly; a `.cmd`/`.bat` wrapper goes through `cmd.exe /d /s /c` with quoted args, since Node refuses to spawn batch files without a shell. The installer warns only when neither `claude` nor `devin` is on `PATH`.
|
||||
- **No bin-name overlap** — the installer's own bin in `package.json` is `plan2code-install` (→ `install.js`), so `plan2code` belongs to the launcher alone. npx runs a package's only bin whatever it's named, so the README's `npx … plan2code.git` command is unaffected; keep it the only bin, or npx will need `-c plan2code-install`.
|
||||
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person canceled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
|
||||
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder menu (`Choose a folder...` first and the default, the recent folders under it; with no recent folders, or no TTY, it goes straight to the picker), then the model menu. `Choose a folder...` runs a native folder picker that chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person canceled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
|
||||
|
||||
**Desktop shortcut** — after the shims are written, `installLauncher()` (now async) calls `offerDesktopShortcut()`. It asks `Also add a Plan2Code shortcut to your desktop? (y/N)`, skips the question when stdin isn't a TTY, and refreshes an existing marked shortcut without asking. `installDesktopShortcut()` writes it to the real desktop (`[Environment]::GetFolderPath('Desktop')` on Windows, which covers OneDrive redirection; `xdg-user-dir DESKTOP` on Linux; `~/Desktop` otherwise):
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
|
||||
| `pr-prep.mjs` (own) | pr-prep | `template` (the PR template and its headings), `pr-url` (the create-a-PR link through `git-repo.mjs`) and `spec` (the branch's spec folder for the save offer). Read-only |
|
||||
| `coverage.mjs` (own) | test | `read --lcov` / `--go-func`: coverage output as per-file lines, hits and percent, plus the total. Read-only, runs no tool |
|
||||
| `dead-code.mjs` (own) | dead-code | `detect` (the dead-code tools the project already has, languages, file counts), `run --tool` (a tool's output as candidates), `narrow` (folders ranked by candidates), `keep list\|filter\|add\|remove` (the shared keep list, `.plan2code/dead-code/keep.md`; rows matched by file, name and the hash of the item's declaration line, `#n` for the n-th identical line, `file:` for a whole file; `remove` takes `--hash` or `--line` and exits 2 `ambiguous-entry` when two rows share a name), `backup` and `restore --verify` (copies outside the project and a checked put-back), `report write` (`.plan2code/dead-code/reports/DEAD-CODE-<date>.md`; `tool` one id or a list of ids) and `gitignore-check` / `gitignore-add`. Writes only code removals the agent makes, `keep.md` and, on a yes, a report and the `.gitignore` line |
|
||||
| `deps.mjs` (own) | deps | One file in fixed sections, one adapter per ecosystem behind one interface (npm, pnpm and Yarn; Cargo; pip; uv; Go; .NET): `detect` (lockfiles, members, missing tools, the run folder under the OS temp folder), `scan` (rows, held, notScanned, stillOpen; a declared runtime it cannot cut by sets `runtimeNotChecked`; a missing or failed audit sets `notAudited`), `notes` (release-note slices via `gh api` or `fetch`), `label` (the pure FR-6 to FR-9 rules: Safe, Check first, Warning), `batches` (`--picks`, `--split` narrowing), `backup`, `apply` (the package manager's own update; `failed` also on `unpicked`, `overshot` past a runtime-cut target, `undoFailed` or `needsNewerRuntime`), `restore --verify` (byte for byte; a file it cannot put back is `mismatched {path, reason}` with `verified: false`, never a crash), `handoff` (`specs/<package>-upgrade/UPGRADE-<date>.md`, never outside `specs/`) and `cleanup`. Never runs `--force`, an audit fix or a tool install. Writes only manifests and lockfiles (through `apply` and `restore`) and a ticked brief. Tests: `scripts/test-script-deps.mjs` against stub CLIs on a temp PATH and fixtures in `scripts/fixtures/deps/` named with each tool's version |
|
||||
| `deps.mjs` (own) | deps | One file in fixed sections, one adapter per ecosystem behind one interface (npm, pnpm and Yarn; Cargo; pip; uv; Go; .NET): `detect` (lockfiles, members, missing tools, the run folder under the OS temp folder), `scan` (rows, held, notScanned, stillOpen; a declared runtime it cannot cut by sets `runtimeNotChecked`; a missing or failed audit sets `notAudited`), `notes` (release-note slices via `gh api` or `fetch`), `fit` (the newest version the project's runtime runs, per adapter; a runtime hold with one becomes a pick, `unknown` rows go to the agent), `pins` (each row's exact version written in the project's own files, outside its lockfile and manifests: `pins.json`), `label` (the pure FR-6 to FR-9 rules: Safe, Check first, Warning; `reasons` plus `reasonsPlain` in plain English; a row with a pin is never Safe; a record's `usedIn` lists the files that import the package), `checks` (the checks for the baseline, or one group's targeted checks narrowed by `usedIn` and pins), `baseline` and `compare` (read `run-check.mjs --log` logs, never run checks: tests red before or flaky never blame a group), `batches` (`--picks`, `--split` narrowing), `backup`, `apply` (the package manager's own update; `failed` also on `unpicked`, `overshot` past a runtime-cut target, `undoFailed` or `needsNewerRuntime`), `fix` (one approved replacement in one project file after `apply`: never a lockfile or manifest of the batch, never under `node_modules`, `.git` or `specs`, never binary or over 1 MB, the text found exactly once; the file is backed up into the batch's backup first, so restore puts it back), `restore --verify` (byte for byte, fixed files included and named in `fixed[]`; a file it cannot put back is `mismatched {path, reason}` with `verified: false`, never a crash), `install-tool` (the exact install line of a scanner the scan listed missing; runs nothing, the prompt runs it through `run-check.mjs` after approval), `handoff` (`specs/<package>-upgrade/UPGRADE-<date>.md`, never outside `specs/`) and `cleanup`. Never runs `--force`, an audit fix or a tool install. Writes manifests and lockfiles only through `apply` and `restore`, any other project file only through `fix` after the person approved that exact change, and a ticked brief. Tests: `scripts/test-script-deps.mjs` against stub CLIs on a temp PATH and fixtures in `scripts/fixtures/deps/` named with each tool's version |
|
||||
| `agents-md.mjs` | init, init-update | AGENTS.md structure, budget, orphans, broken links, always-inline sections. With no AGENTS.md yet (Init's run, so said once), `notices` warns when `.gitignore` keeps `specs--completed/` out of git, since archived specs are then not backed up |
|
||||
| `agent-files.mjs` | init, init-update | Detect and replace other agents' config files with AGENTS.md pointers |
|
||||
| `pathfinder.mjs` (own) | 0-pathfinder | `init` (the map in its Step 5 state from `--destination`, `--scores` and `--fog`; refuses an existing map) and `add` (the next `questions/NN-<slug>.md` plus its map row), with the references' templates kept as the fallback, then `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate` (which also prints the exact PLAN-DRAFT status line `specs.mjs` reads), `lint`, `brief-data`. Writes rows as `[Name](link): tail` with no em dash, and still reads maps written the old way |
|
||||
@@ -35,9 +35,10 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
|
||||
| `git.mjs` (own) | git | `state`, `plan`, `branch-check`, `init-check`, `delete-check`, `cleanup-list`, `conflicts`, `pr-url`, `classify-error`: the repo snapshot, each action's exact command and confirm text (shared by the terminal and the board), branch-name, delete, cleanup and git init checks, a stopped rebase's conflicts, the pull-request link and git's errors sorted into kinds with a next step. Read-only: the agent runs every command it prints, and `guard()` refuses force push, hook skipping, amend, remote delete and blanket add |
|
||||
| `ui-prototype.mjs` (shared, with `ui-prototype-round.mjs`, `ui-prototype-page.mjs`, `ui-prototype-drafts.mjs`, `ui-prototype-block.mjs`) | ui-prototype, pathfinder, plan, revise-plan, quick-task (ride-along) | `sweep` (drafts older than 30 days), `new-round`, `assemble` (the page from `round.json`, the variant files and the shell in `references/ui-prototype-shell/`, images and fonts embedded; exit 4 `round-mismatch` when a drafts round's `round.json` names another `name` or `round` than its folder), `check` (the contract's rules, the three image rules `image-type`, `image-size` and `image-missing`, and the size ceiling), `open` (the default browser), `read-block` (a pasted choice block from stdin into fields) and `save` (the pair `specs/<spec>/prototypes/<name>.html` and `.md`, then that prototype's drafts removed). Writes only under `~/.plan2code/prototypes/<project key>/` and, on `save`, the spec's `prototypes/`; never writes project code, never opens a page outside the drafts or `specs/`, never fetches anything over the network. The helper modules are imported only by `ui-prototype.mjs` |
|
||||
| `lessons.mjs` | dashboard, pathfinder, plan, revise-plan, document, implement(-review), review, finalize, quick-task, xray, diagnose, pr-prep, test, dead-code, ui-prototype | Learning's one script. Every answer carries `state` (`not-set-up`, `off`, `on`, `paused`, `unknown`) and `active`, decided only by `learningState()` in the bundled `web-console/learning.mjs`, which it loads at run time through `consoleModule("learning.mjs")` (exit 3 `no-console` without it), so the dashboard and the skills never disagree. `state` (the state, since when Paused for you, the waiting count, whether AGENTS.md exists, whether on the default branch) / `switch on\|off` (the team switch) / `pause on\|off` (Paused for you, refused unless On) / `read` (the lessons for the named paths and the branch's changed files, `marked` when their About files changed since, with a `run` handle so a later read hands over only new areas) / `note` (a lesson, an area, a doubt or an AGENTS.md fix, checked, then held as waiting; nothing while Off or Paused for you; a secret exits 5) / `check` (the secret refusal and the email, handle and person-name flags; reads only) / `list` (the approval list of everything waiting, new failure log lines, the first-ask card) / `decide` (applies the person's choices, or `--first-ask yes\|no`; a test map row fix carries `row` on its list item and is reworded with `row` or with `after` as its one table line, read back by `rowFromLine()` in `test-map.mjs`, and every row is validated and secret-checked again at Apply) / `log-lines` (failure log lines added since Learning was first switched on) / `areas --suggest` (first areas from the test map) / `report` (lessons per area, the oldest, marked and gone ones) / `remove --confirm` (deletes every saved lesson). Writes only the project's `.plan2code/settings.json` and `.plan2code/lessons/<area>.md`, the pointer line and upkeep sentence in the project's `AGENTS.md`, its failure log lines (moved into lessons, marked `(kept in the log)`, or added on a first-ask no), accepted fixes to `AGENTS.md` or an `.agents-docs/` file, and, through the core, the pause and the waiting lessons on this machine only, in `~/.plan2code/learning/<repository key>/`. Never stages or commits |
|
||||
| `changes.mjs` | implement, implement-review, quick-task | The sign-off page's Changes tab. `start --session <folder>` snapshots the working tree (tracked, modified and new files, never ignored ones) into a git tree object through a temporary index and `git write-tree`, so the real index, HEAD, branches and working tree stay as they were, and writes the tree id to `<session>/changes-start.json`; a rerun replaces it. `diff --session <folder> [--cap 524288]` snapshots the tree now, compares it with the start tree and writes `<session>/changes.diff` (unified, `git diff --no-color -M` headers; over the cap it is cut at a file boundary with a notice, every file still named; a file that may hold a secret keeps its name and counts, its lines hidden; the counts of hidden and cut files travel as `# counts: <added> <removed> <path>` trailer lines (tab separated fields) that the page applies to files with no lines of their own), printing `{ ok, files, added, removed, truncated, hidden, file }`. Exit 3 for no repository, no snapshot or a snapshot git no longer has, 4 when git cannot snapshot. Work done before `start` never shows, and nothing has to be committed. The notes for Implement and Quick Task (`notes/implement.md`, `notes/quick-task.md`) say when to run each; the page draws the result as a `diff` doc block |
|
||||
|
||||
**Shared reference for `lessons.mjs`:** `src/shared-references/lessons.md` ships as `references/lessons.md` (through `additionalReferences`) to the same fifteen skills and the dashboard. It is the prose half of Learning: the fixed words (Learning, lesson, waiting; Not set up, Off, On, Paused for you), when a skill runs each command (Start, While working, End, unattended runs, Learning off), and that a failed call means one "Lessons could not be read this run." and carrying on without lessons.
|
||||
|
||||
**Conventions** (`common.mjs`): Node 18+ built-ins only; one JSON object on stdout (`ok: false` plus `error`, `message`, `next` on a handled failure, the same line on stderr); exit 0 ok, 1 crash, 2 bad arguments, 3 not found, 4 invalid or check failed, 5 refused; `--help` documents commands and exit codes; writes take `--dry-run`; `PLAN2CODE_NOW` pins the clock for tests. A SKILL.md names a script as `node "<S>/<name>.mjs"`, where `<S>` is `scripts/` beside it.
|
||||
|
||||
**Tests:** `scripts/test-skill-scripts.mjs` (installer plumbing and the shared scripts), `scripts/test-script-<skill>.mjs` (a skill's own, and the newer shared scripts: `test-script-test-map.mjs`, `test-script-test-match.mjs`, `test-script-test-commands.mjs`, `test-script-run-check.mjs`, `test-script-pr-prep.mjs`, `test-script-coverage.mjs`, `test-script-lessons.mjs`, `test-script-deps.mjs`), with fixtures from `scripts/skill-script-helpers.mjs`. Importing that module rebuilds `skills/` unless `npm_lifecycle_event` is `test` (`npm test` has just built it). Git fixtures go through `copyFixture()` (`scripts/fixture-helpers.mjs`): built once per test file, copied per test, since every `git` process costs a few hundred milliseconds on Windows; a remote inside the fixture is added with `slashed()` so the copy's `.git/config` can be pointed at its own origin. They run the built `skills/` tree, and one test fails if any SKILL.md or shipped reference names a `<S>/<name>.mjs` that skill does not ship. The per-skill scripts import `./common.mjs`, which only sits beside them in the built tree, so run them from `skills/`, not `src/`.
|
||||
**Tests:** `scripts/test-skill-scripts.mjs` (installer plumbing and the shared scripts), `scripts/test-script-<skill>.mjs` (a skill's own, and the newer shared scripts: `test-script-test-map.mjs`, `test-script-test-match.mjs`, `test-script-test-commands.mjs`, `test-script-run-check.mjs`, `test-script-pr-prep.mjs`, `test-script-coverage.mjs`, `test-script-lessons.mjs`, `test-script-deps.mjs`, `test-script-changes.mjs`), with fixtures from `scripts/skill-script-helpers.mjs`. Importing that module rebuilds `skills/` unless `npm_lifecycle_event` is `test` (`npm test` has just built it). Git fixtures go through `copyFixture()` (`scripts/fixture-helpers.mjs`): built once per test file, copied per test, since every `git` process costs a few hundred milliseconds on Windows; a remote inside the fixture is added with `slashed()` so the copy's `.git/config` can be pointed at its own origin. They run the built `skills/` tree, and one test fails if any SKILL.md or shipped reference names a `<S>/<name>.mjs` that skill does not ship. The per-skill scripts import `./common.mjs`, which only sits beside them in the built tree, so run them from `skills/`, not `src/`.
|
||||
@@ -11,6 +11,7 @@ Which checks cover which files, read by PR Prep and Test (`test-map.mjs read` ch
|
||||
| Update Dependencies script | `src/plan2code-deps-scripts/**`, `scripts/fixtures/deps/**` | `npm run build:skills && node scripts/node-test.mjs scripts/test-script-deps.mjs` | no |
|
||||
| UI Prototype script and shell | `src/skill-scripts/ui-prototype*.mjs`, `src/plan2code-ui-prototype-references/**`, `scripts/fixtures/ui-prototype/**` | `npm run build:skills && node scripts/node-test.mjs scripts/test-script-ui-prototype.mjs scripts/test-ui-prototype-page.mjs` | no |
|
||||
| Lessons script | `src/skill-scripts/lessons.mjs`, `src/web-console/learning.mjs` | `npm run build:skills && node scripts/node-test.mjs scripts/test-script-lessons.mjs` | no |
|
||||
| Changes tab and script | `src/skill-scripts/changes.mjs`, `src/web-console/public/diff-parse.js`, `src/web-console/public/diff-view.js`, `src/web-console/public/styles/diff.css` | `npm run build:skills && node scripts/node-test.mjs scripts/test-script-changes.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-page-changes.mjs` | no |
|
||||
| Learning on the console | `src/web-console/learning.mjs`, `src/web-console/public/screens/learning-row.js`, `src/web-console/public/styles/learning.css` | `node scripts/node-test.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-page-learning.mjs` | no |
|
||||
| Workflow prompts | `src/plan2code-*.md` | `node scripts/validate-char-count.js && node scripts/check-skill-table.mjs` | no |
|
||||
| Desktop app | `plan2code-app/**` | `cd plan2code-app && cargo test` | no |
|
||||
|
||||
@@ -30,6 +30,8 @@ A rule stated in six files is read six times and still skipped. The console sees
|
||||
|
||||
Documents are read from `file` blocks rather than pasted so the page and the disk cannot disagree, and a progress post only has to ask for `refresh`. `assumed` and `draft` exist so a half-finished doc is not read as decisions. A doc `version` never goes back because the page keys its "new version" marker on it.
|
||||
|
||||
A `diff` block follows the same rule: the agent writes a change set to a `.diff` file with `changes.mjs diff` and names it, so the agent never carries a patch through its own context and a large change costs a few typed tokens, not thousands. The server only reads it (read-only, the one file named, directly inside the session folder, so a block can never point the page at a project or system file) and caps it at the file block's 512 KB. Its text is code the repository holds, so the wording scan leaves it out as it does a `file` block.
|
||||
|
||||
## Noted questions
|
||||
|
||||
A person's note on an open question may change what it asks, and the agent's reply in the thread does not say what happens to the question. The server therefore records the fact (`noted`) when the note lands, and `validate()` refuses a new open required question until each noted one is reworded, deleted or confirmed with `stands: true`. A thread cannot answer this: it stays true forever after one reply. The page shows the same flag as a tag, and keeps the arrival notice and a New mark until the new question is opened, since eight seconds is easy to miss mid-sentence.
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# General
|
||||
|
||||
### A new file under src/web-console/ needs a row in the AGENTS-architecture console files tables; run scripts/test-web-console-shape.mjs after adding one, since it fails until the row exists.
|
||||
- Kind: convention
|
||||
- About: scripts/test-web-console-shape.mjs, .agents-docs/AGENTS-architecture-console-page.md
|
||||
- Noted: 2026-11-14, implement-review
|
||||
|
||||
### When a card in src/plan2code-deps.md changes (what it lists or asks), change the same card in src/web-console/notes/deps.md in the same edit: the console builds the card from the notes.
|
||||
- Kind: correction
|
||||
- About: src/plan2code-deps.md, src/web-console/notes/deps.md
|
||||
- Why: A review fix widened the code-changes card in the prompt only, and the re-check found the notes still listing the old rows.
|
||||
- Noted: 2026-11-14, implement-review
|
||||
@@ -36,7 +36,7 @@ Details: [Status line](./.agents-docs/AGENTS-architecture-statusline.md)
|
||||
|
||||
## Web Console
|
||||
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console/<version>/` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), 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 (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task, Diagnose, UI Prototype or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker of game rows in two columns, ordered Recently played or A to Z (saved in `activityOrder`), with never-picked games under Not played yet, once two are listed, that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest<Id>` keys in `looks.json` (and the time each game was last picked in `activityPlayed<Id>`) (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 23-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, setup, Changelog, Git, Handoff and UI Prototype) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strenLine truncated
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console/<version>/` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review, and in Implement, Implement + Review and Quick Task a **Changes** tab: a `diff` doc block fed by the `changes.mjs` skill script, parsed by `public/diff-parse.js` and drawn by `public/diff-view.js`), build progress, the living document, a spec's saved prototypes (a **Prototypes** tab: an `.md` read in place, an `.html` opened in the default browser), an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task, Diagnose, UI Prototype or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker of game rows in two columns, ordered Recently played or A to Z (saved in `activityOrder`), with never-picked games under Not played yet, once two are listed, that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest<Id>` keys in `looks.json` (and the time each game was last picked in `activityPlayed<Id>`) (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 23-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, setup, Changelog, Git, Handoff and UI Prototype) a **SLine 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`.
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ custom agent that has none; for Codex the question names its sandbox, which that
|
||||
launch and remembers no answer. `plan2code --keep-permissions` keeps the prompts without asking, and
|
||||
`plan2code --bypass-permissions` turns them off without asking. With no terminal to ask on (a script or a pipe) the
|
||||
prompts stay on unless `--bypass-permissions` is given. The installer then offers a desktop shortcut (answer `y`),
|
||||
which opens a folder picker first. Uninstalling (`U`, or `plan2code uninstall` from any terminal) removes both.
|
||||
which opens a folder menu first: Choose a folder, with the project folders you opened lately under it (with none yet, it goes straight to the folder dialog). In a terminal, `plan2code` offers the same recent folders as a numbered menu. Uninstalling (`U`, or `plan2code uninstall` from any terminal) removes both.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
@@ -439,7 +439,7 @@ console or the terminal; add `--web` to skip the question and go straight to the
|
||||
| `/plan2code-pr-prep` | Before you open a pull request. Picks the checks the branch's changes need from the project's `## Test map` (or its config files), runs the ones you keep, says Ready, Ready with notes or Not ready, and writes a PR description to copy with the create-a-PR link; never commits, pushes or opens the PR |
|
||||
| `/plan2code-test` | Parts of the code have no tests. Asks where to look, finds the untested files (plus real coverage when the project already has a coverage tool), shows a plan in the project's own style, then writes and runs unit and integration tests; never changes source code, hands a real bug to `/plan2code-diagnose` |
|
||||
| `/plan2code-dead-code` | Code nothing calls anymore. Uses the project's own dead-code tools, one per language (Knip, vulture, cargo check and others), or searches by itself, checks every item for callers across the project, labels each Safe to remove, Check first or Warning, removes only what you pick, then runs the tests and build and puts back anything that breaks them; never commits, never installs anything |
|
||||
| `/plan2code-deps` | Clear a dependency backlog in one sitting. Scans every manifest (npm, pnpm, Yarn, Cargo, pip, uv, Go, .NET), labels each update Safe, Check first or Warning with a reason, applies the ones you pick in batches, runs the install and your checks after each batch and puts back whatever breaks; a ticked Warning writes `specs/<package>-upgrade/UPGRADE-<date>.md`, which the dashboard shows as *Upgrade ready* for `/plan2code-quick-task` or `/plan2code-1-plan`; never commits, never installs a tool, never edits source code |
|
||||
| `/plan2code-deps` | Clear a dependency backlog in one sitting. Scans every manifest (npm, pnpm, Yarn, Cargo, pip, uv, Go, .NET), labels each update Safe, Check first or Warning with a reason, applies the ones you pick in batches, runs the install and your checks after each batch and puts back whatever breaks; a ticked Warning writes `specs/<package>-upgrade/UPGRADE-<date>.md`, which the dashboard shows as *Upgrade ready* for `/plan2code-quick-task` or `/plan2code-1-plan`; never commits; installs a scanner or fixes a small break in your code only after you approve that exact change |
|
||||
| `/plan2code-ui-prototype` | See a screen before it gets built. Draws several versions of a screen or flow on one page that opens in your browser, with live dials for fonts, colors, spacing and feel; Copy and paste brings your pick back for the next round, and a yes saves it as `specs/<spec>/prototypes/<name>.html` and `.md`; never changes your code |
|
||||
| `/plan2code-changelog` | Check the CHANGELOG version against the default branch, suggest entries for new work you can edit, keep `package.json` aligned, then hand off to Git to commit |
|
||||
| `/plan2code-git` | Branches, pull, push and commits on one board (or plain instructions in the terminal); asks before every push, publish and delete |
|
||||
|
||||
+4
-2
@@ -48,7 +48,9 @@ You also need Node.js 18 or newer (the app checks at start and says what to inst
|
||||
Run `plan2code` in your project, as always. When the app is installed and a window can open,
|
||||
`plan2code` asks which agent and model (as before) and then opens the app on that folder instead of
|
||||
running the agent in your terminal. The desktop shortcut the installer can create runs the same
|
||||
command, so it opens the app too.
|
||||
command, so it opens the app too; it asks for the folder first, with **Choose a folder** at the top and the folders you opened lately under it (with none yet, it goes straight to the folder dialog).
|
||||
|
||||
Start the app itself (from the Start menu, the Dock or a launcher) and it asks for a folder the same way: **Choose a folder** first, then your recent folders, newest first. It no longer reopens the last folder on its own.
|
||||
|
||||
Three things keep today's terminal flow:
|
||||
|
||||
@@ -112,7 +114,7 @@ separate context-window meter of its own, so there is only ever one gauge to rea
|
||||
threshold is tuned. The terminal panel has its own toolbar: dock it to the bottom or the right, collapse
|
||||
it to a thin strip, or maximize it; its size is remembered. An "agent may need you" badge appears on a
|
||||
collapsed or small panel once the agent has sat quiet for a while. **Change project** (in the project
|
||||
menu) asks first if an agent is running, then stops it and the console before opening the new folder.
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
+3
-3
@@ -208,7 +208,7 @@ const SOURCE_PROMPTS = [
|
||||
// ui-prototype.md rides along (with its references, shell and scripts) for the
|
||||
// offer of a UI prototype, which runs in the same conversation; every carried
|
||||
// name starts with ui-prototype so none collides with this skill's own files.
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'run-check.mjs', 'lessons.mjs', 'ui-prototype.mjs', 'ui-prototype-round.mjs', 'ui-prototype-page.mjs', 'ui-prototype-drafts.mjs', 'ui-prototype-block.mjs'],
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'run-check.mjs', 'lessons.mjs', 'changes.mjs', 'ui-prototype.mjs', 'ui-prototype-round.mjs', 'ui-prototype-page.mjs', 'ui-prototype-drafts.mjs', 'ui-prototype-block.mjs'],
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
@@ -280,7 +280,7 @@ const SOURCE_PROMPTS = [
|
||||
description: 'Execute implementation phase by phase',
|
||||
// review.md rides along for the web console's review offer on the sign-off
|
||||
// card, which runs the review in the same session before the phase is approved.
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'run-check.mjs', 'lessons.mjs'],
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'run-check.mjs', 'lessons.mjs', 'changes.mjs'],
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
@@ -298,7 +298,7 @@ const SOURCE_PROMPTS = [
|
||||
name: 'implement-review',
|
||||
displayName: 'Implementation + Review Mode',
|
||||
description: 'Implement one phase, review it, then request sign-off',
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'run-check.mjs', 'lessons.mjs'],
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'run-check.mjs', 'lessons.mjs', 'changes.mjs'],
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'plan2code-3-implement.md', target: 'implement.md' },
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@
|
||||
"play": "node scripts/play.mjs",
|
||||
"pretest": "node scripts/fix-line-endings.mjs",
|
||||
"test:fast": "node scripts/test-fast.mjs",
|
||||
"test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-lessons.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-learning.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-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-dashboard.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scriLine truncated
|
||||
"test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-lessons.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-learning.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-card-rows.mjs scripts/test-spec-carry.mjs scripts/test-spec-carry-page.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-Line truncated
|
||||
},
|
||||
"devDependencies": {
|
||||
"gpt-tokenizer": "2.9.0",
|
||||
|
||||
@@ -8,6 +8,8 @@ The app is optional. The Node web console and the skills never depend on it, so
|
||||
|
||||
**Agent picker.** The launch card lists Claude Code, Devin and Codex, then any custom agents from `~/.plan2code/agents.json` (added in the console's User Preferences → Agents & models, the same list the `plan2code` command uses). The app starts on an agent that is installed (your last pick when it still is), never assumes Claude Code, and a custom agent has no effort row; New Session reuses whichever agent you started. The Model dropdown offers the same list the `plan2code` launcher's model question does (the shipped `models.json` plus anything you added in User Preferences), a custom agent its own `models`, and it hides for an agent with none; `/plan2code` only does something in an agent that loads the installed Plan2Code skills.
|
||||
|
||||
**Project picker.** The app takes its folder from `--project` (what the `plan2code` command and the desktop shortcut pass) and never reopens the last one by itself. Started with no folder, and from **Change project**, it shows one picker: **Choose a folder** (focused, the default; it opens the system folder dialog) with the recent folders under it, newest first, leaving out the folder already open. The list is `recentFolders` in `~/.plan2code/launcher.json`, shared with the `plan2code` command, which keeps it by the same rule: `recent_folders` and `open_recent_folder` in `src-tauri/src/main.rs` over `project.rs`, held to `scripts/fixtures/recent-folders-cases.json` (the launcher's JS runs the same cases). A recent folder that has gone away is left out of the list (one that vanishes between the listing and the click shows an error on the picker), and Change project is refused while an Implementation Loop runs.
|
||||
|
||||
**No agent installed.** The first-run checklist and the launch card show what an agent CLI is, each built-in's install command and an **Install page** link, and a note that other agents are added under Agents. Install one, press **Check again** (the app looks at `PATH` and `agents.json` again), and Start works without restarting the app.
|
||||
|
||||
**Taskbar signal.** The console page tells the app when it is busy, your move, or needs attention (the same states as its tab icon), and the app shows it:
|
||||
|
||||
@@ -36,7 +36,7 @@ file directly after checking it against the release's checksum list.
|
||||
launch card or checklist shown first, and New Session keeps them
|
||||
- [ ] `plan2code --classic` runs the agent in the terminal with the app installed
|
||||
- [ ] Linux only: with `DISPLAY` and `WAYLAND_DISPLAY` unset, `plan2code` runs the terminal flow
|
||||
- [ ] The desktop shortcut opens the folder picker and then the app
|
||||
- [ ] The desktop shortcut opens the folder menu (Choose a folder first, recent folders under it) and then the app
|
||||
- [ ] macOS: the first start is stopped by Gatekeeper, **Open Anyway** in System Settings (Privacy &
|
||||
Security) lets it through, and `docs/desktop-app.md` describes what you saw
|
||||
- [ ] macOS and Linux: start the app from the Dock, Finder or a `.desktop` file (not a terminal) on
|
||||
@@ -75,7 +75,8 @@ file directly after checking it against the release's checksum list.
|
||||
- [ ] The top bar's project and agent menus open under their name, close on a click elsewhere (the
|
||||
console frame and the terminal included) or Escape, and are not cut off by the bar
|
||||
- [ ] **Change project** in the top bar's project menu, with an agent running: it asks first, then the folder
|
||||
picker 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
|
||||
- [ ] Change project, pick a different folder: the old agent and console stop, the new folder opens
|
||||
on the launch card (or the checklist, if its own first run has not passed yet)
|
||||
- [ ] Reload the window (or navigate away and back) while an agent is running: the terminal redraws
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Hide the extra console window on Windows release builds.
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
@@ -812,8 +813,8 @@ async fn update_skills(
|
||||
Ok(UpdateOutcome { message, status })
|
||||
}
|
||||
|
||||
/// The OS folder picker, shown when no folder is known; a choice becomes the
|
||||
/// launcher's remembered folder.
|
||||
/// The OS folder picker, the folder picker's Choose a folder row on a bare
|
||||
/// start; a choice goes to the top of the recent folders.
|
||||
#[tauri::command(async)]
|
||||
fn pick_project_folder(
|
||||
app: tauri::AppHandle,
|
||||
@@ -886,6 +887,68 @@ fn change_project(
|
||||
Ok(Some(text))
|
||||
}
|
||||
|
||||
/// The recent project folders that still exist, newest first, for the page's
|
||||
/// folder picker: `{ dir, name }` each, `name` the folder's own name (the full
|
||||
/// path for a root, which has none). The project already open is left out
|
||||
/// (none on a bare start), since picking it would change nothing. Off the
|
||||
/// main thread: each row checks the disk, and a saved folder on an
|
||||
/// unreachable share must not freeze the window.
|
||||
#[tauri::command(async)]
|
||||
fn recent_folders(state: State<'_, AppState>) -> Vec<serde_json::Value> {
|
||||
let current = state
|
||||
.project
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|p| p.as_ref().map(|p| p.dir.clone()));
|
||||
project::recent_folders(current.as_deref())
|
||||
.into_iter()
|
||||
.map(|dir| {
|
||||
let full = dir.to_string_lossy().into_owned();
|
||||
let name = dir
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| full.clone());
|
||||
serde_json::json!({ "dir": full, "name": name })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether opening `dir` must first tear the current project down: only when
|
||||
/// a project is set and it is a different folder (`same_folder`'s rule, so a
|
||||
/// trailing separator, and case on Windows, do not count).
|
||||
fn needs_teardown(current: Option<&Path>, dir: &Path, windows: bool) -> bool {
|
||||
current.is_some_and(|cur| {
|
||||
!project::same_folder(&cur.to_string_lossy(), &dir.to_string_lossy(), windows)
|
||||
})
|
||||
}
|
||||
|
||||
/// Open one of the recent folders from the folder picker. A different folder
|
||||
/// than the open project tears the old one down first (as `change_project`
|
||||
/// does) and goes to the top of the recent folders; the same folder is kept
|
||||
/// as it is, with nothing torn down.
|
||||
#[tauri::command(async)]
|
||||
fn open_recent_folder(state: State<'_, AppState>, dir: String) -> Result<Option<String>, String> {
|
||||
refuse_while_looping(&state, "project")?;
|
||||
let path = Path::new(&dir);
|
||||
if !path.is_dir() {
|
||||
return Err(format!("{dir} is not a folder"));
|
||||
}
|
||||
let current = state
|
||||
.project
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.as_ref()
|
||||
.map(|p| p.dir.clone());
|
||||
match current {
|
||||
Some(cur) if !needs_teardown(Some(&cur), path, cfg!(windows)) => return Ok(Some(dir)),
|
||||
Some(_) => teardown_project(&state)?,
|
||||
None => {}
|
||||
}
|
||||
let choice = project::remember_folder(path)?;
|
||||
*state.project.lock().map_err(|e| e.to_string())? = Some(choice);
|
||||
Ok(Some(dir))
|
||||
}
|
||||
|
||||
/// The console the agent opened, alive and as it is now, or restarted on the
|
||||
/// same session when it died. The app never starts a dashboard of its own:
|
||||
/// the agent does, by running the skill, and announces it. The one exception
|
||||
@@ -1362,6 +1425,8 @@ fn main() {
|
||||
check_new_release,
|
||||
update_skills,
|
||||
pick_project_folder,
|
||||
recent_folders,
|
||||
open_recent_folder,
|
||||
change_project,
|
||||
console_start,
|
||||
console_status,
|
||||
@@ -1927,4 +1992,21 @@ mod tests {
|
||||
"unexpected message: {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_recent_folder_tears_down_only_a_different_project() {
|
||||
let dir = Path::new("/work/b");
|
||||
// No project yet: nothing to tear down.
|
||||
assert!(!needs_teardown(None, dir, false));
|
||||
// The same folder, as written or with a trailing separator.
|
||||
assert!(!needs_teardown(Some(Path::new("/work/b")), dir, false));
|
||||
assert!(!needs_teardown(Some(Path::new("/work/b/")), dir, false));
|
||||
// A different folder.
|
||||
assert!(needs_teardown(Some(Path::new("/work/a")), dir, false));
|
||||
// Case counts outside Windows, not on it.
|
||||
assert!(needs_teardown(Some(Path::new("/work/B")), dir, false));
|
||||
let win = Path::new(r"C:\Work\B");
|
||||
assert!(!needs_teardown(Some(Path::new(r"c:\work\b\")), win, true));
|
||||
assert!(needs_teardown(Some(Path::new(r"C:\Work\A")), win, true));
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,24 @@
|
||||
//! Which project folder the app works on: the folder the launcher passes in,
|
||||
//! else the one the launcher remembers, else the person picks. The launcher's
|
||||
//! memory is `~/.plan2code/launcher.json` (`lastFolder`, `lastCli`), shared so
|
||||
//! the app and `plan2code` agree on both.
|
||||
//! else the one the person picks from the page's folder picker (the recent
|
||||
//! folders, or the OS dialog). The launcher's memory is
|
||||
//! `~/.plan2code/launcher.json` (`lastFolder`, `lastCli`), shared so the app
|
||||
//! and `plan2code` agree on both. `recentFolders` (newest first, at
|
||||
//! most 5) holds the folders worked on; `lastFolder` is always its first entry.
|
||||
//! The rule for that list is written twice, here and in `src/launcher/plan2code.js`,
|
||||
//! and both are held to `scripts/fixtures/recent-folders-cases.json`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::agents;
|
||||
|
||||
/// Where the project folder came from, in the order it is tried.
|
||||
/// Where the project folder came from: the launcher's argument, or the picker.
|
||||
#[derive(Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProjectSource {
|
||||
Argument,
|
||||
Remembered,
|
||||
Picked,
|
||||
}
|
||||
|
||||
@@ -36,17 +40,103 @@ fn launcher_file() -> Option<PathBuf> {
|
||||
)
|
||||
}
|
||||
|
||||
fn read_launcher() -> serde_json::Map<String, serde_json::Value> {
|
||||
launcher_file()
|
||||
.and_then(|file| std::fs::read_to_string(file).ok())
|
||||
fn read_launcher_from(file: &Path) -> serde_json::Map<String, Value> {
|
||||
std::fs::read_to_string(file)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str(&text).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The folder the launcher remembers, when it is still a directory.
|
||||
fn remembered_folder() -> Option<PathBuf> {
|
||||
let dir = PathBuf::from(read_launcher().get("lastFolder")?.as_str()?);
|
||||
dir.is_dir().then_some(dir)
|
||||
fn read_launcher() -> serde_json::Map<String, Value> {
|
||||
launcher_file()
|
||||
.map(|file| read_launcher_from(&file))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// How many recent project folders the list keeps.
|
||||
const RECENT_FOLDERS_MAX: usize = 5;
|
||||
|
||||
/// One trailing `\` or `/` off a path, but never off a root (`C:\` or `/`).
|
||||
fn trim_folder(p: &str) -> &str {
|
||||
let b = p.as_bytes();
|
||||
let drive_root = b.len() == 3 && b[1] == b':' && b[0].is_ascii_alphabetic();
|
||||
if b.len() > 1 && matches!(b[b.len() - 1], b'\\' | b'/') && !drive_root {
|
||||
&p[..p.len() - 1]
|
||||
} else {
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two paths name the same folder: a trailing separator is ignored,
|
||||
/// and case is on Windows. Twin of `sameFolder` in the launcher.
|
||||
pub fn same_folder(a: &str, b: &str, windows: bool) -> bool {
|
||||
let (x, y) = (trim_folder(a), trim_folder(b));
|
||||
if windows {
|
||||
x.to_lowercase() == y.to_lowercase()
|
||||
} else {
|
||||
x == y
|
||||
}
|
||||
}
|
||||
|
||||
/// The recent folders in the launcher's state: `recentFolders`, else
|
||||
/// `[lastFolder]`, else none. Twin of `readRecent`.
|
||||
fn read_recent(state: &serde_json::Map<String, Value>) -> Vec<String> {
|
||||
if let Some(Value::Array(items)) = state.get("recentFolders") {
|
||||
return items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
.take(RECENT_FOLDERS_MAX)
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
}
|
||||
match state.get("lastFolder").and_then(Value::as_str) {
|
||||
Some(last) if !last.is_empty() => vec![last.to_string()],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A new list with `dir` first, an earlier entry for the same folder removed,
|
||||
/// cut to the max. Twin of `pushRecent`.
|
||||
fn push_recent(list: &[String], dir: &str, windows: bool) -> Vec<String> {
|
||||
std::iter::once(dir.to_string())
|
||||
.chain(
|
||||
list.iter()
|
||||
.filter(|x| !same_folder(x, dir, windows))
|
||||
.cloned(),
|
||||
)
|
||||
.take(RECENT_FOLDERS_MAX)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The folders of `list` worth offering: ones that still exist, minus the one
|
||||
/// in `exclude`. Twin of `listRecent`.
|
||||
fn list_recent(
|
||||
list: &[String],
|
||||
exists: impl Fn(&str) -> bool,
|
||||
exclude: Option<&str>,
|
||||
windows: bool,
|
||||
) -> Vec<String> {
|
||||
list.iter()
|
||||
.filter(|x| exists(x) && !exclude.is_some_and(|e| same_folder(x, e, windows)))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The folders the person worked on lately that are still folders, newest
|
||||
/// first, minus `exclude` (the project already open, by `same_folder`'s
|
||||
/// rule). The page's folder picker draws them.
|
||||
pub fn recent_folders(exclude: Option<&Path>) -> Vec<PathBuf> {
|
||||
let exclude = exclude.map(|p| p.to_string_lossy().into_owned());
|
||||
list_recent(
|
||||
&read_recent(&read_launcher()),
|
||||
|p| Path::new(p).is_dir(),
|
||||
exclude.as_deref(),
|
||||
cfg!(windows),
|
||||
)
|
||||
.into_iter()
|
||||
.map(PathBuf::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The id of the agent the launcher last ran (it may be a custom one). The
|
||||
@@ -127,41 +217,44 @@ pub fn launch_choice_in(args: &[String], agents_file: Option<&Path>) -> LaunchCh
|
||||
LaunchChoice { agent, model }
|
||||
}
|
||||
|
||||
/// The folder to open on: the launcher's argument wins, then its memory, then
|
||||
/// nothing (the page asks with the folder picker).
|
||||
/// The folder to open on: only the launcher's argument. Without one the page
|
||||
/// shows its folder picker; the last folder is the picker's first recent row,
|
||||
/// never reopened silently.
|
||||
pub fn resolve(args: &[String]) -> Option<ProjectDir> {
|
||||
if let Some(dir) = argument_folder(args) {
|
||||
return Some(ProjectDir {
|
||||
dir,
|
||||
source: ProjectSource::Argument,
|
||||
});
|
||||
}
|
||||
remembered_folder().map(|dir| ProjectDir {
|
||||
argument_folder(args).map(|dir| ProjectDir {
|
||||
dir,
|
||||
source: ProjectSource::Remembered,
|
||||
source: ProjectSource::Argument,
|
||||
})
|
||||
}
|
||||
|
||||
/// A folder the person picked becomes the remembered one, so the next start
|
||||
/// (app or launcher) opens on it. The launcher's other keys are kept.
|
||||
/// A folder the person picked goes to the top of the recent folders and
|
||||
/// becomes `lastFolder`, so the next start (app or launcher) lists it first.
|
||||
/// The launcher's other keys are kept.
|
||||
pub fn remember_folder(dir: &Path) -> Result<ProjectDir, String> {
|
||||
let file = launcher_file().ok_or("no home folder found")?;
|
||||
let mut state = read_launcher();
|
||||
state.insert(
|
||||
"lastFolder".to_string(),
|
||||
serde_json::Value::String(dir.to_string_lossy().into_owned()),
|
||||
);
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(err)?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&serde_json::Value::Object(state)).map_err(err)?;
|
||||
crate::loop_driver::write_atomic(&file, &json)?;
|
||||
remember_folder_in(&file, dir)?;
|
||||
Ok(ProjectDir {
|
||||
dir: dir.to_path_buf(),
|
||||
source: ProjectSource::Picked,
|
||||
})
|
||||
}
|
||||
|
||||
/// `remember_folder`'s write, into `file`.
|
||||
fn remember_folder_in(file: &Path, dir: &Path) -> Result<(), String> {
|
||||
let mut state = read_launcher_from(file);
|
||||
let recent = push_recent(&read_recent(&state), &dir.to_string_lossy(), cfg!(windows));
|
||||
state.insert("lastFolder".to_string(), Value::String(recent[0].clone()));
|
||||
state.insert(
|
||||
"recentFolders".to_string(),
|
||||
Value::Array(recent.into_iter().map(Value::String).collect()),
|
||||
);
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(err)?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&Value::Object(state)).map_err(err)?;
|
||||
crate::loop_driver::write_atomic(file, &json)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -286,4 +379,112 @@ mod tests {
|
||||
assert_eq!(found, Some(cwd.join("codex")));
|
||||
let _ = std::fs::remove_dir_all(&cwd);
|
||||
}
|
||||
|
||||
const CASES: &str = include_str!("../../../scripts/fixtures/recent-folders-cases.json");
|
||||
|
||||
/// Each case of the fixture group `group` with the platform values it runs under:
|
||||
/// `true` for Windows. Both platform sets run on every OS; a case with none runs under both.
|
||||
fn cases(group: &str) -> Vec<(Value, bool)> {
|
||||
let all: Value = serde_json::from_str(CASES).unwrap();
|
||||
let mut out = Vec::new();
|
||||
for case in all[group].as_array().unwrap() {
|
||||
let winds: &[bool] = match case.get("platform").and_then(Value::as_str) {
|
||||
Some("win32") => &[true],
|
||||
Some("posix") => &[false],
|
||||
_ => &[true, false],
|
||||
};
|
||||
for &windows in winds {
|
||||
out.push((case.clone(), windows));
|
||||
}
|
||||
}
|
||||
assert!(!out.is_empty(), "no {group} cases");
|
||||
out
|
||||
}
|
||||
|
||||
fn strings(value: &Value) -> Vec<String> {
|
||||
value
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_str().unwrap().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_recent_follows_the_shared_cases() {
|
||||
for (case, _) in cases("read") {
|
||||
let state = case["state"].as_object().unwrap();
|
||||
assert_eq!(
|
||||
read_recent(state),
|
||||
strings(&case["expect"]),
|
||||
"{}",
|
||||
case["name"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_recent_follows_the_shared_cases() {
|
||||
for (case, windows) in cases("push") {
|
||||
let got = push_recent(
|
||||
&strings(&case["list"]),
|
||||
case["dir"].as_str().unwrap(),
|
||||
windows,
|
||||
);
|
||||
assert_eq!(
|
||||
got,
|
||||
strings(&case["expect"]),
|
||||
"{} (windows: {windows})",
|
||||
case["name"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_recent_follows_the_shared_cases() {
|
||||
for (case, windows) in cases("list") {
|
||||
let exists = strings(&case["exists"]);
|
||||
let got = list_recent(
|
||||
&strings(&case["list"]),
|
||||
|p| exists.iter().any(|e| e == p),
|
||||
case["exclude"].as_str(),
|
||||
windows,
|
||||
);
|
||||
assert_eq!(
|
||||
got,
|
||||
strings(&case["expect"]),
|
||||
"{} (windows: {windows})",
|
||||
case["name"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remember_folder_keeps_the_other_keys_and_writes_both_lists() {
|
||||
let home =
|
||||
std::env::temp_dir().join(format!("p2c-project-remember-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let file = home.join(".plan2code").join("launcher.json");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(
|
||||
&file,
|
||||
r#"{"lastFolder":"/old","lastCli":"codex","lastModels":{"codex":"m1"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
remember_folder_in(&file, Path::new("/new")).unwrap();
|
||||
let state = read_launcher_from(&file);
|
||||
assert_eq!(state["lastCli"], "codex");
|
||||
assert_eq!(state["lastModels"]["codex"], "m1");
|
||||
assert_eq!(state["lastFolder"], "/new");
|
||||
assert_eq!(state["recentFolders"], serde_json::json!(["/new", "/old"]));
|
||||
|
||||
// Picking the older folder again moves it up, with no duplicate.
|
||||
remember_folder_in(&file, Path::new("/old")).unwrap();
|
||||
let state = read_launcher_from(&file);
|
||||
assert_eq!(state["lastFolder"], "/old");
|
||||
assert_eq!(state["recentFolders"], serde_json::json!(["/old", "/new"]));
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
}
|
||||
+159
-27
@@ -3,7 +3,7 @@
|
||||
// request) with a drag handle.
|
||||
|
||||
import { mountTerminal } from './terminal.js';
|
||||
import { NEW_RELEASE_COMMAND, attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, lastAgentNotice, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle, helloRetryAction, retryLabel, RETRY_AFTER_SECONDS } from './meter.js';
|
||||
import { NEW_RELEASE_COMMAND, attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, lastAgentNotice, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, folderPickerRows, loopBanner, loopLocks, loopStopLabels, loopWindowTitle, helloRetryAction, retryLabel, RETRY_AFTER_SECONDS } from './meter.js';
|
||||
|
||||
const { invoke, Channel } = window.__TAURI__.core;
|
||||
|
||||
@@ -57,6 +57,11 @@ const launchEffortEl = document.getElementById('launch-effort');
|
||||
const launchBypassEl = document.getElementById('launch-bypass');
|
||||
const launchBypassWarningEl = document.getElementById('launch-bypass-warning');
|
||||
const launchStartBtn = document.getElementById('launch-start');
|
||||
const folderPickerEl = document.getElementById('folder-picker');
|
||||
const folderPickerPanelEl = document.getElementById('folder-picker-panel');
|
||||
const folderPickerListEl = document.getElementById('folder-picker-list');
|
||||
const folderPickerErrorEl = document.getElementById('folder-picker-error');
|
||||
const folderPickerCancelBtn = document.getElementById('folder-picker-cancel');
|
||||
const firstRunEl = document.getElementById('first-run');
|
||||
const firstRunListEl = document.getElementById('first-run-list');
|
||||
const firstRunStartBtn = document.getElementById('first-run-start');
|
||||
@@ -950,7 +955,10 @@ function stopRetryCountdown() {
|
||||
stateButton.disabled = false;
|
||||
}
|
||||
|
||||
function showState(text, buttonLabel, onButton, onCancel, { tired = false, retryAfter = 0 } = {}) {
|
||||
// One automatic Try reconnecting per run of trouble (cleared when a new page is announced).
|
||||
let autoReconnected = false;
|
||||
|
||||
function showState(text, buttonLabel, onButton, onCancel, { tired = false, retryAfter = 0, autoRetry = false } = {}) {
|
||||
// The poll repeats the same waiting message every tick: that must not
|
||||
// restart a countdown that is already running (or its button).
|
||||
if (retryAfter > 0 && !stateBox.hidden && stateText.textContent === text && stateButton.textContent.startsWith('Try reconnecting')) return;
|
||||
@@ -975,7 +983,15 @@ function showState(text, buttonLabel, onButton, onCancel, { tired = false, retry
|
||||
retryTimer = setInterval(() => {
|
||||
left -= 1;
|
||||
stateButton.textContent = retryLabel(left);
|
||||
if (left <= 0) stopRetryCountdown();
|
||||
if (left <= 0) {
|
||||
stopRetryCountdown();
|
||||
// The button is on now: press it once for the person. If that try
|
||||
// fails, the button stays for them.
|
||||
if (autoRetry && onButton) {
|
||||
autoReconnected = true;
|
||||
onButton();
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
@@ -1020,7 +1036,7 @@ async function pollConsole() {
|
||||
if (action === 'wait-for-phase') {
|
||||
// Covers the old phase's page and its "Lost contact" until the new one
|
||||
// says hello. Never over a question the box is already asking.
|
||||
if (stateCancelEl.hidden) showState(loopDetailEl.textContent, 'Try reconnecting', reconnectConsole, undefined, { retryAfter: RETRY_AFTER_SECONDS });
|
||||
if (stateCancelEl.hidden) showState(loopDetailEl.textContent, 'Try reconnecting', reconnectConsole, undefined, { retryAfter: RETRY_AFTER_SECONDS, autoRetry: !autoReconnected });
|
||||
return;
|
||||
}
|
||||
markConsoleDead();
|
||||
@@ -1110,6 +1126,7 @@ function showAnnounced(notice) {
|
||||
restarting = false;
|
||||
// A new page is a new start: the budget is per run of trouble, not per launch.
|
||||
reconnects = 0;
|
||||
autoReconnected = false;
|
||||
if (!consoleKnown) {
|
||||
consoleKnown = true;
|
||||
if (!pollTimer) pollTimer = setInterval(pollConsole, STATUS_POLL_MS);
|
||||
@@ -1349,25 +1366,138 @@ function setProjectDir(dir) {
|
||||
window.__TAURI__.window.getCurrentWindow().setTitle(windowTitleFor(dir)).catch(() => {});
|
||||
}
|
||||
|
||||
// The state `main()` read at startup: `pickFolder()` and the first-run
|
||||
// The state `main()` read at startup: the folder picker and the first-run
|
||||
// checklist both need it once a folder lands, after the fact.
|
||||
let appState = null;
|
||||
|
||||
// Opens the OS folder picker. A canceled pick (or a failed one) lands on the
|
||||
// "No project folder chosen" state with a button that tries again.
|
||||
async function pickFolder() {
|
||||
try {
|
||||
const dir = await invoke('pick_project_folder');
|
||||
if (!dir) {
|
||||
showState('No project folder chosen', 'Choose folder', pickFolder);
|
||||
return;
|
||||
}
|
||||
setProjectDir(dir);
|
||||
if (appState) appState.projectDir = dir;
|
||||
afterProjectKnown();
|
||||
} catch (error) {
|
||||
showState(`Could not open the folder picker: ${error}`, 'Choose folder', pickFolder);
|
||||
// The open folder picker's way back to its caller (null while none is open).
|
||||
let folderPickerResolve = null;
|
||||
|
||||
function hideFolderPicker() {
|
||||
folderPickerEl.hidden = true;
|
||||
folderPickerEl.classList.remove('is-dialog');
|
||||
folderPickerListEl.replaceChildren();
|
||||
}
|
||||
|
||||
function closeFolderPicker(dir) {
|
||||
const resolve = folderPickerResolve;
|
||||
folderPickerResolve = null;
|
||||
hideFolderPicker();
|
||||
if (resolve) resolve(dir);
|
||||
}
|
||||
|
||||
function setFolderPickerError(text) {
|
||||
folderPickerErrorEl.textContent = text || '';
|
||||
folderPickerErrorEl.hidden = !text;
|
||||
}
|
||||
|
||||
function folderPickerButtons() {
|
||||
return [...folderPickerListEl.querySelectorAll('.folder-picker-row')];
|
||||
}
|
||||
|
||||
// One picker for a bare start (`dialog: false`, full screen) and Change
|
||||
// project (`dialog: true`, over the page, with Cancel and Escape). Choose a
|
||||
// folder runs the OS dialog; a recent row opens that folder. Resolves with
|
||||
// the folder opened, or null when the person cancels the dialog. A canceled
|
||||
// OS dialog comes back here, and an error shows inline with the rows usable.
|
||||
async function showFolderPicker({ dialog }) {
|
||||
if (folderPickerResolve) closeFolderPicker(null);
|
||||
stopRetryCountdown();
|
||||
stateBox.hidden = true;
|
||||
if (!dialog) {
|
||||
hideLaunchCard();
|
||||
hideFirstRun();
|
||||
}
|
||||
setFolderPickerError('');
|
||||
folderPickerCancelBtn.hidden = !dialog;
|
||||
folderPickerEl.classList.toggle('is-dialog', dialog);
|
||||
if (dialog) folderPickerPanelEl.setAttribute('aria-modal', 'true');
|
||||
else folderPickerPanelEl.removeAttribute('aria-modal');
|
||||
// The project already open is left out by the command itself.
|
||||
let recent = [];
|
||||
try {
|
||||
recent = (await invoke('recent_folders')) || [];
|
||||
} catch (error) {
|
||||
setFolderPickerError(`Could not read the recent folders: ${error}`);
|
||||
}
|
||||
folderPickerListEl.replaceChildren(
|
||||
...folderPickerRows(recent).map((row) => {
|
||||
const li = document.createElement('li');
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = `folder-picker-row is-${row.kind}`;
|
||||
const label = document.createElement('span');
|
||||
label.className = 'folder-picker-label';
|
||||
label.textContent = row.label;
|
||||
button.append(label);
|
||||
if (row.detail) {
|
||||
const detail = document.createElement('span');
|
||||
detail.className = 'folder-picker-detail';
|
||||
detail.textContent = row.detail;
|
||||
button.append(detail);
|
||||
}
|
||||
button.onclick = () => chooseFolderRow(row, button, dialog);
|
||||
li.append(button);
|
||||
return li;
|
||||
})
|
||||
);
|
||||
folderPickerEl.hidden = false;
|
||||
folderPickerButtons()[0].focus();
|
||||
return new Promise((resolve) => {
|
||||
folderPickerResolve = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
// One row pressed: the OS dialog for Choose a folder (`change_project` from
|
||||
// Change project, which tears the old project down), else that recent
|
||||
// folder. Nothing chosen keeps the picker up, focus back on the row.
|
||||
async function chooseFolderRow(row, button, dialog) {
|
||||
const buttons = folderPickerButtons();
|
||||
buttons.forEach((b) => { b.disabled = true; });
|
||||
folderPickerCancelBtn.disabled = true;
|
||||
setFolderPickerError('');
|
||||
let dir = null;
|
||||
try {
|
||||
if (row.kind === 'browse') dir = await invoke(dialog ? 'change_project' : 'pick_project_folder');
|
||||
else dir = await invoke('open_recent_folder', { dir: row.dir });
|
||||
} catch (error) {
|
||||
setFolderPickerError(row.kind === 'browse' ? `Could not open the folder picker: ${error}` : `Could not open ${row.dir}: ${error}`);
|
||||
}
|
||||
buttons.forEach((b) => { b.disabled = false; });
|
||||
folderPickerCancelBtn.disabled = false;
|
||||
if (dir) {
|
||||
closeFolderPicker(dir);
|
||||
return;
|
||||
}
|
||||
button.focus();
|
||||
}
|
||||
|
||||
folderPickerCancelBtn.onclick = () => closeFolderPicker(null);
|
||||
// Escape is heard on the document: a click on the backdrop or the heading
|
||||
// leaves focus on the page, where a listener on the picker never sees it.
|
||||
document.addEventListener('keydown', (event) => {
|
||||
if (event.key !== 'Escape' || folderPickerEl.hidden) return;
|
||||
if (folderPickerCancelBtn.hidden || folderPickerCancelBtn.disabled) return;
|
||||
event.preventDefault();
|
||||
closeFolderPicker(null);
|
||||
});
|
||||
folderPickerEl.addEventListener('keydown', (event) => {
|
||||
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
|
||||
const buttons = folderPickerButtons();
|
||||
const at = buttons.indexOf(document.activeElement);
|
||||
if (at < 0) return;
|
||||
event.preventDefault();
|
||||
const next = event.key === 'ArrowDown' ? Math.min(at + 1, buttons.length - 1) : Math.max(at - 1, 0);
|
||||
buttons[next].focus();
|
||||
});
|
||||
|
||||
// A bare start: the picker, full screen, until a folder is opened.
|
||||
async function chooseStartFolder() {
|
||||
const dir = await showFolderPicker({ dialog: false });
|
||||
if (!dir) return;
|
||||
setProjectDir(dir);
|
||||
if (appState) appState.projectDir = dir;
|
||||
afterProjectKnown();
|
||||
}
|
||||
|
||||
// Once a project folder is known: the first-run checklist (once, until it
|
||||
@@ -1380,17 +1510,19 @@ function afterProjectKnown() {
|
||||
}
|
||||
}
|
||||
|
||||
// Switches to a folder picked fresh: the Rust side tears the old project's
|
||||
// agent and console down before the new one is remembered, so nothing from
|
||||
// it carries over. Picking nothing (canceled) leaves the current project as
|
||||
// it was.
|
||||
// Switches to a folder picked in the folder picker's dialog: the Rust side
|
||||
// tears the old project's agent and console down before the new one is
|
||||
// remembered, so nothing from it carries over. Cancel (or Escape) leaves
|
||||
// the current project as it was; the folder already open is not listed.
|
||||
async function doChangeProject() {
|
||||
showState('Choose the new project folder...');
|
||||
try {
|
||||
const dir = await invoke('change_project');
|
||||
const dir = await showFolderPicker({ dialog: true });
|
||||
if (!dir) {
|
||||
if (agentActive()) hideState();
|
||||
// Cancel leaves the page as it was: a running agent gets the keyboard
|
||||
// back, and a dashboard still on screen is never covered.
|
||||
if (agentActive() || frameReady) hideState();
|
||||
else afterProjectKnown();
|
||||
if (agentActive()) terminal.focus();
|
||||
return;
|
||||
}
|
||||
setProjectDir(dir);
|
||||
@@ -1521,7 +1653,7 @@ async function main() {
|
||||
setProjectDir(state.projectDir);
|
||||
afterProjectKnown();
|
||||
} else {
|
||||
pickFolder();
|
||||
chooseStartFolder();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -216,6 +216,42 @@
|
||||
#launch-start:hover { background: #357a5c; }
|
||||
#launch-start:disabled { background: #444; color: #888; cursor: not-allowed; }
|
||||
|
||||
/* The folder picker: full screen on a bare start, a dialog over the page
|
||||
(with Cancel) from Change project. Choose a folder comes first; each
|
||||
recent folder shows its name with the full path muted under it. */
|
||||
#folder-picker {
|
||||
position: absolute; inset: 0; z-index: 2; display: flex; align-items: center; justify-content: center;
|
||||
background: #1e1e1e; padding: 24px; box-sizing: border-box;
|
||||
}
|
||||
#folder-picker[hidden] { display: none; }
|
||||
#folder-picker.is-dialog { background: rgba(0, 0, 0, 0.55); }
|
||||
#folder-picker-panel { display: flex; flex-direction: column; gap: 12px; width: min(440px, 100%); max-height: 100%; }
|
||||
#folder-picker.is-dialog #folder-picker-panel {
|
||||
background: var(--panel); border: 1px solid var(--rule-2); border-radius: 10px; padding: 18px; box-sizing: border-box;
|
||||
}
|
||||
#folder-picker h2 { margin: 0; font-size: 17px; text-align: center; }
|
||||
#folder-picker-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; overflow-y: auto; }
|
||||
.folder-picker-row {
|
||||
appearance: none; width: 100%; text-align: left; font: inherit; cursor: pointer;
|
||||
display: flex; flex-direction: column; gap: 2px; padding: 8px 12px; border-radius: 8px;
|
||||
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink);
|
||||
}
|
||||
.folder-picker-row:hover:not(:disabled) { background: var(--panel-2); border-color: var(--accent-line); }
|
||||
.folder-picker-row:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.folder-picker-row:disabled { opacity: 0.6; cursor: default; }
|
||||
.folder-picker-row.is-browse { font-weight: 600; background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
.folder-picker-row.is-browse:hover:not(:disabled) { background: var(--accent); border-color: var(--accent); filter: brightness(1.08); }
|
||||
.folder-picker-label { font-size: 13.5px; }
|
||||
.folder-picker-detail { font-size: 12px; color: var(--ink-3); overflow-wrap: anywhere; }
|
||||
#folder-picker-error { margin: 0; font-size: 12px; color: #d7ba7d; }
|
||||
#folder-picker-error[hidden], #folder-picker-cancel[hidden] { display: none; }
|
||||
#folder-picker-cancel {
|
||||
align-self: center; appearance: none; font: inherit; font-size: 13.5px; font-weight: 600; padding: 7px 13px;
|
||||
border-radius: 8px; cursor: pointer; border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink);
|
||||
}
|
||||
#folder-picker-cancel:hover { background: var(--panel-2); }
|
||||
#folder-picker-cancel:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
|
||||
#first-run {
|
||||
position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column;
|
||||
align-items: stretch; justify-content: center; gap: 14px; background: #1e1e1e;
|
||||
@@ -359,6 +395,14 @@
|
||||
<button id="dashboard-state-cancel" hidden>Cancel</button>
|
||||
</span>
|
||||
</div>
|
||||
<div id="folder-picker" hidden>
|
||||
<div id="folder-picker-panel" role="dialog" aria-labelledby="folder-picker-title">
|
||||
<h2 id="folder-picker-title">Open a project</h2>
|
||||
<ul id="folder-picker-list"></ul>
|
||||
<p id="folder-picker-error" role="alert" hidden></p>
|
||||
<button id="folder-picker-cancel" type="button" hidden>Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="first-run" hidden>
|
||||
<h2>Before you start</h2>
|
||||
<ul id="first-run-list"></ul>
|
||||
|
||||
@@ -280,6 +280,18 @@ export function folderName(dir) {
|
||||
return lastSegment(dir) || String(dir || "").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* The folder picker's rows: Choose a folder first (the OS dialog), then one
|
||||
* row per recent folder from the `recent_folders` command, newest first,
|
||||
* named by the folder with its full path as the detail.
|
||||
*/
|
||||
export function folderPickerRows(recent) {
|
||||
return [
|
||||
{ kind: 'browse', label: 'Choose a folder...' },
|
||||
...(recent || []).map((r) => ({ kind: 'folder', dir: r.dir, label: r.name, detail: r.dir })),
|
||||
];
|
||||
}
|
||||
|
||||
function lastSegment(dir) {
|
||||
return String(dir || "")
|
||||
.trim()
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
running 2 tests
|
||||
test math::adds ... ok
|
||||
test math::divides ... FAILED
|
||||
@@ -0,0 +1,2 @@
|
||||
Passed MyApp.Tests.Adds [1 ms]
|
||||
Failed MyApp.Tests.Divides [3 ms]
|
||||
@@ -0,0 +1,5 @@
|
||||
=== RUN TestAdds
|
||||
--- PASS: TestAdds (0.00s)
|
||||
=== RUN TestDivides
|
||||
--- FAIL: TestDivides (0.00s)
|
||||
FAIL example.com/m 0.01s
|
||||
@@ -0,0 +1,5 @@
|
||||
PASS src/a.test.js
|
||||
FAIL src/b.test.js
|
||||
math
|
||||
✓ adds (2 ms)
|
||||
✕ divides by zero (5 ms)
|
||||
@@ -0,0 +1,10 @@
|
||||
✔ adds numbers (1.2ms)
|
||||
✖ parses dates (3.4ms)
|
||||
ℹ tests 2
|
||||
ℹ pass 1
|
||||
ℹ fail 1
|
||||
|
||||
✖ failing tests:
|
||||
|
||||
test at scripts/a.mjs:3:1
|
||||
✖ parses dates (3.4ms)
|
||||
@@ -0,0 +1,3 @@
|
||||
tests/test_a.py::test_adds PASSED
|
||||
FAILED tests/test_b.py::test_divides - ZeroDivisionError: division by zero
|
||||
==================== 1 failed, 1 passed in 0.12s ====================
|
||||
@@ -0,0 +1,9 @@
|
||||
TAP version 13
|
||||
ok 1 - adds numbers
|
||||
not ok 2 - parses dates
|
||||
---
|
||||
message: 'expected 2 to equal 3'
|
||||
...
|
||||
not ok 3 - writes the cache # TODO later
|
||||
ok 4 - reads the cache # SKIP no disk
|
||||
1..4
|
||||
@@ -0,0 +1,2 @@
|
||||
Error: something broke
|
||||
at main (build.js:1:1)
|
||||
@@ -0,0 +1,2 @@
|
||||
✓ src/a.test.ts (1 test) 2ms
|
||||
FAIL src/b.test.ts > math > divides by zero
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "pins-fixture",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "pins-fixture",
|
||||
"version": "1.0.0",
|
||||
"devDependencies": {
|
||||
"playwright-core": "1.64.1"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.64.1",
|
||||
"dev": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "pins-fixture",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"devDependencies": {
|
||||
"playwright-core": "1.64.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Checks the one browser build the helper downloads.
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
export const BROWSER = "playwright-core@1.64.1";
|
||||
// Other versions never count: playwright-core 11.64.10 and 1.64.12 are not the locked one.
|
||||
export { chromium };
|
||||
@@ -0,0 +1,208 @@
|
||||
{
|
||||
"$comment": "The rule of the recent-folders list in ~/.plan2code/launcher.json (`recentFolders`, newest first, at most 5) as cases both writers' tests load: the launcher (src/launcher/plan2code.js) and the desktop app (plan2code-app/src-tauri/src/project.rs). A case may carry `platform`: `win32` or `posix`; it runs only with that platform's rule (a case with none runs under both). Paths are plain strings. read: `state` is the launcher.json object, `expect` the list. push: `list`, `dir`, `expect`. list: `list`, `exists` (the folders that exist), `exclude` (a folder or null), `expect`.",
|
||||
"read": [
|
||||
{
|
||||
"name": "the list is used as it is",
|
||||
"state": { "recentFolders": ["/b", "/a"], "lastFolder": "/z" },
|
||||
"expect": ["/b", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "an empty list is used as it is, not replaced by the last folder",
|
||||
"state": { "recentFolders": [], "lastFolder": "/a" },
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "no list falls back to the last folder",
|
||||
"state": { "lastFolder": "/a" },
|
||||
"expect": ["/a"]
|
||||
},
|
||||
{
|
||||
"name": "neither key gives an empty list",
|
||||
"state": { "lastCli": "claude" },
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "an empty state gives an empty list",
|
||||
"state": {},
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "entries that are not strings or are empty are dropped",
|
||||
"state": { "recentFolders": ["/a", 7, "", null, "/b", { "x": 1 }] },
|
||||
"expect": ["/a", "/b"]
|
||||
},
|
||||
{
|
||||
"name": "a list that is not an array falls back to the last folder",
|
||||
"state": { "recentFolders": "/x", "lastFolder": "/a" },
|
||||
"expect": ["/a"]
|
||||
},
|
||||
{
|
||||
"name": "a list that is not an array and no last folder gives an empty list",
|
||||
"state": { "recentFolders": { "0": "/x" } },
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "an empty last folder is no folder",
|
||||
"state": { "lastFolder": "" },
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "more than 5 entries are cut to 5",
|
||||
"state": { "recentFolders": ["/1", "/2", "/3", "/4", "/5", "/6", "/7"] },
|
||||
"expect": ["/1", "/2", "/3", "/4", "/5"]
|
||||
}
|
||||
],
|
||||
"push": [
|
||||
{
|
||||
"name": "a new folder goes first",
|
||||
"list": ["/b", "/a"],
|
||||
"dir": "/c",
|
||||
"expect": ["/c", "/b", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "a first folder starts the list",
|
||||
"list": [],
|
||||
"dir": "/a",
|
||||
"expect": ["/a"]
|
||||
},
|
||||
{
|
||||
"name": "an existing folder moves to the top without a duplicate",
|
||||
"list": ["/c", "/b", "/a"],
|
||||
"dir": "/a",
|
||||
"expect": ["/a", "/c", "/b"]
|
||||
},
|
||||
{
|
||||
"name": "a sixth folder drops the oldest",
|
||||
"list": ["/5", "/4", "/3", "/2", "/1"],
|
||||
"dir": "/6",
|
||||
"expect": ["/6", "/5", "/4", "/3", "/2"]
|
||||
},
|
||||
{
|
||||
"name": "a folder already first stays first",
|
||||
"list": ["/a", "/b"],
|
||||
"dir": "/a",
|
||||
"expect": ["/a", "/b"]
|
||||
},
|
||||
{
|
||||
"name": "a trailing slash matches the bare path",
|
||||
"list": ["/b", "/a"],
|
||||
"dir": "/a/",
|
||||
"expect": ["/a/", "/b"]
|
||||
},
|
||||
{
|
||||
"name": "a bare path matches a listed trailing slash",
|
||||
"list": ["/b", "/a/"],
|
||||
"dir": "/a",
|
||||
"expect": ["/a", "/b"]
|
||||
},
|
||||
{
|
||||
"name": "a trailing backslash matches the bare path",
|
||||
"list": ["D:\\x", "C:\\a"],
|
||||
"dir": "C:\\a\\",
|
||||
"expect": ["C:\\a\\", "D:\\x"]
|
||||
},
|
||||
{
|
||||
"name": "a drive root keeps its separator",
|
||||
"list": ["C:\\", "C:\\a"],
|
||||
"dir": "C:\\a\\",
|
||||
"expect": ["C:\\a\\", "C:\\"]
|
||||
},
|
||||
{
|
||||
"name": "the root of a posix tree is not stripped to nothing",
|
||||
"list": ["/a"],
|
||||
"dir": "/",
|
||||
"expect": ["/", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "a drive root is not the bare drive",
|
||||
"list": ["C:"],
|
||||
"dir": "C:\\",
|
||||
"expect": ["C:\\", "C:"]
|
||||
},
|
||||
{
|
||||
"name": "a drive root with a slash is not the bare drive",
|
||||
"list": ["C:"],
|
||||
"dir": "C:/",
|
||||
"expect": ["C:/", "C:"]
|
||||
},
|
||||
{
|
||||
"name": "a drive root matches itself",
|
||||
"list": ["C:\\"],
|
||||
"dir": "C:\\",
|
||||
"expect": ["C:\\"]
|
||||
},
|
||||
{
|
||||
"name": "the posix root is not an empty path",
|
||||
"list": ["/a", ""],
|
||||
"dir": "/",
|
||||
"expect": ["/", "/a", ""]
|
||||
},
|
||||
{
|
||||
"platform": "win32",
|
||||
"name": "windows ignores case and keeps the new spelling",
|
||||
"list": ["D:\\x", "c:\\git\\a"],
|
||||
"dir": "C:\\Git\\A",
|
||||
"expect": ["C:\\Git\\A", "D:\\x"]
|
||||
},
|
||||
{
|
||||
"platform": "posix",
|
||||
"name": "posix tells case apart",
|
||||
"list": ["/x", "/git/a"],
|
||||
"dir": "/Git/A",
|
||||
"expect": ["/Git/A", "/x", "/git/a"]
|
||||
}
|
||||
],
|
||||
"list": [
|
||||
{
|
||||
"name": "folders that are gone are skipped and the order is kept",
|
||||
"list": ["/c", "/b", "/a"],
|
||||
"exists": ["/a", "/c"],
|
||||
"exclude": null,
|
||||
"expect": ["/c", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "nothing existing gives an empty list",
|
||||
"list": ["/b", "/a"],
|
||||
"exists": [],
|
||||
"exclude": null,
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "the excluded folder is removed",
|
||||
"list": ["/c", "/b", "/a"],
|
||||
"exists": ["/a", "/b", "/c"],
|
||||
"exclude": "/b",
|
||||
"expect": ["/c", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "the excluded folder matches past a trailing slash",
|
||||
"list": ["/c", "/b", "/a"],
|
||||
"exists": ["/a", "/b", "/c"],
|
||||
"exclude": "/b/",
|
||||
"expect": ["/c", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "excluding a drive root leaves the bare drive",
|
||||
"list": ["C:", "C:\\"],
|
||||
"exists": ["C:", "C:\\"],
|
||||
"exclude": "C:\\",
|
||||
"expect": ["C:"]
|
||||
},
|
||||
{
|
||||
"platform": "win32",
|
||||
"name": "windows excludes by folder, not by spelling",
|
||||
"list": ["C:\\Git\\A", "D:\\x"],
|
||||
"exists": ["C:\\Git\\A", "D:\\x"],
|
||||
"exclude": "c:\\git\\a\\",
|
||||
"expect": ["D:\\x"]
|
||||
},
|
||||
{
|
||||
"platform": "posix",
|
||||
"name": "posix keeps a folder that differs only in case",
|
||||
"list": ["/Git/A", "/x"],
|
||||
"exists": ["/Git/A", "/x"],
|
||||
"exclude": "/git/a",
|
||||
"expect": ["/Git/A", "/x"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { helloRetryAction, retryLabel, RETRY_AFTER_SECONDS, attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS, NEW_RELEASE_COMMAND } from "../plan2code-app/ui/meter.js";
|
||||
import { helloRetryAction, retryLabel, RETRY_AFTER_SECONDS, attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, folderPickerRows, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS, NEW_RELEASE_COMMAND } from "../plan2code-app/ui/meter.js";
|
||||
import { findBrowser, launchBrowser } from "./browser.mjs";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -134,6 +134,19 @@ test("the bar reads project menu, New Session, agent menu, with both menus outsi
|
||||
assert.match(INDEX_HTML, /<div id="project-menu"[\s\S]*?<button id="change-project" role="menuitem">/, "Change project lives in the project menu");
|
||||
});
|
||||
|
||||
test("folderPickerRows puts Choose a folder first, then the recent folders in the order given", () => {
|
||||
assert.deepEqual(folderPickerRows([]), [{ kind: "browse", label: "Choose a folder..." }]);
|
||||
const rows = folderPickerRows([
|
||||
{ dir: "C:\\git\\b", name: "b" },
|
||||
{ dir: "/home/me/a", name: "a" },
|
||||
]);
|
||||
assert.deepEqual(rows, [
|
||||
{ kind: "browse", label: "Choose a folder..." },
|
||||
{ kind: "folder", dir: "C:\\git\\b", label: "b", detail: "C:\\git\\b" },
|
||||
{ kind: "folder", dir: "/home/me/a", label: "a", detail: "/home/me/a" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("folderName shows the project folder's own name, or the whole path when it has none", () => {
|
||||
assert.equal(folderName("C:\\git\\azw3-to-pdf"), "azw3-to-pdf");
|
||||
assert.equal(folderName("/home/me/plan2code/"), "plan2code");
|
||||
@@ -444,6 +457,16 @@ test("app.js re-arms the hello check and offers Try reconnecting on the loop's w
|
||||
assert.match(app, /loopStep === 'Starting' && stepBefore !== 'Starting' && consoleKnown\) void pollConsole\(\)/, "a phase starting looks at the console at once, so the countdown does not wait for the next poll");
|
||||
});
|
||||
|
||||
test("app.js tries Try reconnecting once by itself when its countdown ends, once per run of trouble", () => {
|
||||
const app = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "app.js"), "utf8");
|
||||
const show = app.slice(app.indexOf("function showState"), app.indexOf("function hideState"));
|
||||
assert.match(show, /autoRetry/, "showState takes an autoRetry option");
|
||||
assert.match(show, /if \(left <= 0\) \{[^}]*onButton/s, "the countdown's end runs the button's action itself");
|
||||
assert.match(app, /showState\(loopDetailEl\.textContent[^)]*autoRetry: !autoReconnected/s, "the loop's wait for a phase's page tries once");
|
||||
const announced = app.slice(app.indexOf("function showAnnounced"), app.indexOf("window.__TAURI__.event.listen('console-page'"));
|
||||
assert.match(announced, /autoReconnected = false/, "each new page gets its own automatic try");
|
||||
});
|
||||
|
||||
test("app.js refills the reconnect budget on a new page and brings the page back when a loop ends", () => {
|
||||
const app = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "app.js"), "utf8");
|
||||
const announced = app.slice(app.indexOf("function showAnnounced"), app.indexOf("window.__TAURI__.event.listen('console-page'"));
|
||||
@@ -520,7 +543,7 @@ test("main.rs guards the window's agent and project commands, and registers loop
|
||||
assert.ok(at > 0, `${name} exists`);
|
||||
return rust.slice(at, rust.indexOf("\n}\n", at));
|
||||
};
|
||||
for (const [name, what] of [["agent_start", "agent"], ["agent_restart", "agent"], ["change_project", "project"], ["pick_project_folder", "project"]]) {
|
||||
for (const [name, what] of [["agent_start", "agent"], ["agent_restart", "agent"], ["change_project", "project"], ["pick_project_folder", "project"], ["open_recent_folder", "project"]]) {
|
||||
assert.ok(body(name).includes(`refuse_while_looping(&state, "${what}")?;`), `${name} refuses while a loop runs`);
|
||||
}
|
||||
assert.ok(!body("agent_input").includes("refuse_while_looping"), "typing stays open for a trust or login prompt");
|
||||
|
||||
@@ -30,19 +30,19 @@ export const BUDGETS = {
|
||||
notes: {
|
||||
"changelog.md": 1400,
|
||||
"dead-code.md": 4900,
|
||||
"deps.md": 5700,
|
||||
"deps.md": 9000, // raised by the pin, newer-Node, baseline and full-suite lines, then the fix card and the install card (8823 bytes)
|
||||
"diagnose.md": 2840, // raised by the lessons card line's bytes only
|
||||
"document.md": 400,
|
||||
"finalize.md": 2000,
|
||||
"git.md": 6500,
|
||||
"handoff.md": 300,
|
||||
"implement.md": 5700,
|
||||
"implement.md": 6416, // raised by the Changes tab's lines only
|
||||
"init.md": 300,
|
||||
"loop.md": 11712, // raised by the failed report's nextStep line's bytes only
|
||||
"loop.md": 11857, // raised by the failed report's nextStep line's and the Changes tab 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
|
||||
"pr-prep.md": 4500,
|
||||
"quick-task.md": 4869, // raised by the UI prototype line's, the prototype recap line's, the prototype archive wording's and the lessons card line's bytes only
|
||||
"quick-task.md": 5194, // raised by the UI prototype line's, the prototype recap line's, the prototype archive wording's, the lessons card line's and the Changes tab lines' bytes only
|
||||
"review.md": 1140, // raised by the lessons card line's bytes only
|
||||
"revise-plan.md": 1422, // raised by the UI prototype line's bytes only
|
||||
"test.md": 5540, // raised by the lessons card line's bytes only
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"test-install-update.mjs",
|
||||
"test-line-endings.mjs",
|
||||
"test-script-changelog.mjs",
|
||||
"test-script-changes.mjs",
|
||||
"test-script-coverage.mjs",
|
||||
"test-script-dead-code.mjs",
|
||||
"test-script-deps.mjs",
|
||||
@@ -36,6 +37,7 @@
|
||||
"test-us-english.mjs",
|
||||
"test-web-console-agents-doc.mjs",
|
||||
"test-web-console-card-rows.mjs",
|
||||
"test-web-console-diff-parse.mjs",
|
||||
"test-web-console-git-board.mjs",
|
||||
"test-web-console-prototypes.mjs",
|
||||
"test-web-console-send-state.mjs",
|
||||
@@ -111,6 +113,7 @@
|
||||
"test-web-console-page-activities.mjs",
|
||||
"test-web-console-page-ask.mjs",
|
||||
"test-web-console-page-cards.mjs",
|
||||
"test-web-console-page-changes.mjs",
|
||||
"test-web-console-page-dashboard.mjs",
|
||||
"test-web-console-page-git.mjs",
|
||||
"test-web-console-page-help.mjs",
|
||||
|
||||
+151
-6
@@ -131,6 +131,18 @@ function sandbox(clis, { installed, project = true, lookup = true, agents } = {}
|
||||
|
||||
const NOTICE_LINE = /is out \(you have v/;
|
||||
|
||||
/**
|
||||
* The run's folder was recorded: first in `recentFolders` (compared by real path, since a temp
|
||||
* folder can reach the launcher under another spelling), `lastFolder` equal to it, and `older`
|
||||
* after it in order.
|
||||
*/
|
||||
function assertRecordedFirst({ recentFolders, lastFolder }, folder, older = []) {
|
||||
assert.ok(Array.isArray(recentFolders), "recentFolders is written");
|
||||
assert.equal(fs.realpathSync(recentFolders[0]), fs.realpathSync(folder));
|
||||
assert.equal(lastFolder, recentFolders[0]);
|
||||
assert.deepEqual(recentFolders.slice(1), older);
|
||||
}
|
||||
|
||||
/** Write the console's cached release check, `ageMs` old. */
|
||||
function writeCache(box, latest, ageMs = 0) {
|
||||
fs.mkdirSync(path.dirname(box.cacheFile), { recursive: true });
|
||||
@@ -307,11 +319,9 @@ test("launcher: a launched model is remembered per agent in launcher.json", (t)
|
||||
assert.equal(box.run(["--cli", "claude", "--model", "opus"]).status, 0);
|
||||
assert.equal(box.run(["--cli", "codex", "-m", "x"]).status, 0);
|
||||
assert.equal(box.run(["--cli", "codex", "-my"]).status, 0);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), {
|
||||
lastFolder: box.home,
|
||||
lastCli: "codex",
|
||||
lastModels: { claude: "opus", codex: "y" },
|
||||
});
|
||||
const { recentFolders, lastFolder, ...rest } = JSON.parse(fs.readFileSync(box.stateFile, "utf8"));
|
||||
assert.deepEqual(rest, { lastCli: "codex", lastModels: { claude: "opus", codex: "y" } });
|
||||
assertRecordedFirst({ recentFolders, lastFolder }, box.dir, [box.home]);
|
||||
});
|
||||
|
||||
test("launcher: --cli picks the CLI and is never forwarded; the pick is merged into launcher.json", (t) => {
|
||||
@@ -326,7 +336,9 @@ test("launcher: --cli picks the CLI and is never forwarded; the pick is merged i
|
||||
assert.deepEqual(box.argsOf("devin"), ["--", "/plan2code"]);
|
||||
}
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), { lastFolder: box.home, lastCli: "devin" });
|
||||
const { recentFolders, lastFolder, ...rest } = JSON.parse(fs.readFileSync(box.stateFile, "utf8"));
|
||||
assert.deepEqual(rest, { lastCli: "devin" });
|
||||
assertRecordedFirst({ recentFolders, lastFolder }, box.dir, [box.home]);
|
||||
});
|
||||
|
||||
test("launcher: with both installed and no terminal to ask in, the last pick wins", (t) => {
|
||||
@@ -1319,3 +1331,136 @@ test("launcher setup: no agent and no display keeps the old 127 and install step
|
||||
assert.match(result.stderr, /none was found/);
|
||||
assert.equal(box.appExists(), false);
|
||||
});
|
||||
|
||||
// The recent-folders rule: the same cases the desktop app's project.rs loads (the fixture holds
|
||||
// both platforms' rules, so each runs on every OS: "win32" and "linux" are passed explicitly).
|
||||
const RECENT_CASES = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts", "fixtures", "recent-folders-cases.json"), "utf8"));
|
||||
const RECENT_PLATFORMS = { win32: "win32", posix: "linux" };
|
||||
|
||||
/** The platform values ("win32" or "linux") a fixture case runs under. */
|
||||
function recentPlatforms(testCase) {
|
||||
return testCase.platform ? [RECENT_PLATFORMS[testCase.platform]] : ["win32", "linux"];
|
||||
}
|
||||
|
||||
test("launcher recent folders: readRecent follows the shared cases", () => {
|
||||
const { readRecent } = require(LAUNCHER);
|
||||
assert.ok(RECENT_CASES.read.length > 0);
|
||||
for (const c of RECENT_CASES.read) assert.deepEqual(readRecent(c.state), c.expect, c.name);
|
||||
});
|
||||
|
||||
test("launcher recent folders: pushRecent follows the shared cases", () => {
|
||||
const { pushRecent } = require(LAUNCHER);
|
||||
assert.ok(RECENT_CASES.push.length > 0);
|
||||
for (const c of RECENT_CASES.push) {
|
||||
for (const platform of recentPlatforms(c)) assert.deepEqual(pushRecent(c.list, c.dir, platform), c.expect, `${c.name} (${platform})`);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher recent folders: listRecent follows the shared cases", () => {
|
||||
const { listRecent } = require(LAUNCHER);
|
||||
assert.ok(RECENT_CASES.list.length > 0);
|
||||
for (const c of RECENT_CASES.list) {
|
||||
const exists = new Set(c.exists);
|
||||
for (const platform of recentPlatforms(c)) {
|
||||
assert.deepEqual(listRecent(c.list, { exists: (p) => exists.has(p), exclude: c.exclude, platform }), c.expect, `${c.name} (${platform})`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher recent folders: pushRecent returns a new array and leaves its input alone", () => {
|
||||
const { pushRecent } = require(LAUNCHER);
|
||||
const list = ["/b", "/a"];
|
||||
pushRecent(list, "/c", "linux");
|
||||
assert.deepEqual(list, ["/b", "/a"]);
|
||||
});
|
||||
|
||||
test("launcher recent folders: recordFolder writes both keys from a state with only lastFolder and keeps the rest", (t) => {
|
||||
const box = sandbox([]);
|
||||
t.after(box.cleanup);
|
||||
fs.mkdirSync(path.dirname(box.stateFile), { recursive: true });
|
||||
fs.writeFileSync(box.stateFile, JSON.stringify({ lastFolder: "/old", lastCli: "devin" }));
|
||||
const picked = path.join(box.dir, "picked");
|
||||
const script = `require(${JSON.stringify(LAUNCHER)}).recordFolder(${JSON.stringify(picked)});`;
|
||||
const result = spawnSync(process.execPath, ["-e", script], {
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, HOME: box.home, USERPROFILE: box.home },
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), {
|
||||
lastFolder: picked,
|
||||
recentFolders: [picked, "/old"],
|
||||
lastCli: "devin",
|
||||
});
|
||||
});
|
||||
|
||||
test("launcher folder menu: from the command, the current folder comes first, then the recents, then browse", () => {
|
||||
const { folderMenuRows } = require(LAUNCHER);
|
||||
const cwd = path.join(os.tmpdir(), "here");
|
||||
const recent = [path.join(os.tmpdir(), "one"), path.join(os.tmpdir(), "two")];
|
||||
assert.deepEqual(folderMenuRows({ fromShortcut: false, cwd, recent }), [
|
||||
{ kind: "folder", dir: cwd, name: "here", detail: `${cwd} (current folder)`, label: `here ${cwd} (current folder)` },
|
||||
{ kind: "folder", dir: recent[0], name: "one", detail: recent[0], label: `one ${recent[0]}` },
|
||||
{ kind: "folder", dir: recent[1], name: "two", detail: recent[1], label: `two ${recent[1]}` },
|
||||
{ kind: "browse", label: "Choose another folder..." },
|
||||
]);
|
||||
});
|
||||
|
||||
test("launcher folder menu: from the shortcut, browse comes first, then the recents", () => {
|
||||
const { folderMenuRows } = require(LAUNCHER);
|
||||
const recent = [path.join(os.tmpdir(), "one")];
|
||||
assert.deepEqual(folderMenuRows({ fromShortcut: true, cwd: os.tmpdir(), recent }), [
|
||||
{ kind: "browse", label: "Choose a folder..." },
|
||||
{ kind: "folder", dir: recent[0], name: "one", detail: recent[0], label: `one ${recent[0]}` },
|
||||
]);
|
||||
});
|
||||
|
||||
test("launcher folder menu: a drive root keeps its full text as its name", () => {
|
||||
const { folderMenuRows } = require(LAUNCHER);
|
||||
const root = path.parse(process.cwd()).root;
|
||||
const [row] = folderMenuRows({ fromShortcut: false, cwd: root, recent: [] });
|
||||
assert.equal(row.label, `${root} ${root} (current folder)`);
|
||||
assert.equal(row.name, root);
|
||||
assert.equal(row.detail, `${root} (current folder)`);
|
||||
});
|
||||
|
||||
test("launcher folder menu: Enter picks row 1, a number its row, anything else asks again", () => {
|
||||
const { folderMenuPick } = require(LAUNCHER);
|
||||
const rows = [{ kind: "folder", dir: "/a", label: "a" }, { kind: "folder", dir: "/b", label: "b" }, { kind: "browse", label: "x" }];
|
||||
assert.equal(folderMenuPick(rows, ""), rows[0]);
|
||||
assert.equal(folderMenuPick(rows, " "), rows[0]);
|
||||
assert.equal(folderMenuPick(rows, "2"), rows[1]);
|
||||
assert.equal(folderMenuPick(rows, " 3 "), rows[2]);
|
||||
for (const answer of ["0", "9", "x", "1.5", "-1"]) assert.equal(folderMenuPick(rows, answer), null, answer);
|
||||
});
|
||||
|
||||
test("launcher folder menu: with recent folders but no terminal, it starts in the current folder without a menu and records it", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const older = path.join(box.dir, "older");
|
||||
fs.mkdirSync(older);
|
||||
fs.mkdirSync(path.dirname(box.stateFile), { recursive: true });
|
||||
fs.writeFileSync(box.stateFile, JSON.stringify({ recentFolders: [older], lastFolder: older, lastCli: "claude" }));
|
||||
const result = box.run([]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.doesNotMatch(result.stdout, /Which project folder\?/);
|
||||
assert.doesNotMatch(result.stdout, /Opening Plan2Code in/);
|
||||
assert.notEqual(box.argsOf("claude"), null);
|
||||
const { recentFolders, lastFolder, ...rest } = JSON.parse(fs.readFileSync(box.stateFile, "utf8"));
|
||||
assert.deepEqual(rest, { lastCli: "claude" });
|
||||
assertRecordedFirst({ recentFolders, lastFolder }, box.dir, [older]);
|
||||
});
|
||||
|
||||
test("launcher folder menu: a folder that fails the project check is not recorded", (t) => {
|
||||
const box = sandbox(["claude"], { project: false });
|
||||
t.after(box.cleanup);
|
||||
const older = path.join(box.dir, "older");
|
||||
fs.mkdirSync(older);
|
||||
fs.mkdirSync(path.dirname(box.stateFile), { recursive: true });
|
||||
const state = { recentFolders: [older], lastFolder: older, lastCli: "claude" };
|
||||
fs.writeFileSync(box.stateFile, JSON.stringify(state));
|
||||
const result = box.run([]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stderr, /doesn't look like a project/);
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), state);
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
// Tests for the skills' scripts/changes.mjs: `start` snapshots the working tree
|
||||
// through a temporary index and `diff` writes what changed since.
|
||||
//
|
||||
// See skill-script-helpers.mjs for how these run.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { SKILLS, runScript, tmp, write, read, gitInit } from "./skill-script-helpers.mjs";
|
||||
|
||||
const SKILL = "plan2code-3-implement";
|
||||
const run = (root, session, ...a) => runScript(SKILL, "changes.mjs", [...a, "--session", session, "--root", root]);
|
||||
|
||||
// A repository with a few committed files and a session folder beside it.
|
||||
function fixture(name) {
|
||||
const root = tmp(name);
|
||||
const session = tmp(`${name}-session`);
|
||||
const g = gitInit(root);
|
||||
write(root, "a.txt", "one\ntwo\nthree\n");
|
||||
write(root, "gone.txt", "bye\nbye\n");
|
||||
write(root, "old-name.txt", "keep this\nand this\nand more of it\nand a fourth line\n");
|
||||
write(root, "src/b.js", "export const b = 1;\n");
|
||||
write(root, ".gitignore", "ignored/\n");
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "init");
|
||||
return { root, session, g };
|
||||
}
|
||||
|
||||
const state = (g) => ({ status: g("status", "--porcelain"), head: g("rev-parse", "HEAD"), branch: g("branch", "--show-current"), staged: g("diff", "--cached", "--name-only") });
|
||||
const names = (diff) => [...diff.matchAll(/^diff --git a\/(.+) b\/(.+)$/gm)].map((m) => m[2]);
|
||||
|
||||
test("changes: start then diff lists exactly what changed since, and leaves the repository alone", () => {
|
||||
const { root, session, g } = fixture("changes-basic");
|
||||
// Work done before start must never show up.
|
||||
write(root, "before.txt", "earlier work\n");
|
||||
fs.appendFileSync(path.join(root, "a.txt"), "before\n");
|
||||
const before = state(g);
|
||||
const s = run(root, session, "start");
|
||||
assert.equal(s.code, 0, s.stderr);
|
||||
assert.match(s.json.tree, /^[0-9a-f]{40,64}$/);
|
||||
const startFile = JSON.parse(read(session, "changes-start.json"));
|
||||
assert.equal(startFile.tree, s.json.tree);
|
||||
assert.ok(!Number.isNaN(Date.parse(startFile.at)));
|
||||
assert.deepEqual(state(g), before, "start leaves status, HEAD, branch and the real index as they were");
|
||||
|
||||
// The run's own work: modify, add, delete, rename, ignored file.
|
||||
fs.appendFileSync(path.join(root, "a.txt"), "four\n");
|
||||
write(root, "new.txt", "fresh\nfile\n");
|
||||
fs.rmSync(path.join(root, "gone.txt"));
|
||||
fs.renameSync(path.join(root, "old-name.txt"), path.join(root, "new-name.txt"));
|
||||
write(root, "ignored/x.txt", "never shown\n");
|
||||
const mid = state(g);
|
||||
const d = run(root, session, "diff");
|
||||
assert.equal(d.code, 0, d.stderr);
|
||||
assert.deepEqual(state(g), mid, "diff leaves the repository alone too");
|
||||
assert.equal(d.json.file, "changes.diff");
|
||||
assert.equal(d.json.files, 4);
|
||||
assert.equal(d.json.added, 3, "four, two new lines");
|
||||
assert.equal(d.json.removed, 2, "the two lines of gone.txt");
|
||||
assert.equal(d.json.truncated, false);
|
||||
assert.deepEqual(d.json.hidden, []);
|
||||
const diff = read(session, "changes.diff");
|
||||
assert.deepEqual(names(diff).sort(), ["a.txt", "gone.txt", "new-name.txt", "new.txt"]);
|
||||
assert.ok(!diff.includes("before.txt") && !/^[+-]before$/m.test(diff), "work done before start never appears as a change");
|
||||
assert.ok(!diff.includes("ignored"), ".gitignore'd files never appear");
|
||||
assert.match(diff, /^rename from old-name\.txt$/m);
|
||||
assert.match(diff, /^rename to new-name\.txt$/m);
|
||||
assert.match(diff, /^similarity index 100%$/m);
|
||||
});
|
||||
|
||||
test("changes: a pure rename counts as one file, a binary file is listed with no lines", () => {
|
||||
const { root, session } = fixture("changes-binary");
|
||||
run(root, session, "start");
|
||||
fs.renameSync(path.join(root, "src", "b.js"), path.join(root, "src", "c.js"));
|
||||
fs.writeFileSync(path.join(root, "pic.bin"), Buffer.from([0, 1, 2, 3, 0, 255, 254, 0]));
|
||||
const d = run(root, session, "diff");
|
||||
assert.equal(d.code, 0, d.stderr);
|
||||
assert.equal(d.json.files, 2);
|
||||
assert.equal(d.json.added, 0, "binary adds nothing and a pure rename adds nothing");
|
||||
assert.equal(d.json.removed, 0);
|
||||
assert.ok(Number.isFinite(d.json.added) && Number.isFinite(d.json.removed), "never NaN");
|
||||
const diff = read(session, "changes.diff");
|
||||
assert.match(diff, /^Binary files .*pic\.bin differ$/m);
|
||||
assert.ok(!/^@@/m.test(diff), "no hunks at all");
|
||||
assert.match(diff, /^rename from src\/b\.js$/m);
|
||||
});
|
||||
|
||||
test("changes: no changes is an empty file, not an error", () => {
|
||||
const { root, session } = fixture("changes-empty");
|
||||
run(root, session, "start");
|
||||
const d = run(root, session, "diff");
|
||||
assert.equal(d.code, 0, d.stderr);
|
||||
assert.deepEqual({ files: d.json.files, added: d.json.added, removed: d.json.removed, truncated: d.json.truncated }, { files: 0, added: 0, removed: 0, truncated: false });
|
||||
assert.equal(read(session, "changes.diff"), "");
|
||||
});
|
||||
|
||||
test("changes: a patch over the cap is cut at a file boundary, every file still named", () => {
|
||||
const { root, session } = fixture("changes-cap");
|
||||
run(root, session, "start");
|
||||
for (const n of ["f1", "f2", "f3"]) write(root, `${n}.txt`, `${n} line\n`.repeat(200));
|
||||
const d = run(root, session, "diff", "--cap", "1000");
|
||||
assert.equal(d.code, 0, d.stderr);
|
||||
assert.equal(d.json.truncated, true);
|
||||
assert.equal(d.json.files, 3);
|
||||
assert.equal(d.json.added, 600, "counts cover the whole change, not the cut patch");
|
||||
const diff = read(session, "changes.diff");
|
||||
assert.deepEqual(names(diff).sort(), ["f1.txt", "f2.txt", "f3.txt"]);
|
||||
assert.match(diff, /^\\ No more lines shown: this change is too large to show in full\.$/m);
|
||||
assert.match(diff, /^# truncated: true$/m);
|
||||
assert.ok(diff.length < 1500, "the big first file shows no lines of itself");
|
||||
assert.ok(!diff.includes("f1 line"));
|
||||
const bad = run(root, session, "diff", "--cap", "0");
|
||||
assert.equal(bad.code, 2);
|
||||
});
|
||||
|
||||
test("changes: capPatch keeps whole files that fit and cuts the rest to their headers", async () => {
|
||||
const { capPatch } = await import(pathToFileURL(path.join(SKILLS, SKILL, "scripts", "changes.mjs")).href);
|
||||
const small = "diff --git a/s b/s\n--- a/s\n+++ b/s\n@@ -1 +1 @@\n-a\n+b\n";
|
||||
const big = "diff --git a/big b/big\nrename from x\nrename to big\n--- a/x\n+++ b/big\n@@ -1 +1 @@\n" + "+line\n".repeat(500);
|
||||
const patch = small + big;
|
||||
const fit = capPatch(patch, patch.length);
|
||||
assert.deepEqual(fit, { patch, truncated: false });
|
||||
const cut = capPatch(patch, 600);
|
||||
assert.equal(cut.truncated, true);
|
||||
assert.ok(cut.patch.startsWith(small), "the first file stays whole");
|
||||
assert.ok(cut.patch.endsWith("diff --git a/big b/big\nrename from x\nrename to big\n"), "the cut file keeps its name and rename lines");
|
||||
assert.ok(!cut.patch.includes("+line"));
|
||||
assert.ok(cut.patch.includes("No more lines shown"));
|
||||
const first = capPatch(patch, 100);
|
||||
assert.ok(!first.patch.includes("@@"), "a first file over the cap shows no lines");
|
||||
assert.ok(first.patch.includes("diff --git a/s b/s") && first.patch.includes("diff --git a/big b/big"));
|
||||
});
|
||||
|
||||
test("changes: a sensitive file shows its name and counts but no lines", () => {
|
||||
const { root, session } = fixture("changes-secret");
|
||||
run(root, session, "start");
|
||||
write(root, ".env", "API_KEY=hunter2\nOTHER=1\n");
|
||||
write(root, "ok.txt", "fine\n");
|
||||
const d = run(root, session, "diff");
|
||||
assert.equal(d.code, 0, d.stderr);
|
||||
assert.equal(d.json.files, 2);
|
||||
assert.equal(d.json.added, 3, "the hidden file's lines still count");
|
||||
assert.deepEqual(d.json.hidden, [".env"]);
|
||||
const diff = read(session, "changes.diff");
|
||||
assert.ok(!diff.includes("hunter2") && !diff.includes("OTHER=1"));
|
||||
assert.match(diff, /^diff --git a\/\.env b\/\.env$/m);
|
||||
assert.match(diff, /^Lines hidden: this file may hold a secret\.$/m);
|
||||
assert.match(diff, /^# hidden: \.env$/m);
|
||||
assert.match(diff, /^# counts: 2\t0\t\.env$/m, "a hidden file's counts travel in the trailer");
|
||||
assert.match(diff, /^\+fine$/m, "other files keep their lines");
|
||||
});
|
||||
|
||||
test("changes: failures are plain exit 3s, bad arguments exit 2", () => {
|
||||
const { root, session } = fixture("changes-fail");
|
||||
const noStart = run(root, session, "diff");
|
||||
assert.equal(noStart.code, 3);
|
||||
assert.equal(noStart.json.error, "no-start");
|
||||
assert.ok(noStart.json.message && noStart.json.next);
|
||||
|
||||
const notRepo = tmp("changes-norepo");
|
||||
const sess2 = tmp("changes-norepo-session");
|
||||
for (const cmd of ["start", "diff"]) {
|
||||
if (cmd === "diff") write(sess2, "changes-start.json", JSON.stringify({ tree: "a".repeat(40), at: "x" }));
|
||||
const r = run(notRepo, sess2, cmd);
|
||||
assert.equal(r.code, 3, `${cmd}: ${r.stderr}`);
|
||||
assert.equal(r.json.error, "not-a-repo");
|
||||
assert.ok(r.json.next);
|
||||
}
|
||||
|
||||
write(session, "changes-start.json", JSON.stringify({ tree: "b".repeat(40), at: "x" }));
|
||||
const gone = run(root, session, "diff");
|
||||
assert.equal(gone.code, 3);
|
||||
assert.equal(gone.json.error, "start-missing");
|
||||
|
||||
const usage = runScript(SKILL, "changes.mjs", ["start", "--root", root]);
|
||||
assert.equal(usage.code, 2, "--session is required");
|
||||
assert.equal(runScript(SKILL, "changes.mjs", ["nope", "--session", session]).code, 2);
|
||||
});
|
||||
|
||||
test("changes: start twice overwrites the snapshot", () => {
|
||||
const { root, session } = fixture("changes-twice");
|
||||
const a = run(root, session, "start");
|
||||
fs.appendFileSync(path.join(root, "a.txt"), "first run work\n");
|
||||
const b = run(root, session, "start");
|
||||
assert.notEqual(a.json.tree, b.json.tree);
|
||||
assert.equal(JSON.parse(read(session, "changes-start.json")).tree, b.json.tree);
|
||||
fs.appendFileSync(path.join(root, "a.txt"), "second run work\n");
|
||||
const d = run(root, session, "diff");
|
||||
const diff = read(session, "changes.diff");
|
||||
assert.equal(d.json.files, 1);
|
||||
assert.match(diff, /^[+]second run work$/m);
|
||||
assert.ok(!/^[+-]first run work$/m.test(diff), "work before the second start is context at most, never a change");
|
||||
});
|
||||
|
||||
test("changes: hiding holds for a spaced name, a sensitive rename, diff.noprefix and a cap", () => {
|
||||
const { root, session, g } = fixture("changes-secret-hard");
|
||||
write(root, "old.pem", "OLDSECRET1\nOLDSECRET2\nOLDSECRET3\nOLDSECRET4\n");
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "pem");
|
||||
g("config", "diff.noprefix", "true");
|
||||
run(root, session, "start");
|
||||
write(root, "my cert.pem", "SPACEDSECRET\n");
|
||||
fs.renameSync(path.join(root, "old.pem"), path.join(root, "renamed.txt"));
|
||||
write(root, "plain.txt", "visible\n".repeat(800));
|
||||
const d = run(root, session, "diff", "--cap", "3000");
|
||||
assert.equal(d.code, 0, d.stderr);
|
||||
const diff = read(session, "changes.diff");
|
||||
for (const secret of ["SPACEDSECRET", "OLDSECRET"]) assert.ok(!diff.includes(secret), `${secret} must not appear`);
|
||||
assert.ok(d.json.hidden.includes("my cert.pem"), JSON.stringify(d.json.hidden));
|
||||
assert.ok(d.json.hidden.includes("old.pem"), "a rename out of a sensitive name is hidden");
|
||||
assert.equal(d.json.files, 3);
|
||||
assert.equal(d.json.truncated, true, "the visible file is cut by the cap");
|
||||
assert.match(diff, /^# hidden: my cert\.pem$/m);
|
||||
});
|
||||
@@ -57,7 +57,7 @@ function copyManifest(rel, { crlf = false } = {}) {
|
||||
test("deps --help names every command and every exit code", () => {
|
||||
const r = runDeps(["--help"]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
for (const command of ["detect", "scan", "notes", "label", "batches", "backup", "apply", "restore", "handoff", "cleanup"]) {
|
||||
for (const command of ["detect", "scan", "notes", "fit", "pins", "label", "checks", "baseline", "compare", "batches", "backup", "apply", "restore", "handoff", "cleanup"]) {
|
||||
assert.match(r.stdout, new RegExp(`deps\\.mjs ${command}\\b`), command);
|
||||
}
|
||||
for (const exit of ["0 ok", "1 crash", "2 bad arguments", "3 not found", "4 invalid", "5 refused"]) assert.ok(r.stdout.includes(exit), exit);
|
||||
@@ -1084,8 +1084,20 @@ test("scan attaches the test map rows covering a lockfile's members; a Shared ro
|
||||
const { scan } = detectAndScan(root, { npm: npmRules() }, ["--no-audit"]);
|
||||
const byLock = Object.fromEntries(scan.lockfiles.map((l) => [l.lockfile, l.checks]));
|
||||
// The root lockfile resolves the root folder, so every row falls in it.
|
||||
assert.deepEqual(byLock["package-lock.json"], { rows: ["App", "Web", "Build"], commands: ["npm test -w app", "x", "npm test"], discovered: [], full: true });
|
||||
assert.deepEqual(byLock["web/package-lock.json"], { rows: ["Web"], commands: ["x"], discovered: [], full: false });
|
||||
// Each command gets a stable id across the scan: the same command in two lockfiles keeps one id.
|
||||
assert.deepEqual(byLock["package-lock.json"], {
|
||||
rows: ["App", "Web", "Build"],
|
||||
commands: ["npm test -w app", "x", "npm test"],
|
||||
discovered: [],
|
||||
full: true,
|
||||
list: [
|
||||
{ id: "c1", area: "App", run: "npm test -w app", paths: ["packages/app/**"], shared: false },
|
||||
{ id: "c2", area: "Web", run: "x", paths: ["web/**"], shared: false },
|
||||
{ id: "c3", area: "Build", run: "npm test", paths: ["scripts/**"], shared: true },
|
||||
],
|
||||
build: [],
|
||||
});
|
||||
assert.deepEqual(byLock["web/package-lock.json"], { rows: ["Web"], commands: ["x"], discovered: [], full: false, list: [{ id: "c2", area: "Web", run: "x", paths: ["web/**"], shared: false }], build: [] });
|
||||
assert.equal(scan.noChecks, false);
|
||||
});
|
||||
|
||||
@@ -2444,7 +2456,7 @@ test("handoff writes one brief per package in the 4.5 format, every section pres
|
||||
"",
|
||||
"## Why it was held back",
|
||||
"",
|
||||
"- **chalk**: Warning (major, range ^4.1.0 → ^5.3.0, breaking notes, calls a changed API, used in 2 files)",
|
||||
"- **chalk**: Warning (a big change, the allowed range widens from ^4.1.0 to ^5.3.0, the notes say something was removed or changed, your code uses something that changed, 2 files use it)",
|
||||
"",
|
||||
"## What the notes say changed",
|
||||
"",
|
||||
@@ -2484,8 +2496,8 @@ test("handoff: a pair shares one brief listing both packages; a scoped name gets
|
||||
assert.match(pair, /^# Upgrade react 18\.3\.1 to 19\.0\.0 and react-dom 18\.3\.1 to 19\.0\.0\n/);
|
||||
for (const section of ["Why it was held back", "What the notes say changed", "Where the code calls it", "Checks that cover it", "How to apply"]) assert.match(pair, new RegExp(`^## ${section}$`, "m"), section);
|
||||
assert.match(pair, /^\*\*Status:\*\* Ready$/m);
|
||||
assert.match(pair, /- \*\*react\*\*: Warning \(major, .*used in 9 files/, "a major with unreadable notes in 9 files");
|
||||
assert.match(pair, /- \*\*react-dom\*\*: Check first \(major/);
|
||||
assert.match(pair, /- \*\*react\*\*: Warning \(a big change, .*9 files use it/, "a big change with unreadable notes in 9 files");
|
||||
assert.match(pair, /- \*\*react-dom\*\*: Check first \(a big change/);
|
||||
assert.match(pair, /### react\n\nThe notes could not be read\./);
|
||||
assert.match(pair, /### react-dom\n\nThe notes were not read\./);
|
||||
assert.match(pair, /npm update react react-dom --package-lock-only/, "one command moves both");
|
||||
@@ -2535,6 +2547,485 @@ test("handoff refuses an id not in labels.json (exit 3) and writes nothing; upgr
|
||||
assert.equal(deps.upgradeFolder(".."), "package-upgrade");
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------ pins */
|
||||
|
||||
const PINS = fx("pins", "project");
|
||||
|
||||
/** The pins fixture project copied into a temp folder, with extra files on top. */
|
||||
function pinsProject(extra = {}) {
|
||||
const dir = tmp("deps-pins");
|
||||
fs.cpSync(PINS, dir, { recursive: true });
|
||||
for (const [rel, content] of Object.entries(extra)) write(dir, rel, content);
|
||||
return dir;
|
||||
}
|
||||
|
||||
const PW = { id: "package-lock.json#playwright-core", package: "playwright-core", current: "1.64.1", target: "1.66.0" };
|
||||
|
||||
test("findPins finds a whole-token exact version beside the package name, never a stray number", () => {
|
||||
const root = pinsProject();
|
||||
const pins = deps.findPins(root, [PW], { skip: ["package.json", "package-lock.json"] });
|
||||
assert.deepEqual(pins, [{ id: PW.id, file: "scripts/test-browser-helper.mjs", line: 4, text: 'export const BROWSER = "playwright-core@1.64.1";' }], "the 11.64.10 and 1.64.12 line is no pin");
|
||||
});
|
||||
|
||||
test("findPins skips lockfiles, files a lockfile entry owns, binary files and files over 1 MB", () => {
|
||||
const big = `playwright-core 1.64.1\n${"x".repeat(deps.PIN_FILE_CAP)}`;
|
||||
const root = pinsProject({ "web/package-lock.json": '{"playwright-core": "1.64.1"}\n', "notes/big.txt": big, "docs/readme.md": "Uses playwright-core 1.64.1 today.\n" });
|
||||
fs.writeFileSync(path.join(root, "assets.bin"), Buffer.concat([Buffer.from("playwright-core 1.64.1\n"), Buffer.from([0, 1, 2])]));
|
||||
const files = deps.findPins(root, [PW], { skip: ["package.json", "package-lock.json"] }).map((p) => p.file);
|
||||
assert.deepEqual(files.sort(), ["docs/readme.md", "scripts/test-browser-helper.mjs"]);
|
||||
const owned = deps.findPins(root, [PW], { skip: ["package-lock.json"] }).map((p) => p.file);
|
||||
assert.ok(owned.includes("package.json"), "a manifest not on the skip list is searched");
|
||||
assert.deepEqual(deps.findPins(root, [PW], { files: ["docs/readme.md"] }).map((p) => p.file), ["docs/readme.md"], "files limits the search");
|
||||
assert.deepEqual(deps.findPins(root, []), [], "no rows, no search");
|
||||
});
|
||||
|
||||
test("label: a pin outside the row's own files moves a Safe row to Check first, naming the file", () => {
|
||||
const before = labeled();
|
||||
assert.equal(before.r1.label, "safe");
|
||||
const pins = { pins: [{ id: "r1", file: "scripts/test-browser-helper.mjs", line: 4, text: "x" }, { id: "r1", file: "package-lock.json", line: 9, text: "x" }] };
|
||||
const after = Object.fromEntries(deps.label(SCAN, RECORDS, pins).map((l) => [l.id, l]));
|
||||
assert.equal(after.r1.label, "check-first");
|
||||
assert.ok(after.r1.reasons.includes("exact version used in scripts/test-browser-helper.mjs"), after.r1.reasons.join("; "));
|
||||
assert.match(after.r1.reasonsPlain.join(" "), /scripts\/test-browser-helper\.mjs names this exact version \(1\.2\.3\)/);
|
||||
const own = Object.fromEntries(deps.label(SCAN, RECORDS, [{ id: "r1", file: "package-lock.json" }]).map((l) => [l.id, l]));
|
||||
assert.equal(own.r1.label, "safe", "a pin in its own lockfile moves with the update");
|
||||
assert.deepEqual(deps.label(SCAN, RECORDS, null), deps.label(SCAN, RECORDS), "no pins.json changes nothing");
|
||||
const warning = Object.fromEntries(deps.label(SCAN, RECORDS, [{ id: "r5", file: "a.js" }]).map((l) => [l.id, l]));
|
||||
assert.equal(warning.r5.label, "warning", "the Warning rules stay as they are");
|
||||
});
|
||||
|
||||
test("pins --run writes pins.json, label reads it, and the row with a pin in a test file leaves Safe", () => {
|
||||
const root = pinsProject();
|
||||
const lock = { lockfile: "package-lock.json", manifest: "package.json", adapter: "npm", ecosystem: "npm", manager: "npm", members: ["."], checks: { rows: ["Root"], discovered: [] }, rows: [{ ...PW, jump: "minor", inRange: false, range: { from: "1.64.1", to: "1.66.0" }, pinned: true, security: null, declaredIn: [{ file: "package.json", range: "1.64.1" }] }] };
|
||||
const dir = runFolder({ "scan.json": { root, noChecks: false, lockfiles: [lock] } });
|
||||
const r = runDeps(["pins", "--run", dir]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.equal(r.json.count, 1);
|
||||
assert.deepEqual(r.json.pins.map((p) => [p.file, p.line]), [["scripts/test-browser-helper.mjs", 4]]);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, "pins.json"), "utf8")), { pins: r.json.pins });
|
||||
const records = path.join(dir, "records-in.json");
|
||||
fs.writeFileSync(records, JSON.stringify([{ id: PW.id, notes: "read", breaking: [], usedIn: ["scripts/test-browser-helper.mjs"] }]));
|
||||
const unpinned = deps.label({ noChecks: false, lockfiles: [lock] }, JSON.parse(fs.readFileSync(records, "utf8")));
|
||||
assert.equal(unpinned[0].label, "safe", "without the pin the row is Safe");
|
||||
const l = runDeps(["label", "--run", dir, "--records", records]);
|
||||
assert.equal(l.code, 0, l.stderr);
|
||||
assert.equal(l.json.labels[0].label, "check-first");
|
||||
assert.ok(l.json.labels[0].reasons.includes("exact version used in scripts/test-browser-helper.mjs"));
|
||||
});
|
||||
|
||||
test("pins: a run folder that is not there and a run with no scan.json exit 3", () => {
|
||||
const gone = runDeps(["pins", "--run", path.join(os.tmpdir(), "plan2code-deps-19990101-deadbeef")]);
|
||||
assert.equal(gone.code, 3);
|
||||
assert.equal(gone.json.error, "run-missing");
|
||||
const empty = runDeps(["pins", "--run", runFolder()]);
|
||||
assert.equal(empty.code, 3);
|
||||
assert.equal(empty.json.next, "Run scan first.");
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------ checks: failing tests */
|
||||
|
||||
const LOGS = fx("logs");
|
||||
const logText = (name) => fs.readFileSync(path.join(LOGS, name), "utf8");
|
||||
|
||||
test("failedTests reads each runner's failing tests; TODO and SKIP lines are no failures", () => {
|
||||
const cases = {
|
||||
"tap.txt": ["parses dates"],
|
||||
"node-spec.txt": ["parses dates"],
|
||||
"jest.txt": ["divides by zero"],
|
||||
"vitest.txt": ["src/b.test.ts > math > divides by zero"],
|
||||
"pytest.txt": ["tests/test_b.py::test_divides"],
|
||||
"cargo.txt": ["math::divides"],
|
||||
"go.txt": ["TestDivides"],
|
||||
"dotnet.txt": ["MyApp.Tests.Divides"],
|
||||
};
|
||||
for (const [file, names] of Object.entries(cases)) assert.deepEqual(deps.failedTests(logText(file)), { names, known: true }, file);
|
||||
assert.deepEqual(deps.failedTests(logText("unknown.txt")), { names: [], known: false }, "an unknown format falls back to the command");
|
||||
assert.deepEqual(deps.failedTests("ok 1 - adds\nok 2 - parses\n"), { names: [], known: true }, "a known format with nothing failing");
|
||||
assert.deepEqual(deps.failedTests("\x1b[31m--- FAIL: TestColor (0.00s)\x1b[0m\n"), { names: ["TestColor"], known: true }, "color codes are dropped");
|
||||
});
|
||||
|
||||
test("baseline without --outcome reads a bare FAIL line as a failure, and a TODO line as none", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "deps-bare-"));
|
||||
const jestDefault = path.join(dir, "jest-default.txt");
|
||||
fs.writeFileSync(jestDefault, "PASS src/a.test.js\nFAIL src/b.test.js\n");
|
||||
const todo = path.join(dir, "todo.txt");
|
||||
fs.writeFileSync(todo, "ok 1 - adds\nnot ok 2 - later # TODO\n");
|
||||
assert.deepEqual(deps.readCheckLog(jestDefault), { names: [], known: false, outcome: "failed" });
|
||||
assert.equal(deps.readCheckLog(todo).outcome, "passed");
|
||||
});
|
||||
|
||||
test("judgeCheck and compareCheck: red before, flaky and new failures by name; a whole command when the log is unknown", () => {
|
||||
const log = (names, outcome = names.length ? "failed" : "passed", known = true) => ({ names, known, outcome });
|
||||
const base = (first, retry) => {
|
||||
const j = deps.judgeCheck(first, retry);
|
||||
return { failing: j.names, flaky: j.flaky, known: j.known, commandFailed: j.commandFailed, ...(j.timeout ? { timeout: true } : {}) };
|
||||
};
|
||||
const red = base(log(["a"]), log(["a"]));
|
||||
assert.deepEqual(red.failing, ["a"]);
|
||||
const wobbly = base(log(["b"]), log([]));
|
||||
assert.deepEqual([wobbly.failing, wobbly.flaky], [[], ["b"]]);
|
||||
assert.deepEqual(deps.compareCheck(red, deps.judgeCheck(log(["a"]), log(["a"]))), { newFailures: [], stillFailing: ["a"], flaky: [], blame: false, known: true });
|
||||
assert.equal(deps.compareCheck(wobbly, deps.judgeCheck(log(["b"]), log(["b"]))).blame, false, "flaky before never blames");
|
||||
const broke = deps.compareCheck(red, deps.judgeCheck(log(["a", "c"]), log(["a", "c"])));
|
||||
assert.deepEqual([broke.newFailures, broke.blame], [["c"], true]);
|
||||
assert.equal(deps.compareCheck(red, deps.judgeCheck(log(["c"]), log([]))).blame, false, "a test that fails once and passes on the retry is flaky now");
|
||||
const unknownPass = base(log([], "passed", false));
|
||||
assert.equal(deps.compareCheck(unknownPass, deps.judgeCheck(log([], "failed", false))).blame, true, "a command that passed before and fails now");
|
||||
const unknownFail = base(log([], "failed", false));
|
||||
assert.equal(deps.compareCheck(unknownFail, deps.judgeCheck(log([], "failed", false))).blame, false, "a command already failing as a whole");
|
||||
assert.equal(deps.compareCheck(red, deps.judgeCheck(log([], "failed", false))).blame, true, "a run that names no test now, after named failures before, is blamed");
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------ checks: commands */
|
||||
|
||||
const CHECKS_LOCK = "package-lock.json";
|
||||
const TOOLS_LOCK = "tools/package-lock.json";
|
||||
/** A run folder: the root version list with test map rows (one Shared) and a build check, and tools/ with only a confirmed command. */
|
||||
function checksRun({ records = null, pins = null, list = null } = {}) {
|
||||
const lock = {
|
||||
lockfile: CHECKS_LOCK,
|
||||
manifest: "package.json",
|
||||
adapter: "npm",
|
||||
ecosystem: "npm",
|
||||
manager: "npm",
|
||||
members: ["."],
|
||||
install: "npm ci",
|
||||
checks: {
|
||||
rows: ["App", "Web", "Everything"],
|
||||
commands: ["npm test -w app", "npm test -w web", "npm test"],
|
||||
discovered: [],
|
||||
full: true,
|
||||
list: list || [
|
||||
{ id: "c1", area: "App", run: "npm test -w app", paths: ["packages/app/**"], shared: false },
|
||||
{ id: "c2", area: "Web", run: "npm test -w web", paths: ["web/**"], shared: false },
|
||||
{ id: "c3", area: "Everything", run: "npm test", paths: ["scripts/**"], shared: true },
|
||||
],
|
||||
build: [{ command: "npm run build", cwd: "." }],
|
||||
},
|
||||
rows: ["a", "b", "c", "d"].map((p) => ({ id: `${CHECKS_LOCK}#${p}`, package: p, current: "1.0.0", target: "1.0.1" })),
|
||||
held: [],
|
||||
};
|
||||
const tools = {
|
||||
lockfile: TOOLS_LOCK,
|
||||
manifest: "tools/package.json",
|
||||
adapter: "npm",
|
||||
ecosystem: "npm",
|
||||
manager: "npm",
|
||||
members: ["tools"],
|
||||
install: "npm ci",
|
||||
checks: { rows: [], commands: [], discovered: [{ command: "npm run lint", cwd: "tools" }], full: false, list: [], build: [] },
|
||||
rows: [{ id: `${TOOLS_LOCK}#e`, package: "e", current: "1.0.0", target: "1.0.1" }],
|
||||
held: [],
|
||||
};
|
||||
const batches = [...["a", "b", "c", "d"].map((p, i) => ({ id: `b${i + 1}`, lockfile: CHECKS_LOCK, picks: [`${CHECKS_LOCK}#${p}`] })), { id: "b5", lockfile: TOOLS_LOCK, picks: [`${TOOLS_LOCK}#e`] }];
|
||||
const files = {
|
||||
"scan.json": { root: tmp("deps-checks"), noChecks: false, lockfiles: [lock, tools] },
|
||||
"batches.json": { batches },
|
||||
};
|
||||
if (records) files["records.json"] = records;
|
||||
if (pins) files["pins.json"] = pins;
|
||||
return runFolder(files);
|
||||
}
|
||||
|
||||
test("checks lists every check with an id for the baseline, the Shared rows too; full is the full suite", () => {
|
||||
const r = runDeps(["checks", "--run", checksRun()]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.deepEqual(
|
||||
r.json.checks.map((c) => [c.id, c.command, c.cwd, c.kind, c.lockfile, Boolean(c.shared)]),
|
||||
[
|
||||
["install", "npm ci", ".", "install", CHECKS_LOCK, false],
|
||||
["c1", "npm test -w app", ".", "map", CHECKS_LOCK, false],
|
||||
["c2", "npm test -w web", ".", "map", CHECKS_LOCK, false],
|
||||
["c3", "npm test", ".", "map", CHECKS_LOCK, true],
|
||||
["d1", "npm run build", ".", "build", CHECKS_LOCK, false],
|
||||
["install-2", "npm ci", "tools", "install", TOOLS_LOCK, false],
|
||||
["d2", "npm run lint", "tools", "discovered", TOOLS_LOCK, false],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(r.json.full, [{ id: "c3", command: "npm test", cwd: ".", area: "Everything" }]);
|
||||
});
|
||||
|
||||
test("checks --batch narrows by usedIn and pins and adds the build; a Shared row runs only when it alone covers a file", () => {
|
||||
const dir = checksRun({
|
||||
records: [
|
||||
{ id: `${CHECKS_LOCK}#a`, usedIn: ["packages/app/src/x.js"] },
|
||||
{ id: `${CHECKS_LOCK}#c`, usedIn: ["tools2/y.js"] },
|
||||
{ id: `${CHECKS_LOCK}#d`, usedIn: ["scripts\\helper.mjs", "packages/app/z.js"] },
|
||||
],
|
||||
pins: { pins: [{ id: `${CHECKS_LOCK}#b`, file: "web/test/pin.test.js", line: 3, text: "b 1.0.0" }] },
|
||||
});
|
||||
const a = runDeps(["checks", "--run", dir, "--batch", "b1"]);
|
||||
assert.equal(a.code, 0, a.stderr);
|
||||
assert.equal(a.json.narrowed, true);
|
||||
assert.deepEqual(a.json.commands.map((c) => c.id), ["c1", "d1"], "the App row and the build");
|
||||
assert.deepEqual(a.json.install, { id: "install", command: "npm ci", cwd: "." });
|
||||
assert.deepEqual(a.json.full.map((c) => c.id), ["c3"], "the Shared row is left for the end");
|
||||
assert.equal(a.json.message, null);
|
||||
const b = runDeps(["checks", "--run", dir, "--batch", "b2"]);
|
||||
assert.deepEqual(b.json.commands.map((c) => c.id), ["c2", "d1"], "narrowed by the pin's file");
|
||||
const d = runDeps(["checks", "--run", dir, "--batch", "b4"]);
|
||||
assert.deepEqual(d.json.commands.map((c) => c.id), ["c1", "c3", "d1"], "scripts/helper.mjs is covered only by the Shared row");
|
||||
assert.deepEqual(d.json.full, [], "it ran in the group, so nothing is left for the end");
|
||||
const c = runDeps(["checks", "--run", dir, "--batch", "b3"]);
|
||||
assert.equal(c.json.narrowed, false);
|
||||
assert.deepEqual(c.json.commands.map((x) => x.id), ["c1", "c2", "d1"]);
|
||||
assert.match(c.json.message, /No test map row covers/);
|
||||
const none = runDeps(["checks", "--run", checksRun(), "--batch", "b1"]);
|
||||
assert.equal(none.json.narrowed, false);
|
||||
assert.match(none.json.message, /Nothing says which files/);
|
||||
assert.ok(!none.json.commands.some((x) => x.id === "c3"), "with other tests, not narrowed still leaves the Shared row out");
|
||||
const tools = runDeps(["checks", "--run", dir, "--batch", "b5"]);
|
||||
assert.deepEqual([tools.json.commands.map((x) => x.id), tools.json.install.id], [["d2"], "install-2"], "a folder with only a confirmed command runs it");
|
||||
assert.equal(runDeps(["checks", "--run", dir, "--batch", "b9"]).code, 3, "an unknown batch");
|
||||
});
|
||||
|
||||
test("checks --batch: a pin file no narrower row covers runs the full suite in the group, narrowed or not", () => {
|
||||
const dir = checksRun({
|
||||
records: [{ id: `${CHECKS_LOCK}#a`, usedIn: ["packages/app/src/x.js"] }],
|
||||
pins: {
|
||||
pins: [
|
||||
{ id: `${CHECKS_LOCK}#a`, file: "tests/browser.test.mjs", line: 4, text: "a 1.0.0" },
|
||||
{ id: `${CHECKS_LOCK}#c`, file: "tests/other.test.mjs", line: 2, text: "c 1.0.0" },
|
||||
{ id: `${CHECKS_LOCK}#b`, file: "web/pin.test.js", line: 3, text: "b 1.0.0" },
|
||||
],
|
||||
},
|
||||
});
|
||||
const narrowed = runDeps(["checks", "--run", dir, "--batch", "b1"]);
|
||||
assert.equal(narrowed.code, 0, narrowed.stderr);
|
||||
assert.equal(narrowed.json.narrowed, true);
|
||||
assert.deepEqual(narrowed.json.commands.map((c) => c.id), ["c1", "c3", "d1"], "the App row, then the full suite for the uncovered pin");
|
||||
assert.deepEqual(narrowed.json.full, []);
|
||||
assert.match(narrowed.json.message, /covers tests\/browser\.test\.mjs, which names the exact version, so the full suite runs/);
|
||||
const wide = runDeps(["checks", "--run", dir, "--batch", "b3"]);
|
||||
assert.equal(wide.json.narrowed, false);
|
||||
assert.deepEqual(wide.json.commands.map((c) => c.id), ["c1", "c2", "c3", "d1"], "every row, plus the full suite for the pin");
|
||||
assert.match(wide.json.message, /tests\/other\.test\.mjs/);
|
||||
const covered = runDeps(["checks", "--run", dir, "--batch", "b2"]);
|
||||
assert.deepEqual(covered.json.commands.map((c) => c.id), ["c2", "d1"], "a pin a narrower row covers changes nothing");
|
||||
assert.equal(covered.json.message, null);
|
||||
});
|
||||
|
||||
test("checks --batch: a folder whose only test is a Shared row runs it, so a group never runs without a test", () => {
|
||||
const dir = checksRun({ list: [{ id: "c1", area: "Everything", run: "npm test", paths: ["scripts/**"], shared: true }] });
|
||||
const r = runDeps(["checks", "--run", dir, "--batch", "b1"]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.equal(r.json.narrowed, false);
|
||||
assert.deepEqual(r.json.commands.map((c) => c.id), ["c1", "d1"]);
|
||||
assert.match(r.json.message, /full suite is the only test/);
|
||||
assert.deepEqual(r.json.full, []);
|
||||
});
|
||||
|
||||
test("scan saves the build checks test-commands.mjs finds in each version list's folder", () => {
|
||||
const root = project({ "package.json": { name: "fixture-root", private: true, engines: { node: ">=12" }, workspaces: ["packages/*"], scripts: { build: "tsup", test: "node --test" }, dependencies: { chalk: "^4.1.0", "left-pad": "1.1.0", semver: "^7.5.0", mkdirp: "^0.5.5" }, overrides: { ms: "2.1.2" } } });
|
||||
const { scan } = detectAndScan(root, { npm: npmRules() }, ["--no-audit"]);
|
||||
assert.deepEqual(scan.lockfiles[0].checks.build, [{ command: "npm run build", cwd: "." }]);
|
||||
assert.deepEqual(deps.checkList(scan)[0].discovered, [{ id: "d1", command: "npm run build", cwd: ".", kind: "build" }]);
|
||||
assert.equal(deps.label(scan, []).length > 0, true);
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------ checks: baseline and compare */
|
||||
|
||||
function logFile(text) {
|
||||
const dir = tmp("deps-log");
|
||||
return write(dir, "check.log", text);
|
||||
}
|
||||
const TAP = (fails) => ["TAP version 13", "ok 1 - adds numbers", ...fails.map((n, i) => `not ok ${i + 2} - ${n}`), ""].join("\n");
|
||||
|
||||
test("baseline records red-before and flaky tests; compare blames only tests that passed before", () => {
|
||||
const dir = checksRun();
|
||||
const b = runDeps(["baseline", "--run", dir, "--check", "c1", "--log", logFile(TAP(["parses dates", "reads the clock"])), "--outcome", "failed", "--retry-log", logFile(TAP(["parses dates"])), "--retry-outcome", "failed"]);
|
||||
assert.equal(b.code, 0, b.stderr);
|
||||
assert.deepEqual([b.json.failing, b.json.flaky, b.json.known, b.json.commandFailed], [["parses dates"], ["reads the clock"], true, false]);
|
||||
const saved = JSON.parse(fs.readFileSync(path.join(dir, "baseline.json"), "utf8"));
|
||||
assert.deepEqual(saved.checks.c1.failing, ["parses dates"]);
|
||||
|
||||
const same = runDeps(["compare", "--run", dir, "--batch", "b1", "--check", "c1", "--log", logFile(TAP(["parses dates", "reads the clock"])), "--retry-log", logFile(TAP(["parses dates", "reads the clock"]))]);
|
||||
assert.equal(same.code, 0, same.stderr);
|
||||
assert.deepEqual([same.json.newFailures, same.json.stillFailing, same.json.flaky, same.json.blame], [[], ["parses dates"], ["reads the clock"], false], "red before and flaky never blame");
|
||||
|
||||
const broke = runDeps(["compare", "--run", dir, "--batch", "b1", "--check", "c1", "--log", logFile(TAP(["adds more", "parses dates"])), "--outcome", "failed"]);
|
||||
assert.deepEqual([broke.json.newFailures, broke.json.blame], [["adds more"], true], "a test that passed before");
|
||||
const record = JSON.parse(fs.readFileSync(path.join(dir, "compare.json"), "utf8"));
|
||||
assert.equal(record.batches.b1.c1.blame, true);
|
||||
});
|
||||
|
||||
test("baseline and compare judge a log in an unknown format, and a timeout, by the whole command", () => {
|
||||
const dir = checksRun();
|
||||
const unknown = logFile(logText("unknown.txt"));
|
||||
const pass = runDeps(["baseline", "--run", dir, "--check", "install", "--log", unknown, "--outcome", "passed"]);
|
||||
assert.equal(pass.code, 0, pass.stderr);
|
||||
assert.deepEqual([pass.json.known, pass.json.commandFailed], [false, false]);
|
||||
const now = runDeps(["compare", "--run", dir, "--batch", "b1", "--check", "install", "--log", unknown, "--outcome", "failed"]);
|
||||
assert.deepEqual([now.json.known, now.json.blame], [false, true], "passed before, fails now");
|
||||
|
||||
const red = runDeps(["baseline", "--run", dir, "--check", "d1", "--log", unknown, "--outcome", "failed"]);
|
||||
assert.deepEqual([red.json.known, red.json.commandFailed], [false, true]);
|
||||
assert.equal(runDeps(["compare", "--run", dir, "--batch", "b1", "--check", "d1", "--log", unknown, "--outcome", "failed"]).json.blame, false, "already failing as a whole");
|
||||
|
||||
const slow = runDeps(["baseline", "--run", dir, "--check", "c2", "--log", logFile(TAP([])), "--outcome", "timeout"]);
|
||||
assert.deepEqual([slow.json.commandFailed, slow.json.timeout, slow.json.known], [true, true, false]);
|
||||
});
|
||||
|
||||
test("baseline and compare: usage, a missing log, an unknown check and a check with no baseline", () => {
|
||||
const dir = checksRun();
|
||||
const log = logFile(TAP([]));
|
||||
assert.equal(runDeps(["baseline", "--run", dir, "--log", log]).json.error, "missing-check");
|
||||
assert.equal(runDeps(["baseline", "--run", dir, "--check", "c1"]).json.error, "missing-log");
|
||||
const unknownCheck = runDeps(["baseline", "--run", dir, "--check", "c9", "--log", log]);
|
||||
assert.equal(unknownCheck.code, 3);
|
||||
assert.equal(unknownCheck.json.error, "unknown-check");
|
||||
const missing = runDeps(["baseline", "--run", dir, "--check", "c1", "--log", path.join(tmp("deps-log"), "nope.log")]);
|
||||
assert.equal(missing.code, 3);
|
||||
assert.equal(missing.json.error, "log-missing");
|
||||
const unread = runDeps(["baseline", "--run", dir, "--check", "c1", "--log", logFile(logText("unknown.txt"))]);
|
||||
assert.equal(unread.code, 2, "an unknown format needs run-check's outcome");
|
||||
assert.equal(unread.json.error, "missing-outcome");
|
||||
assert.equal(runDeps(["baseline", "--run", dir, "--check", "c1", "--log", log, "--outcome", "maybe"]).json.error, "bad-outcome");
|
||||
const noBase = runDeps(["compare", "--run", dir, "--batch", "b1", "--check", "c2", "--log", log]);
|
||||
assert.equal(noBase.code, 3);
|
||||
assert.equal(noBase.json.next, "Run baseline for this check first.");
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------ runtime fit */
|
||||
|
||||
test("bestFit: the newest version that fits, none, and never one older than the current", () => {
|
||||
const versions = [
|
||||
{ version: "4.1.2", engines: ">=10" },
|
||||
{ version: "5.0.0", engines: ">=16" },
|
||||
{ version: "6.0.1", engines: ">=22" },
|
||||
];
|
||||
const fits = (floor) => (v) => !v.engines || Number(v.engines.replace(">=", "")) <= floor;
|
||||
assert.deepEqual(deps.bestFit({ current: "4.1.0", versions, fits: fits(18) }), { best: "5.0.0", needs: ">=22" });
|
||||
assert.deepEqual(deps.bestFit({ current: "4.1.0", versions, fits: fits(8) }), { best: null, needs: ">=22" });
|
||||
assert.deepEqual(deps.bestFit({ current: "4.1.0", latest: "5.0.0", versions, fits: fits(18) }), { best: "5.0.0", needs: null }, "latest caps the list");
|
||||
assert.deepEqual(deps.bestFit({ current: "5.0.0", versions: [{ version: "4.1.2", engines: ">=10" }, { version: "6.0.1", engines: ">=22" }], fits: fits(18) }), { best: null, needs: ">=22" }, "an older version that fits is never offered");
|
||||
});
|
||||
|
||||
/** A run folder whose scan holds chalk held for the runtime, ms held by an override, and a Cargo crate held for Rust. */
|
||||
function fitRun(root) {
|
||||
const npmLock = {
|
||||
lockfile: "package-lock.json",
|
||||
manifest: "package.json",
|
||||
adapter: "npm",
|
||||
ecosystem: "npm",
|
||||
manager: "npm",
|
||||
members: [".", "packages/app"],
|
||||
runtime: { declared: JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).engines.node, source: "engines", machine: "24.0.0" },
|
||||
checks: { rows: ["Root"], discovered: [] },
|
||||
rows: [],
|
||||
held: [
|
||||
{ id: "package-lock.json#chalk", package: "chalk", current: "4.1.0", latest: "6.0.1", reason: "every newer version needs Node >=22 (the project declares >=12)", file: null, security: null },
|
||||
{ id: "package-lock.json#ms", package: "ms", current: "2.1.2", latest: "2.1.3", reason: "held by overrides in package.json", file: "package.json", security: null },
|
||||
],
|
||||
};
|
||||
const cargoLock = {
|
||||
lockfile: "app/Cargo.lock",
|
||||
manifest: "app/Cargo.toml",
|
||||
adapter: "cargo",
|
||||
ecosystem: "cargo",
|
||||
manager: "cargo",
|
||||
members: ["app"],
|
||||
runtime: { declared: "1.70", source: "rust-version", machine: "1.99.1" },
|
||||
checks: { rows: [], discovered: [] },
|
||||
rows: [],
|
||||
held: [{ id: "app/Cargo.lock#serde", package: "serde", current: "1.0.100", latest: "1.0.200", reason: "every newer version needs Rust 1.80 (the project declares 1.70)", file: null, security: null }],
|
||||
};
|
||||
return runFolder({ "scan.json": { root, noChecks: false, lockfiles: [npmLock, cargoLock] } });
|
||||
}
|
||||
|
||||
test("fit turns a runtime hold with a fitting version into an ordinary row that can be Safe; an override stays held; no adapter means unknown", () => {
|
||||
const root = project();
|
||||
const dir = fitRun(root);
|
||||
const r = runStubbed(["fit", "--run", dir], stubPath({ npm: npmRules() }));
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
const chalk = r.json.rows.find((x) => x.package === "chalk");
|
||||
assert.deepEqual(chalk, { id: "package-lock.json#chalk", package: "chalk", current: "4.1.0", best: "4.1.2", needs: ">=22", source: "registry" });
|
||||
assert.deepEqual(r.json.unknown, ["app/Cargo.lock#serde"]);
|
||||
assert.ok(!r.json.rows.some((x) => x.package === "ms"), "an override hold is not a runtime hold");
|
||||
const scan = JSON.parse(fs.readFileSync(path.join(dir, "scan.json"), "utf8"));
|
||||
const [npmLock, cargoLock] = scan.lockfiles;
|
||||
assert.deepEqual(npmLock.held.map((h) => h.package), ["ms"]);
|
||||
const row = npmLock.rows.find((x) => x.package === "chalk");
|
||||
assert.equal(row.target, "4.1.2");
|
||||
assert.equal(row.inRange, true);
|
||||
assert.deepEqual(row.fit, { runtime: "Node", declared: ">=12", needs: ">=22", latest: "6.0.1" });
|
||||
const [l] = deps.label(scan, [{ id: row.id, notes: "read", breaking: [] }]);
|
||||
assert.equal(l.label, "safe", "labeled by the same rules");
|
||||
assert.match(l.reasonsPlain.join(" "), /newest version that runs on Node >=12; the latest needs Node >=22/);
|
||||
assert.equal(cargoLock.held[0].reason, "needs Rust 1.80 (you declare 1.70)");
|
||||
assert.equal(cargoLock.held[0].raise, "change `rust-version` in `app/Cargo.toml`");
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, "fit.json"), "utf8")).unknown, ["app/Cargo.lock#serde"]);
|
||||
});
|
||||
|
||||
test("fit: with no version that runs on the declared Node the row stays held, saying what it needs and how to raise it", () => {
|
||||
const root = project();
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
|
||||
pkg.engines.node = ">=8";
|
||||
fs.writeFileSync(path.join(root, "package.json"), JSON.stringify(pkg, null, 2) + "\n");
|
||||
const dir = fitRun(root);
|
||||
const r = runStubbed(["fit", "--run", dir], stubPath({ npm: npmRules() }));
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.deepEqual(r.json.rows.find((x) => x.package === "chalk"), { id: "package-lock.json#chalk", package: "chalk", current: "4.1.0", best: null, needs: ">=22", source: "registry" });
|
||||
assert.ok(!r.json.unknown.includes("package-lock.json#chalk"), "the registry answered: none fits");
|
||||
const held = JSON.parse(fs.readFileSync(path.join(dir, "scan.json"), "utf8")).lockfiles[0].held.find((h) => h.package === "chalk");
|
||||
assert.equal(held.reason, "needs Node >=22 (you declare >=8)");
|
||||
assert.equal(held.raise, "change `engines.node` in `package.json`");
|
||||
});
|
||||
|
||||
test("fit: a row the scan already cut keeps its target and learns what the latest needs; a run with no scan exits 3", () => {
|
||||
const { scan, run, bin } = detectAndScan(project(), { npm: npmRules() }, ["--no-audit"]);
|
||||
assert.ok(scan.lockfiles[0].rows.find((x) => x.package === "chalk").newerNotFitting);
|
||||
const r = runStubbed(["fit", "--run", run], bin);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.deepEqual(r.json.rows.find((x) => x.package === "chalk"), { id: "package-lock.json#chalk", package: "chalk", current: "4.1.0", best: "4.1.2", needs: ">=22", source: "registry" });
|
||||
const row = JSON.parse(fs.readFileSync(path.join(run, "scan.json"), "utf8")).lockfiles[0].rows.find((x) => x.package === "chalk");
|
||||
assert.equal(row.target, "4.1.2");
|
||||
assert.equal(row.fit.needs, ">=22");
|
||||
const empty = runDeps(["fit", "--run", runFolder()]);
|
||||
assert.equal(empty.code, 3);
|
||||
assert.equal(empty.json.next, "Run scan first.");
|
||||
});
|
||||
|
||||
test("fit --id --best makes the version worked out with the person a pick; a hold that is not the runtime's and a version not newer are refused", () => {
|
||||
const root = project();
|
||||
const dir = fitRun(root);
|
||||
const first = runStubbed(["fit", "--run", dir], stubPath({ npm: npmRules() }));
|
||||
assert.deepEqual(first.json.unknown, ["app/Cargo.lock#serde"]);
|
||||
const r = runDeps(["fit", "--run", dir, "--id", "app/Cargo.lock#serde", "--best", "1.0.150"]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.deepEqual(r.json.rows, [{ id: "app/Cargo.lock#serde", package: "serde", current: "1.0.100", best: "1.0.150", needs: "1.80", source: "agent" }]);
|
||||
const scan = JSON.parse(fs.readFileSync(path.join(dir, "scan.json"), "utf8"));
|
||||
const cargo = scan.lockfiles[1];
|
||||
assert.deepEqual(cargo.held, []);
|
||||
assert.equal(cargo.rows[0].target, "1.0.150");
|
||||
assert.deepEqual(cargo.rows[0].fit, { runtime: "Rust", declared: "1.70", needs: "1.80", latest: "1.0.200" });
|
||||
const fit = JSON.parse(fs.readFileSync(path.join(dir, "fit.json"), "utf8"));
|
||||
assert.deepEqual(fit.unknown, []);
|
||||
assert.equal(fit.rows.find((x) => x.id === "app/Cargo.lock#serde").source, "agent");
|
||||
const override = runDeps(["fit", "--run", dir, "--id", "package-lock.json#ms", "--best", "2.1.3"]);
|
||||
assert.equal(override.code, 5);
|
||||
assert.equal(override.json.error, "not-a-runtime-hold");
|
||||
const again = fitRun(project());
|
||||
const older = runDeps(["fit", "--run", again, "--id", "app/Cargo.lock#serde", "--best", "1.0.90"]);
|
||||
assert.equal(older.code, 4);
|
||||
assert.equal(older.json.error, "not-newer");
|
||||
assert.equal(runDeps(["fit", "--run", again, "--id", "nope#x", "--best", "1.0.0"]).code, 3);
|
||||
assert.equal(runDeps(["fit", "--run", again, "--id", "app/Cargo.lock#serde"]).code, 2, "--id needs --best");
|
||||
});
|
||||
|
||||
test("fit: when the adapter cannot answer, the held reason keeps a runtime range with spaces whole", () => {
|
||||
const root = project();
|
||||
const dir = fitRun(root);
|
||||
const scan = JSON.parse(fs.readFileSync(path.join(dir, "scan.json"), "utf8"));
|
||||
scan.lockfiles[0].held[0].reason = "every newer version needs Node ^12.17.0 || >=16.0.0 (the project declares >=12)";
|
||||
fs.writeFileSync(path.join(dir, "scan.json"), JSON.stringify(scan));
|
||||
const r = runStubbed(["fit", "--run", dir], stubPath({ git: [{ has: ["--version"], text: "git" }] }));
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.deepEqual(r.json.unknown, ["package-lock.json#chalk", "app/Cargo.lock#serde"], "no npm on PATH: no adapter answers");
|
||||
const held = JSON.parse(fs.readFileSync(path.join(dir, "scan.json"), "utf8")).lockfiles[0].held.find((h) => h.package === "chalk");
|
||||
assert.equal(held.reason, "needs Node ^12.17.0 || >=16.0.0 (you declare >=12)");
|
||||
});
|
||||
|
||||
test("no stub ever received --force or an audit fix", () => {
|
||||
const calls = stubDirs.flatMap(callsOf);
|
||||
assert.ok(calls.length > 20, "the stubbed tests ran first");
|
||||
@@ -2543,3 +3034,327 @@ test("no stub ever received --force or an audit fix", () => {
|
||||
assert.ok(!(c.args.includes("audit") && c.args.includes("fix")), "never audit fix");
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------ plain words */
|
||||
|
||||
// Words a person never reads (specs/deps-skill-rework/wording-audit.md). They stay in field names, commands and file names.
|
||||
const AVOID = /\b(lockfiles?|manifests?|tracked|hand-?offs?|jump)\b/i;
|
||||
|
||||
test("label: every row carries reasonsPlain, one plain sentence per reason in the same order, with no avoid-list word", () => {
|
||||
const pinned = JSON.parse(JSON.stringify(SCAN));
|
||||
pinned.lockfiles[0].rows[0] = { ...pinned.lockfiles[0].rows[0], pinned: true, security: { severity: "high", ids: ["X"] }, runtimeNotChecked: ">=3.10", couldNotRead: "npm" };
|
||||
const scans = [SCAN, pinned, { ...SCAN, noChecks: true }];
|
||||
const lists = [deps.label(SCAN, RECORDS), deps.label(SCAN, []), deps.label(pinned, RECORDS), deps.label(scans[2], RECORDS)];
|
||||
let seen = 0;
|
||||
for (const labels of lists) {
|
||||
for (const l of labels) {
|
||||
assert.ok(Array.isArray(l.reasonsPlain), `${l.id} has reasonsPlain`);
|
||||
assert.equal(l.reasonsPlain.length, l.reasons.length, `${l.id}: reasonsPlain lines up with reasons`);
|
||||
for (const s of l.reasonsPlain) {
|
||||
seen++;
|
||||
assert.ok(typeof s === "string" && s.length > 0, `${l.id}: a plain sentence`);
|
||||
assert.ok(!AVOID.test(s), `${l.id}: "${s}" uses an avoid-list word`);
|
||||
assert.ok(!l.reasons.includes(s), `${l.id}: "${s}" is not just the raw reason`);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.ok(seen > 20, "the fixtures exercise many reasons");
|
||||
assert.ok(deps.label(SCAN, []).some((l) => l.reasonsPlain.includes("I did not read the update notes")));
|
||||
assert.deepEqual(labeled().r1.reasonsPlain, ["2 files use it"]);
|
||||
});
|
||||
|
||||
test("label: reasonsPlain is printed by the label command and saved in labels.json", () => {
|
||||
const dir = runFolder({ "scan.json": SCAN });
|
||||
const r = runDeps(["label", "--run", dir, "--records", path.join(FIXTURES, "label", "records.json")]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.ok(r.json.labels.length > 0);
|
||||
assert.ok(JSON.parse(fs.readFileSync(path.join(dir, "labels.json"), "utf8")).every((l) => Array.isArray(l.reasonsPlain)));
|
||||
assert.ok(r.json.labels.every((l) => Array.isArray(l.reasonsPlain) && l.reasonsPlain.length === l.reasons.length));
|
||||
});
|
||||
|
||||
// The text a person reads: every double-quoted sentence in the prompt, and every multi-word string value in the notes' example cards.
|
||||
function personFacing(markdown) {
|
||||
const out = [];
|
||||
for (const m of markdown.matchAll(/"([^"\n]*\s[^"\n]*)"/g)) out.push(m[1]);
|
||||
return out;
|
||||
}
|
||||
function exampleStrings(markdown) {
|
||||
const out = [];
|
||||
const walk = (v) => {
|
||||
if (typeof v === "string") {
|
||||
if (/\s/.test(v)) out.push(v);
|
||||
} else if (Array.isArray(v)) v.forEach(walk);
|
||||
else if (v && typeof v === "object") Object.values(v).forEach(walk);
|
||||
};
|
||||
for (const m of markdown.matchAll(/```jsonc\n([\s\S]*?)\n```/g)) walk(JSON.parse(m[1]));
|
||||
return out;
|
||||
}
|
||||
const WHITELIST = /package-lock\.json|package\.json|requirements\.txt|pom\.xml|Cargo\.lock/g;
|
||||
|
||||
test("the prompt and the console notes keep avoid-list words out of text a person reads", () => {
|
||||
const prompt = fs.readFileSync(path.join(ROOT, "src", "plan2code-deps.md"), "utf8");
|
||||
const notes = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "deps.md"), "utf8");
|
||||
const strings = [...personFacing(prompt), ...exampleStrings(notes)];
|
||||
assert.ok(strings.length > 10, "there is person-facing text to check");
|
||||
for (const s of strings) {
|
||||
const text = s.replace(WHITELIST, "").replace(/`[^`]*`/g, "");
|
||||
assert.ok(!AVOID.test(text), `"${s}" uses an avoid-list word`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the notes no longer carry a card with the id notes, and the start card is a confirm with a Start button", () => {
|
||||
const notes = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "deps.md"), "utf8");
|
||||
const items = [];
|
||||
for (const m of notes.matchAll(/```jsonc\n([\s\S]*?)\n```/g)) items.push(...(JSON.parse(m[1]).items || []));
|
||||
assert.ok(!items.some((i) => i.id === "notes"), "the release-notes question is gone");
|
||||
const start = items.find((i) => i.id === "start");
|
||||
assert.equal(start.kind, "confirm");
|
||||
assert.equal(start.yesLabel, "Start");
|
||||
assert.match(start.body, /I will read what each update changes before judging it/);
|
||||
assert.ok(!/Release notes|skip the notes/i.test(notes), "no release-notes question or skip option remains");
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------ fixes and tools */
|
||||
|
||||
// A fix is one approved replacement in one project file after apply; it is
|
||||
// backed up into the batch's backup, so restore puts it back with the rest.
|
||||
|
||||
/** Every file under root (relative, forward slashes) with its bytes. */
|
||||
function treeOf(root) {
|
||||
const files = {};
|
||||
const walkTree = (dir) => {
|
||||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const abs = path.join(dir, e.name);
|
||||
if (e.isDirectory()) walkTree(abs);
|
||||
else files[path.relative(root, abs).split(path.sep).join("/")] = fs.readFileSync(abs);
|
||||
}
|
||||
};
|
||||
walkTree(root);
|
||||
return files;
|
||||
}
|
||||
|
||||
function assertSameTree(root, before) {
|
||||
const now = treeOf(root);
|
||||
assert.deepEqual(Object.keys(now).sort(), Object.keys(before).sort(), "the same files");
|
||||
for (const [rel, bytes] of Object.entries(before)) assert.ok(now[rel].equals(bytes), `${rel} byte for byte`);
|
||||
}
|
||||
|
||||
const PIN_TEST = 'import { test } from "node:test";\nconst BUILD = "1.64.1";\ntest("browser build", () => {\n check(BUILD);\n});\n';
|
||||
|
||||
/** A project with a test file, chalk planned, backed up and applied: ready for a fix. */
|
||||
function applied(extra = {}) {
|
||||
const root = project({ "scripts/test-browser.mjs": PIN_TEST, ...extra });
|
||||
const start = treeOf(root);
|
||||
const { run, bin, batches } = planned(root, ["chalk"], {
|
||||
npm: npmRules([{ has: ["update", "chalk"], writes: [{ file: "package-lock.json", bump: { "node_modules/chalk": "4.1.2" } }] }]),
|
||||
});
|
||||
const b = batches[0];
|
||||
assert.equal(runStubbed(["backup", "--run", run, "--batch", b.id], bin).code, 0);
|
||||
const a = runStubbed(["apply", "--run", run, "--batch", b.id], bin);
|
||||
assert.equal(a.code, 0, a.stderr);
|
||||
return { root, run, bin, b, start };
|
||||
}
|
||||
|
||||
const fixArgs = (run, b, file, from, to) => ["fix", "--run", run, "--batch", b.id, "--file", file, "--from", from, "--to", to];
|
||||
|
||||
test("deps --help names fix and install-tool, and the new rule for editing files", () => {
|
||||
const r = runDeps(["--help"]);
|
||||
for (const command of ["fix", "install-tool"]) assert.match(r.stdout, new RegExp(`deps\\.mjs ${command}\\b`), command);
|
||||
assert.ok(!/never edits source code/.test(r.stdout), "the old rule is gone");
|
||||
assert.match(r.stdout, /only through fix, after the person approved that\s+exact change/);
|
||||
});
|
||||
|
||||
test("fix replaces the one place, backs the file up into the batch and records fixes.json", () => {
|
||||
const { root, run, bin, b } = applied();
|
||||
const r = runStubbed(fixArgs(run, b, "scripts/test-browser.mjs", '"1.64.1"', '"1.65.1"'), bin);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.deepEqual(r.json, { ok: true, batch: b.id, file: "scripts/test-browser.mjs", replaced: 1, backedUp: true });
|
||||
assert.equal(fs.readFileSync(path.join(root, "scripts/test-browser.mjs"), "utf8"), PIN_TEST.replace("1.64.1", "1.65.1"));
|
||||
const backup = JSON.parse(fs.readFileSync(path.join(run, "backups", b.id, "backup.json"), "utf8"));
|
||||
assert.deepEqual(backup.files.at(-1), { path: "scripts/test-browser.mjs", existed: true });
|
||||
assert.deepEqual(backup.fixed, ["scripts/test-browser.mjs"]);
|
||||
assert.equal(fs.readFileSync(path.join(run, "backups", b.id, "files", "scripts/test-browser.mjs"), "utf8"), PIN_TEST, "the as-found copy");
|
||||
const fixes = JSON.parse(fs.readFileSync(path.join(run, "fixes.json"), "utf8")).fixes;
|
||||
assert.equal(fixes.length, 1);
|
||||
const { at, ...rest } = fixes[0];
|
||||
assert.deepEqual(rest, { batch: b.id, file: "scripts/test-browser.mjs", from: '"1.64.1"', to: '"1.65.1"' });
|
||||
assert.ok(!Number.isNaN(Date.parse(at)));
|
||||
});
|
||||
|
||||
test("fix needs a backup and an applied batch (exit 5)", () => {
|
||||
const root = project({ "scripts/test-browser.mjs": PIN_TEST });
|
||||
const { run, bin, batches } = planned(root, ["chalk"], { npm: npmRules([{ has: ["update"], text: "" }]) });
|
||||
const b = batches[0];
|
||||
const noBackup = runStubbed(fixArgs(run, b, "scripts/test-browser.mjs", "1.64.1", "1.65.1"), bin);
|
||||
assert.equal(noBackup.code, 5);
|
||||
assert.equal(noBackup.json.error, "no-backup");
|
||||
runStubbed(["backup", "--run", run, "--batch", b.id], bin);
|
||||
const notApplied = runStubbed(fixArgs(run, b, "scripts/test-browser.mjs", "1.64.1", "1.65.1"), bin);
|
||||
assert.equal(notApplied.code, 5);
|
||||
assert.equal(notApplied.json.error, "not-applied");
|
||||
assert.equal(fs.readFileSync(path.join(root, "scripts/test-browser.mjs"), "utf8"), PIN_TEST, "nothing changed");
|
||||
});
|
||||
|
||||
test("restore --verify after a fix puts LF and CRLF files back byte for byte and names the fixes", () => {
|
||||
const crlf = 'line one\r\nconst BUILD = "1.64.1";\r\nline three\r\n';
|
||||
const { root, run, bin, b, start } = applied({ "config/browser.txt": crlf });
|
||||
const lf = runStubbed(fixArgs(run, b, "scripts/test-browser.mjs", "1.64.1", "1.65.1"), bin);
|
||||
assert.equal(lf.code, 0, lf.stderr);
|
||||
// A bare-LF --from spanning a line break matches the CRLF file and is written back with CRLF.
|
||||
const cr = runStubbed(fixArgs(run, b, "config/browser.txt", 'line one\nconst BUILD = "1.64.1";', 'line one\nconst BUILD = "1.65.1";'), bin);
|
||||
assert.equal(cr.code, 0, cr.stderr);
|
||||
assert.equal(fs.readFileSync(path.join(root, "config/browser.txt"), "utf8"), crlf.replace("1.64.1", "1.65.1"), "CRLF kept");
|
||||
const r = runStubbed(["restore", "--run", run, "--batch", b.id, "--verify"], bin);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.equal(r.json.verified, true);
|
||||
assert.deepEqual(r.json.fixed, ["scripts/test-browser.mjs", "config/browser.txt"]);
|
||||
assert.ok(r.json.restored.includes("config/browser.txt"));
|
||||
assertSameTree(root, start);
|
||||
});
|
||||
|
||||
test("a second fix to the same file keeps the first as-found copy", () => {
|
||||
const { root, run, bin, b, start } = applied();
|
||||
assert.equal(runStubbed(fixArgs(run, b, "scripts/test-browser.mjs", "1.64.1", "1.65.1"), bin).code, 0);
|
||||
const second = runStubbed(fixArgs(run, b, "scripts/test-browser.mjs", "check(BUILD)", "check(BUILD, true)"), bin);
|
||||
assert.equal(second.code, 0, second.stderr);
|
||||
assert.equal(second.json.backedUp, false);
|
||||
assert.equal(fs.readFileSync(path.join(run, "backups", b.id, "files", "scripts/test-browser.mjs"), "utf8"), PIN_TEST);
|
||||
const backup = JSON.parse(fs.readFileSync(path.join(run, "backups", b.id, "backup.json"), "utf8"));
|
||||
assert.equal(backup.files.filter((f) => f.path === "scripts/test-browser.mjs").length, 1, "listed once");
|
||||
assert.equal(JSON.parse(fs.readFileSync(path.join(run, "fixes.json"), "utf8")).fixes.length, 2);
|
||||
assert.equal(runStubbed(["restore", "--run", run, "--batch", b.id, "--verify"], bin).json.verified, true);
|
||||
assertSameTree(root, start);
|
||||
});
|
||||
|
||||
test("after restore the group is no longer applied, so fix refuses it until apply runs again", () => {
|
||||
const { run, bin, b } = applied();
|
||||
assert.equal(runStubbed(["restore", "--run", run, "--batch", b.id, "--verify"], bin).json.verified, true);
|
||||
const r = runStubbed(fixArgs(run, b, "scripts/test-browser.mjs", "1.64.1", "1.65.1"), bin);
|
||||
assert.equal(r.code, 5);
|
||||
assert.equal(r.json.error, "not-applied");
|
||||
});
|
||||
|
||||
test("a fixed executable keeps its mode through the put-back (macOS and Linux)", { skip: process.platform === "win32" }, () => {
|
||||
const { root, run, bin, b } = applied();
|
||||
const file = path.join(root, "scripts/test-browser.mjs");
|
||||
fs.chmodSync(file, 0o755);
|
||||
assert.equal(runStubbed(fixArgs(run, b, "scripts/test-browser.mjs", "1.64.1", "1.65.1"), bin).code, 0);
|
||||
assert.equal(runStubbed(["restore", "--run", run, "--batch", b.id, "--verify"], bin).json.verified, true);
|
||||
assert.equal(fs.statSync(file).mode & 0o777, 0o755);
|
||||
});
|
||||
|
||||
test("fix refuses a batch file, a path outside the project, a protected folder, a binary and text found twice or not at all", () => {
|
||||
const twice = "a = 1;\na = 1;\n";
|
||||
const { root, run, bin, b } = applied({ "src/twice.js": twice, "node_modules/x/index.js": "const v = 1;\n", "specs/x/plan.md": "v 1\n" });
|
||||
fs.writeFileSync(path.join(root, "assets.bin"), Buffer.from([0x61, 0x00, 0x62, 0x0a]));
|
||||
const before = treeOf(root);
|
||||
const cases = [
|
||||
["package.json", '"chalk"', '"chalk2"', "fix-batch-file"],
|
||||
["package-lock.json", '"4.1.2"', '"4.1.3"', "fix-batch-file"],
|
||||
["packages/app/package.json", '"is-number"', '"is-num"', "fix-batch-file"],
|
||||
["../outside.txt", "a", "b", "fix-outside"],
|
||||
[path.join(root, "src", "twice.js"), "a = 1", "a = 2", "fix-absolute"],
|
||||
["node_modules/x/index.js", "1", "2", "fix-protected-folder"],
|
||||
["specs/x/plan.md", "1", "2", "fix-protected-folder"],
|
||||
["assets.bin", "a", "c", "fix-binary"],
|
||||
["src/twice.js", "a = 1;", "a = 2;", "fix-many"],
|
||||
["src/twice.js", "b = 1;", "b = 2;", "fix-not-found-text"],
|
||||
["src/missing.js", "a", "b", "fix-not-found"],
|
||||
];
|
||||
for (const [file, from, to, error] of cases) {
|
||||
const r = runStubbed(fixArgs(run, b, file, from, to), bin);
|
||||
assert.equal(r.code, 5, `${file}: ${r.stdout}`);
|
||||
assert.equal(r.json.error, error, file);
|
||||
assert.ok(r.json.message && r.json.next, `${file}: plain message and next`);
|
||||
}
|
||||
assert.match(runStubbed(fixArgs(run, b, "src/twice.js", "a = 1;", "a = 2;"), bin).json.message, /appears 2 times in src\/twice\.js/);
|
||||
assertSameTree(root, before);
|
||||
const backup = JSON.parse(fs.readFileSync(path.join(run, "backups", b.id, "backup.json"), "utf8"));
|
||||
assert.deepEqual(backup.fixed || [], [], "nothing was backed up for a refused fix");
|
||||
assert.ok(!fs.existsSync(path.join(run, "fixes.json")));
|
||||
});
|
||||
|
||||
test("applyFix refuses a file over 1 MB", () => {
|
||||
const root = tmp("deps-fix-big");
|
||||
const store = tmp("deps-fix-store");
|
||||
fs.writeFileSync(path.join(store, "backup.json"), JSON.stringify({ files: [] }));
|
||||
fs.writeFileSync(path.join(root, "big.txt"), "x".repeat(deps.PIN_FILE_CAP + 1) + "\nneedle\n");
|
||||
assert.deepEqual(deps.applyFix(root, store, "big.txt", "needle", "pin"), { ok: false, code: "too-big", reason: "big.txt is over 1 MB" });
|
||||
});
|
||||
|
||||
test("put-back stories: a batch failing after a fix, a skipped fix and a refused fix each end with the tree as found", () => {
|
||||
// Failing after a fix: the fix lands, the checks still fail, restore takes both back.
|
||||
const failing = applied();
|
||||
assert.equal(runStubbed(fixArgs(failing.run, failing.b, "scripts/test-browser.mjs", "1.64.1", "1.65.1"), failing.bin).code, 0);
|
||||
const r1 = runStubbed(["restore", "--run", failing.run, "--batch", failing.b.id, "--verify"], failing.bin);
|
||||
assert.equal(r1.json.verified, true);
|
||||
assert.deepEqual(r1.json.fixed, ["scripts/test-browser.mjs"]);
|
||||
assertSameTree(failing.root, failing.start);
|
||||
|
||||
// A skipped fix: no fix call, restore only.
|
||||
const skipped = applied();
|
||||
const r2 = runStubbed(["restore", "--run", skipped.run, "--batch", skipped.b.id, "--verify"], skipped.bin);
|
||||
assert.equal(r2.json.verified, true);
|
||||
assert.deepEqual(r2.json.fixed, []);
|
||||
assertSameTree(skipped.root, skipped.start);
|
||||
|
||||
// A refused fix: nothing written, restore puts the update back.
|
||||
const refused = applied();
|
||||
assert.equal(runStubbed(fixArgs(refused.run, refused.b, "package.json", '"chalk"', '"chalk2"'), refused.bin).code, 5);
|
||||
const r3 = runStubbed(["restore", "--run", refused.run, "--batch", refused.b.id, "--verify"], refused.bin);
|
||||
assert.equal(r3.json.verified, true);
|
||||
assert.deepEqual(r3.json.fixed, []);
|
||||
assertSameTree(refused.root, refused.start);
|
||||
});
|
||||
|
||||
test("install-tool prints a listed scanner's exact command and runs nothing; an unlisted one or an empty list exits 5", () => {
|
||||
const missingTools = ["cargo", { tool: "cargo-audit", step: "audit", install: "cargo install cargo-audit" }, { tool: "pip-audit", step: "audit", install: "pip install pip-audit" }];
|
||||
const dir = runFolder({ "scan.json": { root: os.tmpdir(), lockfiles: [], missingTools } });
|
||||
const before = fs.readdirSync(dir).sort();
|
||||
const r = runDeps(["install-tool", "--run", dir, "--tool", "cargo-audit"]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.deepEqual(r.json, { ok: true, tool: "cargo-audit", command: "cargo install cargo-audit", step: "audit" });
|
||||
assert.deepEqual(fs.readdirSync(dir).sort(), before, "nothing written");
|
||||
for (const tool of ["govulncheck", "cargo", "rm"]) {
|
||||
const no = runDeps(["install-tool", "--run", dir, "--tool", tool]);
|
||||
assert.equal(no.code, 5, tool);
|
||||
assert.equal(no.json.error, "tool-not-listed");
|
||||
assert.match(no.json.message, /was not in the scan's missing list/);
|
||||
assert.deepEqual(no.json.offered, ["cargo-audit", "pip-audit"]);
|
||||
}
|
||||
const empty = runFolder({ "scan.json": { root: os.tmpdir(), lockfiles: [], missingTools: [] } });
|
||||
const none = runDeps(["install-tool", "--run", empty, "--tool", "pip-audit"]);
|
||||
assert.equal(none.code, 5);
|
||||
assert.match(none.json.next, /found no missing tool/);
|
||||
assert.equal(runDeps(["install-tool", "--run", empty]).json.error, "missing-tool");
|
||||
});
|
||||
|
||||
test("fix refuses a batch file or protected folder named in other letter case, or reached through a link, and keeps the as-found copy", () => {
|
||||
const { root, run, bin, b, start } = applied({ "node_modules/x/index.js": "const v = 1;\n" });
|
||||
const caseless = process.platform === "win32" || process.platform === "darwin";
|
||||
if (caseless) {
|
||||
for (const [file, from, to, error] of [
|
||||
["PACKAGE.JSON", '"chalk"', '"chalk2"', "fix-batch-file"],
|
||||
["Package-Lock.json", '"4.1.2"', '"4.1.3"', "fix-batch-file"],
|
||||
["NODE_MODULES/x/index.js", "1", "2", "fix-protected-folder"],
|
||||
]) {
|
||||
const r = runStubbed(fixArgs(run, b, file, from, to), bin);
|
||||
assert.equal(r.code, 5, `${file}: ${r.stdout}`);
|
||||
assert.equal(r.json.error, error, file);
|
||||
}
|
||||
}
|
||||
let linked = false;
|
||||
try {
|
||||
fs.symlinkSync(path.join(root, "package.json"), path.join(root, "link.json"), "file");
|
||||
linked = true;
|
||||
} catch {}
|
||||
if (linked) {
|
||||
const r = runStubbed(fixArgs(run, b, "link.json", '"chalk"', '"chalk2"'), bin);
|
||||
assert.equal(r.code, 5, r.stdout);
|
||||
assert.equal(r.json.error, "fix-batch-file", "a link to a batch file is that file");
|
||||
fs.rmSync(path.join(root, "link.json"));
|
||||
}
|
||||
const restored = runStubbed(["restore", "--run", run, "--batch", b.id, "--verify"], bin);
|
||||
assert.equal(restored.json.verified, true);
|
||||
assertSameTree(root, start);
|
||||
});
|
||||
@@ -0,0 +1,301 @@
|
||||
// Web console tests, the Changes tab's parser: public/diff-parse.js reads the
|
||||
// unified diff changes.mjs writes into files, hunks and numbered lines, and
|
||||
// never throws on text it cannot read. Run with:
|
||||
// node --test scripts/test-web-console-diff-parse.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { parseDiff, HIDDEN_LINE, TOO_LARGE_LINE } from "../src/web-console/public/diff-parse.js";
|
||||
|
||||
const one = (text) => {
|
||||
const r = parseDiff(text);
|
||||
assert.equal(r.bad, undefined, "read as a diff");
|
||||
assert.equal(r.files.length, 1);
|
||||
return r.files[0];
|
||||
};
|
||||
const shape = (lines) => lines.map((l) => [l.kind, l.oldNo, l.newNo, l.text]);
|
||||
|
||||
test("a modified file with two hunks numbers every line from its hunk header", () => {
|
||||
const f = one(
|
||||
[
|
||||
"diff --git a/src/app.js b/src/app.js",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/src/app.js",
|
||||
"+++ b/src/app.js",
|
||||
"@@ -3,3 +3,4 @@ function start() {",
|
||||
" one",
|
||||
"-two",
|
||||
"+TWO",
|
||||
"+two and a half",
|
||||
" three",
|
||||
"@@ -20,2 +21,1 @@",
|
||||
"-gone",
|
||||
" kept",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
assert.equal(f.path, "src/app.js");
|
||||
assert.equal(f.oldPath, null, "only a rename names an old path");
|
||||
assert.equal(f.status, "modified");
|
||||
assert.equal(f.added, 2);
|
||||
assert.equal(f.removed, 2);
|
||||
assert.equal(f.hunks.length, 2);
|
||||
assert.equal(f.hunks[0].header, "@@ -3,3 +3,4 @@ function start() {");
|
||||
assert.deepEqual(shape(f.hunks[0].lines), [
|
||||
["ctx", 3, 3, "one"],
|
||||
["del", 4, null, "two"],
|
||||
["add", null, 4, "TWO"],
|
||||
["add", null, 5, "two and a half"],
|
||||
["ctx", 5, 6, "three"],
|
||||
]);
|
||||
assert.deepEqual(shape(f.hunks[1].lines), [
|
||||
["del", 20, null, "gone"],
|
||||
["ctx", 21, 21, "kept"],
|
||||
]);
|
||||
});
|
||||
|
||||
test("an added file and a deleted file", () => {
|
||||
const r = parseDiff(
|
||||
[
|
||||
"diff --git a/new.txt b/new.txt",
|
||||
"new file mode 100644",
|
||||
"index 0000000..3333333",
|
||||
"--- /dev/null",
|
||||
"+++ b/new.txt",
|
||||
"@@ -0,0 +1,2 @@",
|
||||
"+hello",
|
||||
"+world",
|
||||
"diff --git a/old.txt b/old.txt",
|
||||
"deleted file mode 100644",
|
||||
"index 4444444..0000000",
|
||||
"--- a/old.txt",
|
||||
"+++ /dev/null",
|
||||
"@@ -1 +0,0 @@",
|
||||
"-bye",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
assert.equal(r.files.length, 2);
|
||||
const [added, deleted] = r.files;
|
||||
assert.equal(added.status, "added");
|
||||
assert.equal(added.path, "new.txt");
|
||||
assert.deepEqual([added.added, added.removed], [2, 0]);
|
||||
assert.deepEqual(shape(added.hunks[0].lines), [
|
||||
["add", null, 1, "hello"],
|
||||
["add", null, 2, "world"],
|
||||
]);
|
||||
assert.equal(deleted.status, "deleted");
|
||||
assert.equal(deleted.path, "old.txt", "a deleted file keeps its own name");
|
||||
assert.deepEqual([deleted.added, deleted.removed], [0, 1]);
|
||||
assert.deepEqual(shape(deleted.hunks[0].lines), [["del", 1, null, "bye"]]);
|
||||
});
|
||||
|
||||
test("a pure rename and a rename with edits", () => {
|
||||
const r = parseDiff(
|
||||
[
|
||||
"diff --git a/a/old name.md b/b/new name.md",
|
||||
"similarity index 100%",
|
||||
"rename from a/old name.md",
|
||||
"rename to b/new name.md",
|
||||
"diff --git a/lib/x.js b/lib/y.js",
|
||||
"similarity index 80%",
|
||||
"rename from lib/x.js",
|
||||
"rename to lib/y.js",
|
||||
"index 5555555..6666666 100644",
|
||||
"--- a/lib/x.js",
|
||||
"+++ b/lib/y.js",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
"-const x = 1;",
|
||||
"+const y = 1;",
|
||||
" export {};",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
assert.equal(r.files.length, 2);
|
||||
const [pure, edited] = r.files;
|
||||
assert.equal(pure.status, "renamed");
|
||||
assert.equal(pure.oldPath, "a/old name.md");
|
||||
assert.equal(pure.path, "b/new name.md");
|
||||
assert.equal(pure.hunks.length, 0);
|
||||
assert.deepEqual([pure.added, pure.removed], [0, 0]);
|
||||
assert.equal(edited.status, "renamed");
|
||||
assert.equal(edited.oldPath, "lib/x.js");
|
||||
assert.equal(edited.path, "lib/y.js");
|
||||
assert.deepEqual([edited.added, edited.removed], [1, 1]);
|
||||
});
|
||||
|
||||
test("a binary file and a hidden file show no lines", () => {
|
||||
const r = parseDiff(
|
||||
[
|
||||
"diff --git a/logo.png b/logo.png",
|
||||
"index 7777777..8888888 100644",
|
||||
"Binary files a/logo.png and b/logo.png differ",
|
||||
"diff --git a/.env b/.env",
|
||||
"index 9999999..aaaaaaa 100644",
|
||||
HIDDEN_LINE,
|
||||
"# hidden: .env",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
assert.equal(r.files.length, 2);
|
||||
const [bin, secret] = r.files;
|
||||
assert.equal(bin.binary, true);
|
||||
assert.equal(bin.hunks.length, 0);
|
||||
assert.equal(secret.path, ".env");
|
||||
assert.equal(secret.hidden, true);
|
||||
assert.equal(secret.hunks.length, 0);
|
||||
assert.equal(secret.truncated, false);
|
||||
});
|
||||
|
||||
test("a hidden file takes its counts from the trailer", () => {
|
||||
const r = parseDiff(
|
||||
["diff --git a/.env b/.env", "new file mode 100644", HIDDEN_LINE, "# hidden: .env", "# counts: 40\t3\t.env", ""].join("\n")
|
||||
);
|
||||
assert.equal(r.files.length, 1);
|
||||
assert.equal(r.files[0].added, 40);
|
||||
assert.equal(r.files[0].removed, 3);
|
||||
});
|
||||
|
||||
test("a truncated set: the files after the too-large line hold only a header", () => {
|
||||
const r = parseDiff(
|
||||
[
|
||||
"diff --git a/kept.txt b/kept.txt",
|
||||
"--- a/kept.txt",
|
||||
"+++ b/kept.txt",
|
||||
"@@ -1 +1 @@",
|
||||
"-a",
|
||||
"+b",
|
||||
TOO_LARGE_LINE,
|
||||
"diff --git a/big.txt b/big.txt",
|
||||
"diff --git a/moved.txt b/there.txt",
|
||||
"rename from moved.txt",
|
||||
"rename to there.txt",
|
||||
"# truncated: true",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
assert.equal(r.tooLarge, true);
|
||||
assert.equal(r.files.length, 3);
|
||||
assert.equal(r.files[0].truncated, false);
|
||||
assert.deepEqual(shape(r.files[0].hunks[0].lines), [
|
||||
["del", 1, null, "a"],
|
||||
["add", null, 1, "b"],
|
||||
]);
|
||||
assert.equal(r.files[1].truncated, true);
|
||||
assert.equal(r.files[1].path, "big.txt");
|
||||
assert.equal(r.files[2].truncated, true);
|
||||
assert.equal(r.files[2].status, "renamed");
|
||||
assert.equal(r.files[2].path, "there.txt");
|
||||
});
|
||||
|
||||
test("a change set too big to print: every name first, the too-large line last, each file listed only", () => {
|
||||
const r = parseDiff(
|
||||
[
|
||||
"diff --git a/a.txt b/a.txt",
|
||||
"diff --git a/old.txt b/new.txt",
|
||||
"rename from old.txt",
|
||||
"rename to new.txt",
|
||||
"diff --git a/.env b/.env",
|
||||
HIDDEN_LINE,
|
||||
TOO_LARGE_LINE,
|
||||
"# truncated: true",
|
||||
"# hidden: .env",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
assert.equal(r.tooLarge, true);
|
||||
assert.deepEqual(
|
||||
r.files.map((f) => [f.path, f.truncated, f.hidden]),
|
||||
[
|
||||
["a.txt", true, false],
|
||||
["new.txt", true, false],
|
||||
[".env", false, true],
|
||||
]
|
||||
);
|
||||
assert.equal("afterCut" in r.files[0], false, "no working field leaks out");
|
||||
});
|
||||
|
||||
test("a line starting +++ or --- inside a hunk stays a changed line", () => {
|
||||
const f = one(
|
||||
[
|
||||
"diff --git a/notes.md b/notes.md",
|
||||
"--- a/notes.md",
|
||||
"+++ b/notes.md",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
"--- a rule",
|
||||
"+++ a plus rule",
|
||||
" same",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
assert.equal(f.path, "notes.md");
|
||||
assert.deepEqual(shape(f.hunks[0].lines), [
|
||||
["del", 1, null, "-- a rule"],
|
||||
["add", null, 1, "++ a plus rule"],
|
||||
["ctx", 2, 2, "same"],
|
||||
]);
|
||||
});
|
||||
|
||||
test("a file with no newline at its end keeps the marker as a meta line", () => {
|
||||
const f = one(
|
||||
[
|
||||
"diff --git a/end.txt b/end.txt",
|
||||
"--- a/end.txt",
|
||||
"+++ b/end.txt",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"\\ No newline at end of file",
|
||||
"+new",
|
||||
"\\ No newline at end of file",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
assert.deepEqual(shape(f.hunks[0].lines), [
|
||||
["del", 1, null, "old"],
|
||||
["meta", null, null, "\\ No newline at end of file"],
|
||||
["add", null, 1, "new"],
|
||||
["meta", null, null, "\\ No newline at end of file"],
|
||||
]);
|
||||
assert.deepEqual([f.added, f.removed], [1, 1], "the marker is not counted");
|
||||
});
|
||||
|
||||
test("paths with spaces and quoted paths", () => {
|
||||
const r = parseDiff(
|
||||
[
|
||||
"diff --git a/with space.txt b/with space.txt",
|
||||
"--- a/with space.txt\t",
|
||||
"+++ b/with space.txt\t",
|
||||
"@@ -1 +1,2 @@",
|
||||
" a",
|
||||
"+b",
|
||||
'diff --git "a/say \\"hi\\".txt" "b/say \\"hi\\".txt"',
|
||||
'--- "a/say \\"hi\\".txt"',
|
||||
'+++ "b/say \\"hi\\".txt"',
|
||||
"@@ -1 +1 @@",
|
||||
"-x",
|
||||
"+y",
|
||||
'diff --git "a/caf\\303\\251 tab\\t.txt" "b/caf\\303\\251 tab\\t.txt"',
|
||||
"new file mode 100644",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
assert.deepEqual(
|
||||
r.files.map((f) => f.path),
|
||||
["with space.txt", 'say "hi".txt', "café tab\t.txt"]
|
||||
);
|
||||
assert.equal(r.files[0].added, 1);
|
||||
});
|
||||
|
||||
test("an empty string is no files, and garbage never throws", () => {
|
||||
assert.deepEqual(parseDiff(""), { files: [], tooLarge: false });
|
||||
for (const junk of ["hello there\nthis is not a diff\n", "@@ -1 +1 @@\n+x\n", "diff --git nonsense", "\u0000\u0001", " \n"]) {
|
||||
const r = parseDiff(junk);
|
||||
assert.deepEqual(r.files, [], junk);
|
||||
assert.equal(r.tooLarge, false);
|
||||
}
|
||||
assert.equal(parseDiff("hello there\nthis is not a diff\n").bad, true);
|
||||
assert.equal(parseDiff("diff --git nonsense").bad, true);
|
||||
assert.equal(parseDiff(" \n").bad, undefined, "blank text is an empty diff");
|
||||
assert.equal(parseDiff(undefined).bad, true);
|
||||
assert.equal(parseDiff(null).bad, true);
|
||||
});
|
||||
@@ -0,0 +1,265 @@
|
||||
// Page tests for the Changes tab: a `diff` doc block (a .diff file saved in the
|
||||
// session folder, changes.mjs diff) drawn as a file list and one unified diff,
|
||||
// with its empty, error and loading states. Run with:
|
||||
// node --test scripts/test-web-console-page-changes.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pageSuite, openSession, itemCard, textOf, styleOf, scrollCard } from "./page-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// Five files: a modified one with two hunks, an added one, a binary one, a
|
||||
// hidden one, then a file cut by the size cap.
|
||||
const DIFF = [
|
||||
"diff --git a/src/app.js b/src/app.js",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/src/app.js",
|
||||
"+++ b/src/app.js",
|
||||
"@@ -3,3 +3,4 @@ function start() {",
|
||||
" one",
|
||||
"-two",
|
||||
"+TWO",
|
||||
"+two and a half",
|
||||
" three",
|
||||
"@@ -20,2 +21,2 @@",
|
||||
"-gone",
|
||||
"+<b>not html</b>",
|
||||
" kept",
|
||||
"diff --git a/docs/new.md b/docs/new.md",
|
||||
"new file mode 100644",
|
||||
"--- /dev/null",
|
||||
"+++ b/docs/new.md",
|
||||
"@@ -0,0 +1,2 @@",
|
||||
"+# New",
|
||||
"+Hello.",
|
||||
"diff --git a/logo.png b/logo.png",
|
||||
"index 7777777..8888888 100644",
|
||||
"Binary files a/logo.png and b/logo.png differ",
|
||||
"diff --git a/.env b/.env",
|
||||
"index 9999999..aaaaaaa 100644",
|
||||
"Lines hidden: this file may hold a secret.",
|
||||
"\\ No more lines shown: this change is too large to show in full.",
|
||||
"diff --git a/big.txt b/big.txt",
|
||||
"# truncated: true",
|
||||
"# hidden: .env",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
// A sign-off card about the report, as Implement posts it.
|
||||
const SIGNOFF = {
|
||||
id: "signoff",
|
||||
kind: "review",
|
||||
title: "Approve this phase",
|
||||
doc: "report",
|
||||
body: "Read the report, then approve it or say what to change.",
|
||||
verdicts: [
|
||||
{ id: "approve", label: "Approve this phase" },
|
||||
{ id: "changes", label: "I want changes" },
|
||||
],
|
||||
};
|
||||
const REPORT = { id: "report", title: "Completion report", blocks: [{ id: "summary", md: "## Summary\n\nPhase 3 draws the Changes tab." }] };
|
||||
|
||||
// Opens an implement session whose Changes doc reads `text` from changes.diff.
|
||||
async function withChanges(t, text, extra = {}) {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" } } });
|
||||
fs.writeFileSync(path.join(s.session, "changes.diff"), text);
|
||||
s.post({
|
||||
docs: [REPORT, { id: "changes", title: "Changes", blocks: [{ id: "c1", diff: "changes.diff" }] }],
|
||||
agent: { status: "waiting" },
|
||||
...extra,
|
||||
});
|
||||
return s;
|
||||
}
|
||||
|
||||
const tab = (s, name) => s.page.locator("#views .view-tab", { hasText: new RegExp(`^${name}`) });
|
||||
|
||||
async function openChanges(s) {
|
||||
await tab(s, "Changes").click();
|
||||
await s.page.locator("#main .diff-view").waitFor();
|
||||
}
|
||||
|
||||
// The rows of the diff pane as [old number, new number, mark, text].
|
||||
async function paneRows(s) {
|
||||
return s.page.locator("#main .diff-pane .diff-line").evaluateAll((rows) =>
|
||||
rows.map((r) => [...r.children].map((c) => c.textContent))
|
||||
);
|
||||
}
|
||||
|
||||
// Whether the element is fully inside the window.
|
||||
async function inViewport(s, locator) {
|
||||
const box = await locator.boundingBox();
|
||||
const size = s.page.viewportSize();
|
||||
return Boolean(box) && box.y >= 0 && box.x >= 0 && box.y + box.height <= size.height && box.x + box.width <= size.width;
|
||||
}
|
||||
|
||||
// What the person sees break: a tab that never shows, a list without its
|
||||
// counts, or the wrong line numbers on the lines.
|
||||
test("the Changes tab lists each file with its counts and draws the first file's lines numbered and marked", async (t) => {
|
||||
const s = await withChanges(t, DIFF);
|
||||
await tab(s, "Changes").waitFor();
|
||||
const tabs = await s.page.locator("#views .view-tab").allTextContents();
|
||||
const report = tabs.findIndex((x) => x.startsWith("Completion report"));
|
||||
assert.ok(report >= 0, `the report tab: ${tabs}`);
|
||||
assert.ok(tabs[report + 1].startsWith("Changes"), `the Changes tab sits beside the report tab: ${tabs}`);
|
||||
await openChanges(s);
|
||||
|
||||
assert.equal(await textOf(s.page.locator("#main .diff-totals")), "5 files changed, +5 -2");
|
||||
assert.match(await textOf(s.page.locator("#main .diff-notice")), /too large to show in full/);
|
||||
const files = s.page.locator("#main .diff-file");
|
||||
assert.equal(await files.count(), 5);
|
||||
const first = files.nth(0);
|
||||
assert.equal(await textOf(first.locator(".diff-file-name strong")), "app.js");
|
||||
assert.equal(await textOf(first.locator(".diff-file-dir")), "src");
|
||||
assert.equal(await textOf(first.locator(".diff-plus")), "+3");
|
||||
assert.equal(await textOf(first.locator(".diff-minus")), "-2");
|
||||
assert.equal(await files.nth(1).locator(".diff-status").textContent(), "Added");
|
||||
assert.equal(await first.getAttribute("aria-selected"), "true", "the first file is picked");
|
||||
assert.equal(await s.page.locator("#main .diff-list").getAttribute("role"), "listbox");
|
||||
|
||||
assert.deepEqual(await s.page.locator("#main .diff-hunk").allTextContents(), ["@@ -3,3 +3,4 @@ function start() {", "@@ -20,2 +21,2 @@"]);
|
||||
assert.deepEqual(await paneRows(s), [
|
||||
["3", "3", "", "one"],
|
||||
["4", "", "-", "two"],
|
||||
["", "4", "+", "TWO"],
|
||||
["", "5", "+", "two and a half"],
|
||||
["5", "6", "", "three"],
|
||||
["20", "", "-", "gone"],
|
||||
["", "21", "+", "<b>not html</b>"],
|
||||
["21", "22", "", "kept"],
|
||||
]);
|
||||
// Diff text is never HTML: the tag stays text.
|
||||
assert.equal(await s.page.locator("#main .diff-pane b").count(), 0);
|
||||
});
|
||||
|
||||
test("clicking a file or pressing the arrows swaps the diff, and binary, hidden and cut files show one plain line", async (t) => {
|
||||
const s = await withChanges(t, DIFF);
|
||||
await openChanges(s);
|
||||
const files = s.page.locator("#main .diff-file");
|
||||
const pane = s.page.locator("#main .diff-pane");
|
||||
|
||||
await files.nth(1).click();
|
||||
await pane.locator(".diff-pane-path", { hasText: "docs/new.md" }).waitFor();
|
||||
assert.deepEqual(await paneRows(s), [
|
||||
["", "1", "+", "# New"],
|
||||
["", "2", "+", "Hello."],
|
||||
]);
|
||||
assert.equal(await files.nth(1).getAttribute("aria-selected"), "true");
|
||||
assert.equal(await files.nth(0).getAttribute("aria-selected"), "false");
|
||||
|
||||
const plain = [
|
||||
[2, "logo.png", "Binary file: no lines to show"],
|
||||
[3, ".env", "Lines hidden: this file may hold a secret"],
|
||||
[4, "big.txt", "Too large to show in full: this file is listed only"],
|
||||
];
|
||||
for (const [i, name, line] of plain) {
|
||||
await files.nth(i).click();
|
||||
await pane.locator(".diff-pane-path", { hasText: name }).waitFor();
|
||||
assert.equal(await textOf(pane.locator(".diff-plain")), line, name);
|
||||
assert.equal(await pane.locator(".diff-line").count(), 0, `${name} shows no lines`);
|
||||
}
|
||||
|
||||
// Arrow keys on the list move the pick.
|
||||
await s.page.locator("#main .diff-list").focus();
|
||||
await s.page.keyboard.press("ArrowUp");
|
||||
await pane.locator(".diff-pane-path", { hasText: ".env" }).waitFor();
|
||||
await s.page.keyboard.press("Home");
|
||||
await pane.locator(".diff-pane-path", { hasText: "src/app.js" }).waitFor();
|
||||
assert.equal(await files.nth(0).getAttribute("aria-selected"), "true");
|
||||
|
||||
// The pick survives a redraw of the same block.
|
||||
await files.nth(1).click();
|
||||
s.post({ title: "Phase 3, again" });
|
||||
await s.page.waitForFunction(() => document.getElementById("title").textContent.includes("Phase 3, again"));
|
||||
await pane.locator(".diff-pane-path", { hasText: "docs/new.md" }).waitFor();
|
||||
});
|
||||
|
||||
test("the empty state offers Check again, which sends the __changes action", async (t) => {
|
||||
const s = await withChanges(t, "");
|
||||
await openChanges(s);
|
||||
const empty = s.page.locator("#main .diff-empty");
|
||||
assert.equal(await textOf(empty.locator(".diff-state-msg")), "Nothing has changed since this run started.");
|
||||
await empty.getByRole("button", { name: "Check again" }).click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code})`);
|
||||
assert.ok(got.actions.some((a) => a.i === "__changes" && a.type === "changes"), JSON.stringify(got.actions));
|
||||
assert.match(got.reply, /Changes tab/);
|
||||
});
|
||||
|
||||
// What the person sees break: a click on a finished session that leaves the
|
||||
// page waiting for an agent who has gone.
|
||||
test("on a finished session Check again sends nothing and says why", async (t) => {
|
||||
const s = await withChanges(t, "");
|
||||
s.post({ finish: { headline: "Phase 3 is done", body: "7 of 7 tasks." } });
|
||||
await s.page.waitForFunction(() => document.body.textContent.includes("Phase 3 is done"));
|
||||
await openChanges(s);
|
||||
const empty = s.page.locator("#main .diff-empty");
|
||||
await empty.getByRole("button", { name: "Check again" }).click();
|
||||
await empty.locator(".diff-state-why", { hasText: "This session is finished." }).waitFor();
|
||||
assert.equal(s.wait(2).code, 10, "nothing reached the agent");
|
||||
});
|
||||
|
||||
test("a block with an error shows the reason and a Reload button that sends the __changes action", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" } } });
|
||||
s.post({ docs: [{ id: "changes", title: "Changes", blocks: [{ id: "c1", error: "No snapshot was taken at the start of this run." }] }] });
|
||||
await tab(s, "Changes").click();
|
||||
const box = s.page.locator("#main .diff-error");
|
||||
await box.waitFor();
|
||||
assert.equal(await textOf(box.locator(".diff-state-msg")), "The changes could not be read: No snapshot was taken at the start of this run.");
|
||||
await box.getByRole("button", { name: "Reload the changes" }).click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code})`);
|
||||
assert.ok(got.actions.some((a) => a.i === "__changes" && a.type === "changes"), JSON.stringify(got.actions));
|
||||
|
||||
// A stale doc is still being read again: the loading rows show.
|
||||
fs.writeFileSync(path.join(s.session, "changes.diff"), DIFF);
|
||||
s.post({ docs: [{ id: "changes", stale: true, blocks: [{ id: "c1", diff: "changes.diff" }] }] });
|
||||
await s.page.locator("#main .diff-view.is-loading .diff-skel-row").first().waitFor();
|
||||
});
|
||||
|
||||
// What the person sees break: a long diff pushing the way to the sign-off off
|
||||
// the screen, or a long line widening the page.
|
||||
test("a long diff scrolls inside its own pane, the way back to the sign-off stays in view, and the added rows differ by theme", async (t) => {
|
||||
const long = Array.from({ length: 640 }, (_, i) => `+line ${i + 1} ${i === 3 ? "x".repeat(600) : ""}`);
|
||||
const text = ["diff --git a/long.txt b/long.txt", "new file mode 100644", "--- /dev/null", "+++ b/long.txt", "@@ -0,0 +1,640 @@", ...long, ""].join("\n");
|
||||
const s = await withChanges(t, text, { items: [SIGNOFF] });
|
||||
await itemCard(s.page, "signoff").waitFor();
|
||||
await openChanges(s);
|
||||
const pane = s.page.locator("#main .diff-pane");
|
||||
assert.equal(await pane.locator(".diff-line").count(), 640);
|
||||
|
||||
// The pane scrolls itself; the column and the page do not grow past the window.
|
||||
const sizes = await pane.evaluate((p) => ({ inner: p.scrollHeight > p.clientHeight, page: document.documentElement.scrollWidth <= window.innerWidth }));
|
||||
assert.ok(sizes.inner, "the diff pane scrolls inside itself");
|
||||
assert.ok(sizes.page, "a long line never gives the page a sideways scroll");
|
||||
// The pane itself scrolls sideways, so its scrollbar sits at the window's
|
||||
// edge of the pane, not under the file's last line.
|
||||
assert.ok(await pane.evaluate((p) => p.scrollWidth > p.clientWidth), "the long line scrolls inside the diff pane");
|
||||
await scrollCard(pane, "end");
|
||||
const back = s.page.locator("#main .doc-head .back-home");
|
||||
assert.ok(await inViewport(s, back), "Back to Questions stays in view with the diff scrolled to its end");
|
||||
assert.ok(await inViewport(s, pane), "the whole diff pane fits in the window");
|
||||
|
||||
// One click from the Changes tab, the sign-off's verdicts are on screen.
|
||||
await back.click();
|
||||
const card = itemCard(s.page, "signoff");
|
||||
await card.waitFor();
|
||||
for (const name of ["Approve this phase", "I want changes"]) {
|
||||
assert.ok(await inViewport(s, card.getByRole("button", { name })), `${name} is inside the window`);
|
||||
}
|
||||
|
||||
await openChanges(s);
|
||||
const added = s.page.locator("#main .diff-line.add").first();
|
||||
await s.page.evaluate(() => document.documentElement.setAttribute("data-theme", "light"));
|
||||
const light = await styleOf(added, "backgroundColor");
|
||||
await s.page.evaluate(() => document.documentElement.setAttribute("data-theme", "dark"));
|
||||
const dark = await styleOf(added, "backgroundColor");
|
||||
assert.notEqual(light, dark, "the added rows take the theme's own soft color");
|
||||
assert.notEqual(light, "rgba(0, 0, 0, 0)");
|
||||
});
|
||||
@@ -445,17 +445,17 @@ test("lessons card: Review on the banner leads to the card over the dashboard, w
|
||||
const dlg = s.page.locator("#lessons-modal");
|
||||
await dlg.locator(".lessons-row").waitFor();
|
||||
assert.equal(await main.getByRole("heading", { name: "What are we doing today?" }).count(), 1, "the menu stays under it");
|
||||
assert.equal(await dlg.getByRole("button", { name: "Send to Plan2Code" }).isDisabled(), true, "nothing chosen yet");
|
||||
assert.equal(await dlg.getByRole("button", { name: "Save lessons" }).isDisabled(), true, "nothing chosen yet");
|
||||
// An emptied Reword field holds the dialog's Send off, as the footer's Send is held elsewhere.
|
||||
await dlg.getByRole("button", { name: "Reword" }).click();
|
||||
const text = dlg.getByLabel("The lesson");
|
||||
await text.waitFor();
|
||||
assert.equal(await dlg.getByRole("button", { name: "Send to Plan2Code" }).isDisabled(), false, "a reword ready to go");
|
||||
assert.equal(await dlg.getByRole("button", { name: "Save lessons" }).isDisabled(), false, "a reword ready to go");
|
||||
await text.fill("");
|
||||
await until(async () => await dlg.getByRole("button", { name: "Send to Plan2Code" }).isDisabled(), 3000);
|
||||
await until(async () => await dlg.getByRole("button", { name: "Save lessons" }).isDisabled(), 3000);
|
||||
await dlg.getByRole("button", { name: "Keep" }).click();
|
||||
await dlg.getByRole("button", { name: "Keep", pressed: true }).waitFor();
|
||||
await dlg.getByRole("button", { name: "Send to Plan2Code" }).click();
|
||||
await dlg.getByRole("button", { name: "Save lessons" }).click();
|
||||
const sent = s.wait(10);
|
||||
assert.equal(sent.code, 0);
|
||||
assert.equal(sent.actions.some((a) => a.i === "__launch"), false, "no skill launched");
|
||||
@@ -467,6 +467,139 @@ test("lessons card: Review on the banner leads to the card over the dashboard, w
|
||||
assert.equal(await dlg.isVisible(), false, "the answered card does not open again");
|
||||
});
|
||||
|
||||
// The dashboard with one lesson waiting, Review pressed and the agent's card up.
|
||||
const LESSON_ID = "20261113-120000-eeeeee";
|
||||
async function reviewOpen(t) {
|
||||
const { s, main } = await dashboard(t, PROJECT("on"), (p) =>
|
||||
writeWaiting(p, { id: LESSON_ID, type: "lesson", text: "Run a page test alone first.", noted: new Date().toISOString() })
|
||||
);
|
||||
await main.locator(".learn-banner").getByRole("button", { name: "Review" }).click();
|
||||
return { s, main, dlg: s.page.locator("#lessons-modal") };
|
||||
}
|
||||
const postCard = (s) => s.post({ items: [CARD([{ ...ROWS[0], id: LESSON_ID }])], agent: { status: "waiting" } });
|
||||
|
||||
test("lessons card: Review shows working at once, and ends when the card opens", async (t) => {
|
||||
const { s, main, dlg } = await reviewOpen(t);
|
||||
const banner = main.locator(".learn-banner");
|
||||
await banner.getByText("Opening lessons…").waitFor();
|
||||
assert.equal(await banner.getAttribute("aria-busy"), "true");
|
||||
assert.equal(await banner.getByRole("button", { name: "Review" }).isDisabled(), true, "no second press while it opens");
|
||||
s.wait(10);
|
||||
postCard(s);
|
||||
await dlg.locator(".lessons-row").waitFor();
|
||||
assert.equal(await banner.getByText("Opening lessons…").count(), 0, "the spinner is gone once the card is up");
|
||||
});
|
||||
|
||||
test("lessons card: Review with nothing to show says so instead of spinning", async (t) => {
|
||||
const { s, main } = await reviewOpen(t);
|
||||
await main.locator(".learn-banner").getByText("Opening lessons…").waitFor();
|
||||
s.wait(10);
|
||||
s.post({ menu: { note: "Nothing is waiting." }, agent: { status: "working" } });
|
||||
s.post({ agent: { status: "waiting" } });
|
||||
await s.page.getByText("No lessons are waiting any more.").waitFor();
|
||||
assert.equal(await main.locator(".learn-banner").getByText("Opening lessons…").count(), 0);
|
||||
});
|
||||
|
||||
test("lessons card: Not now and the corner close leave every lesson waiting and tell the agent", async (t) => {
|
||||
for (const how of ["Not now", "x", "Escape"]) {
|
||||
const { s, dlg } = await reviewOpen(t);
|
||||
s.wait(10);
|
||||
postCard(s);
|
||||
await dlg.locator(".lessons-row").waitFor();
|
||||
assert.equal(await dlg.getByRole("button", { name: "Close without saving" }).count(), 1, "a corner close is there");
|
||||
if (how === "Not now") await dlg.getByRole("button", { name: "Not now" }).click();
|
||||
else if (how === "x") await dlg.getByRole("button", { name: "Close without saving" }).click();
|
||||
else await s.page.keyboard.press("Escape");
|
||||
const sent = s.wait(10);
|
||||
assert.equal(sent.code, 0, how);
|
||||
assert.deepEqual(sent.actions.find((a) => a.i === "lessons").decisions, [], `${how}: nothing decided`);
|
||||
await dlg.waitFor({ state: "hidden" });
|
||||
}
|
||||
});
|
||||
|
||||
test("lessons card: closing with choices made asks first, and Keep editing goes back", async (t) => {
|
||||
const { s, dlg } = await reviewOpen(t);
|
||||
s.wait(10);
|
||||
postCard(s);
|
||||
await dlg.getByRole("button", { name: "Keep" }).click();
|
||||
await dlg.getByRole("button", { name: "Keep", pressed: true }).waitFor();
|
||||
await s.page.keyboard.press("Escape");
|
||||
const ask = dlg.locator(".lessons-unsaved");
|
||||
await ask.waitFor();
|
||||
assert.match(await textOf(ask), /You have choices that are not saved\./);
|
||||
await ask.getByRole("button", { name: "Keep editing" }).click();
|
||||
await ask.waitFor({ state: "hidden" });
|
||||
assert.equal(await dlg.isVisible(), true, "still open");
|
||||
assert.equal(await dlg.getByRole("button", { name: "Keep", pressed: true }).count(), 1, "the choice is kept");
|
||||
// Discard and close leaves everything waiting.
|
||||
await dlg.getByRole("button", { name: "Close without saving" }).click();
|
||||
await ask.getByRole("button", { name: "Discard and close" }).click();
|
||||
const sent = s.wait(10);
|
||||
assert.deepEqual(sent.actions.find((a) => a.i === "lessons").decisions, []);
|
||||
await dlg.waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
test("lessons card: Save lessons shows saving, locks the card, then the banner takes over until the agent is done", async (t) => {
|
||||
const { s, main, dlg } = await reviewOpen(t);
|
||||
s.wait(10);
|
||||
postCard(s);
|
||||
await dlg.getByRole("button", { name: "Keep" }).click();
|
||||
await dlg.getByRole("button", { name: "Keep", pressed: true }).waitFor();
|
||||
// Hold the send so the saving state can be seen.
|
||||
let release;
|
||||
const held = new Promise((r) => (release = r));
|
||||
await s.page.route("**/submit", async (route) => {
|
||||
await held;
|
||||
await route.continue();
|
||||
});
|
||||
await dlg.getByRole("button", { name: "Save lessons" }).click();
|
||||
await dlg.getByText("Saving…").waitFor();
|
||||
assert.equal(await dlg.getAttribute("aria-busy"), "true");
|
||||
assert.equal(await dlg.getByRole("button", { name: "Not now" }).isDisabled(), true);
|
||||
assert.equal(await dlg.getByRole("button", { name: "Close without saving" }).isDisabled(), true);
|
||||
release();
|
||||
await dlg.waitFor({ state: "hidden" });
|
||||
const sent = s.wait(10);
|
||||
assert.deepEqual(sent.actions.find((a) => a.i === "lessons").decisions, [{ id: LESSON_ID, choice: "Keep" }]);
|
||||
await main.locator(".learn-banner").getByText("Saving your lessons…").waitFor();
|
||||
s.post({ menu: { note: "Kept 1 lesson." }, agent: { status: "working" } });
|
||||
s.post({ agent: { status: "waiting" } });
|
||||
await main.getByText("Kept 1 lesson.").waitFor();
|
||||
await until(async () => (await main.getByText("Saving your lessons…").count()) === 0, 5000);
|
||||
});
|
||||
|
||||
test("lessons card: a refused send keeps the dialog open with the choice still made", async (t) => {
|
||||
const { s, dlg } = await reviewOpen(t);
|
||||
s.wait(10);
|
||||
postCard(s);
|
||||
await dlg.getByRole("button", { name: "Keep" }).click();
|
||||
await dlg.getByRole("button", { name: "Keep", pressed: true }).waitFor();
|
||||
await s.page.route("**/submit", (route) => route.fulfill({ status: 409, contentType: "application/json", body: "{}" }));
|
||||
await dlg.getByRole("button", { name: "Save lessons" }).click();
|
||||
await until(async () => (await dlg.getByText("Saving…").count()) === 0, 5000);
|
||||
assert.equal(await dlg.isVisible(), true, "still open");
|
||||
assert.equal(await dlg.getByRole("button", { name: "Keep", pressed: true }).count(), 1, "the choice is kept");
|
||||
});
|
||||
|
||||
test("lessons card: Not now carries a typed note, and a click outside closes only while nothing is chosen", async (t) => {
|
||||
const { s, dlg } = await reviewOpen(t);
|
||||
s.wait(10);
|
||||
postCard(s);
|
||||
await dlg.locator(".lessons-row").waitFor();
|
||||
// Outside click with a choice made: stays open.
|
||||
await dlg.getByRole("button", { name: "Keep" }).click();
|
||||
await dlg.getByRole("button", { name: "Keep", pressed: true }).waitFor();
|
||||
await s.page.mouse.click(5, 5);
|
||||
assert.equal(await dlg.isVisible(), true, "a stray click keeps the dialog while a choice is made");
|
||||
await dlg.getByRole("button", { name: "Keep", pressed: true }).click();
|
||||
await dlg.getByRole("button", { name: "Keep" }).first().waitFor();
|
||||
await dlg.getByLabel("Anything to add?").fill("Ask me again next week.");
|
||||
await dlg.getByRole("button", { name: "Not now" }).click();
|
||||
const sent = s.wait(10);
|
||||
assert.match(sent.reply, /Ask me again next week\./);
|
||||
assert.deepEqual(sent.actions.find((a) => a.i === "lessons").decisions, []);
|
||||
});
|
||||
|
||||
test("the loop stop card says when lessons are waiting", async (t) => {
|
||||
const project = tempProject(PROJECT("on"));
|
||||
writeWaiting(project, { id: "20261113-120000-999999", type: "lesson", text: "Waits.", noted: new Date().toISOString() });
|
||||
|
||||
@@ -992,6 +992,177 @@ test("an image block under the session's shots folder round-trips, and /shots/ s
|
||||
}
|
||||
});
|
||||
|
||||
// The Changes tab: a `diff` block names a .diff file saved directly in the
|
||||
// session folder (changes.mjs diff). The server reads it like a file block,
|
||||
// keeps the name and the text on the block and never lets it reach outside.
|
||||
test("a diff block reads a .diff file in the session folder, refreshes and turns back into text", () => {
|
||||
const res = cli(["open", "--workflow", "implement", "--no-open"]);
|
||||
const sid = res.json.sid;
|
||||
const dir = res.json.session;
|
||||
const post = (name, patch, opts) => cli(["post", "--session", sid, "--file", payload(name, patch)], opts);
|
||||
const doc = () => readState(dir).docs.find((d) => d.id === "changes");
|
||||
try {
|
||||
const first = "diff --git a/a.txt b/a.txt\n--- a/a.txt\n+++ b/a.txt\n@@ -1 +1 @@\n-old\n+new TASK_COMPLETE\n";
|
||||
fs.writeFileSync(path.join(dir, "changes.diff"), first);
|
||||
post("diff-ok.json", { docs: [{ id: "changes", title: "Changes", blocks: [{ id: "c1", diff: "changes.diff" }] }] });
|
||||
const block = doc().blocks[0];
|
||||
assert.equal(block.diff, "changes.diff");
|
||||
assert.equal(block.text, first, "the file's text, loop markers in a diff are not the agent's words");
|
||||
assert.equal(block.md, undefined, "a diff block holds no markdown");
|
||||
assert.equal(block.state, "settled");
|
||||
|
||||
// The same file again is not a new version; a changed one is, re-sent or refreshed.
|
||||
const v1 = doc().version;
|
||||
post("diff-same.json", { docs: [{ id: "changes", blocks: [{ id: "c1", diff: "changes.diff" }] }] });
|
||||
assert.equal(doc().version, v1);
|
||||
const second = first + "+more\n";
|
||||
fs.writeFileSync(path.join(dir, "changes.diff"), second);
|
||||
post("diff-resend.json", { docs: [{ id: "changes", blocks: [{ id: "c1", diff: "changes.diff" }] }] });
|
||||
assert.equal(doc().blocks[0].text, second);
|
||||
assert.equal(doc().version, v1 + 1);
|
||||
const third = second + "+again\n";
|
||||
fs.writeFileSync(path.join(dir, "changes.diff"), third);
|
||||
post("diff-refresh.json", { docs: [{ id: "changes", refresh: true }] });
|
||||
assert.equal(doc().blocks[0].text, third);
|
||||
assert.equal(doc().version, v1 + 2);
|
||||
|
||||
// An empty file is the page's empty state, not an error.
|
||||
fs.writeFileSync(path.join(dir, "changes.diff"), "");
|
||||
post("diff-empty.json", { docs: [{ id: "changes", refresh: true }] });
|
||||
assert.equal(doc().blocks[0].text, "");
|
||||
|
||||
// A diff block cannot carry other content.
|
||||
const both = post("diff-md.json", { docs: [{ id: "changes", blocks: [{ id: "c2", diff: "changes.diff", md: "text" }] }] }, { expectFail: true });
|
||||
assert.equal(both.status, 3);
|
||||
assert.match(both.stderr, /cannot also carry "md", "file" or "image"/);
|
||||
|
||||
// Text over it: the block stops being a diff and a refresh no longer reads it.
|
||||
post("diff-to-md.json", { docs: [{ id: "changes", blocks: [{ id: "c1", md: "Plain words." }] }] });
|
||||
assert.equal(doc().blocks[0].diff, undefined);
|
||||
assert.equal(doc().blocks[0].text, undefined);
|
||||
assert.equal(doc().blocks[0].md, "Plain words.");
|
||||
const none = post("diff-none.json", { docs: [{ id: "changes", refresh: true }] }, { expectFail: true });
|
||||
assert.match(none.stderr, /found no file or diff blocks to re-read/);
|
||||
} finally {
|
||||
cli(["stop", "--session", sid, "--force"]);
|
||||
}
|
||||
});
|
||||
|
||||
// When the changes could not be read, the agent sends the plain reason as the
|
||||
// block's `error` instead of a diff; a diff sent later replaces it.
|
||||
test("a diff block may carry one line of error instead of a diff, never both", () => {
|
||||
const res = cli(["open", "--workflow", "implement", "--no-open"]);
|
||||
const sid = res.json.sid;
|
||||
const dir = res.json.session;
|
||||
const post = (name, patch, opts) => cli(["post", "--session", sid, "--file", payload(name, patch)], opts);
|
||||
const block = () => readState(dir).docs.find((d) => d.id === "changes").blocks[0];
|
||||
try {
|
||||
post("err-ok.json", { docs: [{ id: "changes", title: "Changes", blocks: [{ id: "c1", error: " No snapshot was taken at the start of this run. " }] }] });
|
||||
assert.equal(block().error, "No snapshot was taken at the start of this run.");
|
||||
assert.equal(block().diff, undefined);
|
||||
assert.equal(block().text, undefined);
|
||||
assert.equal(block().state, "settled");
|
||||
|
||||
for (const [name, b, why] of [
|
||||
["err-both.json", { id: "c1", diff: "changes.diff", error: "x" }, /carries "diff" or "error", never both/],
|
||||
["err-md.json", { id: "c1", error: "x", md: "text" }, /an error block cannot also carry "md", "file" or "image"/],
|
||||
["err-lines.json", { id: "c1", error: "one\ntwo" }, /must be one line of prose/],
|
||||
["err-blank.json", { id: "c1", error: " " }, /must be one line of prose/],
|
||||
["err-type.json", { id: "c1", error: 3 }, /must be one line of prose/],
|
||||
]) {
|
||||
fs.writeFileSync(path.join(dir, "changes.diff"), "diff --git a/a b/a\n");
|
||||
const r = post(name, { docs: [{ id: "changes", blocks: [b] }] }, { expectFail: true });
|
||||
assert.equal(r.status, 3, name);
|
||||
assert.match(r.stderr, why, name);
|
||||
}
|
||||
|
||||
// A diff over it clears the error, and an error over a diff clears the text.
|
||||
const text = "diff --git a/a.txt b/a.txt\n--- a/a.txt\n+++ b/a.txt\n@@ -1 +1 @@\n-old\n+new\n";
|
||||
fs.writeFileSync(path.join(dir, "changes.diff"), text);
|
||||
post("err-to-diff.json", { docs: [{ id: "changes", blocks: [{ id: "c1", diff: "changes.diff" }] }] });
|
||||
assert.equal(block().text, text);
|
||||
assert.equal(block().error, undefined);
|
||||
post("diff-to-err.json", { docs: [{ id: "changes", blocks: [{ id: "c1", error: "The snapshot is gone." }] }] });
|
||||
assert.equal(block().error, "The snapshot is gone.");
|
||||
assert.equal(block().diff, undefined);
|
||||
assert.equal(block().text, undefined);
|
||||
} finally {
|
||||
cli(["stop", "--session", sid, "--force"]);
|
||||
}
|
||||
});
|
||||
|
||||
test("a diff block refuses a path, a wrong extension, a missing file and a link out of the session folder", () => {
|
||||
const res = cli(["open", "--workflow", "implement", "--no-open"]);
|
||||
const sid = res.json.sid;
|
||||
const dir = res.json.session;
|
||||
const outside = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-diff-outside-"));
|
||||
const post = (name, diff) => cli(["post", "--session", sid, "--file", payload(name, { docs: [{ id: "changes", blocks: [{ id: "c1", diff }] }] })], { expectFail: true });
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "sub"), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "sub", "changes.diff"), "x\n");
|
||||
fs.writeFileSync(path.join(dir, "notes.txt"), "x\n");
|
||||
fs.writeFileSync(path.join(outside, "secret.diff"), "x\n");
|
||||
const cases = [
|
||||
["sub/changes.diff", /needs a plain name/],
|
||||
["sub\\changes.diff", /needs a plain name/],
|
||||
["../changes.diff", /needs a plain name/],
|
||||
[path.join(outside, "secret.diff"), /needs a plain name/],
|
||||
["notes.txt", /needs a plain name/],
|
||||
["missing.diff", /does not exist in the session folder. Run changes.mjs diff first/],
|
||||
];
|
||||
for (const [name, message] of cases) {
|
||||
const r = post("diff-bad.json", name);
|
||||
assert.equal(r.status, 3, name);
|
||||
assert.match(r.stderr, message, name);
|
||||
}
|
||||
try {
|
||||
fs.symlinkSync(path.join(outside, "secret.diff"), path.join(dir, "link.diff"), "file");
|
||||
} catch {
|
||||
console.log("skipped the link case: this platform cannot create a symbolic link here");
|
||||
return;
|
||||
}
|
||||
const linked = post("diff-link.json", "link.diff");
|
||||
assert.equal(linked.status, 3);
|
||||
assert.match(linked.stderr, /is outside the session folder/);
|
||||
} finally {
|
||||
cli(["stop", "--session", sid, "--force"]);
|
||||
fs.rmSync(outside, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a diff file over 512 KB is cut at a whole line with the too-large line, never an error", () => {
|
||||
const res = cli(["open", "--workflow", "implement", "--no-open"]);
|
||||
const sid = res.json.sid;
|
||||
const dir = res.json.session;
|
||||
try {
|
||||
const line = "+" + "x".repeat(99) + "\n";
|
||||
fs.writeFileSync(path.join(dir, "big.diff"), line.repeat(Math.ceil((600 * 1024) / line.length)));
|
||||
cli(["post", "--session", sid, "--file", payload("diff-big.json", { docs: [{ id: "changes", blocks: [{ id: "c1", diff: "big.diff" }] }] })]);
|
||||
const text = readState(dir).docs.find((d) => d.id === "changes").blocks[0].text;
|
||||
const notice = "\\ No more lines shown: this change is too large to show in full.\n";
|
||||
assert.ok(text.endsWith(notice), "ends with the plain line");
|
||||
const kept = text.slice(0, -notice.length);
|
||||
assert.ok(Buffer.byteLength(kept) <= 512 * 1024, "within the cap");
|
||||
assert.ok(kept.endsWith("\n") && kept.split("\n").every((l) => l === "" || l === line.trimEnd()), "only whole lines");
|
||||
// A file changes.mjs already cut, and that carries the line, does not get a second one.
|
||||
fs.writeFileSync(path.join(dir, "cut.diff"), "diff --git a/a b/a\n" + notice);
|
||||
cli(["post", "--session", sid, "--file", payload("diff-cut.json", { docs: [{ id: "changes", blocks: [{ id: "c1", diff: "cut.diff" }] }] })]);
|
||||
assert.equal(readState(dir).docs.find((d) => d.id === "changes").blocks[0].text.split(notice).length, 2);
|
||||
} finally {
|
||||
cli(["stop", "--session", sid, "--force"]);
|
||||
}
|
||||
});
|
||||
|
||||
// The server and changes.mjs each spell the too-large line: they must match.
|
||||
test("the too-large line the server adds is the one changes.mjs adds", async () => {
|
||||
const { capPatch } = await import("../src/skill-scripts/changes.mjs");
|
||||
const { DIFF_TOO_LARGE } = await import("../src/web-console/patches.mjs");
|
||||
const patch = "diff --git a/a b/a\n" + "+x\n".repeat(50) + "diff --git a/b b/b\n" + "+y\n".repeat(50);
|
||||
const cut = capPatch(patch, 200);
|
||||
assert.equal(cut.truncated, true);
|
||||
assert.ok(cut.patch.includes(DIFF_TOO_LARGE + "\n"));
|
||||
});
|
||||
|
||||
// /app.css is the files under public/styles/ joined in CSS_ORDER (one newline
|
||||
// after each), then the accent rules. The files themselves are never served.
|
||||
test("/app.css is the style files joined in CSS_ORDER with the accent rules last", async () => {
|
||||
|
||||
+131
-10
@@ -37,8 +37,18 @@
|
||||
* Preferences in the web console) are listed after the built-ins and started the same way, with
|
||||
* `--cli <id>` or from the menu. Their rules are copied from src/web-console/agents.mjs below.
|
||||
*
|
||||
* `--pick-folder` (passed by the desktop shortcut, never forwarded to the CLI) asks for the
|
||||
* project folder with a native folder picker first, starting on the folder picked last time.
|
||||
* Folders: the launcher keeps the last 5 project folders opened, newest first, in
|
||||
* ~/.plan2code/launcher.json (`recentFolders`, with `lastFolder` always its first entry; the
|
||||
* desktop app reads and writes the same list by the same rule). At a terminal with recent folders
|
||||
* to offer, it asks which folder to open in a numbered menu: the current folder first (Enter
|
||||
* keeps it), the recent folders, then Choose another folder... for the native folder picker.
|
||||
* With none to offer, or no terminal, it opens in the current folder without asking. A folder is
|
||||
* added to the list only once it passes the project check.
|
||||
*
|
||||
* `--pick-folder` (passed by the desktop shortcut, never forwarded to the CLI) puts Choose a
|
||||
* folder... first in that menu (Enter opens the native folder picker, starting on the folder
|
||||
* opened last time, the first recent folder), with the recent folders under it; with none to
|
||||
* offer it opens the picker straight away.
|
||||
*
|
||||
* When the desktop app is installed (~/.plan2code/app/) and a display exists, `plan2code` opens
|
||||
* the app on the chosen folder, agent and model instead of running the agent in this terminal.
|
||||
@@ -714,7 +724,7 @@ function isDirectory(dir) {
|
||||
}
|
||||
}
|
||||
|
||||
/** `~/.plan2code/launcher.json`: `{ lastFolder, lastCli, lastModels }`, any key possibly missing. */
|
||||
/** `~/.plan2code/launcher.json`: `{ lastFolder, recentFolders, lastCli, lastModels }`, any key possibly missing. */
|
||||
function readState() {
|
||||
try {
|
||||
const state = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
|
||||
@@ -736,6 +746,104 @@ function readLastFolder() {
|
||||
return lastFolder && isDirectory(lastFolder) ? lastFolder : os.homedir();
|
||||
}
|
||||
|
||||
/** How many recent project folders the list keeps. */
|
||||
const RECENT_FOLDERS_MAX = 5;
|
||||
|
||||
/** One trailing `\` or `/` off a path, but never off a root (`C:\` or `/`). */
|
||||
function trimFolder(p) {
|
||||
if (p.length > 1 && /[\\/]$/.test(p) && !/^[A-Za-z]:[\\/]$/.test(p)) return p.slice(0, -1);
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two paths name the same folder: a trailing separator is ignored, and case is on
|
||||
* Windows. The desktop app's `same_folder` (project.rs) holds the same rule, both to
|
||||
* scripts/fixtures/recent-folders-cases.json.
|
||||
*/
|
||||
function sameFolder(a, b, platform = process.platform) {
|
||||
const x = trimFolder(a);
|
||||
const y = trimFolder(b);
|
||||
return platform === 'win32' ? x.toLowerCase() === y.toLowerCase() : x === y;
|
||||
}
|
||||
|
||||
/** The recent folders in `launcher.json`'s state: `recentFolders`, else `[lastFolder]`, else none. */
|
||||
function readRecent(state) {
|
||||
const { recentFolders, lastFolder } = state || {};
|
||||
if (Array.isArray(recentFolders)) {
|
||||
return recentFolders.filter((x) => typeof x === 'string' && x !== '').slice(0, RECENT_FOLDERS_MAX);
|
||||
}
|
||||
return typeof lastFolder === 'string' && lastFolder !== '' ? [lastFolder] : [];
|
||||
}
|
||||
|
||||
/** A new list with `dir` first, an earlier entry for the same folder removed, cut to the max. */
|
||||
function pushRecent(list, dir, platform = process.platform) {
|
||||
return [dir, ...list.filter((x) => !sameFolder(x, dir, platform))].slice(0, RECENT_FOLDERS_MAX);
|
||||
}
|
||||
|
||||
/** The folders of `list` worth offering: ones that still exist, minus the one in `exclude`. */
|
||||
function listRecent(list, { exists = isDirectory, exclude = null, platform = process.platform } = {}) {
|
||||
return list.filter((x) => exists(x) && !(exclude && sameFolder(x, exclude, platform)));
|
||||
}
|
||||
|
||||
/** Put `dir` at the top of the recent folders; `lastFolder` stays the newest entry. */
|
||||
function recordFolder(dir) {
|
||||
const recentFolders = pushRecent(readRecent(readState()), dir);
|
||||
saveState({ recentFolders, lastFolder: recentFolders[0] });
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows of the folder menu. From the `plan2code` command: the current folder first (Enter
|
||||
* keeps it), the recent folders, then a row to browse. From the desktop shortcut: the browse row
|
||||
* first, then the recent folders. `recent` comes already filtered by listRecent.
|
||||
*/
|
||||
function folderMenuRows({ fromShortcut, cwd, recent }) {
|
||||
const name = (dir) => path.basename(dir) || dir;
|
||||
const folder = (dir, detail) => ({ kind: 'folder', dir, name: name(dir), detail, label: `${name(dir)} ${detail}` });
|
||||
const folders = recent.map((dir) => folder(dir, dir));
|
||||
if (fromShortcut) return [{ kind: 'browse', label: 'Choose a folder...' }, ...folders];
|
||||
return [
|
||||
folder(cwd, `${cwd} (current folder)`),
|
||||
...folders,
|
||||
{ kind: 'browse', label: 'Choose another folder...' },
|
||||
];
|
||||
}
|
||||
|
||||
/** The row an answer to the folder menu picks: Enter is row 1, a number its row, else null (ask again). */
|
||||
function folderMenuPick(rows, answer) {
|
||||
const text = String(answer || '').trim();
|
||||
if (!text) return rows[0];
|
||||
if (!/^\d+$/.test(text)) return null;
|
||||
const n = Number(text);
|
||||
return n >= 1 && n <= rows.length ? rows[n - 1] : null;
|
||||
}
|
||||
|
||||
/** One folder menu row as printed: the folder name plain, its path dimmed. */
|
||||
function folderMenuLine(row) {
|
||||
if (row.kind !== 'folder') return row.label;
|
||||
return `${row.name} ${c.dim(row.detail)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask which project folder to open, from the recent folders. `{ kind: 'folder', dir }` opens
|
||||
* that folder; `{ kind: 'browse' }` asks with the folder picker. With no recent folders to offer
|
||||
* or no terminal to ask on, nothing is printed and the answer is what it was before the menu:
|
||||
* the current folder, or the picker from the shortcut.
|
||||
*/
|
||||
async function chooseFolder({ fromShortcut, cwd }) {
|
||||
const recent = listRecent(readRecent(readState()), { exclude: fromShortcut ? null : cwd });
|
||||
if (!recent.length || !process.stdin.isTTY) return { kind: fromShortcut ? 'browse' : 'folder', dir: cwd };
|
||||
const rows = folderMenuRows({ fromShortcut, cwd, recent });
|
||||
console.log('');
|
||||
console.log(c.bright('Which project folder?'));
|
||||
console.log('');
|
||||
rows.forEach((row, i) => console.log(` ${c.cyan(`${i + 1})`)} ${folderMenuLine(row)}`));
|
||||
for (;;) {
|
||||
const row = folderMenuPick(rows, await ask(`Choice ${c.green('[1]')}: `));
|
||||
if (row) return row;
|
||||
console.log(c.dim(`Type a number from 1 to ${rows.length}, or press Enter for row 1.`));
|
||||
}
|
||||
}
|
||||
|
||||
function ask(prompt) {
|
||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
// readline swallows Ctrl+C while it owns the terminal; treat it as leaving.
|
||||
@@ -1437,24 +1545,37 @@ async function pickFolder() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The folder to open in, confirmed as a project: process.cwd(), or the shortcut's folder pick
|
||||
* plus the same check. `{ cwd }` to carry on; `{ exit }` with the code to leave on when the
|
||||
* person canceled, picked a non-folder, or declined the project check.
|
||||
* The folder to open in, confirmed as a project: picked from the folder menu (chooseFolder: the
|
||||
* current folder, a recent one, or the folder picker), plus the project check. The folder is
|
||||
* recorded in the recent folders only once the check passes. `{ cwd }` to carry on; `{ exit }`
|
||||
* with the code to leave on when the person canceled, picked a non-folder, or declined the
|
||||
* project check.
|
||||
*/
|
||||
async function projectCwd(fromShortcut) {
|
||||
let cwd = process.cwd();
|
||||
if (fromShortcut) {
|
||||
const choice = await chooseFolder({ fromShortcut, cwd: process.cwd() });
|
||||
let cwd;
|
||||
if (choice.kind === 'browse') {
|
||||
const folder = await pickFolder();
|
||||
if (!folder) return { exit: 0 };
|
||||
if (!isDirectory(folder)) {
|
||||
console.error(`${ce.red('plan2code:')} ${folder} is not a folder.`);
|
||||
return { exit: 1 };
|
||||
}
|
||||
saveState({ lastFolder: folder });
|
||||
cwd = folder;
|
||||
console.log(`Opening Plan2Code in ${c.cyan(folder)}`);
|
||||
} else {
|
||||
cwd = choice.dir;
|
||||
if (cwd !== process.cwd()) {
|
||||
// A recent folder can be deleted between the menu listing it and the pick.
|
||||
if (!isDirectory(cwd)) {
|
||||
console.error(`${ce.red('plan2code:')} ${cwd} is not a folder.`);
|
||||
return { exit: 1 };
|
||||
}
|
||||
console.log(`Opening Plan2Code in ${c.cyan(cwd)}`);
|
||||
}
|
||||
}
|
||||
if (!(await confirmProject(cwd))) return { exit: 0 };
|
||||
recordFolder(cwd);
|
||||
return { cwd };
|
||||
}
|
||||
|
||||
@@ -1726,4 +1847,4 @@ async function launch() {
|
||||
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
||||
if (require.main === module) launch();
|
||||
|
||||
module.exports = { 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 };
|
||||
module.exports = { 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 };
|
||||
File diff suppressed because it is too large.
Load diff
+53
-40
@@ -4,28 +4,36 @@ Start all UPDATE DEPENDENCIES MODE responses with '📦 [UPDATE DEPENDENCIES]'
|
||||
|
||||
## Role
|
||||
|
||||
Finds the outdated dependencies in the person's own project, labels each update Safe, Check first or Warning with its reason, applies only the updates the person picks, in batches, runs the project's install and checks after each batch, and puts back whatever breaks, leaving the tree exactly as found. Updates that need source changes are handed to Quick Task or Plan as a brief, never made here.
|
||||
Finds the outdated dependencies in the person's own project, labels each update Safe (should just work), Check first (likely fine, worth a look) or Warning (your code probably needs changing) with its reason, applies only the updates the person picks, in groups, runs the project's install and checks after each group, and undoes whatever breaks, leaving the project exactly as found. Small breakage may be fixed with the person's approval; bigger code changes go to Quick Task or Plan as an upgrade brief.
|
||||
|
||||
Plain words for the person: version list (lockfile), package list (manifest), small fix, new features, big change, group (batch), upgrade brief (hand-off), saved in git (tracked), undone (put back), locked to one exact version (pinned), size of the change (jump). Field names stay; sentences a person reads use these words.
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before running a script: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow deps` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-deps/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/deps.md. The start screen, the folder card, the pick list, the progress, the hand-off card and the report all go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
The FIRST thing you do, before anything else in this file, before running a script: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow deps` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-deps/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/deps.md. Every card, the progress and the report go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
|
||||
## Project Context
|
||||
|
||||
Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything it says about slow suites. The test map is what tells the run which checks cover a folder; without one the run discovers commands from the project's config files and the person confirms them. The tool never writes the test map.
|
||||
Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything it says about slow suites. The test map says which checks cover a folder; without one, commands are discovered from config files and the person confirms them. Never write the test map.
|
||||
|
||||
## Scripts
|
||||
|
||||
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-deps/scripts/` globally). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says. `<run>` is the run folder `detect` prints.
|
||||
|
||||
- `node "<S>/deps.mjs" detect`: makes the run folder; prints `lockfiles` (`lockfile`, `ecosystem`, `manager`, `members`, `tracked`, `dirty` files already changed, `updates` quick count, `install` command), `missingTools` (package managers not on this machine), `noLockfile` (list only), `notCovered` (ecosystems not covered yet) and `unrelatedChanges`.
|
||||
- `node "<S>/deps.mjs" detect`: makes the run folder; prints `lockfiles` (`lockfile`, `ecosystem`, `manager`, `members`, `tracked`, `dirty`, `updates`, `install`), `missingTools`, `noLockfile` (list only), `notCovered` and `unrelatedChanges`.
|
||||
- `deps.mjs scan --run <run> [--folders a,b] [--notes]`: writes `scan.json` (rows, `held`, `notScanned`, `stillOpen`, `checks` per lockfile, `noChecks`, `missingTools` with each plugin's `install` line); prints counts. Exit 3 `no registry answered`: every lookup failed.
|
||||
- `deps.mjs notes --run <run> --id <row>`: the release notes between a row's current and target versions (`source`, `url`, `text`, `truncated`).
|
||||
- `deps.mjs label --run <run> --records <file>`: the label rules over `scan.json` and the records; prints `labels` (`id`, `label` safe, check-first or warning, `reasons[]`).
|
||||
- `deps.mjs fit --run <run>`: rows held back for the runtime get the newest version that fits (`rows`, `best`, `needs`); `unknown` ids it cannot answer.
|
||||
- `deps.mjs pins --run <run>`: finds each row's exact version written in the project's own files (`pins.json`).
|
||||
- `deps.mjs label --run <run> --records <file>`: the label rules over `scan.json`, the records and `pins.json`; prints `labels` (`id`, `label` safe, check-first or warning, `reasons[]`, `reasonsPlain[]`).
|
||||
- `deps.mjs checks --run <run> [--batch <b>]`: check ids for the baseline, or a group's `install` and `commands`; `full` is the full suite.
|
||||
- `deps.mjs baseline` and `compare --batch <b>`, each `--run <run> --check <id> --log <file> --outcome <o> [--retry-log <file> --retry-outcome <o>]`: record a check on the untouched tree; after a group, `blame` says whether it broke something that passed before.
|
||||
- `deps.mjs batches --run <run> --picks <ids>` or `--split <batch>`: the check rounds, and the narrowing of a failed one.
|
||||
- `deps.mjs backup --run <run> --batch <b>`: copies the batch's manifests and lockfile (and a pip freeze) outside the project.
|
||||
- `deps.mjs apply --run <run> --batch <b>`: runs the package manager's own update for the batch; prints `changed`, `rangeRaised`, `unpicked`, `offTarget`, `skipped`, `undoFailed`, `needsNewerRuntime`, `failed`, `tail`.
|
||||
- `deps.mjs restore --run <run> --batch <b> --verify`: the byte-for-byte put-back; prints `verified`, `mismatched`, `extra` and the `reinstall` command.
|
||||
- `deps.mjs fix --run <run> --batch <b> --file <f> --from <old> --to <new>`: one approved change in one file after `apply`, backed up so `restore` undoes it.
|
||||
- `deps.mjs restore --run <run> --batch <b> --verify`: the byte-for-byte put-back; prints `verified`, `mismatched`, `fixed`, `extra` and the `reinstall` command.
|
||||
- `deps.mjs install-tool --run <run> --tool <name>`: the exact install `command` for a scanner in `missingTools`; runs nothing.
|
||||
- `deps.mjs handoff --run <run> --ids <ids>`: writes `specs/<package>-upgrade/UPGRADE-<YYYYMMDD>.md` per ticked row.
|
||||
- `deps.mjs cleanup --run <run>`: removes the run folder.
|
||||
- `node "<S>/test-map.mjs" read`, `node "<S>/test-commands.mjs" discover --root <folder>` and `node "<S>/run-check.mjs" --cmd <c> --cwd <d> --timeout <s> --log <file>` (`outcome` passed, failed, timeout or not-started, `exit`, `seconds`, `tail`).
|
||||
@@ -33,8 +41,8 @@ Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything
|
||||
## Hard limits
|
||||
|
||||
- **Never** commit, push, stage, stash or open a PR. Read-only git is fine; the changes stay unstaged for the person.
|
||||
- **Never** add a dependency, and never install a scanner or tool (`npm install -g`, `cargo install`, `pip install pip-audit`, `go install`). A missing tool is named with its install line for the person to run.
|
||||
- **Never** edit source code. Write only manifests and lockfiles (always through `apply` and `restore`, never by hand), and an `UPGRADE-*.md` brief only for a row the person ticks.
|
||||
- **Never** add a dependency. A missing scanner is offered on one card with the exact `command` from `install-tool`, run only after approval and only through `run-check.mjs`, then Step 2's `scan` and `fit` again. Say it changes this machine, not the project.
|
||||
- Manifests and lockfiles change only through `apply` and `restore`, never by hand. Any other file changes only through `fix`, one approval per change; an `UPGRADE-*.md` brief only for a row the person ticks.
|
||||
- **Never** update anything not picked. An update command is only ever run by `apply`; you never run one yourself.
|
||||
- **Every put-back leaves the tree exactly as found**: `restore --verify` and a reinstall, every time.
|
||||
- Never touch registry credentials, never use `--force`, never write an override.
|
||||
@@ -51,90 +59,95 @@ When your tool can start helpers (subagents) and they are not switched off for t
|
||||
|
||||
### Step 1: Detect and start
|
||||
|
||||
Run `detect`. Then, on one card answered together:
|
||||
Run `detect`. The start screen asks nothing: a short summary with a Start button. The notes are always read (`scan` runs with `--notes`), said once: "I will read what each update changes before judging it." Then:
|
||||
|
||||
1. **Release notes** (on by default, the recommended answer): read each update's release notes before labeling. Skipped, every row counts as notes not read, so nothing can be Safe, patches included.
|
||||
2. **Unrelated changes:** when `unrelatedChanges` is above 0, a one-line note that they stay as they are and the run never touches them.
|
||||
3. **Already changed manifests:** when any lockfile has `dirty` files, a confirm naming each one: carrying on backs them up as found and puts them back as found, and the report marks those changes as already there.
|
||||
1. **Unrelated changes:** when `unrelatedChanges` is above 0, one line that those files stay as they are and the run never touches them.
|
||||
2. **Already changed:** when any lockfile has `dirty` files, a confirm naming each one: "These files already have changes. I back them up as they are and undo to exactly that." The report marks those changes as already there.
|
||||
|
||||
Also say, in one line each: `missingTools` (that package manager is not on this machine: name it and its lockfiles, which are not scanned), `noLockfile` (listed only: no lockfile to put back), `notCovered` (not covered yet), and once, any lockfile with `tracked: false` (`git diff` will not show its changes). No `lockfiles` at all: say so and finish.
|
||||
Also say, in one line each: `missingTools` ("`cargo` is not installed here, so `plan2code-app` is not checked"), `noLockfile` ("`plan2code-web` has no version list, so I list it but cannot update it"), `notCovered` ("I do not handle Maven projects yet, so `pom.xml` is left alone"), and once, any lockfile with `tracked: false` ("These files are not saved in git, so `git diff` will not show their changes"). No `lockfiles` at all: say so and finish.
|
||||
|
||||
### Step 2: Folders
|
||||
|
||||
One card listing every folder that holds a lockfile, with its ecosystem and `updates` count, all ticked. The person unticks what to leave out. Run `scan --run <run> --folders <picked>` (add `--notes` when notes are on).
|
||||
One card listing every folder with a version list, with its ecosystem and `updates` count, all ticked. The person unticks what to leave out. Run `scan --run <run> --folders <picked> --notes`.
|
||||
|
||||
- Exit 3 `no registry answered`: stop before the list with one message (the registry may need a sign-in in the person's shell; give the manager's sign-in command, never touch credentials) and offer Scan again.
|
||||
- Rows in `notScanned` go in the Not scanned group with their reason; the rest go on.
|
||||
- Each plugin in `scan`'s `missingTools` (cargo-outdated, cargo-audit, pip-audit, govulncheck): name it with its `install` line. Rows with `notAudited` say "not checked for vulnerabilities", never clean.
|
||||
- Exit 3 `no registry answered`: stop before the list with one message ("No package server answered": the person may need to sign in; give the manager's sign-in command, never touch credentials) and offer Look again.
|
||||
- Then `fit`. Each `unknown` id: work out the newest version that runs on the project's runtime, and offer it only with the person's OK; on a yes, `fit --id <id> --best <v>` makes it a pick.
|
||||
- Rows in `notScanned` go in the "Not looked at" group with their reason; the rest go on.
|
||||
- Each plugin in `scan`'s `missingTools` (cargo-outdated, cargo-audit, pip-audit, govulncheck): offer its install (Hard limits). Rows with `notAudited` say "not checked for security problems", never clean.
|
||||
|
||||
### Step 3: Nothing to update
|
||||
|
||||
No rows at all: say everything is current (with any `held`, `notScanned` and `stillOpen`), `cleanup`, and finish.
|
||||
No rows at all: say "Nothing to update: everything is current" (with any `held`, `notScanned` and `stillOpen`), `cleanup`, and finish.
|
||||
|
||||
### Step 4: Assess
|
||||
|
||||
For every row, build one record: `{ id, notes, source, url, breaking, files, calls }`.
|
||||
For every row, build one record: `{ id, notes, source, url, breaking, files, calls, usedIn }`.
|
||||
|
||||
- `notes`: `read`, `not read` (notes skipped) or `could not read`. With notes on, run `notes --id <row>` per row; `source` and `url` come from it, `source: "none"` is `could not read`.
|
||||
- `notes`: `read` or `could not read`. Run `notes --id <row>` per row; `source` and `url` come from it, `source: "none"` is `could not read`.
|
||||
- `breaking`: lines from the notes that say something was removed, renamed or changed in a way callers must handle, quoted verbatim.
|
||||
- `files` and `calls`: for majors and `0.x` minors (`jump` major or 0.x), search the project's source for the package's imports: `files` is the number of source files importing it; `calls` lists each use of an API the `breaking` lines name, as `{ file, line, api }`. Leave both empty for patches and minors.
|
||||
- `usedIn`: every row, the project files that import or name the package (relative paths).
|
||||
|
||||
With helpers, hand each a batch (Helpers) with the run folder, its row ids and this record shape; check each record has every field before you use it. Write the records as one JSON array to `<run>/records-in.json`.
|
||||
With helpers, hand each a batch (Helpers) with the run folder, its row ids and this record shape; check each record has every field before you use it. Write the records as one JSON array to `<run>/records-in.json`, then run `pins`.
|
||||
|
||||
### Step 5: Checks
|
||||
|
||||
Each lockfile's `checks` in `scan.json` are the test map rows covering its folders (`full: true` means a Shared row hit: the full suite). For each lockfile with none, run `test-commands.mjs discover --root <its folder>` and list what it found, per folder, on one confirm before anything runs; a correction replaces what was found. Add each confirmed command to that lockfile's `checks.discovered` in `<run>/scan.json` as `{ "command": "...", "cwd": "..." }`, `cwd` relative to the project root (`discover` gives it relative to `--root`, `.` being that folder), and set `noChecks` to false once any lockfile has a check.
|
||||
Each lockfile's `checks` in `scan.json` are the test map rows covering its folders (`full: true` means a Shared row hit: the full suite). For each lockfile with none, run `test-commands.mjs discover --root <its folder>` and list what it found, per folder, on one confirm before anything runs ("I found these checks"); a correction replaces what was found. Add each confirmed command to that lockfile's `checks.discovered` in `<run>/scan.json` as `{ "command": "...", "cwd": "..." }`, `cwd` relative to the project root (`discover` gives it relative to `--root`, `.` being that folder), and set `noChecks` to false once any lockfile has a check.
|
||||
|
||||
No checks anywhere: one card with a box for a command to type, or one confirm to apply unchecked. A typed command goes into every lockfile's `checks.discovered` as above (or the one the person names). Applying unchecked leaves `noChecks` true, so nothing can be Safe.
|
||||
No checks anywhere: one card with a box for a command to type, or one confirm to update without checks. A typed command goes into every lockfile's `checks.discovered` as above (or the one the person names). Updating without checks leaves `noChecks` true, so nothing can be Safe.
|
||||
|
||||
**Baseline**, before any change: for each id `checks` lists, run it through `run-check.mjs` with `--log`; a failure runs once more to a second log. Record each with `baseline`. Tests already failing never stop the run: they are named in the report. An install failing there stops the run before any change: say so with its `tail`.
|
||||
|
||||
Then run `label --run <run> --records <run>/records-in.json`. Note each folder the test map lacks for the report.
|
||||
|
||||
### Step 6: The pick list
|
||||
|
||||
One `multi` (`notes/deps.md` gives the shape): options grouped Safe, Check first, Warning, Held back, Not scanned; within a group, rows with `security` first. Each option is one row: package, current to target, jump, folder, the label's reasons (`pinned`, a range change, a file count) and the row's `via` as `via <parent>`. Its `more` holds the notes link and source, the quoted breaking lines, the call sites and any `newerNotFitting`. `batch` follows the planner's rule: `safe:<lockfile>` for a Safe row, its own id (or its pair's first id) for any other. Held back and Not scanned rows are `locked`, with the file or reason that holds them. The item carries `counter: { rounds: "check rounds" }`. Preset `All Safe` ticks the Safe group: the page cannot open with rows ticked, so say in the body that Safe rows are the suggested pick. Check first and Warning rows, security fixes included, are never in the preset. List `stillOpen` below with each reason.
|
||||
One `multi` (`notes/deps.md` gives the shape): options grouped Safe, Check first, Warning, Locked in place, Needs a newer Node (runtime holds, with `raise`), Not looked at; within a group, rows with `security` first. Each option is one row: package, current to new version, size of the change, folder, the label's `reasonsPlain` and `via <parent>`; its `more` (notes link, breaking lines, call sites, `newerNotFitting`) and `batch` as the notes say. Locked in place, Needs a newer Node and Not looked at rows are `locked`, with the file or reason that holds them in plain words. The item carries `counter: { rounds: "check rounds" }`. Preset `All Safe` ticks the Safe group: the page cannot open with rows ticked, so say in the body that Safe rows are the suggested pick. Check first and Warning rows, security fixes included, are never in the preset. List `stillOpen` below with each reason.
|
||||
|
||||
In the terminal, the same as a numbered list in five groups; the person names numbers or says "all safe".
|
||||
In the terminal, the same as a numbered list in six sections; the person names numbers or says "all safe".
|
||||
|
||||
Nothing picked: skip to Step 8.
|
||||
|
||||
### Step 7: Apply in batches
|
||||
### Step 7: Apply in groups
|
||||
|
||||
Run `batches --picks <ids>`. For each batch in order:
|
||||
Run `batches --picks <ids>`. For each batch (a group, to the person) in order:
|
||||
|
||||
1. `backup`. `snapshot.ok` false: nothing changed; mark the batch's picks `not applied: <reason>` and go to the next batch (never plan the batches again: the ids clash).
|
||||
2. `apply`. It fails when `failed` is true (`overshot` and `undoFailed` set it too), `unpicked` is not empty (it moved a package not picked) or `needsNewerRuntime` is not empty. A pick in `skipped` or `offTarget` did not land on its target: its outcome is `not applied: <reason>` (or `landed on <now>`), never `updated`. A batch where every pick is skipped and `undoFailed` is empty changed nothing (with `undoFailed`, it failed: put it back): skip its install, checks, restore and split, mark each pick `not applied: <skipped reason>`, post no run event and go to the next batch.
|
||||
3. The install: the lockfile's `install` from `detect`, through `run-check.mjs` in the lockfile's folder, as the first check. An install that does not pass fails the batch before any other check runs.
|
||||
4. The checks: every command in that lockfile's `checks.commands` from the project root (the full suite when `full`), then every `checks.discovered` command in its `cwd`, each through `run-check.mjs` with `--timeout 600` (longer when `AGENTS.md` says a suite is slow) and `--log` in the session folder or the OS temp folder. Any `outcome` other than `passed` fails the batch; a timeout is a failure.
|
||||
5. All pass: the batch stays and its landed picks are `updated`. The first batch that stays with a pick updated posts the run event (`notes/deps.md`).
|
||||
4. The checks: each of `checks --batch <b>`'s `commands` in its `cwd`, through `run-check.mjs` with `--timeout 600` (longer when `AGENTS.md` says a suite is slow) and `--log` in the session folder or the OS temp folder; a failure runs once more to a second log. Then `compare` each check: `blame` true fails the batch. `stillFailing` and `flaky` tests never fail it.
|
||||
5. **A blamed group:** read the failing `tail`. A small cause (a pinned version, an expected value, a config line): one fix card per change (`notes/deps.md`); only on approval run `fix`, then that group's checks and `compare` again. A skipped fix, or still blamed: put it back as a failed batch (fixes go with it), its picks `not applied: needs a bigger change`, offered as an upgrade brief, no split.
|
||||
6. None blamed: the batch stays and its landed picks are `updated`. The first batch that stays with a pick updated posts the run event (`notes/deps.md`).
|
||||
|
||||
**A failed batch:** `restore --batch <b> --verify`. `verified` false, or a non-zero exit: stop, name each `mismatched` file with its `reason` and leave them to the person. Run the `reinstall` through `run-check.mjs`; when it does not pass, or `extra.ok` is false, stop the run and give the person the command to run by hand. Either stop is an **unfinished put-back**: keep the run folder, and name `<run>/backups/<b>/files/` (and `pip-freeze.txt` for pip), where the as-found copies are, in the stop message, the report and the finish. Then:
|
||||
**A failed batch:** `restore --batch <b> --verify`. `verified` false, or a non-zero exit: stop, name each `mismatched` file with its `reason` and leave them to the person. Run the `reinstall` through `run-check.mjs`; when it does not pass, or `extra.ok` is false, stop the run and give the person the command to run by hand. Either stop is an **undo that did not finish**: keep the run folder, and say in the stop message, the report and the finish: "I could not finish undoing this group. Your original files are saved in `<run>/backups/<b>/files/`" (and `pip-freeze.txt` for pip). Then:
|
||||
|
||||
- **The first failure of the run:** run the same checks once on the restored tree. If they fail there too, the project was already failing: stop, mark every remaining pick `skipped: already failing`, and say so.
|
||||
- `batches --split <b>` and run the new batches the same way. A single pick that fails is marked `failed` with the end of the failing output (`tail`), or, failed by `apply` itself, what failed it (`moved <unpicked>`, `needs <runtime>`). Exit 4 means it cannot be split further.
|
||||
|
||||
After the first batch, each progress line adds the time left, estimated from how long that round took. Post one progress line per install and check, with `quietMinutes` sized to its timeout, and run the console's `chat` check between steps.
|
||||
After the last group, when `full` is not empty, offer the full suite once (a confirm); run it the same way, `compare` it under the last group's id and report what it blames.
|
||||
|
||||
### Step 8: Hand-off, report and finish
|
||||
Post progress as `notes/deps.md` says (time left after the first group), with the console's `chat` check between steps.
|
||||
|
||||
**Hand-off.** One card listing every Warning row and every Check first major that failed and was put back, all unticked, each with what blocks it. For the rows the person ticks, run `handoff --ids <ids>` and name each file written. None to list: skip the card.
|
||||
### Step 8: Code changes, report and finish
|
||||
|
||||
**Report.** On the page (in the terminal, as a table): the headline says Complete, Narrowed (some picks failed or were narrowed) or Stopped; the folders scanned; then each row with its label, reasons and outcome (`updated`, `not applied: <reason>`, `failed: <tail end>`, `skipped`, `not tried`, `not picked`, `held back`, `not scanned`); the `stillOpen` vulnerabilities; missing tools with their install lines; folders the test map lacks (point to `/plan2code-pr-prep` or `/plan2code-test` to add rows); changes already there before the run, marked as such; and any brief written.
|
||||
**Packages that need your code changed.** One card listing every Warning row, every Check first big change that broke and was undone, and every `needs a bigger change` pick, all unticked, each with what blocks it. For the rows the person ticks, run `handoff --ids <ids>` and name each upgrade brief written. None to list: skip the card.
|
||||
|
||||
**Report.** On the page (in the terminal, as a table): the headline says what happened first, in a sentence ("Nothing was changed. 1 update broke the tests and was undone; 3 were not tried"); folders looked at; then each row with its label, `reasonsPlain` and outcome: updated, `not applied: <reason>` as "not updated: <reason>", `failed: <tail end>` as "broke the checks and was undone: <end of the output>", `skipped` as "left out: <reason>", `not tried` as "not tried: an earlier problem stopped the run", not picked, held back as "locked in place: <what holds it>", `not scanned` as "not looked at: <reason>"; tests that were failing before the run; `stillOpen` security problems; missing tools with install lines; folders the test map lacks (point to `/plan2code-pr-prep` or `/plan2code-test`); changes already there before the run, marked as such; each small fix kept (file and the one-line change, from `fixes.json` or `restore`'s `fixed`; none: leave it out); and any upgrade brief written.
|
||||
|
||||
Then `cleanup --run <run>` (not after an unfinished put-back) and the finish.
|
||||
|
||||
## Stop
|
||||
|
||||
On "stop", "cancel", `__stop` or similar: one confirm. Then keep every batch that passed and every pick that passed a narrowing round; end the running install or check when your tool can; `restore --verify` and reinstall the live batch (the page says what it is putting back, `Stopping: putting back vite`). The report says Stopped, never complete, and lists the batches not tried. Then `cleanup` (not after an unfinished put-back) and finish.
|
||||
On "stop", "cancel", `__stop` or similar: one confirm. Then keep every batch that passed and every pick that passed a narrowing round; end the running install or check when your tool can; `restore --verify` and reinstall the live batch. The report says the run stopped, never complete, and lists the groups not tried. Then `cleanup` (not after an undo that did not finish) and finish.
|
||||
|
||||
## Session End
|
||||
|
||||
Every finish, early or not (no lockfiles, a Stop on a start card, the no-registry stop), runs `cleanup --run <run>` first, except after an unfinished put-back (Step 7): then the run folder stays and the finish names its backup path.
|
||||
Every finish, early or not (no lockfiles, a Stop on the start screen, the no-registry stop), runs `cleanup --run <run>` first, except after an undo that did not finish (Step 7): then the run folder stays and the finish names its backup path.
|
||||
|
||||
Work summary: the folders scanned, how many rows by label, what was updated, failed (with why), put back, skipped or not tried, the checks that ran, any brief written, and any tool to install for a fuller scan.
|
||||
Work summary: folders looked at, rows by label, what was updated, what broke and why, what was undone, left out or not tried, the checks that ran, any upgrade brief, and any tool to install for a fuller scan.
|
||||
|
||||
**Next step**, as the closing line: "Review the unstaged manifest and lockfile changes and commit them with `/plan2code-git`." Nothing changed: "Nothing to commit." A brief written: also "Run `/plan2code-quick-task` or `/plan2code-1-plan` on `specs/<package>-upgrade/`." After an unfinished put-back: "Put back the files from `<run>/backups/<b>/files/` (or run the reinstall) before you commit."
|
||||
**Next step**, as the closing line: "Look over the changes to the package list, the version list and any file I fixed (they are not staged) and save them with `/plan2code-git`." Nothing changed: "Nothing to save." A brief written: also "Run `/plan2code-quick-task` or `/plan2code-1-plan` on `specs/<package>-upgrade/`." After an undo that did not finish: "Restore the files from `<run>/backups/<b>/files/` (or run the reinstall) before you save anything."
|
||||
|
||||
On the console, post `finish` with the counts updated, failed and not tried in `headline`, `"dashboard": true`, and `command` `/plan2code-git` when something changed (none after an unfinished put-back); never a `commit` field. A stop before any apply: the body says nothing changed, `command` `/plan2code-deps`.
|
||||
On the console, post `finish` with a `headline` that says what happened first in a sentence (counts updated, broke and not tried), `"dashboard": true`, and `command` `/plan2code-git` when something changed (none after an undo that did not finish); never a `commit` field. A stop before any apply: the body says nothing was changed, `command` `/plan2code-deps`.
|
||||
|
||||
```
|
||||
⋅
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
#!/usr/bin/env node
|
||||
// changes.mjs: what this run changed, for the sign-off page's Changes tab.
|
||||
//
|
||||
// `start` snapshots the working tree into a git tree object (through a
|
||||
// temporary index, so the real index, HEAD, branches and working tree stay
|
||||
// exactly as they were) and remembers its id in the session folder. `diff`
|
||||
// snapshots the tree as it is now, compares the two and writes the unified diff
|
||||
// to <session>/changes.diff, with counts on stdout. Work done before `start`
|
||||
// never shows up, and nothing has to be committed.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { EXIT, fail, gitRepo, out, parseArgs, run } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
changes.mjs: snapshot the working tree, then diff against the snapshot. JSON on stdout.
|
||||
|
||||
node changes.mjs start --session <folder> [--root <dir>]
|
||||
node changes.mjs diff --session <folder> [--root <dir>] [--cap 524288]
|
||||
|
||||
start Snapshots the working tree (tracked, modified and new files, never
|
||||
.gitignore'd ones) into a git tree object and writes
|
||||
<session>/changes-start.json. The real index, HEAD and branches are
|
||||
not touched. Run it again to take a new snapshot.
|
||||
diff Compares the snapshot with the tree now and writes
|
||||
<session>/changes.diff plus the counts:
|
||||
{ ok, files, added, removed, truncated, hidden, file }.
|
||||
--cap Largest patch to keep, in bytes (default 524288). A bigger one is cut
|
||||
at a file boundary with a plain notice; every file stays named.
|
||||
|
||||
Lines of files that may hold a secret are hidden (name and counts stay).
|
||||
|
||||
Exit: 0 ok · 2 bad arguments · 3 not a git repository, no snapshot, or the
|
||||
snapshot is gone · 4 git could not snapshot the working tree.
|
||||
`;
|
||||
|
||||
const DEFAULT_CAP = 524288;
|
||||
const START_FILE = "changes-start.json";
|
||||
const DIFF_FILE = "changes.diff";
|
||||
const TOO_LARGE = "\\ No more lines shown: this change is too large to show in full.";
|
||||
const HIDDEN_LINE = "Lines hidden: this file may hold a secret.";
|
||||
|
||||
/* ------------------------------------------------------------------ git */
|
||||
|
||||
function git(root, args, { env, allowFail = false } = {}) {
|
||||
try {
|
||||
// core.quotePath=false: a non-ASCII path comes back as itself, not as an escaped, quoted string.
|
||||
return execFileSync("git", ["-c", "core.quotePath=false", ...args], {
|
||||
cwd: root,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
env: env || process.env,
|
||||
});
|
||||
} catch (err) {
|
||||
if (allowFail) return null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function notARepo(root) {
|
||||
fail(EXIT.NOT_FOUND, "not-a-repo", `${root} is not inside a git repository, so there is no way to tell what changed.`, "Tell the person the Changes tab has no starting point in a folder without git.");
|
||||
}
|
||||
|
||||
/** The top of the working tree `root` is in, or a not-a-repo failure. */
|
||||
function topLevel(root) {
|
||||
const top = git(root, ["rev-parse", "--show-toplevel"], { allowFail: true });
|
||||
if (top === null || !top.trim()) notARepo(root);
|
||||
return top.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* The tree id of the working tree as it is now, built in a temporary index:
|
||||
* seeded with a copy of the real one so `git add -A` only re-hashes what
|
||||
* changed. The real index is never written.
|
||||
*/
|
||||
export function snapshotTree(root) {
|
||||
const top = topLevel(root);
|
||||
const real = git(top, ["rev-parse", "--git-path", "index"], { allowFail: true });
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-changes-"));
|
||||
try {
|
||||
const indexFile = path.join(dir, "index");
|
||||
if (real && real.trim()) {
|
||||
const source = path.resolve(top, real.trim());
|
||||
if (fs.existsSync(source)) fs.copyFileSync(source, indexFile);
|
||||
}
|
||||
const env = { ...process.env, GIT_INDEX_FILE: indexFile };
|
||||
try {
|
||||
git(top, ["add", "-A"], { env });
|
||||
return git(top, ["write-tree"], { env }).trim();
|
||||
} catch (err) {
|
||||
fail(EXIT.INVALID, "snapshot-failed", `Git could not snapshot the working tree: ${String((err && err.stderr) || err.message).trim().split("\n")[0]}`, "Check that the repository is healthy (git status), then run again.");
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** `<session>/changes-start.json` as an object with a hex `tree`, or null. */
|
||||
export function readStart(session) {
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(path.join(session, START_FILE), "utf8"));
|
||||
if (data && typeof data === "object" && typeof data.tree === "string" && /^([0-9a-f]{40}|[0-9a-f]{64})$/.test(data.tree)) return data;
|
||||
} catch {}
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- patch */
|
||||
|
||||
/** Split a patch into one string per file, each starting at its `diff --git` line. */
|
||||
function splitSections(patch) {
|
||||
if (!patch) return [];
|
||||
return patch.split(/^(?=diff --git )/m).filter((s) => s.startsWith("diff --git "));
|
||||
}
|
||||
|
||||
/** Old and new paths of a file's section (a rename has two). */
|
||||
function sectionPaths(section) {
|
||||
const paths = new Set();
|
||||
for (const line of section.split("\n")) {
|
||||
if (line.startsWith("@@")) break;
|
||||
let m = line.match(/^rename (?:from|to) (.+)$/);
|
||||
if (m) paths.add(unquote(m[1]));
|
||||
// Git adds a trailing tab after a name that holds a space.
|
||||
m = line.match(/^(?:--- a|\+\+\+ b)\/(.+?)\t?$/) || line.match(/^(?:--- |\+\+\+ )"[ab]\/(.+)"\t?$/);
|
||||
if (m) paths.add(unquote(m[1]));
|
||||
}
|
||||
if (!paths.size) {
|
||||
const m = section.split("\n", 1)[0].match(/^diff --git "?a\/(.+?)"? "?b\/(.+?)"?$/);
|
||||
if (m) {
|
||||
paths.add(unquote(m[1]));
|
||||
paths.add(unquote(m[2]));
|
||||
}
|
||||
}
|
||||
return [...paths];
|
||||
}
|
||||
|
||||
/** Undo git's C-style quoting of an odd name (backslash-t, -n, -quote, -backslash). */
|
||||
function unquote(p) {
|
||||
return p.replace(/\\(["\\tn])/g, (_, c) => (c === "t" ? "\t" : c === "n" ? "\n" : c));
|
||||
}
|
||||
|
||||
/** Old and new paths per changed file, from `git diff --name-status -z`, in patch order. */
|
||||
function nameEntries(text) {
|
||||
const tok = (text || "").split("\0");
|
||||
const entries = [];
|
||||
for (let i = 0; i < tok.length && tok[i]; ) {
|
||||
const n = /^[RC]/.test(tok[i]) ? 2 : 1;
|
||||
entries.push(tok.slice(i + 1, i + 1 + n));
|
||||
i += 1 + n;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** The lines of a section that name the file and how it moved, no content. */
|
||||
function headerOnly(section) {
|
||||
const keep = /^(diff --git |rename (from|to) |similarity index |new file mode |deleted file mode |old mode |new mode )/;
|
||||
return (
|
||||
section
|
||||
.split("\n")
|
||||
.filter((l) => keep.test(l))
|
||||
.join("\n") + "\n"
|
||||
);
|
||||
}
|
||||
|
||||
/** Only the `diff --git` line and any rename lines: what a cut file keeps. */
|
||||
function nameOnly(section) {
|
||||
return (
|
||||
section
|
||||
.split("\n")
|
||||
.filter((l) => /^(diff --git |rename (from|to) )/.test(l))
|
||||
.join("\n") + "\n"
|
||||
);
|
||||
}
|
||||
|
||||
const bytes = (s) => Buffer.byteLength(s, "utf8");
|
||||
|
||||
/**
|
||||
* Cut `patch` to at most `cap` bytes at a file boundary, never mid-line: the
|
||||
* files that fit stay whole, the rest shrink to their header lines under one
|
||||
* plain notice, so the file list stays complete. `headerOf` says what a cut
|
||||
* file keeps (default: its `diff --git` line and any rename lines). A patch
|
||||
* within the cap comes back unchanged. The result's size can pass the cap only
|
||||
* when the headers alone do.
|
||||
*/
|
||||
export function capPatch(patch, cap, headerOf = nameOnly) {
|
||||
if (bytes(patch) <= cap) return { patch, truncated: false };
|
||||
const sections = splitSections(patch);
|
||||
const sizes = sections.map(bytes);
|
||||
const heads = sections.map((s) => headerOf(s));
|
||||
const headSizes = heads.map(bytes);
|
||||
const notice = TOO_LARGE + "\n";
|
||||
let kept = 0;
|
||||
let total = 0;
|
||||
let cutSize = headSizes.reduce((a, b) => a + b, 0);
|
||||
// Largest k whose whole sections plus the cut ones' headers fit.
|
||||
let best = 0;
|
||||
for (let k = 0; k <= sections.length; k++) {
|
||||
if (k > 0) {
|
||||
total += sizes[k - 1];
|
||||
cutSize -= headSizes[k - 1];
|
||||
}
|
||||
if (total + (k < sections.length ? bytes(notice) + cutSize : 0) <= cap) best = k;
|
||||
else if (k > 0) break;
|
||||
}
|
||||
kept = best;
|
||||
let text = sections.slice(0, kept).join("");
|
||||
if (kept < sections.length) {
|
||||
if (text && !text.endsWith("\n")) text += "\n";
|
||||
text += notice + heads.slice(kept).join("");
|
||||
}
|
||||
return { patch: text, truncated: kept < sections.length };
|
||||
}
|
||||
|
||||
/** Replace the lines of every sensitive file's section; returns the paths hidden. */
|
||||
function hideSensitive(patch, isSensitive, entries) {
|
||||
const hidden = [];
|
||||
const split = splitSections(patch);
|
||||
// The NUL-delimited name list is exact and comes in patch order. A count
|
||||
// mismatch falls back to the patch text, and a section whose name cannot be
|
||||
// read at all is hidden: never show lines of a file that cannot be named.
|
||||
const exact = entries && entries.length === split.length;
|
||||
const sections = split.map((section, i) => {
|
||||
const paths = exact ? entries[i] : sectionPaths(section);
|
||||
const secret = paths.filter((p) => isSensitive(p));
|
||||
if (!secret.length && paths.length) return section;
|
||||
for (const p of paths) if (!hidden.includes(p) && isSensitive(p)) hidden.push(p);
|
||||
return headerOnly(section) + HIDDEN_LINE + "\n";
|
||||
});
|
||||
return { patch: sections.join(""), hidden };
|
||||
}
|
||||
|
||||
function sumNumstat(text) {
|
||||
let added = 0;
|
||||
let removed = 0;
|
||||
for (const line of (text || "").split("\n")) {
|
||||
if (!line.trim()) continue;
|
||||
const [a, d] = line.split("\t");
|
||||
// A binary file prints "-" for both counts: it adds nothing.
|
||||
if (/^\d+$/.test(a)) added += Number(a);
|
||||
if (/^\d+$/.test(d)) removed += Number(d);
|
||||
}
|
||||
return { added, removed };
|
||||
}
|
||||
|
||||
/** Per-file counts from `numstat -z`, keyed by the new path; a binary file counts 0. */
|
||||
function fileCounts(text) {
|
||||
const tok = (text || "").split("\0");
|
||||
const counts = new Map();
|
||||
for (let i = 0; i < tok.length && tok[i]; ) {
|
||||
const m = /^(\d+|-)\t(\d+|-)\t([\s\S]*)$/.exec(tok[i]);
|
||||
if (!m) break;
|
||||
const renamed = m[3] === "";
|
||||
const key = renamed ? tok[i + 2] : m[3];
|
||||
counts.set(key, [/^\d+$/.test(m[1]) ? Number(m[1]) : 0, /^\d+$/.test(m[2]) ? Number(m[2]) : 0]);
|
||||
i += renamed ? 3 : 1;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- commands */
|
||||
|
||||
function sessionFolder(args) {
|
||||
if (!args.session) fail(EXIT.USAGE, "missing-session", "--session <folder> is required.", "Pass the console session folder (the `session` path `console.mjs open` printed).");
|
||||
return path.resolve(args.session);
|
||||
}
|
||||
|
||||
function startCommand(args) {
|
||||
const session = sessionFolder(args);
|
||||
const root = path.resolve(args.root || process.cwd());
|
||||
const tree = snapshotTree(root);
|
||||
fs.mkdirSync(session, { recursive: true });
|
||||
fs.writeFileSync(path.join(session, START_FILE), JSON.stringify({ tree, at: new Date().toISOString() }) + "\n");
|
||||
out({ ok: true, tree });
|
||||
}
|
||||
|
||||
async function diffCommand(args) {
|
||||
const session = sessionFolder(args);
|
||||
const root = path.resolve(args.root || process.cwd());
|
||||
let cap = DEFAULT_CAP;
|
||||
if (args.cap !== undefined) {
|
||||
if (!/^[1-9]\d*$/.test(String(args.cap))) fail(EXIT.USAGE, "bad-cap", `--cap must be a positive whole number of bytes, not "${args.cap}".`, "Pass --cap 524288, or leave it out.");
|
||||
cap = Number(args.cap);
|
||||
}
|
||||
const start = readStart(session);
|
||||
if (!start) fail(EXIT.NOT_FOUND, "no-start", "No snapshot was taken at the start of this run.", "Run changes.mjs start first, or tell the person the Changes tab has no starting point.");
|
||||
const top = topLevel(root);
|
||||
if (git(top, ["cat-file", "-e", `${start.tree}^{tree}`], { allowFail: true }) === null) {
|
||||
fail(EXIT.NOT_FOUND, "start-missing", "The snapshot taken at the start of this run is gone from the repository (git cleaned it up).", "Tell the person the Changes tab has no starting point, or run changes.mjs start and redo the comparison from there.");
|
||||
}
|
||||
const now = snapshotTree(root);
|
||||
// Fixed prefixes: a user's diff.noprefix or diff.mnemonicPrefix must not change the headers.
|
||||
const diffArgs = ["diff", "--no-color", "-M", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/"];
|
||||
const entries = nameEntries(git(top, ["diff", "--name-status", "-z", "-M", "--no-ext-diff", start.tree, now]));
|
||||
const numstat = git(top, ["diff", "--numstat", "-M", "--no-ext-diff", start.tree, now]);
|
||||
const { added, removed } = sumNumstat(numstat);
|
||||
let patch;
|
||||
let oversize = false;
|
||||
try {
|
||||
patch = git(top, [...diffArgs, start.tree, now]);
|
||||
} catch (err) {
|
||||
if (!(err && (err.code === "ENOBUFS" || err.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"))) throw err;
|
||||
// Too big to even read: keep only the names, so the file list stays complete.
|
||||
oversize = true;
|
||||
patch = entries.map((e) => `diff --git a/${e[0]} b/${e[e.length - 1]}\n${e.length > 1 ? `rename from ${e[0]}\nrename to ${e[1]}\n` : ""}`).join("");
|
||||
}
|
||||
const files = (patch.match(/^diff --git /gm) || []).length;
|
||||
|
||||
const { isSensitive } = await gitRepo();
|
||||
const shown = hideSensitive(patch, isSensitive, entries);
|
||||
const capped = oversize ? { patch: shown.patch + TOO_LARGE + "\n", truncated: true } : capPatch(shown.patch, cap);
|
||||
let text = capped.patch;
|
||||
const trailer = [];
|
||||
if (capped.truncated) trailer.push("# truncated: true");
|
||||
for (const p of shown.hidden) trailer.push(`# hidden: ${p}`);
|
||||
// Hidden and cut files carry no lines for the page to count: give it their counts.
|
||||
if (shown.hidden.length || capped.truncated) {
|
||||
const counts = fileCounts(git(top, ["diff", "--numstat", "-z", "-M", "--no-ext-diff", start.tree, now]));
|
||||
for (const [p, [a, d]] of counts) {
|
||||
if ((capped.truncated || shown.hidden.includes(p)) && !/[\t\n]/.test(p)) trailer.push(`# counts: ${a}\t${d}\t${p}`);
|
||||
}
|
||||
}
|
||||
if (trailer.length) text += (text && !text.endsWith("\n") ? "\n" : "") + trailer.join("\n") + "\n";
|
||||
|
||||
fs.mkdirSync(session, { recursive: true });
|
||||
fs.writeFileSync(path.join(session, DIFF_FILE), text);
|
||||
out({ ok: true, files, added, removed, truncated: capped.truncated, hidden: shown.hidden, file: DIFF_FILE });
|
||||
}
|
||||
|
||||
// Run only as a script: the tests import capPatch without starting it.
|
||||
const isMain = (() => {
|
||||
try {
|
||||
return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
if (isMain) {
|
||||
run(USAGE, async (argv) => {
|
||||
const args = parseArgs(argv, { values: ["session", "root", "cap"] });
|
||||
const [command] = args._;
|
||||
if (command === "start") return startCommand(args);
|
||||
if (command === "diff") return diffCommand(args);
|
||||
fail(EXIT.USAGE, "unknown-command", command ? `Unknown command "${command}".` : "No command given.", "Use `start` or `diff` (changes.mjs --help).");
|
||||
});
|
||||
}
|
||||
@@ -9,11 +9,12 @@ Docs and their blocks merge by `id`; a new id is added at the end. Patch blocks
|
||||
- `{"id":"b2","state":"settled"}` settles b2 and keeps its text; blocks you leave out stay.
|
||||
- `{"id":"b3","_delete":true}` removes a block; a doc entry with `"_delete":true` removes the tab.
|
||||
|
||||
## Block content: one of three
|
||||
## Block content: one of four
|
||||
|
||||
- `md`: markdown you write.
|
||||
- `file`: the console reads the text from that project file (inside the project, 512 KB at most). Re-send the block, or the doc with `"refresh":true`, after the file changes. `"select":"tasks"` keeps only its `- [ ] **Task N.M:**` lines. Never paste a file you can name.
|
||||
- `image`: `{"id":"s1","image":"shots/run.png","alt":"..."}`: a PNG, JPEG or WebP (5 MB at most) saved directly in the session's `shots/` folder (the `session` path `open` printed), named with letters, digits, `.`, `_` or `-`. Anything else is exit 3.
|
||||
- `diff`: `{"id":"changes","diff":"changes.diff"}`: a unified diff `changes.mjs diff` wrote, saved directly in the session folder (a name ending `.diff`, 512 KB at most, longer text is cut). The page draws it as the Changes tab. Never paste a diff you can name; re-send the block after running `changes.mjs diff` again. When the changes could not be read, send `{"id":"changes","error":"<one line: why>"}` instead (never both): the tab shows the reason and a Reload button.
|
||||
|
||||
## State
|
||||
|
||||
|
||||
@@ -1,53 +1,71 @@
|
||||
# Update Dependencies
|
||||
|
||||
Every card, headline and activity line is read by a person: use the plain words of `plan2code-deps.md` (version list, package list, small fix, new features, big change, group, upgrade brief, saved in git, undone, locked to one exact version, size of the change), never the field names.
|
||||
|
||||
## Start screen
|
||||
|
||||
One `--wait` batch after `detect`. The notes box is a `choice`, on as the recommended option; leave out the dirty confirm when no lockfile has `dirty` files. Missing tools, no-lockfile manifests, ecosystems not covered and untracked lockfiles go in `body` lines, one each:
|
||||
One `--wait` batch after `detect`, no question: a `confirm` whose Start button begins the run, with a summary body: what was found (folders, counts), the one line "I will read what each update changes before judging it.", and one line each for missing tools, packages with no version list, ecosystems not covered and files not saved in git. The "Already changed" `confirm` is its own card, only when a lockfile has `dirty` files.
|
||||
|
||||
```jsonc
|
||||
{"title":"Update dependencies","headline":{"stage":"Start","cleared":0,"total":4},"items":[{"id":"notes","kind":"choice","title":"Release notes","allowOther":false,"body":"Safe needs the notes read. 3 other changed files stay as they are.\n\n- cargo is not on this machine: `plan2code-app` is not scanned.","options":[{"text":"Read each update's release notes","recommended":true},{"text":"Skip the notes","detail":"Every row counts as notes not read: nothing can be Safe."}]},{"id":"dirty","kind":"confirm","title":"Already changed","body":"`package.json` already has changes. They are backed up as found and put back as found.","yesLabel":"Carry on","noLabel":"Stop"}]}
|
||||
{"title":"Update dependencies","headline":{"stage":"Start","cleared":0,"total":4},"items":[{"id":"start","kind":"confirm","title":"What I found","yesLabel":"Start","noLabel":"Stop","body":"3 folders have updates to look at, 14 updates in all.\n\nI will read what each update changes before judging it. 3 other changed files stay as they are.\n\n- `cargo` is not installed here, so `plan2code-app` is not checked.\n- `plan2code-web` has no version list, so I list it but cannot update it."},{"id":"dirty","kind":"confirm","title":"Already changed","body":"`package.json` already has changes. I back them up as they are and undo to exactly that.","yesLabel":"Carry on","noLabel":"Stop"}]}
|
||||
```
|
||||
|
||||
## The folder card
|
||||
|
||||
One `multi`, `--wait`: one option per folder holding a lockfile, `text` the folder, `detail` the ecosystem and the quick count. All are suggested: preset `All folders` with every key. A send with none ticked means every folder.
|
||||
One `multi`, `--wait`: one option per folder with a version list, `text` the folder, `detail` the ecosystem and how many updates. All are suggested: preset `All folders` with every key. A send with none ticked means every folder.
|
||||
|
||||
## Not scanned, no registry
|
||||
|
||||
`scan` exit 3: a `confirm` "No registry answered", `body` with the sign-in command, `"yesLabel":"Scan again","noLabel":"Stop"`.
|
||||
`scan` exit 3: a `confirm` "No package server answered", `body` with the sign-in command, `"yesLabel":"Look again","noLabel":"Stop"`.
|
||||
|
||||
## Install a missing scanner
|
||||
|
||||
One `confirm` per plugin in `missingTools`, after the folder card, `--wait`: `title` "Install <tool>?", `body` the step it adds, the exact `command` from `install-tool` in a code block, and "This changes this machine, not the project.", `"yesLabel":"Install it","noLabel":"Skip that check"`.
|
||||
|
||||
## Checks
|
||||
|
||||
For lockfiles with no test map row: one `confirm` listing each discovered command and the folder it runs in, `"yesLabel":"Use these","noLabel":"Not right"`; a "Not right" note replaces what was found. No checks anywhere: a `text` card for a command (`required:false`), then, left empty, a `confirm` "Apply unchecked" (`"yesLabel":"Apply unchecked","noLabel":"Stop"`).
|
||||
For folders with no test map row: one `confirm` "I found these checks" listing each command and the folder it runs in, `"yesLabel":"Use these","noLabel":"Not right"`; a "Not right" note replaces what was found. No checks anywhere: a `text` card for a command (`required:false`), then, left empty, a `confirm` "Update without checks" (`"yesLabel":"Update without checks","noLabel":"Stop"`).
|
||||
|
||||
## The pick list
|
||||
|
||||
One `multi`, `--wait`, `required:false`. Options in five groups, in order: Safe, Check first, Warning, Held back, Not scanned; `security` rows first in their group. `k` is a number in order; keep a key-to-row-id map in the run folder. `text` is `package current → target`; `detail` the jump, folder and reasons; `more` the notes link and source, quoted breaking lines, call sites and newer versions the runtime holds back. `batch` is `safe:<lockfile>` for a Safe row, the row id (or its pair's first id) otherwise. Held back and Not scanned rows are `locked`. Rows cannot open ticked, so `All Safe` is the suggested pick; leave it out with no Safe rows. `body` also lists missing scan plugins with their `install` lines and `stillOpen` with reasons.
|
||||
One `multi`, `--wait`, `required:false`. Options in six sections, in order: Safe, Check first, Warning, Locked in place, Needs a newer Node, Not looked at; `security` rows first in their section. `k` is a number in order; keep a key-to-row-id map in the run folder. `text` is `package current → new version`; `detail` the size of the change (small fix, new features, big change), folder and `reasonsPlain`; `more` the notes link and source, quoted breaking lines, call sites and newer versions the runtime holds back. `batch` is `safe:<lockfile>` for a Safe row, the row id (or its pair's first id) otherwise. A row whose exact version a project file names says so in `detail` (its `reasonsPlain`). Needs a newer Node rows: `detail` the held reason and its `raise`. Locked in place, Needs a newer Node and Not looked at rows are `locked`. Rows cannot open ticked, so `All Safe` is the suggested pick; leave it out with no Safe rows. `body` also lists `stillOpen` with reasons.
|
||||
|
||||
```jsonc
|
||||
{"headline":{"stage":"Pick list","cleared":2},"items":[{"id":"picks","kind":"multi","title":"What to update","required":false,"body":"- Safe: 2 (the suggested pick: press All Safe)\n- Check first: 1\n- Warning: 1\n- Held back: 1\n\nNothing is updated until you send.","counter":{"rounds":"check rounds"},"options":[{"k":"1","group":"Safe","text":"vite 7.1.2 → 7.1.9","detail":"patch · plan2code-app · in range","batch":"safe:plan2code-app/package-lock.json","more":"Notes: [GitHub releases](https://github.com/vitejs/vite/releases), no breaking lines."},{"k":"2","group":"Safe","text":"tsup 8.3.0 → 8.5.1","detail":"minor · plan2code-metrics · in range","batch":"safe:plan2code-metrics/package-lock.json"},{"k":"3","group":"Check first","text":"eslint 9.6.1 → 10.2.1","detail":"major · plan2code-bot · range ^9.6.1 → ^10.2.1","batch":"plan2code-bot/package-lock.json#eslint"},{"k":"4","group":"Warning","text":"commander 12.1.0 → 14.0.0","detail":"major · plan2code-metrics · the code calls a changed API in 3 files","batch":"plan2code-metrics/package-lock.json#commander","more":"> Removed `program.storeOptionsAsProperties()`\n\n- src/cli.ts:14"},{"k":"5","group":"Held back","text":"glob 10.4.5","detail":"held by `overrides` in package.json","locked":true}],"presets":[{"label":"All Safe","ks":["1","2"]}]}]}
|
||||
{"headline":{"stage":"Pick list","cleared":2},"items":[{"id":"picks","kind":"multi","title":"What to update","required":false,"body":"- Safe (should just work): 2, the suggested pick: press All Safe\n- Check first (likely fine, worth a look): 2\n- Warning (your code probably needs changing): 1\n- Locked in place: 1\n- Needs a newer Node: 1\n\nNothing is updated until you send.","counter":{"rounds":"check rounds"},"options":[{"k":"1","group":"Safe","text":"vite 7.1.2 → 7.1.9","detail":"small fix · plan2code-app · fits the allowed range","batch":"safe:plan2code-app/package-lock.json","more":"Notes: [GitHub releases](https://github.com/vitejs/vite/releases), nothing removed or changed."},{"k":"2","group":"Safe","text":"tsup 8.3.0 → 8.5.1","detail":"new features · plan2code-metrics · fits the allowed range","batch":"safe:plan2code-metrics/package-lock.json"},{"k":"3","group":"Check first","text":"eslint 9.6.1 → 10.2.1","detail":"big change · plan2code-bot · the allowed range widens from ^9.6.1 to ^10.2.1","batch":"plan2code-bot/package-lock.json#eslint"},{"k":"4","group":"Warning","text":"commander 12.1.0 → 14.0.0","detail":"big change · plan2code-metrics · your code uses something that changed, in 3 files","batch":"plan2code-metrics/package-lock.json#commander","more":"> Removed `program.storeOptionsAsProperties()`\n\n- src/cli.ts:14"},{"k":"5","group":"Check first","text":"playwright-core 1.64.1 → 1.66.0","detail":"new features · root · scripts/test-browser-helper.mjs names this exact version (1.64.1), and the update does not change that file","batch":"package-lock.json#playwright-core"},{"k":"6","group":"Locked in place","text":"glob 10.4.5","detail":"locked by an override in package.json","locked":true},{"k":"7","group":"Needs a newer Node","text":"chalk 4.1.2","detail":"needs Node >=20 (you declare >=18) · change engines.node in package.json","locked":true}],"presets":[{"label":"All Safe","ks":["1","2"]}]}]}
|
||||
```
|
||||
|
||||
## Progress
|
||||
|
||||
One post per install and check, no `--wait`: `headline.stage` `Batch 2 of 5`, `activity` naming the batch and the command (`Installing for plan2code-app`, then `Running npm test in plan2code-app`), `quietMinutes` sized to the timeout plus a margin. After the first batch, `activity` ends with the time left. A put-back says so: `Putting back eslint`.
|
||||
The baseline, before the pick list: one post per check, `headline.stage` `Before any change`, `activity` `Running npm test before any change`. Tests failing there are named in the report, never a stop.
|
||||
|
||||
The first batch that stays with a pick updated posts `{"run":{"event":"deps","id":"apply"}}`, once per run.
|
||||
One post per install and check, no `--wait`: `headline.stage` `Group 2 of 5`, `activity` naming the group and the command (`Installing for plan2code-app`, then `Running npm test in plan2code-app`), `quietMinutes` sized to the timeout plus a margin. After the first group, `activity` ends with the time left. A fix and an undo say so: `Fixing scripts/test-browser-helper.mjs`, `Putting back the update and the fix`, `Undoing eslint`.
|
||||
|
||||
After the last group, when `checks` lists a `full` suite: one `confirm` "Run the full suite", `body` naming the commands, `"yesLabel":"Run the full suite","noLabel":"Skip"`.
|
||||
|
||||
The first group that stays with a pick updated posts `{"run":{"event":"deps","id":"apply"}}`, once per run.
|
||||
|
||||
Helpers are reported as `helpers`, each `done` or `failed`, before the pick list goes up.
|
||||
|
||||
## The fix card
|
||||
|
||||
One `choice` per change, `--wait`, when `compare` blames a group and the cause is small: `title` "Fix this to keep the update"; `body` the file, the failing check in one plain line, and the exact change as a fenced `diff` (the line before, the line after). "Other" carries an edited replacement: apply that instead.
|
||||
|
||||
```jsonc
|
||||
{"items":[{"id":"fix-1","kind":"choice","title":"Fix this to keep the update","body":"`scripts/test-browser-helper.mjs` still names the old version, so `npm test` fails.\n\n```diff\n- const BUILD = \"1.64.1\";\n+ const BUILD = \"1.65.1\";\n```","options":[{"text":"Make this change","recommended":true},{"text":"Skip it and undo the update"}]}]}
|
||||
```
|
||||
|
||||
## Stop
|
||||
|
||||
On `__stop`: a `confirm` "Stop the run", `"yesLabel":"Stop","noLabel":"Keep going"`, `body` naming what stays and what is put back. Yes: put back the live batch, then the report and the finish.
|
||||
On `__stop`: a `confirm` "Stop the run", `"yesLabel":"Stop","noLabel":"Keep going"`, `body` naming what stays and what is undone. Yes: undo the live group, then the report and the finish.
|
||||
|
||||
## The hand-off card
|
||||
## The code-changes card
|
||||
|
||||
One `multi`, `--wait`, `required:false`, after the last batch: every Warning row and every Check first major that failed and was put back, nothing ticked, `detail` what blocks it.
|
||||
One `multi`, `title` "Packages that need your code changed", `--wait`, `required:false`, after the last group: every Warning row, every Check first big change that broke and was undone, and every pick not applied for needing a bigger change, nothing ticked, `detail` what blocks it. Ticked rows get an upgrade brief.
|
||||
|
||||
## The report
|
||||
|
||||
Doc `report`: one `md` block, the headline first (Complete, Narrowed or Stopped), then the folders scanned, the rows table with each label, reasons and outcome, still-open vulnerabilities, missing tools with install lines, folders the test map lacks (point to PR Prep or Test), changes already there before the run, and each brief written. After an unfinished put-back: the mismatched files or the hand-run command, and `<run>/backups/<b>/files/`.
|
||||
Doc `report`: one `md` block, a headline sentence first that says what happened ("Nothing was changed. 1 update broke the tests and was undone; 3 were not tried"), then folders looked at, the rows table with each label, reason and outcome in plain words, still-open security problems, missing tools with install lines, folders the test map lacks (point to PR Prep or Test), changes already there before the run, and each upgrade brief written. After an undo that did not finish: the files that differ or the command to run by hand, and `<run>/backups/<b>/files/`.
|
||||
|
||||
## The finish
|
||||
|
||||
`headline` the counts updated, failed and not tried; `body` the summary and any brief written; `"dashboard":true`; `command` `/plan2code-git` when something changed; never `commit`. A stop before any apply: `body` says nothing changed, `"command":"/plan2code-deps"`. An unfinished put-back: no `command`; `body` names what the report does.
|
||||
`headline` a sentence saying what happened first (counts updated, broke and not tried); `body` the summary and any upgrade brief written; `"dashboard":true`; `command` `/plan2code-git` when something changed; never `commit`. A stop before any apply: `body` says nothing was changed, `"command":"/plan2code-deps"`. An undo that did not finish: no `command`; `body` names what the report does.
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
## First post of a phase
|
||||
|
||||
Before the first task, snapshot the tree for the Changes tab: `node "<S>/changes.mjs" start --session <session folder>` (the `session` path `open` printed, not the sid; once per phase, a rerun replaces the snapshot). A non-zero exit: say so in one line and carry on; the sign-off's `diff` then posts the error.
|
||||
|
||||
```jsonc
|
||||
{"headline":{"stage":"Phase 3: API layer","cleared":0,"total":9},"docs":[{"id":"phasefile","title":"phase-3.md","blocks":[{"id":"body","file":"specs/<feature>/phase-3.md"}]}],"agent":{"status":"working","activity":"Checking the prerequisites","quietMinutes":15}}
|
||||
```
|
||||
@@ -28,6 +30,8 @@ Loop mode (`notes/loop.md`) posts `loopOutcome` instead. Otherwise the Completio
|
||||
{"docs":[{"id":"report","title":"Completion report","blocks":[{"id":"summary","state":"settled","md":"## Summary\n\n..."},{"id":"files","state":"settled","md":"## Files\n\n..."},{"id":"verify","state":"settled","md":"## How to check it\n\n..."}]}],"items":[{"id":"signoff","kind":"review","title":"Approve this phase","doc":"report","body":"Phase 3 is built. Read the report, try the checks, then approve it, review the code first, see it running, or say what to change.","verdicts":[{"id":"review","label":"Review the code first"},{"id":"approve","label":"Approve this phase"},{"id":"show","label":"Show me it working"},{"id":"changes","label":"I want changes"}],"token":{"approve":"approved","changes":"needs changes","show":"show me"},"nothingYet":"Nothing is marked complete until you approve.","gate":{"id":"signoff","authoritative":true}}]}
|
||||
```
|
||||
|
||||
**Changes tab:** first run `node "<S>/changes.mjs" diff --session <session folder>`, then add a second doc after `report` in the same post: `{"id":"changes","title":"Changes","blocks":[{"id":"diff","diff":"changes.diff"}]}` (the card keeps `"doc":"report"`). `files: 0` posts it as is. A non-zero exit sends `{"id":"diff","error":"<its message, one line>"}` instead; the sign-off goes on. On an `__changes` send (the tab's Check again or Reload button), run `diff` again, re-send the block (`"refresh":true` on the doc while it stays a diff), then wait as usual. Code changed before the card reopens (a `changes` verdict, a note's change, review fixes): run `diff` again and re-send the block in that post. A later phase re-sends the doc after its new `start`.
|
||||
|
||||
Posted with `--wait`. An approval whose note asks for a change: do the change first and ask again. `changes`: address it, update the report, reopen the item with a `thread` reply. `review`: read `building-review.md`. `show`: below.
|
||||
|
||||
A later phase in the same session asks with a new id (`signoff-phase-2`, title "Approve Phase 2"); the old card is a record.
|
||||
@@ -62,4 +66,4 @@ Yes: `specs.mjs tick`, `{"headline":{"cleared":N}}` with the next item. After th
|
||||
|
||||
## Implement + Review (`implement-review`)
|
||||
|
||||
Stage 2 publishes findings as in `building-review.md` (The findings). Stage 3 has no "Check the fixes" item. The post starting Stage 2 carries `"run":{"event":"review","id":"review"}` (scores 1 point; the final `run` leaves it out). Stage 4 is the sign-off above, `show` included, without the `review` verdict, with review results and unresolved findings in the report and "Reviewed and ready for sign-off" in `body`. Its finish `run` is `implement-review-phase`.
|
||||
Stage 2 publishes findings as in `building-review.md` (The findings). Stage 3 has no "Check the fixes" item. The post starting Stage 2 carries `"run":{"event":"review","id":"review"}` (scores 1 point; the final `run` leaves it out). Stage 4 is the sign-off above, `show` and the Changes tab included (run `changes.mjs diff` after the review's fixes, so the tab shows the fixed code), without the `review` verdict, with review results and unresolved findings in the report and "Reviewed and ready for sign-off" in `body`. Its finish `run` is `implement-review-phase`.
|
||||
@@ -36,6 +36,8 @@ approve.
|
||||
- Build the phase `--phase` names, without asking (Choosing the phase).
|
||||
- No sign-off card, no "Approve this phase", no Show me it working, no Continue
|
||||
offer. A loop run notes lessons and never lists them: no `lessons` card.
|
||||
- Take the `changes.mjs start` snapshot as `notes/implement.md` says, but run
|
||||
no `diff` and post no Changes tab: a loop phase has no sign-off.
|
||||
- Never run `specs.mjs mark --to done`, and never set `[x]` on the phase in
|
||||
`overview.md`. Tasks inside the phase file are still checked off as they
|
||||
finish: `[x]`, `[!]` when blocked, `[?]` when assumed.
|
||||
|
||||
@@ -15,7 +15,7 @@ Read `building.md` first.
|
||||
```
|
||||
|
||||
A `modify` reposts the changed blocks.
|
||||
- **Building** after `yes`: the Plan tab is the live task list; steps are the tasks. Settle the verdict in the post that starts it:
|
||||
- **Building** after `yes`: before the first edit (a resumed run: when editing starts), run `changes.mjs start` as `notes/implement.md` (First post of a phase) says. The Plan tab is the live task list; steps are the tasks. Settle the verdict in the post that starts it:
|
||||
|
||||
```jsonc
|
||||
{"stopWarning":"","settle":true,"headline":{"stage":"Building","cleared":0,"total":4},"agent":{"status":"working","activity":"Task 1 of 4: step one","quietMinutes":10}}
|
||||
@@ -28,7 +28,7 @@ Read `building.md` first.
|
||||
```
|
||||
|
||||
A step that cannot be done is `- [!]` with the reason, not counted in `cleared`. A step added mid-build raises `headline.total` in the same post. Tick Verify boxes in the post that reports the checks. Do not `wait` until the build is done.
|
||||
- **See it running, before the finish:** once built, post `review` "See it running" (`"doc":"plan"`, verdicts `show` ("Show me it working"), `fine` ("No need, finish up"), tokens `show me` / `no`) with `--wait`. On `show`, see `notes/implement.md` → Show me it working; its one line goes in the finish `body`. `fine` settles the card in the finish post. After `show`, settle it in the post that shows it, then post `review` "Does it look right?" (`"doc":"shown"`, verdicts `fine` ("Looks right, finish up"), `changes` ("I want changes"), tokens `approved` / `needs changes`) with `--wait`. `changes`: make it, reshow if visible, reopen with a `thread` reply, wait again. Only `fine` leads to the finish.
|
||||
- **See it running, before the finish:** once built, post `review` "See it running" (`"doc":"plan"`, verdicts `show` ("Show me it working"), `fine` ("No need, finish up"), tokens `show me` / `no`) with `--wait`, the `changes` doc in the same post (`notes/implement.md` → Sign-off, Changes tab); before "Does it look right?", run `diff` again and re-send its block. On `show`, see `notes/implement.md` → Show me it working; its one line goes in the finish `body`. `fine` settles the card in the finish post. After `show`, settle it in the post that shows it, then post `review` "Does it look right?" (`"doc":"shown"`, verdicts `fine` ("Looks right, finish up"), `changes` ("I want changes"), tokens `approved` / `needs changes`) with `--wait`. `changes`: make it, re-run `diff` and re-send its block, reshow if visible, reopen with a `thread` reply, wait again. Only `fine` leads to the finish.
|
||||
- **Archive a finished folder:** launched on a diagnosed folder now Fixed or an upgrade folder now Done, with nothing past the diagnosis or brief, or on a folder of only prototypes now built, post `confirm` "Archive this bug?" ("Archive this upgrade?", "Archive this prototype?") in the same post as "See it running": dry run's `files` in `body`, with any prototype not built named there, `yesLabel` "Archive it", `noLabel` "Keep it in specs/", `consequences` naming `specs--completed/<name>/`. Yes: `node "<S>/specs.mjs" archive <spec>`, and say where it went in the finish `body`.
|
||||
- **Finish after the build:** `command` is the filled-in commit command in the project's format (AGENTS.md), `"where":"When you are happy with it, commit it from your terminal:"`, with `review` (**Review it now**), `"commit":true`, `"changelog":true` and `"dashboard":true`. Review and dashboard are required. Whichever button is pressed, what follows is `building-review.md`.
|
||||
- **Lessons first:** with lessons to offer (`references/lessons.md`, End), post its `card` as one `lessons` item with `--wait` before the finish.
|
||||
|
||||
@@ -262,7 +262,7 @@ function mergeDocs(current, patchList) {
|
||||
// version: the agent no longer has to track what the page holds, and a
|
||||
// repost of unchanged content is not a new version.
|
||||
if (prev && typeof entry.version !== "number" && typeof prev.version === "number") {
|
||||
const text = (blocks) => JSON.stringify((blocks || []).map((b) => [b.id, b.md, b.state, b.image, b.alt]));
|
||||
const text = (blocks) => JSON.stringify((blocks || []).map((b) => [b.id, b.md, b.state, b.image, b.alt, b.diff, b.text, b.error]));
|
||||
if (text(prev.blocks) !== text(doc.blocks)) doc.version = prev.version + 1;
|
||||
}
|
||||
}
|
||||
@@ -403,9 +403,9 @@ export function resolveDocFiles(patch, state, worktree) {
|
||||
const prev = (state.docs || []).find((d) => d && d.id === entry.id);
|
||||
const named = new Set((blocks || []).map((b) => b && b.id));
|
||||
const again = ((prev && prev.blocks) || [])
|
||||
.filter((b) => b && typeof b.file === "string" && !named.has(b.id))
|
||||
.map((b) => ({ id: b.id, file: b.file, ...(b.select ? { select: b.select } : {}) }));
|
||||
if (!again.length && !blocks) throw new Error(rule(`doc "${entry.id}"`, "refresh", "found no file blocks to re-read", { id: entry.id, blocks: [FILE_RIGHT] }));
|
||||
.filter((b) => b && (typeof b.file === "string" || typeof b.diff === "string") && !named.has(b.id))
|
||||
.map((b) => (typeof b.diff === "string" ? { id: b.id, diff: b.diff } : { id: b.id, file: b.file, ...(b.select ? { select: b.select } : {}) }));
|
||||
if (!again.length && !blocks) throw new Error(rule(`doc "${entry.id}"`, "refresh", "found no file or diff blocks to re-read", { id: entry.id, blocks: [FILE_RIGHT] }));
|
||||
blocks = [...(blocks || []), ...again];
|
||||
} else if (refresh !== undefined) throw new Error(rule(`doc "${entry.id}"`, "refresh", "must be true", { id: entry.id, refresh: true }));
|
||||
if (!blocks) return rest;
|
||||
@@ -452,6 +452,9 @@ export function shotType(buf) {
|
||||
return null;
|
||||
}
|
||||
|
||||
export const DIFF_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.diff$/;
|
||||
export const DIFF_TOO_LARGE = "\\ No more lines shown: this change is too large to show in full.";
|
||||
|
||||
export function resolveDocImages(patch, state, dir) {
|
||||
if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch;
|
||||
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
|
||||
@@ -486,6 +489,50 @@ export function resolveDocImages(patch, state, dir) {
|
||||
if (shotType(fs.readFileSync(real)) !== want) throw bad(`is not a ${want.toUpperCase()} image (its bytes say otherwise)`);
|
||||
return `${SHOTS_DIR_NAME}/${name}`;
|
||||
};
|
||||
// Diff blocks: `{ "id": "changes", "diff": "changes.diff" }` names a unified
|
||||
// diff the agent saved directly in the session folder (changes.mjs diff). The
|
||||
// server reads it like a file block, with the same 512 KB cap, and stores the
|
||||
// name beside the text so the page can tell a diff from markdown. When the
|
||||
// changes could not be read, `{ "id": "changes", "error": "<one line>" }`
|
||||
// carries the plain reason instead, and the page shows it with a Reload button.
|
||||
const DIFF_RIGHT = { id: "d1", diff: "changes.diff" };
|
||||
const ERROR_RIGHT = { id: "d1", error: "No snapshot was taken at the start of this run." };
|
||||
const readDiff = (name, docId, blockId) => {
|
||||
const at = `doc "${docId}" block "${blockId}"`;
|
||||
if (typeof name !== "string" || !name.trim()) throw new Error(rule(at, "diff", "must be a file name", DIFF_RIGHT));
|
||||
const bad = (wrong) => new Error(rule(at, "diff", `${name} ${wrong}`, DIFF_RIGHT));
|
||||
if (!DIFF_NAME.test(name)) throw bad("needs a plain name saved directly in the session folder: letters, digits, dots, dashes or underscores, ending .diff");
|
||||
let real;
|
||||
try {
|
||||
real = fs.realpathSync.native(path.resolve(dir, name));
|
||||
} catch {
|
||||
throw bad("does not exist in the session folder. Run changes.mjs diff first");
|
||||
}
|
||||
let realDir;
|
||||
try {
|
||||
realDir = fs.realpathSync.native(path.resolve(dir));
|
||||
} catch {
|
||||
realDir = path.resolve(dir);
|
||||
}
|
||||
if (fold(path.dirname(real)) !== fold(realDir)) throw bad(`is outside the session folder (${path.resolve(dir)}); only a diff saved there can be shown`);
|
||||
const stat = fs.statSync(real);
|
||||
if (!stat.isFile()) throw bad("is not a file");
|
||||
const fd = fs.openSync(real, "r");
|
||||
let raw;
|
||||
try {
|
||||
// One byte past the cap tells a file that fits from one that does not.
|
||||
const buf = Buffer.alloc(Math.min(stat.size, DOC_FILE_MAX + 1));
|
||||
raw = buf.subarray(0, fs.readSync(fd, buf, 0, buf.length, 0));
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
if (raw.length <= DOC_FILE_MAX) return raw.toString("utf8").replace(/\r\n/g, "\n");
|
||||
// Over the cap is not an error (changes.mjs cuts there itself): keep whole
|
||||
// lines and say so, so a hand-made big file still degrades.
|
||||
const head = raw.subarray(0, DOC_FILE_MAX);
|
||||
const text = head.subarray(0, head.lastIndexOf(0x0a) + 1).toString("utf8").replace(/\r\n/g, "\n");
|
||||
return text.includes(DIFF_TOO_LARGE) ? text : `${text}${DIFF_TOO_LARGE}\n`;
|
||||
};
|
||||
const docs = patch.docs.map((entry) => {
|
||||
if (!isPlainObject(entry) || !Array.isArray(entry.blocks)) return entry;
|
||||
const prevBlocks = (state.docs || []).find((d) => d && d.id === entry.id)?.blocks || [];
|
||||
@@ -494,15 +541,32 @@ export function resolveDocImages(patch, state, dir) {
|
||||
blocks: entry.blocks.map((b) => {
|
||||
if (!isPlainObject(b)) return b;
|
||||
const prevBlock = prevBlocks.find((x) => x && x.id === b.id);
|
||||
if (b.diff !== undefined && b.diff !== null) {
|
||||
if (["md", "file", "image"].some((k) => k in b && b[k] != null)) {
|
||||
throw new Error(rule(`doc "${entry.id}" block "${b.id}"`, "diff", 'a diff block cannot also carry "md", "file" or "image"', DIFF_RIGHT));
|
||||
}
|
||||
if (b.error != null) throw new Error(rule(`doc "${entry.id}" block "${b.id}"`, "error", 'a diff block carries "diff" or "error", never both', DIFF_RIGHT));
|
||||
return { state: prevBlock?.state || "settled", ...b, diff: b.diff, text: readDiff(b.diff, entry.id, b.id), error: null, md: null, file: null, image: null };
|
||||
}
|
||||
if (b.error !== undefined && b.error !== null) {
|
||||
const at = `doc "${entry.id}" block "${b.id}"`;
|
||||
if (["md", "file", "image"].some((k) => k in b && b[k] != null)) throw new Error(rule(at, "error", 'an error block cannot also carry "md", "file" or "image"', ERROR_RIGHT));
|
||||
if (typeof b.error !== "string" || !b.error.trim() || /[\r\n]/.test(b.error.trim())) throw new Error(rule(at, "error", "must be one line of prose: why the changes could not be read", ERROR_RIGHT));
|
||||
return { state: prevBlock?.state || "settled", ...b, error: b.error.trim(), diff: null, text: null, md: null, file: null, image: null };
|
||||
}
|
||||
// Text, a file or an image over what was a diff: it stops being one.
|
||||
const wasDiff = prevBlock && typeof prevBlock.diff === "string";
|
||||
const wasError = prevBlock && typeof prevBlock.error === "string";
|
||||
const notDiff = (wasDiff || wasError) && ("md" in b || "file" in b || "image" in b) ? { diff: null, text: null, error: null } : {};
|
||||
if (b.image === undefined || b.image === null) {
|
||||
// Text or a file over what was an image: it stops being one.
|
||||
return ("md" in b || "file" in b) && prevBlock && typeof prevBlock.image === "string" ? { ...b, image: null, alt: null } : b;
|
||||
return ("md" in b || "file" in b) && prevBlock && typeof prevBlock.image === "string" ? { ...b, ...notDiff, image: null, alt: null } : { ...b, ...notDiff };
|
||||
}
|
||||
if (("md" in b && b.md != null) || ("file" in b && b.file != null)) {
|
||||
throw new Error(rule(`doc "${entry.id}" block "${b.id}"`, "image", 'an image block cannot also carry "md" or "file"', IMAGE_RIGHT));
|
||||
}
|
||||
if (b.alt != null && typeof b.alt !== "string") throw new Error(rule(`doc "${entry.id}" block "${b.id}"`, "alt", "must be text", IMAGE_RIGHT));
|
||||
return { state: prevBlock?.state || "settled", ...b, image: check(b.image, entry.id, b.id), md: null, file: null };
|
||||
return { state: prevBlock?.state || "settled", ...b, ...notDiff, image: check(b.image, entry.id, b.id), md: null, file: null };
|
||||
}),
|
||||
};
|
||||
});
|
||||
@@ -1293,10 +1357,11 @@ export function validate(state) {
|
||||
}
|
||||
// A doc block read from a file (`file`) is the file's own words, already on
|
||||
// disk: the agent cannot reword it, and refusing it would wedge every post
|
||||
// that refreshes it. Only what the agent typed is scanned.
|
||||
// that refreshes it. A diff block is code the repository holds, never prose
|
||||
// the agent wrote: its text may name any word. Only what the agent typed is scanned.
|
||||
for (const d of state.docs || []) {
|
||||
if (!isPlainObject(d)) continue;
|
||||
const typed = Array.isArray(d.blocks) ? { ...d, blocks: d.blocks.filter((b) => !(isPlainObject(b) && typeof b.file === "string")) } : d;
|
||||
const typed = Array.isArray(d.blocks) ? { ...d, blocks: d.blocks.filter((b) => !(isPlainObject(b) && (typeof b.file === "string" || typeof b.diff === "string"))) } : d;
|
||||
scan(typed, `doc "${d.id}"`);
|
||||
}
|
||||
scan(state.finish || {}, "finish");
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
adopt, askSuggestions, banner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter,
|
||||
renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope,
|
||||
wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding,
|
||||
wireActivities, wireLoopSetup, wireHelp, launchSkill, sendLearning, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace,
|
||||
wireActivities, wireLoopSetup, wireHelp, launchSkill, sendLearning, beginLearningSave, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace,
|
||||
openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen,
|
||||
renderCard, send, refreshLessonsSend,
|
||||
} from "./screens/core.js";
|
||||
@@ -37,7 +37,7 @@ import { sound } from "./sound.js";
|
||||
// and the few calls a screen makes into another are handed to state.js first.
|
||||
onSave(save);
|
||||
useHooks({
|
||||
launchSkill, sendLearning, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, askSuggestions, banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope,
|
||||
launchSkill, sendLearning, beginLearningSave, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, askSuggestions, banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope,
|
||||
openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen,
|
||||
renderCard, send, refreshLessonsSend,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
// Plan2Code Web Console - a unified diff (changes.mjs diff) read into files, hunks and numbered lines; defines only.
|
||||
//
|
||||
// The Changes tab draws what this returns. It never throws: text it cannot
|
||||
// read comes back as `{ files: [], tooLarge: false, bad: true }`, which the tab
|
||||
// shows as its error state.
|
||||
|
||||
// The lines changes.mjs writes in place of a file's lines, and after the last
|
||||
// file it kept whole when the change set was over its cap.
|
||||
export const HIDDEN_LINE = "Lines hidden: this file may hold a secret.";
|
||||
export const TOO_LARGE_LINE = "\\ No more lines shown: this change is too large to show in full.";
|
||||
|
||||
const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/;
|
||||
|
||||
// A path git quoted ("a/with \"quote\".txt"): C escapes, octal bytes as UTF-8.
|
||||
// Returns [path, rest of the line] or null.
|
||||
function unquote(s) {
|
||||
if (s[0] !== '"') return null;
|
||||
const bytes = [];
|
||||
const enc = new TextEncoder();
|
||||
const named = { n: 10, t: 9, r: 13, a: 7, b: 8, f: 12, v: 11, '"': 34, "\\": 92 };
|
||||
let i = 1;
|
||||
while (i < s.length) {
|
||||
const c = s[i];
|
||||
if (c === '"') return [new TextDecoder().decode(new Uint8Array(bytes)), s.slice(i + 1)];
|
||||
if (c === "\\") {
|
||||
const n = s[i + 1];
|
||||
if (/[0-7]/.test(n || "")) {
|
||||
const oct = /^[0-7]{1,3}/.exec(s.slice(i + 1))[0];
|
||||
bytes.push(parseInt(oct, 8) & 0xff);
|
||||
i += 1 + oct.length;
|
||||
continue;
|
||||
}
|
||||
if (n in named) {
|
||||
bytes.push(named[n]);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// One whole character, so a surrogate pair stays one.
|
||||
const ch = String.fromCodePoint(s.codePointAt(i));
|
||||
bytes.push(...enc.encode(ch));
|
||||
i += ch.length;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const strip = (p, prefix) => (p.startsWith(prefix) ? p.slice(prefix.length) : p);
|
||||
|
||||
// The two paths of a `diff --git a/x b/y` line. Unquoted paths with spaces are
|
||||
// ambiguous, so the halves are taken equal when they can be (the usual case:
|
||||
// the same file on both sides); the ---, +++ and rename lines correct it later.
|
||||
function gitLinePaths(rest) {
|
||||
if (rest[0] === '"') {
|
||||
const a = unquote(rest);
|
||||
if (!a) return null;
|
||||
const after = a[1].replace(/^ /, "");
|
||||
const b = after[0] === '"' ? unquote(after) : [after, ""];
|
||||
if (!b) return null;
|
||||
return [strip(a[0], "a/"), strip(b[0], "b/")];
|
||||
}
|
||||
const half = (rest.length - 1) / 2;
|
||||
if (Number.isInteger(half) && rest[half] === " " && rest.slice(0, half).slice(2) === rest.slice(half + 1).slice(2)) {
|
||||
return [strip(rest.slice(0, half), "a/"), strip(rest.slice(half + 1), "b/")];
|
||||
}
|
||||
const quotedB = rest.indexOf(' "b/');
|
||||
if (quotedB > 0) {
|
||||
const b = unquote(rest.slice(quotedB + 1));
|
||||
if (b) return [strip(rest.slice(0, quotedB), "a/"), strip(b[0], "b/")];
|
||||
}
|
||||
const at = rest.indexOf(" b/");
|
||||
if (at < 0) return null;
|
||||
return [strip(rest.slice(0, at), "a/"), strip(rest.slice(at + 1), "b/")];
|
||||
}
|
||||
|
||||
// The path on a ---, +++, rename from or rename to line: quoted or plain, with
|
||||
// the trailing tab git adds after a name holding a space dropped.
|
||||
function linePath(raw) {
|
||||
const q = unquote(raw);
|
||||
if (q) return q[0];
|
||||
return raw.replace(/\t$/, "");
|
||||
}
|
||||
|
||||
function newFile(paths) {
|
||||
return {
|
||||
path: paths[1],
|
||||
oldPath: paths[0],
|
||||
status: "modified",
|
||||
added: 0,
|
||||
removed: 0,
|
||||
binary: false,
|
||||
hidden: false,
|
||||
truncated: false,
|
||||
hunks: [],
|
||||
};
|
||||
}
|
||||
|
||||
function finish(file, afterCut) {
|
||||
if (file.status !== "renamed") file.oldPath = null;
|
||||
if (afterCut && !file.hunks.length && !file.binary && !file.hidden) file.truncated = true;
|
||||
file.afterCut = afterCut;
|
||||
return file;
|
||||
}
|
||||
|
||||
export function parseDiff(text) {
|
||||
const bad = { files: [], tooLarge: false, bad: true };
|
||||
if (typeof text !== "string") return bad;
|
||||
try {
|
||||
return readDiff(text);
|
||||
} catch {
|
||||
return bad;
|
||||
}
|
||||
}
|
||||
|
||||
function readDiff(text) {
|
||||
const lines = text.replace(/\r\n/g, "\n").split("\n");
|
||||
const files = [];
|
||||
let tooLarge = false;
|
||||
let file = null;
|
||||
let fileAfterCut = false;
|
||||
let hunk = null;
|
||||
let oldNo = 0;
|
||||
let newNo = 0;
|
||||
let oldLeft = 0;
|
||||
let newLeft = 0;
|
||||
let lastWasLine = false;
|
||||
const close = () => {
|
||||
if (file) files.push(finish(file, fileAfterCut));
|
||||
file = null;
|
||||
hunk = null;
|
||||
};
|
||||
|
||||
for (const line of lines) {
|
||||
// Inside a hunk, its counts decide: a line starting "+++" or "---" there
|
||||
// is a changed line, never a header.
|
||||
if (hunk && (oldLeft > 0 || newLeft > 0)) {
|
||||
const c = line[0];
|
||||
if (c === "+" && newLeft > 0) {
|
||||
hunk.lines.push({ kind: "add", oldNo: null, newNo: newNo++, text: line.slice(1) });
|
||||
newLeft--;
|
||||
file.added++;
|
||||
lastWasLine = true;
|
||||
continue;
|
||||
}
|
||||
if (c === "-" && oldLeft > 0) {
|
||||
hunk.lines.push({ kind: "del", oldNo: oldNo++, newNo: null, text: line.slice(1) });
|
||||
oldLeft--;
|
||||
file.removed++;
|
||||
lastWasLine = true;
|
||||
continue;
|
||||
}
|
||||
// An empty line stands for an empty context line some tools trim.
|
||||
if ((c === " " || line === "") && oldLeft > 0 && newLeft > 0) {
|
||||
hunk.lines.push({ kind: "ctx", oldNo: oldNo++, newNo: newNo++, text: line.slice(1) });
|
||||
oldLeft--;
|
||||
newLeft--;
|
||||
lastWasLine = true;
|
||||
continue;
|
||||
}
|
||||
if (c === "\\" && line !== TOO_LARGE_LINE && lastWasLine) {
|
||||
hunk.lines.push({ kind: "meta", oldNo: null, newNo: null, text: line });
|
||||
lastWasLine = false;
|
||||
continue;
|
||||
}
|
||||
// Anything else ends the hunk early and is read below.
|
||||
hunk = null;
|
||||
}
|
||||
|
||||
if (line === TOO_LARGE_LINE) {
|
||||
close();
|
||||
tooLarge = true;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("diff --git ")) {
|
||||
close();
|
||||
const paths = gitLinePaths(line.slice("diff --git ".length));
|
||||
if (!paths) throw new Error("unreadable diff header");
|
||||
file = newFile(paths);
|
||||
fileAfterCut = tooLarge;
|
||||
lastWasLine = false;
|
||||
continue;
|
||||
}
|
||||
if (!file) continue;
|
||||
// The marker after the last line of a file with no newline at its end.
|
||||
if (hunk && line[0] === "\\" && lastWasLine) {
|
||||
hunk.lines.push({ kind: "meta", oldNo: null, newNo: null, text: line });
|
||||
lastWasLine = false;
|
||||
continue;
|
||||
}
|
||||
const h = HUNK.exec(line);
|
||||
if (h) {
|
||||
oldNo = Number(h[1]);
|
||||
oldLeft = h[2] === undefined ? 1 : Number(h[2]);
|
||||
newNo = Number(h[3]);
|
||||
newLeft = h[4] === undefined ? 1 : Number(h[4]);
|
||||
hunk = { header: line, lines: [] };
|
||||
file.hunks.push(hunk);
|
||||
lastWasLine = false;
|
||||
continue;
|
||||
}
|
||||
if (file.hunks.length) continue;
|
||||
// The extended header lines, before any hunk.
|
||||
if (line.startsWith("new file mode")) file.status = "added";
|
||||
else if (line.startsWith("deleted file mode")) file.status = "deleted";
|
||||
else if (line.startsWith("rename from ")) {
|
||||
file.status = "renamed";
|
||||
file.oldPath = linePath(line.slice("rename from ".length));
|
||||
} else if (line.startsWith("rename to ")) {
|
||||
file.status = "renamed";
|
||||
file.path = linePath(line.slice("rename to ".length));
|
||||
} else if (line.startsWith("--- ")) {
|
||||
const p = linePath(line.slice(4));
|
||||
if (p !== "/dev/null") file.oldPath = strip(p, "a/");
|
||||
} else if (line.startsWith("+++ ")) {
|
||||
const p = linePath(line.slice(4));
|
||||
if (p !== "/dev/null") file.path = strip(p, "b/");
|
||||
} else if (/^Binary files .* differ$/.test(line) || line === "GIT binary patch") file.binary = true;
|
||||
else if (line === HIDDEN_LINE) file.hidden = true;
|
||||
}
|
||||
close();
|
||||
// A change set too big for git to print at all comes as every file's name
|
||||
// first and the too-large line last (changes.mjs): no file follows the
|
||||
// line, and each file it names is listed only.
|
||||
if (tooLarge && !files.some((f) => f.afterCut)) {
|
||||
for (const f of files) if (!f.hunks.length && !f.binary && !f.hidden) f.truncated = true;
|
||||
}
|
||||
// A hidden or cut file has no lines to count: changes.mjs sends its counts as trailer lines.
|
||||
for (const line of lines) {
|
||||
const m = /^# counts: (\d+)\t(\d+)\t(.+)$/.exec(line);
|
||||
if (!m) continue;
|
||||
for (const f of files) {
|
||||
if (f.path === m[3] && !f.hunks.length) {
|
||||
f.added = Number(m[1]);
|
||||
f.removed = Number(m[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const f of files) delete f.afterCut;
|
||||
// Text with no file section at all is not a diff.
|
||||
if (!files.length && text.trim()) return { files: [], tooLarge: false, bad: true };
|
||||
return { files, tooLarge };
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
// Plan2Code Web Console - the Changes tab: a diff block drawn as a file list and one unified diff; defines only.
|
||||
//
|
||||
// The block is `{ id, diff: "changes.diff", text }` (or `{ id, error }` when
|
||||
// the agent could not read the changes). Diff text is file content from the
|
||||
// repository, so every node is built with el() and filled with textContent:
|
||||
// nothing from it ever goes through innerHTML or md().
|
||||
|
||||
import { el } from "./render.js";
|
||||
import { parseDiff } from "./diff-parse.js";
|
||||
import { agentWorking, workingMs, patience, WORKING_GRACE_MS } from "./selectors.js";
|
||||
import { hooks, page, redraw } from "./state.js";
|
||||
import { sendState } from "./send-state.js";
|
||||
|
||||
// The picked file and the scroll of each pane, per diff block, so a redraw
|
||||
// of the same block keeps the person where they were.
|
||||
const picks = new Map();
|
||||
// The last parse of each block's text: a redraw does not parse again.
|
||||
const parsed = new Map();
|
||||
|
||||
const blockKey = (b) => String(b.id || "") + "|" + String(b.diff || "");
|
||||
|
||||
function parseOnce(b) {
|
||||
const key = blockKey(b);
|
||||
const hit = parsed.get(key);
|
||||
if (hit && hit.text === b.text) return hit.result;
|
||||
const result = parseDiff(b.text);
|
||||
parsed.set(key, { text: b.text, result });
|
||||
return result;
|
||||
}
|
||||
|
||||
const baseName = (p) => String(p || "").split("/").pop();
|
||||
const folderOf = (p) => {
|
||||
const parts = String(p || "").split("/");
|
||||
parts.pop();
|
||||
return parts.join("/");
|
||||
};
|
||||
|
||||
// What a rename row reads: old -> new, by name when the folder stayed.
|
||||
function renameLabel(f) {
|
||||
return folderOf(f.oldPath) === folderOf(f.path) ? `${baseName(f.oldPath)} → ${baseName(f.path)}` : `${f.oldPath} → ${f.path}`;
|
||||
}
|
||||
|
||||
const STATUS_WORD = { added: "Added", deleted: "Deleted", renamed: "Renamed" };
|
||||
|
||||
function counts(f) {
|
||||
const box = el("span", "diff-counts");
|
||||
box.appendChild(el("span", "diff-plus", `+${f.added}`));
|
||||
box.appendChild(el("span", "diff-minus", `-${f.removed}`));
|
||||
return box;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- states */
|
||||
|
||||
// Asks the agent to read the changes again. Refused whenever Send itself
|
||||
// would be (a finished or paused session, the loop building, no connection),
|
||||
// and, as the brief button is, while a turn is in flight.
|
||||
async function askAgain(button, status, reply) {
|
||||
const state = sendState(true);
|
||||
if (state.disabled || page.gone || page.pendingResult || (agentWorking() && workingMs() <= patience(WORKING_GRACE_MS))) {
|
||||
status.textContent = state.why || "Wait for Plan2Code to finish, then ask again.";
|
||||
return;
|
||||
}
|
||||
const label = button.textContent;
|
||||
button.disabled = true;
|
||||
button.textContent = "Asking…";
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [{ i: "__changes", type: "changes" }], reply }),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
hooks.banner("Asked for the changes again. The tab updates when they are read.", "good");
|
||||
setTimeout(() => hooks.banner(null), 5000);
|
||||
page.pendingResult = true;
|
||||
redraw();
|
||||
} catch (err) {
|
||||
if (err && err.pending) page.pendingResult = true;
|
||||
status.textContent =
|
||||
err && err.pending ? "Your last answers are still being picked up. Try again in a moment." : "That did not go through. Try again in a moment.";
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = label;
|
||||
}
|
||||
}
|
||||
|
||||
function stateBox(kind, message, buttonLabel, reply) {
|
||||
const box = el("div", "diff-state diff-" + kind);
|
||||
box.appendChild(el("p", "diff-state-msg", message));
|
||||
if (buttonLabel) {
|
||||
const btn = el("button", "btn small diff-again", buttonLabel);
|
||||
btn.type = "button";
|
||||
const status = el("p", "diff-state-why");
|
||||
status.setAttribute("role", "status");
|
||||
btn.addEventListener("click", () => askAgain(btn, status, reply));
|
||||
box.appendChild(btn);
|
||||
box.appendChild(status);
|
||||
}
|
||||
return box;
|
||||
}
|
||||
|
||||
function drawLoading() {
|
||||
const view = el("div", "diff-view is-loading");
|
||||
view.setAttribute("aria-busy", "true");
|
||||
view.appendChild(el("p", "diff-totals", "Reading the changes…"));
|
||||
const cols = el("div", "diff-cols");
|
||||
const list = el("div", "diff-list diff-skeleton");
|
||||
for (let i = 0; i < 4; i++) list.appendChild(el("span", "diff-skel-row"));
|
||||
const pane = el("div", "diff-pane diff-skeleton");
|
||||
for (let i = 0; i < 8; i++) pane.appendChild(el("span", "diff-skel-row"));
|
||||
cols.appendChild(list);
|
||||
cols.appendChild(pane);
|
||||
view.appendChild(cols);
|
||||
return view;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- ready */
|
||||
|
||||
function drawHunks(f) {
|
||||
if (f.binary) return el("p", "diff-plain", "Binary file: no lines to show");
|
||||
if (f.hidden) return el("p", "diff-plain", "Lines hidden: this file may hold a secret");
|
||||
if (f.truncated) return el("p", "diff-plain", "Too large to show in full: this file is listed only");
|
||||
if (!f.hunks.length) return el("p", "diff-plain", f.status === "renamed" ? "Renamed only: no lines changed" : "No lines changed");
|
||||
const code = el("div", "diff-code");
|
||||
const rows = el("div", "diff-rows");
|
||||
for (const h of f.hunks) {
|
||||
rows.appendChild(el("div", "diff-hunk", h.header));
|
||||
for (const l of h.lines) {
|
||||
const row = el("div", "diff-line " + l.kind);
|
||||
row.appendChild(el("span", "diff-no", l.oldNo == null ? "" : String(l.oldNo)));
|
||||
row.appendChild(el("span", "diff-no", l.newNo == null ? "" : String(l.newNo)));
|
||||
row.appendChild(el("span", "diff-sign", l.kind === "add" ? "+" : l.kind === "del" ? "-" : ""));
|
||||
row.appendChild(el("code", "diff-text", l.text));
|
||||
rows.appendChild(row);
|
||||
}
|
||||
}
|
||||
code.appendChild(rows);
|
||||
return code;
|
||||
}
|
||||
|
||||
function drawPane(f) {
|
||||
const pane = el("section", "diff-pane");
|
||||
pane.setAttribute("aria-label", "Lines of " + f.path);
|
||||
const head = el("header", "diff-pane-head");
|
||||
head.appendChild(el("strong", "diff-pane-path", f.status === "renamed" ? `${f.oldPath} → ${f.path}` : f.path));
|
||||
head.appendChild(counts(f));
|
||||
pane.appendChild(head);
|
||||
pane.appendChild(drawHunks(f));
|
||||
return pane;
|
||||
}
|
||||
|
||||
function drawReady(b, result) {
|
||||
const key = blockKey(b);
|
||||
const files = result.files;
|
||||
const memory = picks.get(key) || {};
|
||||
let picked = files.findIndex((f) => f.path === memory.path);
|
||||
if (picked < 0) picked = 0;
|
||||
|
||||
const view = el("div", "diff-view");
|
||||
const added = files.reduce((n, f) => n + f.added, 0);
|
||||
const removed = files.reduce((n, f) => n + f.removed, 0);
|
||||
const totals = el("p", "diff-totals");
|
||||
totals.appendChild(el("span", null, `${files.length} ${files.length === 1 ? "file" : "files"} changed, `));
|
||||
totals.appendChild(el("span", "diff-plus", `+${added}`));
|
||||
totals.appendChild(document.createTextNode(" "));
|
||||
totals.appendChild(el("span", "diff-minus", `-${removed}`));
|
||||
view.appendChild(totals);
|
||||
if (result.tooLarge) {
|
||||
view.appendChild(el("p", "diff-notice", "This change is too large to show in full: every file is listed, but some show no lines."));
|
||||
}
|
||||
|
||||
const cols = el("div", "diff-cols");
|
||||
const list = el("ul", "diff-list");
|
||||
list.setAttribute("role", "listbox");
|
||||
list.setAttribute("aria-label", "Changed files");
|
||||
list.tabIndex = 0;
|
||||
const idBase = "diff-" + String(b.id || "block").replace(/[^A-Za-z0-9_-]/g, "") + "-";
|
||||
const rows = files.map((f, i) => {
|
||||
const row = el("li", "diff-file");
|
||||
row.id = idBase + i;
|
||||
row.setAttribute("role", "option");
|
||||
const name = el("span", "diff-file-name");
|
||||
name.appendChild(el("strong", null, f.status === "renamed" ? renameLabel(f) : baseName(f.path)));
|
||||
if (STATUS_WORD[f.status]) name.appendChild(el("span", "diff-status diff-status-" + f.status, STATUS_WORD[f.status]));
|
||||
row.appendChild(name);
|
||||
const folder = folderOf(f.path);
|
||||
if (folder) row.appendChild(el("span", "diff-file-dir", folder));
|
||||
row.appendChild(counts(f));
|
||||
row.addEventListener("click", () => pick(i, false));
|
||||
list.appendChild(row);
|
||||
return row;
|
||||
});
|
||||
cols.appendChild(list);
|
||||
let pane = drawPane(files[picked]);
|
||||
cols.appendChild(pane);
|
||||
view.appendChild(cols);
|
||||
|
||||
const remember = () => {
|
||||
picks.set(key, {
|
||||
path: files[picked].path,
|
||||
listTop: list.scrollTop,
|
||||
paneTop: pane.scrollTop,
|
||||
paneLeft: pane.scrollLeft,
|
||||
});
|
||||
};
|
||||
const watch = () => pane.addEventListener("scroll", remember, { passive: true });
|
||||
function mark() {
|
||||
rows.forEach((r, i) => {
|
||||
r.setAttribute("aria-selected", i === picked ? "true" : "false");
|
||||
r.classList.toggle("is-picked", i === picked);
|
||||
});
|
||||
list.setAttribute("aria-activedescendant", rows[picked].id);
|
||||
}
|
||||
function pick(i, fromKeys) {
|
||||
if (i < 0 || i >= files.length) return;
|
||||
const changed = i !== picked;
|
||||
picked = i;
|
||||
mark();
|
||||
if (changed) {
|
||||
const next = drawPane(files[picked]);
|
||||
pane.replaceWith(next);
|
||||
pane = next;
|
||||
watch();
|
||||
}
|
||||
if (fromKeys) rows[picked].scrollIntoView({ block: "nearest" });
|
||||
remember();
|
||||
}
|
||||
list.addEventListener("keydown", (e) => {
|
||||
const step = { ArrowDown: 1, ArrowUp: -1 }[e.key];
|
||||
const jump = { Home: 0, End: files.length - 1 }[e.key];
|
||||
if (step === undefined && jump === undefined) return;
|
||||
e.preventDefault();
|
||||
pick(step !== undefined ? picked + step : jump, true);
|
||||
});
|
||||
list.addEventListener("scroll", remember, { passive: true });
|
||||
watch();
|
||||
mark();
|
||||
|
||||
// Back to where the person was once the view is on the page (a fresh
|
||||
// element has no layout to scroll yet).
|
||||
if (memory.path === files[picked].path) {
|
||||
requestAnimationFrame(() => {
|
||||
list.scrollTop = memory.listTop || 0;
|
||||
pane.scrollTop = memory.paneTop || 0;
|
||||
pane.scrollLeft = memory.paneLeft || 0;
|
||||
});
|
||||
}
|
||||
picks.set(key, { ...memory, path: files[picked].path });
|
||||
return view;
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- entry */
|
||||
|
||||
// One diff block as the Changes tab. `doc` is the block's document, when
|
||||
// known: a doc marked stale is still being read again.
|
||||
export function drawDiff(b, doc) {
|
||||
if (typeof b.error === "string" && b.error.trim()) {
|
||||
return wrap(stateBox("error", `The changes could not be read: ${b.error.trim()}`, "Reload the changes", "Please refresh the Changes tab."));
|
||||
}
|
||||
if (typeof b.text !== "string" || (doc && doc.stale)) return drawLoading();
|
||||
const result = parseOnce(b);
|
||||
if (result.bad) {
|
||||
return wrap(stateBox("error", "The changes could not be read: the diff is not in a shape this page can draw.", "Reload the changes", "Please refresh the Changes tab."));
|
||||
}
|
||||
if (!result.files.length) {
|
||||
return wrap(stateBox("empty", "Nothing has changed since this run started.", "Check again", "Please refresh the Changes tab."));
|
||||
}
|
||||
return drawReady(b, result);
|
||||
}
|
||||
|
||||
function wrap(box) {
|
||||
const view = el("div", "diff-view");
|
||||
view.appendChild(box);
|
||||
return view;
|
||||
}
|
||||
@@ -3,10 +3,14 @@
|
||||
// Shared by the documents tab and the finished screen, so neither imports the other.
|
||||
|
||||
import { el, md } from "./render.js";
|
||||
import { drawDiff } from "./diff-view.js";
|
||||
|
||||
// A block's content: its markdown, or for an image block (a screenshot the
|
||||
// agent saved under the session's shots/ folder) a captioned picture.
|
||||
export function blockBody(b) {
|
||||
// A block's content: its markdown, for an image block (a screenshot the
|
||||
// agent saved under the session's shots/ folder) a captioned picture, and for
|
||||
// a diff block (changes.mjs diff) the Changes tab. `doc` is the block's
|
||||
// document, when known.
|
||||
export function blockBody(b, doc) {
|
||||
if (isDiffBlock(b)) return drawDiff(b, doc);
|
||||
if (typeof b.image !== "string") return md(b.md, "md");
|
||||
const fig = el("figure", "doc-figure");
|
||||
const img = el("img", "doc-img");
|
||||
@@ -27,13 +31,31 @@ export function downloadDoc(doc) {
|
||||
// assumptions or drafts. Without the marks a half-finished document reads,
|
||||
// once it leaves the page, as a set of decisions.
|
||||
const mark = { assumed: "> **Assumed for now, still open.**\n\n", draft: "> **Draft.**\n\n" };
|
||||
const blocks = (doc.blocks || []).map((b) => (mark[b.state] || "") + (typeof b.image === "string" ? b.alt || "" : b.md || ""));
|
||||
const blocks = (doc.blocks || []).map((b) => (mark[b.state] || "") + blockText(b));
|
||||
const first = (doc.blocks || [])[0];
|
||||
const titled = first && /^\s*#\s/.test(first.md || "");
|
||||
const body = [titled || !doc.title ? null : `# ${doc.title}`, ...blocks].filter((x) => x != null).join("\n\n");
|
||||
saveFile(`${docFileName(doc)}.md`, body, "text/markdown");
|
||||
}
|
||||
|
||||
// A diff block names its .diff file, or carries only the agent's reason it
|
||||
// could not read one.
|
||||
function isDiffBlock(b) {
|
||||
return typeof b.diff === "string" || (typeof b.error === "string" && b.md == null && b.image == null);
|
||||
}
|
||||
|
||||
// What one block contributes to a saved file: a diff block's text as a fenced
|
||||
// diff (its error line when it has none), an image's caption, else markdown.
|
||||
function blockText(b) {
|
||||
if (isDiffBlock(b)) {
|
||||
if (typeof b.error === "string" && b.error.trim()) return `The changes could not be read: ${b.error.trim()}`;
|
||||
if (typeof b.text !== "string") return "";
|
||||
const fence = b.text.includes("```") ? "~~~~" : "```";
|
||||
return `${fence}diff\n${b.text.replace(/\n$/, "")}\n${fence}`;
|
||||
}
|
||||
return typeof b.image === "string" ? b.alt || "" : b.md || "";
|
||||
}
|
||||
|
||||
function docFileName(doc) {
|
||||
const name = (doc.title || "document").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
||||
return name || "document";
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
<link rel="modulepreload" href="/spec-states.js" />
|
||||
<link rel="modulepreload" href="/state.js" />
|
||||
<link rel="modulepreload" href="/doc-files.js" />
|
||||
<link rel="modulepreload" href="/diff-view.js" />
|
||||
<link rel="modulepreload" href="/diff-parse.js" />
|
||||
<link rel="modulepreload" href="/send-state.js" />
|
||||
<link rel="modulepreload" href="/mention-box.js" />
|
||||
<link rel="modulepreload" href="/uploads.js" />
|
||||
|
||||
@@ -85,7 +85,7 @@ import { mountAgentsView } from "./agents-view.js";
|
||||
|
||||
// What the entry needs from the screens at start-up, handed on from here: only
|
||||
// the core imports a screen.
|
||||
export { launchSkill, sendLearning, wakeHoldsChime, wireDashboard } from "./dashboard.js";
|
||||
export { launchSkill, sendLearning, beginLearningSave, wakeHoldsChime, wireDashboard } from "./dashboard.js";
|
||||
export { renderLearningRow, learningBlocked, refreshLessonsSend } from "./learning-row.js";
|
||||
import { renderLessonsDialog } from "./learning-row.js";
|
||||
export { fillSky } from "./starting.js";
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
loadOverview,
|
||||
finish,
|
||||
loopDriving,
|
||||
learningBusyNow,
|
||||
LEARNING_BUSY_MS,
|
||||
} from "../selectors.js";
|
||||
import { hooks, page, redraw, saveNow } from "../state.js";
|
||||
import { el, approvalTip, mdInto, releasesLink, copyButton, lightDismiss, SVG_NS } from "../render.js";
|
||||
@@ -1393,10 +1395,29 @@ async function sendDelete(spec) {
|
||||
// The Learning banner above the title, or null: only while lessons wait and
|
||||
// Learning is on or not set up. Review sends the __learning action.
|
||||
function learningBanner(sc) {
|
||||
const state = sc && sc.learning && sc.learning.state;
|
||||
const busy = learningBusyNow(state);
|
||||
// Review pressed, or the choices just saved: the banner says what the agent
|
||||
// is doing, in the same place, so the wait is never silent.
|
||||
const working = busy && (busy.what === "review" || busy.what === "decide") ? busy : null;
|
||||
const text = learningBannerText(sc && sc.learning);
|
||||
if (!text) return null;
|
||||
if (!text && !working) return null;
|
||||
const banner = el("div", "dash-nudge learn-banner");
|
||||
banner.setAttribute("role", "status");
|
||||
if (working) {
|
||||
banner.classList.add("is-busy");
|
||||
banner.setAttribute("aria-busy", "true");
|
||||
const line = el("span", "dash-nudge-text learn-busy");
|
||||
line.append(el("span", "spinner tiny"), document.createTextNode(working.what === "review" ? "Opening lessons…" : "Saving your lessons…"));
|
||||
banner.appendChild(line);
|
||||
if (working.what === "review") {
|
||||
const review = el("button", "btn small primary", "Review");
|
||||
review.type = "button";
|
||||
review.disabled = true;
|
||||
banner.appendChild(review);
|
||||
}
|
||||
return banner;
|
||||
}
|
||||
banner.appendChild(el("span", "dash-nudge-text", text));
|
||||
const review = el("button", "btn small primary", "Review");
|
||||
review.type = "button";
|
||||
@@ -1408,19 +1429,66 @@ function learningBanner(sc) {
|
||||
return banner;
|
||||
}
|
||||
|
||||
// The agent finishing with nothing to show ends the wait early: a Review whose
|
||||
// card never came (the banner was stale) says so at once instead of spinning
|
||||
// to the limit, and a saved choice stops when the agent is back to waiting.
|
||||
// `seen` waits for the send to be picked up first (or three seconds), so the
|
||||
// gap before the agent collects it is not read as "finished".
|
||||
function watchLearningBusy(busy) {
|
||||
const timer = setInterval(() => {
|
||||
if (page.learningBusy !== busy) return clearInterval(timer);
|
||||
if (Date.now() - busy.at > LEARNING_BUSY_MS) {
|
||||
clearInterval(timer);
|
||||
page.learningBusy = null;
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
if (page.pendingResult || agentWorking()) {
|
||||
busy.seen = true;
|
||||
return;
|
||||
}
|
||||
// Idle and never seen busy: the agent was quicker than the page's poll
|
||||
// (or the send is a moment from being picked up), so give it three seconds.
|
||||
if (!busy.seen && Date.now() - busy.at < 3000) return;
|
||||
clearInterval(timer);
|
||||
page.learningBusy = null;
|
||||
if (busy.what === "review") {
|
||||
hooks.banner("No lessons are waiting any more.", "info");
|
||||
setTimeout(() => hooks.banner(null), 4000);
|
||||
}
|
||||
redraw();
|
||||
}, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* The lessons dialog's Save lessons went through: the banner's place says
|
||||
* "Saving your lessons…" until the agent is done with the choices.
|
||||
*/
|
||||
export function beginLearningSave() {
|
||||
const sc = scan();
|
||||
const busy = { what: "decide", from: sc && sc.learning && sc.learning.state, at: Date.now(), seen: false };
|
||||
page.learningBusy = busy;
|
||||
watchLearningBusy(busy);
|
||||
setTimeout(redraw, LEARNING_BUSY_MS + 500);
|
||||
redraw();
|
||||
}
|
||||
|
||||
// A Learning control that changes the project: a __learning action to the
|
||||
// dashboard agent, posted the way sendDelete() posts. No hop: the agent runs
|
||||
// lessons.mjs, rescans and posts the menu again.
|
||||
export async function sendLearning(what) {
|
||||
if (hooks.learningBlocked()) return;
|
||||
// Switching on or off shows as working at once, before the agent answers.
|
||||
// Switching on or off, or opening Review, shows as working at once, before
|
||||
// the agent answers.
|
||||
const sc = scan();
|
||||
const from = sc && sc.learning && sc.learning.state;
|
||||
if ((what === "switch-on" || what === "switch-off") && from) {
|
||||
page.learningBusy = { what, from, at: Date.now() };
|
||||
if ((what === "switch-on" || what === "switch-off" || what === "review") && from) {
|
||||
const busy = { what, from, at: Date.now(), seen: false };
|
||||
page.learningBusy = busy;
|
||||
redraw();
|
||||
// One redraw at the limit, so a switch the agent never answers stops spinning.
|
||||
setTimeout(redraw, 30500);
|
||||
// One redraw at the limit, so an action the agent never answers stops spinning.
|
||||
setTimeout(redraw, LEARNING_BUSY_MS + 500);
|
||||
if (what === "review") watchLearningBusy(busy);
|
||||
}
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
|
||||
@@ -191,7 +191,7 @@ export function renderDoc(main, id) {
|
||||
box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
|
||||
}
|
||||
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
|
||||
box.appendChild(blockBody(b));
|
||||
box.appendChild(blockBody(b, doc));
|
||||
main.appendChild(box);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9,11 +9,11 @@
|
||||
// in dashboard.js, reached through hooks: a screen never imports another),
|
||||
// and is disabled whenever a card would be.
|
||||
|
||||
import { page, redraw, hooks } from "../state.js";
|
||||
import { page, redraw, hooks, stage } from "../state.js";
|
||||
import { el, mdInto, lightDismiss } from "../render.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { sendState } from "../send-state.js";
|
||||
import { loopDriving, isOpen, stagedCount } from "../selectors.js";
|
||||
import { loopDriving, isOpen, stagedCount, learningBusyNow } from "../selectors.js";
|
||||
|
||||
const TOP_STATES = new Set(["not-set-up", "off", "paused"]);
|
||||
|
||||
@@ -48,23 +48,14 @@ export function learningBlocked() {
|
||||
return "";
|
||||
}
|
||||
|
||||
// How long a switch on or off may show as working before the row gives up
|
||||
// waiting for the new state (the agent normally answers in a second or two).
|
||||
const BUSY_MS = 30000;
|
||||
|
||||
/**
|
||||
* The switch the person just pressed while the agent works on it, or null.
|
||||
* sendLearning() sets page.learningBusy the instant a switch is pressed;
|
||||
* it ends when the scan shows a different state, the send fails, or BUSY_MS pass.
|
||||
* The switch the person just pressed while the agent works on it, or null (the
|
||||
* rule is learningBusyNow() in selectors.js; Review and a saved choice show in
|
||||
* the banner instead).
|
||||
*/
|
||||
function busySwitch(state) {
|
||||
const busy = page.learningBusy;
|
||||
if (!busy) return null;
|
||||
if (busy.from !== state || Date.now() - busy.at > BUSY_MS) {
|
||||
page.learningBusy = null;
|
||||
return null;
|
||||
}
|
||||
return busy;
|
||||
const busy = learningBusyNow(state);
|
||||
return busy && (busy.what === "switch-on" || busy.what === "switch-off") ? busy : null;
|
||||
}
|
||||
|
||||
function agentButton(text, cls, what) {
|
||||
@@ -203,6 +194,80 @@ function wireOutside() {
|
||||
|
||||
/* ------------------------------------------------------------- the dialogs */
|
||||
|
||||
// The dialog's own state, kept across the dashboard's redraws: a send from it
|
||||
// in flight (the card locks), and the "choices not saved" ask after a close
|
||||
// was asked for while something is chosen.
|
||||
let saving = false;
|
||||
let askingClose = false;
|
||||
// The card the dialog shows now, for the handlers made once with the dialog.
|
||||
let shownItem = null;
|
||||
|
||||
/** How many lessons the person has chosen on the card so far (its draft). */
|
||||
function chosenCount(item) {
|
||||
try {
|
||||
const d = JSON.parse(page.local.drafts["lessons-" + item.id] || "null");
|
||||
return d && d.picks && typeof d.picks === "object" ? Object.values(d.picks).filter(Boolean).length : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the staged choices from the dialog. While it goes the card locks and
|
||||
* the button says Saving…; the dialog closes by itself once the send is in,
|
||||
* and the dashboard's banner takes over with "Saving your lessons…". `undo`
|
||||
* puts staged choices back the way they were when the send did not go.
|
||||
*/
|
||||
async function saveLessons(item, undo) {
|
||||
if (saving) return;
|
||||
saving = true;
|
||||
askingClose = false;
|
||||
redraw();
|
||||
try {
|
||||
await hooks.send();
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
if (page.local.sent && page.local.sent[item.id]?.value) {
|
||||
hooks.beginLearningSave();
|
||||
return;
|
||||
}
|
||||
if (undo) undo();
|
||||
redraw();
|
||||
}
|
||||
|
||||
/** Not now: leave every lesson waiting, and tell the agent so it is not left holding a card no one can answer. */
|
||||
function leaveAllWaiting(item) {
|
||||
// A send that cannot go says so, rather than a close that does nothing.
|
||||
const state = sendState(true);
|
||||
if (state.disabled) {
|
||||
hooks.banner(state.why || "Plan2Code cannot take that right now. Try again in a moment.", "warn");
|
||||
return;
|
||||
}
|
||||
const before = page.local.staged[item.id];
|
||||
// A note typed in "Anything to add?" goes with it.
|
||||
stage(item.id, { type: "answer", kind: "lessons", decisions: [], ...(before && before.text ? { text: before.text } : {}) });
|
||||
return saveLessons(item, () => stage(item.id, before === undefined ? null : before));
|
||||
}
|
||||
|
||||
/** The close, the Not now button and Escape: straight out when nothing is chosen, an ask first when something is. */
|
||||
function requestClose(item) {
|
||||
if (saving) return;
|
||||
if (chosenCount(item) > 0) {
|
||||
askingClose = true;
|
||||
redraw();
|
||||
queueMicrotask(() => document.querySelector("#lessons-modal .lessons-unsaved .btn")?.focus());
|
||||
return;
|
||||
}
|
||||
leaveAllWaiting(item);
|
||||
}
|
||||
|
||||
function spinnerLabel(text) {
|
||||
const wrap = document.createDocumentFragment();
|
||||
wrap.append(el("span", "spinner tiny"), document.createTextNode(text));
|
||||
return wrap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Review from the dashboard (FR-18): the dashboard agent posts the lessons
|
||||
* card while the workflow is still `dashboard`, and its page draws no question
|
||||
@@ -220,45 +285,97 @@ export function renderLessonsDialog(on) {
|
||||
const sent = item && ((page.local.sent && page.local.sent[item.id]?.value) || item.submitted);
|
||||
let dlg = document.getElementById("lessons-modal");
|
||||
if (!item || sent) {
|
||||
if (dlg && dlg.open) dlg.close();
|
||||
if (dlg && dlg.open) {
|
||||
dlg.close();
|
||||
// The Review button that opened it is the place to land again.
|
||||
document.querySelector(".learn-banner button:not(:disabled)")?.focus();
|
||||
}
|
||||
askingClose = false;
|
||||
return;
|
||||
}
|
||||
shownItem = item;
|
||||
if (!dlg) {
|
||||
dlg = el("dialog", "modal lessons-dialog");
|
||||
dlg.id = "lessons-modal";
|
||||
dlg.setAttribute("aria-label", "Lessons to review");
|
||||
// Not light-dismissed, and Escape does not close it: the agent is waiting
|
||||
// on this card, and the dialog is the only place it is drawn. Leave them
|
||||
// all waiting, then Send, is the way out.
|
||||
dlg.addEventListener("cancel", (e) => e.preventDefault());
|
||||
// The agent is waiting on this card, and the dialog is the only place it
|
||||
// is drawn, so a close is never only a hide: Escape, the corner ×, Not now
|
||||
// and a click outside all leave every lesson waiting and say so (a click
|
||||
// outside only while nothing is chosen, so a stray one never costs picks).
|
||||
dlg.addEventListener("cancel", (e) => {
|
||||
e.preventDefault();
|
||||
if (shownItem) requestClose(shownItem);
|
||||
});
|
||||
lightDismiss(dlg, () => {
|
||||
if (shownItem && !saving && !chosenCount(shownItem)) leaveAllWaiting(shownItem);
|
||||
return false;
|
||||
});
|
||||
document.body.appendChild(dlg);
|
||||
}
|
||||
const scroll = dlg.scrollTop;
|
||||
dlg.classList.toggle("is-saving", saving);
|
||||
dlg.setAttribute("aria-busy", saving ? "true" : "false");
|
||||
const card = hooks.renderCard(item);
|
||||
if (saving) card.inert = true;
|
||||
const x = el("button", "modal-x", "×");
|
||||
x.type = "button";
|
||||
x.setAttribute("aria-label", "Close without saving");
|
||||
x.disabled = saving;
|
||||
x.addEventListener("click", () => requestClose(item));
|
||||
const actions = el("div", "modal-actions");
|
||||
const go = el("button", "btn primary", "Send to Plan2Code");
|
||||
go.type = "button";
|
||||
go.id = "lessons-send";
|
||||
go.addEventListener("click", () => hooks.send());
|
||||
actions.appendChild(go);
|
||||
if (stagedCount() > 1) actions.appendChild(el("p", "help", "Anything else ready to send goes with it."));
|
||||
dlg.replaceChildren(card, actions);
|
||||
if (askingClose && !saving) {
|
||||
const ask = el("div", "lessons-unsaved");
|
||||
ask.setAttribute("role", "alert");
|
||||
ask.appendChild(el("p", "lessons-unsaved-text", "You have choices that are not saved."));
|
||||
const row = el("div", "modal-actions");
|
||||
const keep = el("button", "btn ghost", "Keep editing");
|
||||
keep.type = "button";
|
||||
keep.addEventListener("click", () => {
|
||||
askingClose = false;
|
||||
redraw();
|
||||
});
|
||||
const drop = el("button", "btn danger", "Discard and close");
|
||||
drop.type = "button";
|
||||
drop.addEventListener("click", () => leaveAllWaiting(item));
|
||||
const save = el("button", "btn primary", "Save lessons");
|
||||
save.type = "button";
|
||||
save.disabled = !page.local.staged[item.id] || sendState().disabled;
|
||||
save.addEventListener("click", () => saveLessons(item));
|
||||
row.append(keep, drop, save);
|
||||
ask.appendChild(row);
|
||||
actions.appendChild(ask);
|
||||
} else {
|
||||
const later = el("button", "btn ghost", "Not now");
|
||||
later.type = "button";
|
||||
later.id = "lessons-later";
|
||||
later.disabled = saving;
|
||||
later.addEventListener("click", () => requestClose(item));
|
||||
const go = el("button", "btn primary");
|
||||
go.type = "button";
|
||||
go.id = "lessons-send";
|
||||
if (saving) go.appendChild(spinnerLabel("Saving…"));
|
||||
else go.textContent = "Save lessons";
|
||||
go.addEventListener("click", () => saveLessons(item));
|
||||
actions.append(later, go);
|
||||
if (stagedCount() > 1) actions.appendChild(el("p", "help", "Anything else ready to send goes with it."));
|
||||
}
|
||||
dlg.replaceChildren(card, actions, x);
|
||||
refreshLessonsSend();
|
||||
if (!dlg.open) dlg.showModal();
|
||||
dlg.scrollTop = scroll;
|
||||
}
|
||||
|
||||
/**
|
||||
* The dialog's Send, set again whenever what is staged changes, including the
|
||||
* quiet staging of typing (a Reword field emptied, a note): on only while the
|
||||
* lessons card holds an answer and a send can go.
|
||||
* The dialog's Save lessons, set again whenever what is staged changes,
|
||||
* including the quiet staging of typing (a Reword field emptied, a note): on
|
||||
* only while the lessons card holds an answer and a send can go.
|
||||
*/
|
||||
export function refreshLessonsSend() {
|
||||
const go = document.getElementById("lessons-send");
|
||||
if (!go) return;
|
||||
const items = (page.S && Array.isArray(page.S.items) && page.S.items) || [];
|
||||
const item = items.find((i) => i && i.kind === "lessons" && isOpen(i));
|
||||
go.disabled = !item || !page.local.staged[item.id] || sendState().disabled;
|
||||
go.disabled = saving || !item || !page.local.staged[item.id] || sendState().disabled;
|
||||
}
|
||||
|
||||
function dialog(id, cls, title) {
|
||||
|
||||
@@ -12,6 +12,31 @@ import { ASK_BUSY_MS, chatAnswering } from "./chat.js";
|
||||
|
||||
export const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||
|
||||
// How long a Learning action may show as working before the page gives up
|
||||
// waiting for the agent (it normally answers in a second or two).
|
||||
export const LEARNING_BUSY_MS = 30000;
|
||||
|
||||
/**
|
||||
* The Learning action the person just pressed while the agent works on it, or
|
||||
* null. sendLearning() (dashboard.js) sets page.learningBusy the instant a
|
||||
* button is pressed: `switch-on` and `switch-off` end when the scan shows a
|
||||
* different state than `from`, `review` ends when its lessons card is open,
|
||||
* and any of them ends after LEARNING_BUSY_MS. The agent finishing with
|
||||
* nothing to show is ended by sendLearning()'s watcher, not here.
|
||||
*/
|
||||
export function learningBusyNow(state) {
|
||||
const busy = page.learningBusy;
|
||||
if (!busy) return null;
|
||||
const end = () => {
|
||||
page.learningBusy = null;
|
||||
return null;
|
||||
};
|
||||
if (Date.now() - busy.at > LEARNING_BUSY_MS) return end();
|
||||
if ((busy.what === "switch-on" || busy.what === "switch-off") && busy.from !== state) return end();
|
||||
if (busy.what === "review" && ((page.S && page.S.items) || []).some((i) => i && i.kind === "lessons" && isOpen(i))) return end();
|
||||
return busy;
|
||||
}
|
||||
|
||||
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
||||
// listening. The difference is the cost of being wrong: a working agent that
|
||||
// goes quiet is worth mentioning early, whereas the gap between `wait`
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/* diff.css: The Changes tab, a diff block drawn as a file list and one unified diff. */
|
||||
|
||||
/* Every color is a token, so light and dark both come from tokens.css. Added
|
||||
lines take the success pair (--ok, --ok-soft), removed lines the danger
|
||||
pair (--warn, --warn-soft). */
|
||||
|
||||
.diff-view { --diff-gutter: 3.4em; --diff-sign: 1.6em; min-width: 0; }
|
||||
|
||||
.diff-totals { margin: 0 0 10px; color: var(--ink-2); font-size: 13.5px; font-variant-numeric: tabular-nums; }
|
||||
.diff-notice {
|
||||
margin: 0 0 12px; padding: 8px 12px; border: 1px solid var(--stage); border-radius: 8px;
|
||||
background: var(--stage-soft); color: var(--ink); font-size: 13px;
|
||||
}
|
||||
.diff-plus { color: var(--ok); font-weight: 600; }
|
||||
.diff-minus { color: var(--warn); font-weight: 600; }
|
||||
.diff-counts { display: inline-flex; gap: 6px; font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* Two columns, each scrolling inside itself: the tab never grows past the
|
||||
window, so the doc's head (with its way back to the sign-off card) stays in
|
||||
view however long the diff is. */
|
||||
.diff-cols {
|
||||
display: grid; grid-template-columns: 240px minmax(0, 1fr); gap: 12px; align-items: start;
|
||||
--diff-max: max(260px, calc(100vh - 280px));
|
||||
}
|
||||
|
||||
.diff-list {
|
||||
list-style: none; margin: 0; padding: 6px; max-height: var(--diff-max); overflow-y: auto; overscroll-behavior: contain;
|
||||
background: var(--panel); border: 1px solid var(--rule); border-radius: var(--radius);
|
||||
}
|
||||
.diff-list:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
|
||||
.diff-file {
|
||||
display: grid; gap: 2px; padding: 7px 10px; border-radius: calc(var(--radius) / 2); cursor: pointer;
|
||||
}
|
||||
.diff-file:hover { background: var(--panel-2); }
|
||||
.diff-file.is-picked { background: var(--accent-soft); box-shadow: inset 3px 0 var(--accent); }
|
||||
.diff-file-name { display: flex; flex-wrap: wrap; gap: 6px; align-items: baseline; min-width: 0; }
|
||||
.diff-file-name strong { font-weight: 600; overflow-wrap: anywhere; }
|
||||
.diff-file-dir { color: var(--ink-3); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.diff-status {
|
||||
font: 700 10px/1.4 var(--mono); letter-spacing: 0.04em; text-transform: uppercase;
|
||||
padding: 0 5px; border-radius: 4px; border: 1px solid var(--rule-2); color: var(--ink-2);
|
||||
}
|
||||
.diff-status-added { border-color: var(--ok); color: var(--ok); }
|
||||
.diff-status-deleted { border-color: var(--warn); color: var(--warn); }
|
||||
.diff-status-renamed { border-color: var(--accent); color: var(--accent); }
|
||||
|
||||
/* The pane scrolls both ways, so the sideways scrollbar for a long line sits
|
||||
at the bottom of the pane, never under the file's last row. */
|
||||
.diff-pane {
|
||||
min-width: 0; max-height: var(--diff-max); overflow: auto; overscroll-behavior: contain;
|
||||
background: var(--panel); border: 1px solid var(--rule); border-radius: var(--radius);
|
||||
}
|
||||
.diff-pane-head {
|
||||
display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap;
|
||||
padding: 9px 14px; border-bottom: 1px solid var(--rule);
|
||||
position: sticky; top: 0; left: 0; z-index: 1; background: var(--panel);
|
||||
}
|
||||
.diff-pane-path { font-weight: 600; overflow-wrap: anywhere; }
|
||||
|
||||
/* Long lines scroll sideways with the pane, all rows together, never the page. */
|
||||
.diff-rows { display: grid; min-width: 100%; width: max-content; font: 12px/1.55 var(--mono); }
|
||||
.diff-hunk { padding: 3px 14px; color: var(--ink-3); background: var(--panel-2); white-space: pre; }
|
||||
.diff-line { display: grid; grid-template-columns: var(--diff-gutter) var(--diff-gutter) var(--diff-sign) auto; }
|
||||
.diff-no { text-align: right; padding-right: 8px; color: var(--ink-3); font-variant-numeric: tabular-nums; user-select: none; }
|
||||
.diff-sign { text-align: center; color: var(--ink-3); user-select: none; }
|
||||
.diff-text { font: inherit; white-space: pre; padding-right: 14px; color: var(--ink); background: none; border: 0; }
|
||||
.diff-line.add { background: var(--ok-soft); }
|
||||
.diff-line.add .diff-sign { color: var(--ok); font-weight: 700; }
|
||||
.diff-line.del { background: var(--warn-soft); }
|
||||
.diff-line.del .diff-sign { color: var(--warn); font-weight: 700; }
|
||||
.diff-line.meta .diff-text { color: var(--ink-3); font-style: italic; }
|
||||
|
||||
.diff-plain { margin: 0; padding: 16px 14px; color: var(--ink-2); }
|
||||
|
||||
/* Empty and error: a plain line and a button to ask again. */
|
||||
.diff-state { padding: 16px 18px; border: 1px solid var(--rule); border-radius: var(--radius); background: var(--panel); }
|
||||
.diff-state.diff-error { border-color: var(--warn); background: var(--warn-soft); }
|
||||
.diff-state-msg { margin: 0 0 12px; }
|
||||
.diff-state-why { margin: 8px 0 0; color: var(--ink-2); font-size: 13px; }
|
||||
.diff-state-why:empty { display: none; }
|
||||
|
||||
/* Loading: muted rows where the list and the lines will be. */
|
||||
.diff-skeleton { display: grid; gap: 10px; padding: 14px; }
|
||||
.diff-skel-row { display: block; height: 14px; border-radius: 4px; background: var(--rule); }
|
||||
.diff-pane.diff-skeleton .diff-skel-row:nth-child(3n) { width: 70%; }
|
||||
.diff-pane.diff-skeleton .diff-skel-row:nth-child(4n + 1) { width: 85%; }
|
||||
|
||||
/* Narrow window: the file list stacks above the diff as a short list. */
|
||||
@media (max-width: 720px) {
|
||||
.diff-cols { grid-template-columns: minmax(0, 1fr); --diff-max: max(240px, calc(100vh - 340px)); }
|
||||
.diff-list { max-height: 152px; }
|
||||
}
|
||||
|
||||
@media print {
|
||||
.diff-list, .diff-pane { max-height: none; overflow: visible; }
|
||||
.diff-text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.diff-rows { width: auto; }
|
||||
}
|
||||
@@ -197,6 +197,39 @@
|
||||
.modal.lessons-dialog { width: min(720px, calc(100vw - 32px)); }
|
||||
.lessons-dialog .card { margin: 0; box-shadow: none; border: 0; padding: 0; }
|
||||
|
||||
/* Switching Learning on or off: shown the moment the button is pressed. */
|
||||
/* The lessons dialog: closable (the corner ×, Not now, Escape), and locked
|
||||
while Save lessons goes. */
|
||||
.lessons-dialog .modal-actions { align-items: center; justify-content: flex-end; }
|
||||
.lessons-dialog .modal-actions .btn { margin: 0; }
|
||||
.lessons-dialog .modal-actions .btn .spinner { margin-right: 8px; }
|
||||
.modal-x {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 12px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 0;
|
||||
font-size: 22px;
|
||||
line-height: 1;
|
||||
color: var(--ink-3);
|
||||
background: none;
|
||||
border: 0;
|
||||
border-radius: calc(var(--radius) * 0.5);
|
||||
cursor: pointer;
|
||||
}
|
||||
.modal-x:hover:not(:disabled),
|
||||
.modal-x:focus-visible { color: var(--ink); background: var(--panel-2); }
|
||||
.modal-x:disabled { opacity: 0.4; cursor: default; }
|
||||
.lessons-dialog.is-saving .card { opacity: 0.6; }
|
||||
.lessons-unsaved { flex: 1 1 100%; padding: 10px 12px; border-left: 4px solid var(--warn); background: var(--warn-soft); border-radius: calc(var(--radius) * 0.5); }
|
||||
.lessons-unsaved .modal-actions { flex-wrap: wrap; }
|
||||
.lessons-unsaved .btn { white-space: nowrap; }
|
||||
.lessons-unsaved-text { margin: 0 0 8px; font-size: 13.5px; color: var(--ink); }
|
||||
|
||||
/* Switching Learning on or off, opening Review, saving: shown the moment the
|
||||
button is pressed. */
|
||||
.learn-busy { display: inline-flex; align-items: center; gap: 8px; color: var(--ink-3); }
|
||||
.learn-banner.is-busy .dash-nudge-text { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.learn-row.is-busy .learn-pill { opacity: 0.6; }
|
||||
@@ -28,6 +28,8 @@ export const SERVABLE = new Set([
|
||||
"card-rows.js",
|
||||
"state.js",
|
||||
"doc-files.js",
|
||||
"diff-parse.js",
|
||||
"diff-view.js",
|
||||
"send-state.js",
|
||||
"mention-box.js",
|
||||
"md-field.js",
|
||||
@@ -320,7 +322,7 @@ export const SERVABLE = new Set([
|
||||
// Layers first, then one file per screen, then responsive and print last so
|
||||
// its overrides still come after everything they override. The files are not
|
||||
// on SERVABLE: they reach the page only through /app.css.
|
||||
export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "learning.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "prefs.css", "agents.css", "notepad.css", "activities.css", "git.css", "responsive.css"];
|
||||
export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "learning.css", "poses.css", "docs.css", "diff.css", "ask.css", "ending.css", "help.css", "looks.css", "prefs.css", "agents.css", "notepad.css", "activities.css", "git.css", "responsive.css"];
|
||||
|
||||
// The files joined with one newline between them (each file's own last newline
|
||||
// is that one), as the server serves them before the accent rules. The test
|
||||
|
||||
Reference in new issue
Block a user