Merge pull request #13 from jparkerweb/feature/utility-updates

Feature/utility updates
This commit is contained in:
jparkerweb authored and GitHub committed 2026-10-18 17:24:09 -07:00
commit a19dc6c5df
163 files changed
+29657 -19386

No files matched your search

+104 -42
View File
@@ -15,10 +15,13 @@ plan2code/
│ │ ├── resolve.md # Per-type resolution + graduating the fog
│ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff
│ │ └── trail.md # Every-response map visual + pathed resume command
│ ├── shared-references/ # Reference files shared across skills
│ │ └── building-habits.md # Find the cause, test first, pin behaviour (quick-task, implement, implement-review)
│ ├── plan2code-review-references/ # Reference files for review skill
│ │ ├── verification-protocol.md # Deep verification + confidence calibration
│ │ ├── dimensions.md # 11 dimensions with detailed checklists
│ │ ├── false-positives.md # Known false-positive patterns
│ │ ├── reviewer-brief.md # Fill-in brief for the one fresh helper that runs the analysis
│ │ └── session-end.md # Next-step routing at review session end
│ ├── plan2code-init-update-references/ # Reference files for init-update skill
│ │ └── ai-agent-file-sync.md # Step 7: replace AI configs with AGENTS.md refs
@@ -41,16 +44,18 @@ plan2code/
│ └── plan2code.ico # Desktop shortcut icon (Windows)
├── src/web-console/ # Local browser UI bundled into every skill (Node.js, zero deps, no build)
│ ├── console.mjs # CLI the agent drives: open, post, wait, chat, keep, status, stop, help
│ ├── server.mjs, lib.mjs, picker.mjs
│ ├── server.mjs, routes.mjs, static.mjs, cmd-*.mjs, picker.mjs, and the by-job files (files, sessions, patches, scan, inbox, workspace, settings)
│ ├── console.md, console-*.md, notes/, building*.md # Agent-facing contract (console.md read once, the rest on demand)
│ └── public/ # Page assets served to the browser
├── scripts/ # Development scripts
│ ├── bench-web-console.mjs # Start-path timing
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs puppeteer-core)
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs a local Chrome or Edge, through `playwright-core`)
│ ├── browser.mjs # The one place a browser is launched (Chrome, then Edge, through `playwright-core`; `PLAN2CODE_TEST_BROWSER` forces one); page tests, the screenshots and the bench use it
│ ├── css-snapshot.mjs # Dev-only: every element's computed style on every screen, both themes; take one before a stylesheet move and `--compare` after
│ ├── check-skill-table.mjs # src/plan2code.md "What each skill reads and writes" table vs each skill's prompt and references
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area, and their shared setup
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area (the page tests are `-page-*`, the source shape `-shape`), and their shared setup
│ ├── test-launcher.mjs, test-getting-started.mjs # Launcher suite; newcomer docs kept in step
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, test-git-repo.mjs, skill-script-helpers.mjs, fixture-helpers.mjs # Skill script suites and fixtures
│ └── validate-char-count.js # Pre-commit character count validator
@@ -102,9 +107,11 @@ plan2code/
| `plan2code-2-document.md` | 2 | Create implementation specs |
| `plan2code-3-implement.md` | 3 | Execute implementation (phase by phase) |
| `plan2code-3-implement-review.md` | 3 | Execute one phase, run focused review and fixes, then request approval |
| `plan2code-review.md` | review | Post-implementation comprehensive review |
| `plan2code-review.md` | review | Post-implementation comprehensive review, analysed by one fresh helper when the tool has one (verified in session; the report says who reviewed) |
| `plan2code-4-finalize.md` | 4 | Validate, summarize, feedback, archive (steps 1–7, +optional 6.5) |
| `plan2code-handoff.md` | handoff | Compact the conversation into a self-contained handoff document for a fresh session |
| `plan2code-xray.md` | xray | Explain how and why an area works (files, commits, PRs via `gh` when present), or rank the rough spots worth fixing into `ARCHITECTURE-BRIEF-<date>.md` for Pathfinder or Plan; never edits code |
| `plan2code-diagnose.md` | diagnose | Find a bug's cause under the find-the-cause-first habit (`references/building-habits.md`) and write it up as `specs/<bug-name>/DIAGNOSIS-<YYYYMMDD>.md` without fixing it, then offer Quick Task to fix it, or Plan when the fix is big. The dashboard scan reports such a folder as spec state `diagnosed` ("Bug diagnosed"), which lights Quick Task (suggested) and Plan. Once Quick Task marks the diagnosis `Fixed` (nothing past it in the folder) the state is `fixed` ("Bug fixed"): no pipeline card lights, the picker never pre-selects it, and Quick Task offers to archive it with `specs.mjs archive` |
| `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 |
@@ -124,7 +131,7 @@ Examples:
Some workflows use companion reference files for depth that does not need to load on every invocation. The orchestrator (main workflow file) loads them via `Read` directives during execution.
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`)
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`). A file several skills read lives in `src/shared-references/` instead and ships to each through `additionalReferences` (e.g., `building-habits.md` into Quick Task, Implement and Implement + Review).
**How the installer handles them:** the directory is copied verbatim to `skills/<skill-name>/references/`, so `Read references/<file>.md` resolves consistently for every agent. There is one output format, with no flat-file sibling directory or path rewrite.
@@ -143,14 +150,14 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
| Script | Skills | Does |
|---|---|---|
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/lib.mjs`, so the dashboard and the skills share one spec classifier |
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/scan.mjs`, so the dashboard and the skills share one spec classifier |
| `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update, git | The `<subject>` / `AI Assisted` commit command (two `-m` flags), with optional `git add` |
| `review-scope.mjs` | review, implement(-review), quick-task | Review Mode's git fallback: files, lines, doc share, base branch |
| `agents-md.mjs` | init, init-update | AGENTS.md structure, budget, orphans, broken links, always-inline sections |
| `agent-files.mjs` | init, init-update | Detect and replace other agents' config files with AGENTS.md pointers |
| `pathfinder.mjs` (own) | 0-pathfinder | `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate`, `lint`, `brief-data` |
| `feedback-payload.mjs` (own) | 4-finalize | STEP 6.5's payload (real sha256 prompt hashes) and the gh / browser / print submission tiers |
| `handoff-path.mjs` (own) | handoff | Timestamped path, OS temp dir, git ignore check |
| `xray.mjs` (own) | xray | `hotspots` (churn, files changed together, often-changed files with no test, from `git log` over a capped window) and `history <path>` (commits following renames, a blame summary, PR titles and first paragraphs through `gh` when signed in, and which sources were used). Read-only |
| `changelog-state.mjs` (own) | changelog | `state`, `bump`, `set-package-version`: the default branch's version, whether the branch's entry can be extended (not released, not on another branch), the file's heading style, the gap since the entry was last touched; only `set-package-version` writes, and only the version field |
| `git.mjs` (own) | git | `state`, `plan`, `branch-check`, `init-check`, `delete-check`, `cleanup-list`, `conflicts`, `pr-url`, `classify-error`: the repo snapshot, each action's exact command and confirm text (shared by the terminal and the board), branch-name, delete, cleanup and git init checks, a stopped rebase's conflicts, the pull-request link and git's errors sorted into kinds with a next step. Read-only: the agent runs every command it prints, and `guard()` refuses force push, hook skipping, amend, remote delete and blanket add |
@@ -175,90 +182,145 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| File | Role |
|---|---|
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`; `help <topic>` prints one contract file, `help topics` lists them). `post --wait <N>` posts and waits in one command |
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `delete-spec`, `handoff new`, `delete-handoff` (both on `handoffs.mjs`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`; `help <topic>` prints one contract file, `help topics` lists them). `post --wait <N>` posts and waits in one command |
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()`; plus `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `subagents.js`, `mentions.js`, `favicon.js`, `git-board.js`, `git-board-view.js`, `pr-url.js`, `app.css`, `render.js`, `palette.js`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server and the tests import `answers.js`, `palette.js`, `labels.js`, `boot.js`, `chat.js`, `help.js` and `starters.js`) parses them as ES modules without a reparse warning |
| `public/` (other files) | `index.html`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server and the tests import the pure modules) parses them as ES modules without a reparse warning. The stylesheet is the files in `public/styles/`, joined by the server into the one `/app.css` the page asks for |
| `cmd-chat.mjs` | the `chat` command: hand over Quick questions now, never waiting |
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files |
| `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser |
| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent |
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop |
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
| `inbox.mjs` | the Quick question chat's inbox beside the card slot |
| `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 patch merge, `resolveDocFiles()` 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 |
| `scan.mjs` | what the dashboard knows about the repo: `scanProject()`, `classifySpec()` (a folder's files to a spec state), `TASK_LINE_RE` and `removeSpec()` |
| `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 → Cleanup |
| `settings.mjs` | the person's saved console settings: Subagents and pull-request hosts |
| `static.mjs` | serving the page's own files: `SERVABLE` (the allow-list), `TYPES`, caching and ETags, the accent colors, and `CSS_ORDER` + `joinedStyles()`, the one place the cascade order is stated |
| `workspace.mjs` | the session's extra folders, and the folders remembered per project and spec |
| `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/looks.js` | how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches |
| `public/mention-box.js` | the @name suggestions popover under a text box |
| `public/net.js` | the page talking to its own server |
| `public/palette.js` | the highlight colors, the sound events and the card widths, as data (importable by Node so a test can check every shade in both themes) |
| `public/render.js` | Markdown to DOM, safely: no HTML string is ever produced, only nodes built with `createElement` and `textContent`; also the shared page helpers (`el`, `md`, `copyButton`, `lightDismiss`) |
| `public/selectors.js` | what the page reads off its state: the questions, the finish, the scan, who has the ball |
| `public/send-state.js` | whether Send is available, and what its button says |
| `public/skills.js` | the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (`SKILL_CATALOG`, `START_POSES`, `CONSOLE_WORKFLOWS` and the rest, in `answers.js`) are lookups on it |
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click |
| `public/spec-states.js` | the spec states (`diagnosed`, `fixed`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
| `public/state.js` | the page's shared state (`page.S` the server's truth, `page.local` what is staged) and the `redraw()` / save hooks every screen calls; defines only |
| `public/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry |
| `public/screens/ask.js` | the Ask chat, the Subagents tab, and attaching files to notes |
| `public/screens/cards.js` | question cards: every kind, the pager, settled and in-flight records |
| `public/screens/cleanup.js` | User Preferences, Cleanup tab |
| `public/screens/core.js` | the core every screen sits inside: connection, the render loop, the page chrome and Send; the only file that imports the screens, and only `app.js` imports it |
| `public/screens/dashboard.js` | the dashboard: cards, the spec picker, handoff chips, delete, and the first-open wake-up |
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button |
| `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home |
| `public/screens/git-host.js` | hosts the git board: tabs, panels and what each click sends |
| `public/screens/help-dialog.js` | the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js) |
| `public/screens/looks.js` | User Preferences: looks, sounds and the launcher's model menus |
| `public/screens/starting.js` | the launching, starting and waiting screens, with Planny's poses |
| `public/screens/workspace.js` | the read-only Workspace of extra folders, and @mentions |
| `public/styles/ask.css` | The Ask pane and its Quick question chat |
| `public/styles/dashboard.css` | The dashboard: the menu, the spec picker, its confirm and the launching pane |
| `public/styles/docs.css` | Documents and the doc tools |
| `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 |
| `public/styles/looks.css` | The looks button and the highlight swatches |
| `public/styles/pieces.css` | Shared pieces: cards, options, settled answers, pager, forms, checklist, markdown and the modal |
| `public/styles/planny.css` | Planny the mascot: the flight, his moods and variants, and the wake-up |
| `public/styles/poses.css` | The start-screen poses, one per skill. After the dashboard on purpose: its narrow-window rules override the dashboard's |
| `public/styles/responsive.css` | Print, then the narrow-window rules: last, so its overrides come after everything they override |
| `public/styles/shell.css` | The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival |
| `public/styles/tokens.css` | Colours, type, sizes and the light and dark themes: the variables every other file reads |
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (18 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; The git board sits right after Watching a build), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `console.mjs` and `lib.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `cmd-open.mjs`, `cmd-post-wait.mjs` and `sessions.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
| `public/git-board.js` | PURE, one import (`pr-url.js`): the git board's rules from a `state.git` snapshot: branch order and the Remote only fold at `REMOTE_FOLD` 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (`boardAwaiting()`: from a click until the agent's next post, not just until `wait` collects it), the plain sentence each click sends as `reply`, the "Last refreshed" line, which files start ticked in the commit dialog, and the pull-request link; the next step (ten rules, `nextStep()`), the tab that owns it, per-tab badges (`tabBadges()`), the busy mode and per-control gate (`busyMode()`, `controlAllowed()`), the tab to show (`pickTab()`), and the create-panel sources and clean-up groups. `app.js` only renders what it says |
| `public/git-board-view.js` | No DOM access of its own: `drawGitBoard(ctx)` draws the tabbed board (header, tab strip with Done with git, the card slot, step strip, Changes / Branches / Sync) from the helpers it is handed (`el`, `md`, `copyButton`), every control through one gate; `app.js` hosts it, and `scripts/test-web-console-git-board.mjs` drives it with a recording fake `el` |
| `public/git-board-view.js` | No DOM access of its own: `drawGitBoard(ctx)` draws the tabbed board (header, tab strip with Done with git, the card slot, step strip, Changes / Branches / Sync) from the helpers it is handed (`el`, `md`, `copyButton`), every control through one gate; `screens/git-host.js` hosts it, and `scripts/test-web-console-git-board.mjs` drives it with a recording fake `el` |
| `public/pr-url.js` | PURE, no imports: `prUrl()`, the "open a pull request" link for the GitHub, GitLab, Azure DevOps and Bitbucket shapes (`null` for an unknown kind, no web address, or a non-https result). `git-repo.mjs` re-exports it, and the board's base picker rebuilds the link in the browser with the same code |
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `console.mjs`, `lib.mjs` and the page |
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `cmd-chat.mjs`, `cmd-post-wait.mjs`, `workspace.mjs` and the page |
| `public/meter.js` | PURE, no imports: the session meter. `WEIGHTS` (the one place per-event points live; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, `console.mjs`, `lib.mjs`, the page and the tests; in `SERVABLE` and preloaded |
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network |
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) |
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by `app.js` and the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Split out of `app.js` because `app.js` cannot be imported outside a browser, so anything left in it is untestable. The `scripts/test-web-console-*.mjs` tests import it directly. |
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by the page's looks and screens and by the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Kept out of the page's entry because `app.js` cannot be imported outside a browser, so anything left in it is untestable. The `scripts/test-web-console-*.mjs` tests import it directly. |
| `public/labels.js` | `taskLabel()` / `activityLabel()`: rewrites a build's `Task 4.2 of 6` activity line to `Task 2 of 6` (only for `implement` / `implement-review`; a plan's `Task 2.1` is a real section number). A separate module for the same reason as `answers.js`: pure, so `node --test` can import it |
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `app.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of `app.js`'s render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `screens/dashboard.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of the screens' render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
| `console.md` | the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (`post --wait`, the exit codes, handling a send, `settle`), posting, the payload and its kinds, documents (including `file` blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters |
| `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, and recovery |
| `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`). Each skill's Interface line reads `<D>/console.md` and its own notes file right after `open`; a test checks every skill names one that exists |
| `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`). Each skill's Interface line reads `<D>/console.md` and its own notes file right after `open`; a test checks every skill names one that exists |
| `building.md` · `building-review.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`, `file` blocks re-read with `refresh`), the chat check between tasks, questions mid-build and stop requests; `building-review.md` is the review run on the page (the sign-off's `review` verdict, **Review it now**, Implement + Review's Stage 2), read only when asked for |
Key design points:
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `app.js`.
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `screens/help-dialog.js`.
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences: Role, Theme, Card width, Highlight color, Sounds and Models. `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `DEFAULT_ACCENT` in `palette.js` is `ocean`.
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (`server.mjs` `/version` route). `renderHelpVersion()` in `app.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
- **Models in User Preferences.** `GET` / `POST /models` in `server.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `lib.mjs`). `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (the `/version` route in `routes.mjs`). `renderHelpVersion()` in `screens/help-dialog.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
- **Models in User Preferences.** `GET` / `POST /models` in `routes.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `files.mjs`). `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (cancelled). The agent loops. Nothing blocks for the whole time a person takes.
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `lib.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`). The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `console.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch }` when it found anything to clean.
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `patches.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`, `__pickup`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`), a pick-up also with `handoffFile`. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean.
- **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `<gitdir>/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it.
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `server.mjs`, which paints `data-width` on first load; `app.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `models.json`) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `app.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `app.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never greyed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `lib.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never greyed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
- **No git process.** `repoRoots()` in `lib.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `lib.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
- **The first paint needs no fetch.** `server.mjs` renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to `app.css`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
- **No git process.** `repoRoots()` in `sessions.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `sessions.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
- **The first paint needs no fetch.** `routes.mjs` (`renderIndex()`) renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to the joined stylesheet by `static.mjs`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
- **Reads are stat-gated.** `fileStamp()` (mtime:size:ino) decides whether `state.json`, `result.json` and `looks.json` changed before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (`readState()` returns it; `/submit` clones before editing). `wait` stats `result.json` every 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
- **The Workspace and the session meter live beside `state.json`, one writer each, and outlive every hop.** Three session files, none of which `switchWorkflow()` ever touches, so both survive dashboard → skill → dashboard (a new console session starts with a count of 0, and with the folders remembered for its folder and spec, below):
| File | Writer | Holds |
|---|---|---|
| `workspace.json` | `server.mjs` | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()`, now in `lib.mjs`, computed by the server at boot) |
| `workspace.json` | the server (`workspace.mjs`) | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()` in `sessions.mjs`, computed by the server at boot) |
| `ledger.ndjson` | `console.mjs` | append-only, one JSON line per entry. Meter events: `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch, with `tasks` when a built phase reports one) and `answer` (one per item the person answered in a collected send, written by `ledgerAnswers()`, id `<launch>:answer:<send stamp>:<item>`). Also `folder-issue` reports |
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `lib.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console-workspace.md` and `console-meter.md`, and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `workspace.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console-workspace.md` and `console-meter.md`, and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
- **The Subagents switch is a standing instruction, injected only on change.** The page's icon button (`#btn-subagents`, after Write a brief) and `#subagents-modal` show only when the frame's `subagents` block says `offered && supported`. `offered` comes from `public/subagents.js`; `supported` means the latest `{ "type": "open" }` line in `events.ndjson` carries `caps: ["subagents"]` (`latestOpenCaps()`), so an older skill copy's `open` hides the button. Four places hold it, one writer each:
| File | Writer | Holds |
|---|---|---|
| `~/.plan2code/console/subagents.json` | `server.mjs` | per project folder → workflow: `{ on, instruction, max }`, `instruction: null` being the shipped default; on `PROTECTED_CONSOLE_FILES` |
| `<session>/subagents-setting.json` | `server.mjs` | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`syncSubagentSetting()`), `revision` bumped only by a real change |
| `<session>/subagents-setting.json` | the server (`settings.mjs`) | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`serverSubagents().sync` in `settings.mjs`), `revision` bumped only by a real change |
| `<session>/subagents-cursor.json` | `console.mjs` | `{ revision, state }`, the last block handed over; `open` resets it, and it moves only after the print |
| `state.json` → `helpers` | `console.mjs post` | the helpers the agent reports, merged by `id`, checked by `checkHelpers()` plus the prose scan; dropped by `switchWorkflow()` on a dashboard hop |
`POST /subagents` (origin-checked; `400` `not-offered` / `bad` / `too-long` / `max`) saves the store and bumps the session setting. `consume()`, `cmdChat()`, `deliverChat()` and `open` append `blockFor()`'s lines last in `reply` and the `subagents` field; a change alone never ends a `wait` slice. The page's Subagents tab (before Ask) draws `state.helpers` through `helperRows()`. Helpers never reach the meter ledger. Contract: `console-subagents.md`.
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or the loop's marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `server.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `lib.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `routes.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `sessions.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
- **Answers carry their terminal token.** Each item ships `fallbackText` and `token`, so a click resolves to the literal word the prompt already expects (`approved`, `a`, `skip`). No workflow needs a second code path, and declining the console degrades to prose with nothing lost.
- **A build tells the page how long silence is normal.** The page calls a working agent stuck after two minutes without a post, which is right for a conversation and wrong for a twenty-minute build task. `agent.quietMinutes` (1 to 60, counted only while `working`) stretches the stuck, adrift and Send-grace thresholds; `quietLimitMs()` in `answers.js` is the one rule.
- **A finished quick task's review button is a request through the wait loop**, like the brief: `{ "i": "__review" }` or `{ "i": "__done" }`. The agent keeps waiting after posting a finish that carries `review`, and takes the review up by posting `"finish": null`, which puts the session back to work. Implementation's review needs no such machinery: it is a verdict on the sign-off card, asked before approval, so the session never left work to take it up.
- **Back to the dashboard is the same kind of post-finish request.** A finish with `finish.dashboard: true` shows the button; a press arrives as `{ "i": "__dashboard", "type": "dashboard" }`, and the agent runs `open --resume <sid> --no-open --workflow dashboard` then posts `"finish": null` with a fresh `menu`. The agent waits ~10 minutes after the finish for it (alongside `__review` / `__done` on a quick task); after that the page swaps the button for the `/plan2code` command. `finish.command` is optional — without one the page shows the "All done" line — and `validate()` rejects a `<placeholder>` command and a non-boolean `dashboard`. The session-level actions are therefore `__brief`, `__stop`, `__launch`, `__review`, `__done` and `__dashboard`; a new post-finish button should copy this precedent.
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `lib.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
- **`validate()` in `lib.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
- **Handoffs live outside every repo, in `~/.plan2code/handoffs/`, and the console owns them** (`handoffs.mjs`; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through `console.mjs`). `handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]` claims one for this checkout and prints `{ ok, id, path, meta }` (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers **Stop with a handoff** (`#stop-handoff`, suggested) above **Just stop and save** (`#stop-go`); the first sends `__stop` with `handoff: true` and `STOP_HANDOFF_REPLY`, and `wait` adds `handoffSkill` (the built Handoff skill's `SKILL.md`, `handoffFor()`); console-stop.md gives the order (answers, save, `handoff new --from-stop`, write, paused finish naming the file, `stop`). On a dashboard, `cmdOpen()` adds `scan.handoffs` (`listHandoffs(worktree)`) and `scan.handoffsDir` after `scanProject()`, which stays handoff-free because `specs.mjs list` shares it. The picker draws them as dashed `.spec-chip.is-handoff` chips after the specs (`specSel = "handoff:<id>"`); a picked one replaces the skill cards with `renderHandoffPreview()`: **Pick it up here**, **Read it all** (`GET /handoff?id=`, served only for an id in the dashboard's own `state.scan.handoffs`), **Copy for a new conversation** (`handoffCopyText()`) and **Delete** (`openHandoffDelete()`, one step). Pick it up sends `{ "i": "__pickup", "type": "pickup", "handoff": <id> }`; `HOP_ACTIONS.pickup` (`pickupHop()`) reads the stored `.json` only, never the page, and falls back to Quick Task with `fallback: true` when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); `markPickedUp()` stamps `usedAt` as the hop is printed, so the next scan drops the chip. Delete sends `__delete` with `handoff` in place of `spec`, and the agent runs `delete-handoff --handoff <id>` (`removeHandoff()`, exit 3 on a refusal, nothing touched). `open` sweeps handoffs untouched for 30 days (`staleHandoffs()`, the `.json`'s mtime, else the `.md`'s), picked up or not, and reports them in `swept.handoffs`; Cleanup never lists the folder (`KEPT_PLAN2CODE_ENTRIES`).
- **A Bug fixed spec deletes in one step.** Its chip shows a visible **Delete** (`.spec-chip-del-label`) instead of the hover ✕, `openDeleteConfirm()` gives it a fixed-bug warning and a **Delete it** button, and `deleteStep()` sends `__delete` on the first press, with no name to type. `chipDetail()` drops the scan's repeated "bug fixed" detail under the label.
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `inbox.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 17 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `app.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 17 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
- **Stuck sessions are explained twice, in Help and on the status line.** `stuck` ("When something looks stuck") is the second tab in `HELP_TABS`; its panel opens with a `help-callout` ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (`openHelpOn("stuck")`) inside the existing `role="status"` element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from `renderCloseGuide()` in `renderHandoff()` (Safe to close, Start fresh, Carry on). Tests in `scripts/test-web-console-source.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-git`, `-qa`, `-speed`, `-hardening`). Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
**Adding a file under `public/` needs three edits, not one:** the file itself, the `SERVABLE` allow-list in `server.mjs`, and (for a module the page imports) a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a new module missing from it 404s and the page dies at import with no useful error (a test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint.
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files table above, which the docs-table test (same file) checks.
## Status Line
@@ -294,10 +356,10 @@ Typing `plan2code` in any directory opens the dashboard skill against the curren
| Devin | `devin --permission-mode bypass [args] -- /plan2code` |
| Codex | `codex --dangerously-bypass-approvals-and-sandbox [args] $plan2code` (Codex starts a skill with `$name`; the launch line follows Codex's documentation) |
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 exits 127 and prints `SKILL_STEPS`: how to install an agent, `cd` into the project, and type `/plan2code` (`$plan2code` in Codex). An uninstalled `--cli` pick prints that CLI's own steps after its error (its install command, `cd` into the project, then `plan2code --cli <id>` or its prompt). `--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. 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 exits 127 and prints `SKILL_STEPS`: how to install an agent, `cd` into the project, and type `/plan2code` (`$plan2code` in Codex). An uninstalled `--cli` pick prints that CLI's own steps after its error (its install command, `cd` into the project, then `plan2code --cli <id>` or its prompt). `--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` is the one subcommand: it is never forwarded and opens no agent, it runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists. 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. (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
- **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) and a `version.json` (the installed version). (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
- **npm-style shims** — written into npm's global bin (`npm config get prefix`; `<prefix>/bin` off Windows): an sh shim everywhere, plus `.cmd` and `.ps1` on Windows, so cmd.exe, PowerShell and Git Bash all resolve it. On macOS/Linux, when the npm bin isn't writable (system Node), it falls back to `~/.local/bin`.
- **Marker-based ownership** — every shim contains `plan2code-launcher`; `uninstallLauncher()` removes only files carrying it, leaving any other `plan2code` bin alone.
- **Resolving the CLI** — the launcher walks `PATH` (+ `PATHEXT` on Windows) itself. 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`.
@@ -314,4 +376,4 @@ On a terminal it first prints a Planny banner (`renderBanner()`). With more than
The macOS and Linux shortcuts carry the `plan2code-launcher` marker as a comment line. A `.lnk` has nowhere to hide one (its Description is the hover tooltip), so it's recognized by what it runs: the UTF-16 strings `plan2code.ps1` and `--pick-folder` stored in the file (`plan2code.cmd` also matches, so shortcuts from before the PowerShell switch get refreshed). `uninstallLauncher()` removes only a recognized shortcut, plus the icons (`plan2code.ico`, `plan2code.png`), `bin/models.json` and `launcher.json` (never the user's `~/.plan2code/models.json`). A shortcut failure prints a warning and never fails the command install.
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. Every global install writes `~/.plan2code/install.json`, the install record listing the pieces installed (skills, launcher, statusline, loop, metrics, bot); `install.js --update` (what `plan2code update` runs) reinstalls exactly those, with no menu and never uninstalling, or with no record the skills and the `plan2code` command. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
+5 -5
View File
@@ -13,7 +13,7 @@
## Gotchas / Pitfalls
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` and `docs/index.html` (footer `Version X.Y.Z`) also carry the version. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number.
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` (the `Version X.Y.Z` line near the top) also carries the version, and `version.json`'s `releaseDate` moves with it. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number.
- **CHANGELOG ordering:** Entries in `CHANGELOG.md` must be in reverse-chronological order — newest version at the top, oldest at the bottom. New entries are always inserted immediately after the file header.
- **CHANGELOG house format is not Keep a Changelog:** version headings are `## vX.Y.Z` — with a `v` prefix and **no date**. The release date is recorded only in `version.json`'s `releaseDate`. Category headings carry emoji: `### ✨ Added`, `### 🔧 Changed`, `### 🐛 Fixed`, `### 💥 Breaking`, `### 🗑️ Removed`, `### 📚 Documentation`. Older entries contain one-off variants (`🎁 Added`, `📦 Updated`, `📝 Documentation`, `🏎️ Improved`, `🧪 Testing`) — do not introduce new ones. The `.claude/skills/plan2code-changelog/` skill automates version selection and formatting; use it rather than hand-rolling an entry.
- **PowerShell mangles the CHANGELOG emoji:** `Get-Content` / `Select-String` render the `###` heading emoji as `?` under the default Windows console encoding, so a heading audit done that way reports garbage. Read `CHANGELOG.md` with a file-read or grep tool instead.
@@ -26,12 +26,12 @@
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 20,000 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
- **User Feedback table format:** The `## User Feedback` markdown table in `overview.md` has a strict format the collector regex depends on. Field names must be exactly `Rating`, `Reason`, `Went Well`, `Went Poorly`. Pipe characters in values must be escaped as `\|`.
- **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class.
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `lib.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
- **Web console oversized bodies:** `readBody()` in `server.mjs` calls `req.destroy()` past `MAX_BODY`, so an oversized JSON body gets no response at all: the client sees a connection reset, never a status code. A route that must answer 413 has to stop buffering and drain the rest of the body instead, as `readRaw()` (the `POST /upload` reader) does; memory still stays capped.
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `lib.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `patches.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
- **Web console oversized bodies:** `readBody()` and `readRaw()` (the `POST /upload` reader) in `routes.mjs` drain the rest of the body past `MAX_BODY` instead of calling `req.destroy()`, so an oversized body gets a 413 rather than a connection reset, and memory still stays capped. A new body reader must drain the same way.
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `sessions.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalises its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
- **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`.
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/app.css`. No test ties them together.
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/styles/tokens.css`. No test ties them together.
- **Reference file sizing guideline:** Files in `src/plan2code-*-references/` directories target ~100-200 lines each (soft guideline; evaluate splitting above 300). They are NOT subject to the 20,000 character limit. The pre-commit hook (`validate-char-count.js`) only checks `src/plan2code-*.md` flat files — subdirectory contents are automatically excluded.
- **The splitting guideline has a hard ceiling — reference files cannot always be split:** each new reference costs the orchestrator a `Read references/<file>.md` line plus its fallback blockquote (~150-200 chars), which adds up across a prompt's 20,000-char budget. When a reference legitimately exceeds 300 lines (e.g. `plan2code-0-pathfinder-references/chart.md`), that is an accepted trade-off, not an oversight. Nested folders under `-references/` work: `references/` is the real path on every agent.
- **Windows global bins for loop, metrics and bot are wrappers, not `npm link`:** on win32 the installer writes `<name>.cmd` and `<name>.ps1` into `npm config get prefix`, each running `node <package>/dist/bin/<name>.js` (`install.js:1302-1323` for the loop; the metrics and bot installers do the same). After a source change, `npm run build` in the package is enough; no reinstall.
+26 -8
View File
@@ -5,7 +5,8 @@
```bash
# Install dev dependencies (sets up husky pre-commit hooks only; each sub-package
# below needs its own npm install, Node 18+)
# below needs its own npm install. Running `npm test` needs Node 20+; users of
# the installed skills still need only Node 18+)
npm install
# Run the interactive installer
@@ -21,16 +22,22 @@ npm test
# One web console or launcher test
node --test --test-name-pattern "<regex>" scripts/test-web-console-<area>.mjs
# Web console start-up benchmark (puppeteer-core optional)
# Web console start-up benchmark (the paint columns use a local Chrome or Edge through
# playwright-core, which `npm install` already provides)
node scripts/bench-web-console.mjs [--runs 7] [--workflow dashboard]
# Refresh the web console screenshots in docs/screenshots/ (needs a local Chrome or Edge).
# Rerun after any change a person would see on the console page, and open every image
# before committing: right screen, both themes, no username or home path in frame.
npm i --no-save puppeteer-core # once; never added to package.json
# PLAN2CODE_TEST_BROWSER=chrome|msedge forces which browser the page tests and these scripts use
node scripts/capture-screenshots.mjs # every screen
node scripts/capture-screenshots.mjs --only dashboard # one screen (dashboard-utilities scrolls to the utility cards)
# Compare every element's computed style on every screen before and after a stylesheet change
# (dev-only, not in npm test): take a baseline first, then compare after each move
node scripts/css-snapshot.mjs --out before.json
node scripts/css-snapshot.mjs --compare before.json
# Plan2Code Loop
cd plan2code-loop && npm install # First time setup
cd plan2code-loop && npm run build # Build the CLI
@@ -51,7 +58,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
| Variable | Effect |
|----------|--------|
| `PLAN2CODE_CONSOLE_HOME` | Replaces `~/.plan2code/console`: sessions, `looks.json` and the runtime handle dir all move under it (`src/web-console/lib.mjs`). Always set it for scratch runs so `stop --all` cannot reach real sessions. |
| `PLAN2CODE_CONSOLE_HOME` | Replaces `~/.plan2code/console`: sessions, `looks.json` and the runtime handle dir all move under it (`src/web-console/files.mjs`). Always set it for scratch runs so `stop --all` cannot reach real sessions. |
| `PLAN2CODE_NO_BROWSER` | `open` does not launch a browser (`NO_BROWSER` also works). |
| `PLAN2CODE_BROWSER` | Browser command line to run with the link appended, instead of the system default. |
| `PLAN2CODE_MODELS_DIR` | Moves the launcher model menus (`bin/models.json`, `models.json`) away from `~/.plan2code`, for tests. |
@@ -84,12 +91,13 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
## Non-Interactive Flags
`install.js` takes no arguments for normal use, but exposes two build hooks. Any argument other than these two (when neither is present) exits 1 with usage; extra arguments beside either flag are ignored.
`install.js` takes no arguments for normal use, but exposes two build hooks and the non-interactive update. Any argument other than these three (when none is present) exits 1 with usage; extra arguments beside `--build-skills` or `--verify-skills` are ignored, while `--update` must be the only argument.
| Flag | Action |
|------|--------|
| `--build-skills` | Regenerate `skills/` from `src/`, pruning stale skills and reference files |
| `--verify-skills` | Diff local `skills/` against `src/`; exits 1 on drift. Diagnostic only, the installer rebuilds anyway |
| `--update` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, statusline, loop, metrics, bot), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx |
## How the Installer Works
@@ -134,6 +142,16 @@ See the `skills/` build-artifact gotcha in [Code Style & Gotchas](./AGENTS-code-
## Adding a New Workflow Prompt / Skill
1. Create `src/plan2code-<name>.md` with body content only and keep it under 20,000 characters.
2. Register it in `SOURCE_PROMPTS` in `install.js` (with the web-console `additionalReferences` entry every skill carries); add a `generateStepLabel()` case when needed. List any shared scripts it runs in `scripts: [...]`, and put its own scripts in `src/plan2code-<name>-scripts/`. Add it to the skill/workflow table and the "What each skill reads and writes" table in `src/plan2code.md` (the latter is checked by `scripts/check-skill-table.mjs`), and to the workflow lists in `src/web-console/public/answers.js`, `public/meter.js` and the `console.mjs` usage text.
3. Update command inventories in `README.md`, `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md`, and `CHANGELOG.md`. Update `docs/index.html` only for core pipeline steps.
4. Run `npm run build:skills` and `npm test`.
2. Register it in `SOURCE_PROMPTS` in `install.js` (with the web-console `additionalReferences` entry every skill carries); add a `generateStepLabel()` case when needed. List any shared scripts it runs in `scripts: [...]`, and put its own scripts in `src/plan2code-<name>-scripts/` (with a `scripts/test-script-<name>.mjs` added to `package.json`'s `test` list).
3. Register it with the web console (a short list; `npm test` names anything missed):
- `src/web-console/public/skills.js`: one entry (workflow, label, start pose, flags, subagents line) with its card, and the card's `states` and `greyed`. Utilities go in group `"extra"` before Changelog.
- `src/web-console/public/meter.js`: a `WEIGHTS` entry if its launch scores.
- `src/web-console/public/index.html`: its start pose, an `<svg class="pose pose-<workflow>" data-pose="<workflow>">` in `<template id="start-poses">` (pose CSS in `public/styles/poses.css`).
- Its help topic: a `src/web-console/notes/<workflow>.md` (named in the skill's Interface line) or a `HELP_TOPICS` alias in `src/web-console/cmd-help.mjs`.
- `src/plan2code.md`: the skill/workflow table and "What each skill reads and writes" (`scripts/check-skill-table.mjs`: every backticked token must appear in the skill's prompt).
- `console.md` (the `open --workflow` list and the `notes/<workflow>.md` row) and the `console.mjs` usage text.
- Optional: `STARTER_SET_FOR` in `public/starters.js` (unlisted gets "general").
**Adding a spec state** is shorter: one entry in `src/web-console/public/spec-states.js`, the detection in `classifySpec()` in `src/web-console/scan.mjs`, the `states` of each card in `skills.js` that takes it, and a line in the dashboard skill (`src/plan2code.md`); then `npm test`.
4. Update command inventories in `README.md` (dashboard-card and command tables), `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md` (prompt table, own-script rows, notes list), and `CHANGELOG.md`. Update `docs/index.html` for core pipeline steps, and for a utility only when it is a headline change (its `.utils` block).
5. Run `npm run build:skills` and `npm test`.
+1 -1
View File
@@ -1 +1 @@
U0VOQwFN8bEUaLv1Wy6i2en7ydepjfDOZeW4ZjqIiNjiNpAKdGr/OKrabfeu6QHczfH3n0mh1oKtVK+mWZ2tUZ+nC3Hif+20X9Xq8vCqFXoE8E6kAVRN5B+wGxbk5i/ww9/hdDSHjoXWsIj7c5RFf5jq/eeAv86S1vHgyOincxbOXy6RaMJd3vO9I9T+Q0G9XymXcIvjRnH1Yy675vsue3uFYA2YiPnHkalFQs01k7pUszqLIs3NEhrbqrYGnD/d5uy4TwHk+/2grbCdEUuwAH+RV+R5QFr3rovIcSRdv5o6qvDSdIi0527nyWzvQqGEusXd5QiIoRJsQfMtegLVGkokU/KFx4qzqNWESQxKjQI0hqJWTt+ZHBo7YbcSRBngX02qTQC0nejXO88JUz5zWFSHjebXKPACEbQt0XpwJ8AWlzg2xej5jvlkpoC+PsSd133OC1vNOtqLhU15APBhARWPmQl8B9UH1zrQHKucv6FiFOx+Q/Mq39LFgsjTsofKY+sNffA92uC3OlS+Vzo2k8a0qb9gfB/+JiohUqznbgJZe/+uNohdbKKd8djyMqjxm9BxblVSJCu6IoBWIf3K1RPunAISwAMExk+iOIg9Nk65cCJA+3hl+bgemNQ2T7KllTzr2zI+auMz5RcXRYdLb19eW/JV9OTSDtMewswsGyeH+yxne0t53/6oFo901dnS2950Pi2v0Uci0tTd7LwEWoFW2Ow1EHZRx7/XKTRu7CiKCp79+i8DnmwffmEIgypTSNrQhc5kjxrZ7Ij3EAPHn9Zj7Ru4TxWLgF4jwnidCdOGT7jdDgoxiBVAAr9hMACzFQ3+J7RfYzFy9u5SGusUjR7CHHbzNnO96jhW9re0bDyTwBxy20WPVkRmchmMK6g2jhD3E7tGPuJKHwZnKQqFggFEjzp6dSZZKNaZA1oLyYuzSLe3Ym1jfW5/QFG26+1W88ERGUKcH8sBM68A4JlSBi/IdQNZVSK+kTjcOM90Aqr7ntxNl+86zPw56XyZckBtLShERyjOCfQ2CMHuXXzAXajoDgyuO+6wmquR3VUhB5f+Denp/TPn5kSP0Lr4ojP3spaxR6M0lzeAb1JuwCH56KodvBAC8qFnkDQFlWCajDl2Ilw6BoJP4iU+E3CAE6tBkxBZVe2XGFNFv5wGaiHlcolSXS0pIJViJAfJ23cuFDKXC/MHGysLIrxGFOYuPnYI+e2M37LHGowWV+LCOjEog44eU679Ng1dPUs1Hx5JxhgcBWkfEW9Ii2qq4NqBTtRUYP8JWWaYwOlCtTko9jUqFNlFNpRglTAuLifaQDdC6FPiCG4Lm4NtGC1r5Q+sVrdR8msi+FKDgmM7cmILhXucFWxdALVjInfU67ETRgjhqH2sGuQs7c6UCs1dEugO4MnzZEPrgJ144kSzd+zM0LVqTF0SWPr3eii25AavX1adufsXURYUUh8pwNhdLbfG+iaNxAj/RDCKdYwa6t9N4/1D5V4/UNLfkXfXDgrw77Nr0CyA34wWwd1rLxeluaQeujbIpakvqRoDZrDyJzRnSMQ6Ih+SUp1/U84C/6yMphrFQZDeyQq/vpUHc4VJiswSpjlqJKryxFEAgQJXsRWPqa6pvaXFCnXqm+gcIi2aRRGaCoRgx7i3wAu3XNfbDHn7ySUZJByrXZmZGnGo4BrgH5wGaLR0u3s060fbyVCkah5/c6PEsvIUNJs2aVZoQtU5BKMnxGc7A7K5bbj967E5tA/LQp0jMJ3A/RbS/1gmuKY8m5ugvRfzTPdpb7CI30l7pd4zGeDme00HC26HWXYRGbjTxPSGsvbMUPB+RSEQ4eLP/cDFk+lo6qknttkmjVn+L8pMF1EbuN2DL9w/KFGCOvhzrWrzSpyuwJbepW0/Idy7RE4wiwqrOnXX1ujzLthQybP/h1Pgcsct5xBB1E1kILv/nY/WPW1eVtlceJfNq+LvupGE7J3FHstzsYDaIwDidwyIzYoCTOElr3ePGypB2rmn21NEVojXUXngx6j2QceQLVNjEsqO/9bETsKbljvL7+MuX0KMbWtmzniBtb0nJL9OcemfT4lxpe0F4slbpG+XRxNZ7sVkgAFgvaM42dtTHdhl3hSsHTFMMsub7e10C2XFkfgF/e4bY/Rf9PXyofWnGHm+uGRxmx8nash6fufCtddKsmxjhjw2mrVzo6B76IQHj5Y0Ybr+14DN8JmT7h5dQp/4Fm0Ok+GoRcqkCPGLMvzq+PGfj/t499YQcNQeLilenMXLKSLF03q5vFt76gnOQbF5GC6+JWMYm1lbIMdNAY2xYRlOH/NuptcJbadXZzcsT34FXT6YbsV4O/Qxyglcr5w+rauiL6KbnjVezso7zGFK7QYDCOuyMl7Y8mZHov2Q0igf8Lw+jI1BfLCzcfclsg+d8zfhwJHrVdXkD3nc9C4ajJk6fFhwovWm3nPdu81dCoedoGZBIo7yz+EqUjF9Y3ZYzDzIvA5ngafs6B/kFc3eGk7vbBu8HA9EjUBNWUrA8t9xq/orhEzKj+GTtZ4azOFK5FBd7VQKZn0gOUG9+hvcjGQEB1cwt7qbMH0QraWYgtzODf3WWRQDEh8z0hvMHe3AUrLIdf0IN61iN//Okg+9KfgNZ5mGnJOdLGO7gboRTkOd6PLnTfkjgQbvqKuealTSSqio0CBqROwwkPyvtai8Gq/zncelsGGkmp/3WQP3aPaIQ2QFQH2aW70Z0AQlqS0IwBDnpxcP6PaCrGCanpCxg5FfgfgU/GzuAxwyafbCbZnhQdzMgaCWVwwFywUiWPwt1farNN5DbdbG/0GJhyJmyDcNY1WmVS5D0g7N2W2NWjHqYmlqxxQ5bBWnn6RRSQrx/C+7NgGkAHcROMwqQb1959Mfvz174dMBYApwg7bVsgNWlf7ESw051O56bbBTEbeiUBvVARl86R/Dh2dXRfz/ywEveR3qJ+mCFSdyn7q3Ymj4NYVLsoWJiya6AusRHwy9ndlG+PCpzgI9YRqMPebkJqFpYlG/ZOZFf0dczqBjy8/oqCE1mhfusc/0rTuonbQyP+ISVnU3yfKSNxPHsbtsZPhLIinlg0pV7LUxGvNUmTdXIXRXO4YmLLIEDPkY4dUD9V1mvohiaSs5T3S0bowtb7x2aFYIagO2WoMJ8DTUSfgdx8+V8K3Jw7LFPWrJduMtyzH4my77UoxHj08WXotfE+s0TK4C9IGR8KtGwluZ0C+FZBGROsvWmVXvXvR55jtVulffAGa+H9MD+rRtIRXkO7jq9g+SAucuNkEOGJZkC3flcq9Mxv933XMXRGNU0P2n3/Anj+R+QZqIlrP3pWAvNq60/1f2mYCa2dtcO8qljSCI9Km5O1T9El5tjrquEaD8E74ZJT68pv7yH7uJmI+az8n4xR8fm4Rj/nNJ+ZPUU1UW+R7WESOePJ4kwK/h2FiSD5tXmzWGBjvnvX49KrkWN5f4zPAYWf2Pz2LDZzI3GJC/u7wbf5YO+yBXKCZ0NryY2IGuwtJBiS6XqpCey6EhhgzvSRNAfuD8N+Lqr+biCbM0LlFoIW3SWrR05OOrw5p8jv6L8bsgq/5zTT5weEeOjuLzzydX0PLOsPJaBgXBMXQB97PkBrx4nZi+YmWKmStCMl76qhxur7svPwm9YoBe9RFQI6LIhhgy2GEe6OLUSuLG7UTJkGK9fNdkC0VXgPekiCZuvgFnSkYJlA4myle4N0B9QfUxRbhlPSHvA+M7iF4vSWRRXJ8ehrZajYHlUZG/Y59NeB4sy1cdpcLkDt+gaRqzLciHUQVrEqfqwQum9+KWab17ioU+uHZL1YqqbAmn19+4m9awe9fblhSHWAUIjfeBn7I6rF4nhVsKku+FAznl47as5gUeMWrryC8Rku9X3xBuuuWg/SchgtCnfXT0kddX82ri7pJ9tcaC41GvFBqaUsuT5Of1sDAkggfYzZCp0bCeBsQ41Dg4YpKFuissiMZLHNijtF5thd7sf+1i/AlAoCOfi5pSlBqEM8m0Z9EIssWhPyRCjJvvZ+J6+HCxbB4n3fwZdaBoEuEYtBzzPjSZNCH8KDQB4Ng1RdSYBl3NEYN6VyLA3Ini0PS24U/Y2ooioUPllrmCx53IDZDDjHtevTAERMIVs4WN5HkSmq2UooNcMXJUNq7DTkNVc8+BfMxirHa/Gizr+UXNKnrxjqUgpV9Yrc6VOimw3EQWPP2dGY41p0Z/AxOiOItIkbeLZCYGpYhAstnnwRDju/1fuwUdBi6ECh1kss/0+HnzHNVsIEhcvR4IBa9QFFxMxfsu6f4IaaB45S6beItNyYHpIqbK+KIAb0sPNd/03FfhOVCc1ZOsilK1OUtk9MnaqVDC5+H29fqDOkjEws0ShxibEaklPtNR/XYPOzDf/j0dUbPNaA18qkwU5pZDVy9ZA4OIgVDOJlNLi2UWEmcsVH/VB6OLC8pvdoLQy0mduKOasI9gDTYlw1Eo7ges4qe+f2iYjNydAs+EnWdVuIB3yOJ/Rf6qI8vxTi4IkkocQK3cb+lGUZJEfRUOk0nJ3zoi5y5xiet/8HsZr5Yz5hqKktboiiWb6MBJB1GEEtA3Tz9sseve7MRoPRxmpP0UJZ0QkftuBRugzF1tSqE6q55vYH68mzOFhQzzTOl13NpUM6AfJAgwUCc0lo37R2pWzUDogfVrYhb48i9+tyMTeO1YvnrT5+DSOaPaCFK591xCPTC4K2lv4iNYNisNgFSBw9GeV17MtiulqDBKauSRP54HcorSXIYwCuJ4LyU+jR3dwaztlBLehT3WmxfE5JQtK6hWnM0dKBexsyTg9IvzqZJbbsvrF2nmRAw2ibZV+8Tta/iwpnt0RMTeMsFkYo2q+pOAzZ/R4IqtEM92XvKkd2ShwvPdeyRoHfKwdmVFjp9nWBK//dNpxMx+Yl+vYIPXwyuS+4lbUqPbYVIs6QlBCXuos0bYJJdjslbjImyhKn92DxkZCtmNH42c4mScpHNV2XoZd5F2Cul4AdzLine truncated
U0VOQwFCLraZiofXGk3ma3rfAp+AwimbD2xmPARjOXLQKQDASKq6WUdAn5Xu24Z6rJgFAocX+aoaxr7aEcSFrlFujCdvGz8V8xc24n8bf5xsAEXkLEYouPry356TXt0FXr6hMN0uJvih1b0zJQI2g0NP0Nqjb6W3QsusKfvxJdVSWCC6fXd8YVGjqXIBBB0TnReajLcbE6innfSbpK9bPioIuychW0VEPtytUTo/+z8xxIwZphis8Wx4zVUUm2b6CZVgbh/Uhxq54dkicULYd58KfsBgRaUscASNvjwgw6ggjvo7R1Wj47xm0L0nSFDPoERuOomxW0lI4ib5wfJ+3j2hBoueX5dHVMpVaGOZpL7RLvJf0AbBE8kwCL4hLxjBuatt95R+sfCpxHXu8hga1AzFKa2gL/IE6nzq5GMC5UKJ9JIhjmM6GxekM3c5yh+AbBgUxfv4Fa2OnRzNBvICB+xJfDSP3G0lE+OwkenYURIzMrW+gS24NXJ12rzhlyhEp0iAvr6wGAskcTpe9nXShyL9M69FXmCJuNZdenQv8pPr9zuw0M5b6BdKG9Tcp8j1Qm4BBA8J22Vd0uF7D6ByjpKkknbPdQMh3A/s09qix7t20eP/OGTh1JBZkOXxbSt5N/mjYUeLXAzqCYN0c3GsX6Za45OU618l4PO+kC223EdAjD4dWbN1CW65uJY0m2XckZr+2p3f9ow00BHnfzIZVG+aMSicaIJdGGudWdABVCsb7zvFr/Pv2pRWZjSOtSh2OrIkFeobEuqOFra1ifRCn6Y2/LChsPJBUqDwV4qDNjFouWL1JR59XntCn/Vcn94S9HmeP1gFS0ceOWGDDnaocbqCF3RL6SW9PN7GZCORjiyYhVZn6i7gIBIvmlg8mqmYYAaTGm9abwB278V2UJEn/YD/Hbr2krnVZEoEG73pk+oFGDRiY+G+cA2bpWhVt0bXKluanQJV1UTby0/RhbGGjhFMr+dPqHLRoeuLbnYkvcvLbdjz3vRXRbJdO3GARy81hWjPEZnvEaT0SR0683uMsCzCz3pWqL8BMIN2GuMIIsn7D0lZwb5eKrDjEZIkyVZhYiwX1kSsjK+JfIweRvxRoa2fCZ20tP5alIozh6m+Q2eWyzdxyRqXCHZkd8kUUT+XbLj5cw9tl3oINfwRUFYxAPwq/bhJS3bpl5ElPdo/ZKOKQuHpjt2nLdyXDYjXtpY9nUMKDO5in/bkqzSnSM52Va++1vaaYBtZnYx0v1HFoPtepx34pwkX0yjKIqIsHOzQVNNAYL5cQlzATMNISYsmne8c8ioRRuK07nyHGZhLroVaxJ2fgL6VQVjlxWmyeI9b+tBf3fRGtYwP3SwS1B4SYySFZ70bNZyROaQdE8Rin8mH7Pw8WquuCEE+LR63KLdC0QnV3iAr8d4aJSsYlDjqMXMASgtqof/jKCE2KZtCR+T2DrnXMhvgsRVwZ18Iufd9clv8hxrEUYx8D0sP+Ao9LJYAWGJ0Kt7GSfdwDLaRjL4jkToeFIImwIZPDpckCsraOcWD+vuR+kuuOBCtSxN+rm9pZ1VulMAG0KkkpydTeNPlbRuLbgfmwk8o7QQnmjcWL96sLQszm0JnYlQDHLRfAmaBj7L4JbsiGhCe5+2SfIrfqDCZhUYF+OwILtwXbhBGl5DcbCeRUSz9NUrz3ywF8TZa8TgBM89PiJb/pvMNrE7m+SmDJugiQ6UWcoYD9eC/katecM+b7KLGBYpO5qFx2+QpJff/YRhmHpz5O8UjJVKJK+xLAbvyiVs44OL+yJ5MIq8TUB7ojZDaTkpuwLKeezycktpzUENMbona5GbjvSaJWmD97TgBgAY9iP38h6lOHzKh0Mda5aVSWVn1Rq1pJ3IsZBPSC9QQe/p4DItw5aXeiMQwdozY5j95qICXfxvfnZP/MSIAyj9SZWKhNIuCDvOUxDHj2h4EZ6X+sCBAvhQG4YFAIzPqS8nnUIdgBtbStZBkQoY+n+m8qPsaYf7QdWeGPRI2vcfcCXyR9DvePV6ER3sTI2GKUUr61peCejc+cBwIWvqacr7Xl5QqTgTXGYvgu/Sh3FMws9iEPNScfd9K/hRbqTpJv4CeDu4fyFwTzuP/BHRQuv5pqJvzHdmTppwAfqAmo5pAWig9WpglQc+rWmlJYAtUvF7SIop/uXcH3r0xmlMilpc4PDMzaw3gu6kLIec63jrS0+cX5CD0DjfuT9nSgsdR8plkFi7UwtIRGhFO3B0gCIG+frznPAFUpm5KtnjjG1jIKsAXcfB1ZViS7/yHVcC4FeO4XOOJyVZSAImWKJ7ljGtpjLCK8BtiqrCuf26wlj3iw9jMm8wS5f+G+INg7bFgnlNRfqId2EeYJ21q9rODCCLMf2DUjJmVEuqk/grPparL3OgIV579+RUhXMUechv3zwkSdk/w5zyKyCc4j6tbAERg2KJP3CEQnCrdUeqMSdy06/prdkHnByPAX+7tx3JzVjOPxv3L7FNmahhTW6lWSJX2IR2VRwsP1UL6kf4pPeT9T5Ou47mmRy3CP+JLFDYt+3cQs9qYry+Xz2MfTJnyNJb7vGfPaQv/rPfJZyOmlFhQSzXfGtAPVF8srKnUNgdX6EJsw08rDZQhr0pCcu92VkNvNigzDtxIb+u+WYNprGb+sJFT+rtPQbP5v9+akyBw1Op7+Kek+S1XgK4PF+29QiEHKfPq4pgYnO5BLaUvNJVEImZV4nXM1ve2+YRDjtxRB0f2zBau0CfI+QpSfAHPk/COZojZU5Pdd/IiVPttEaSo7dvlhINIbmvTmHIA/XcHuOERmTpIZycVumSeKhDXxnahJzEeWZwDoxIkxIhFM94hLH6rc13fcAUvo3T+jKt7d9k13rF6dw+rd63+Bq83bBDHFero8tZmWdQ0Tpnv231EbSwv4L16N7J7ALtvPbnyNWR5wWzN9bc2/xglGys4txTcBt32P/dBR8QsBQ26CISfoElUR+vWQyo+OTOMP9sXyWPN0q2jC+EA/j+xg0TT2dW7RtkpjLR9uEMZpvJSMYnep+HtWw+6fns+W8kTV8zjv9cwod0TOA+qLbd3VCaQr/TDImqHigciRLV4NCLOTWGYuZiWbHCfikIyG4HBJlRgFumVTlgGKsVPRtdx5gqZBvZqaE2CSAtESC/O7q6ocoGx7cyLEs5Oq9sp2JZQPfxyLTtfG77OdAsr4KFFwGvgjH1Laz6rqw+DL15Ysj/WTl7yJ6toQ0KaRVTUf+3pNhpyCsqfWOLy4A8bMWAoPTdvh4sN+lOgNmHfe5Wym/UfR/UTz6cDGSrQgbSN3PXFzzSBM/Lm77MRljbBbFp0qXJAsteajVeXJX2JVFhGhQ8TzAUL3jhblbY0psVHuBoW9oyQ+UREc5/fH9hbRSDVcCr/5BWnY3Og3YOESOhHFx+lNFT+v96QU5lkat8b80llUwM/aJ8t+tzK+nyKhQwGgXpek6hVwnDhAFuwGXbxaCJNR5XJWrvChcn+m/5TDEm/U7mRblkiwEBm+i3mBDEioH9vHcRTu7wB+FoR6Q0FJbr1tm2lG3tvBg05pEglHkXrz//3iH61NjH251++zW93BFzngQLoRRBcreFfdiEP6VoHsVC5cFjzcnymLEdUtBp/ihbDZ3Tzn72c0oOzV8td4lgDDzxlJLZglwqj2Yx0yJLAPUAG7hJCWk+NbvyDsYSLWxn+ywOMH2onyh3pnPV7S3nKuJ3k6o52gdLmBOM6kHZvDmyTl4yua5zABGr6UWSHlgtCS1BRs8bH+RV79irRp1F8LUl8C+aENK1OlvD37kRRrlbZlqUV0cFib1ItRy2I69E2H1MfjgPE8gwksVmvX/JSGR6GC1SOFEqRRaGQtVAgSNrZ9W+qVpevtsK7Eytg2HVo8ZmPifWRZe5YOawhE7fFaih0/4gEoegRa6hDGK+X0uWao+95Vgtf1DosETrxlICRbDZT6oyqqWjGrIHi4X3ZSAgXF7VsZ+EeYRLRbJ84H8l552PnjXXPufQkOP3o6fFJYCMEnqowtqRhTIl5stzBbHLWVmQ6UCKPlhUHePsjI5snYy8/zuw6HRxYY+p6odEi0sn31PXO3RCeRBMtNQ5xWhddJK2KX33Ygc+qXBLSe3LG1PcbTCCf1H+E8x06JM5tVGG1WsmZnEIBxCpQUZN3/fUe65B37QYyxBwZDFwxetjthnT2E4WR1INRVUgJySBYrgHJr9PJF84dAdyrbXJsh2TckR4rCRYpOC4Yf4p/GqQim69YA09EIHA+9PgywDyiZ3lSKYHwrLgGZliiJx0envl2YlL9udzPcLzpjGOLzwTj2vpOAe3cDgscYGLPSUK76yqS1cPCXfz+xpmrvVFgUxRSx5i/hj4TFQotyI9sTfHTSXBJBvywpxC2GMoZrTSR+4ksLv2kLatRtVGnUHSAA/Lx6fbFKQleOqN3sFn9exSQAo3EWEA1wT/Uep6uSBWAg12Laf8l9hgoIniThbqv3D1AgfRth3aXfY5sK0S7HQfwCfbMWr2HSU0JydhxufKFV3z6aV1fCpXAgkXoZ151Brrpgi4urtwgFWfD4Cvlrq1SXM8aW2F84EpvOkADhrEvpzf2ZJ8w7mOzZxZCxoQ3CbBhjHjyfnoPMUMldvYctLobZxOBUqfwxC2SlcCyQCvlRLDs+M6z/qONNOhg29pZK368WHEbzUNmevtq7cleE4MGk2NU88Br99YPFc0qaxY+xDSaZKFDhERe+2QRNY3jTC07aK8tfoChkK4uahAghWDImK50i3DCLnUI5TlOaxkOaujA40QtEmnt5CNQuLeSCKtduT4rmDn2zDdep+BCCJlS1lJfonIhtDl/fCUT1Zj4Q/JWOlwUJDs+3yalPC78fqWTgHrNOREN/o5VRkOegZDz36eE6sFr4cpKfjSdeeojMb8MMKAFRAJce3MR6HflkKqEpTyVPMkeB/u48Z2wANGcYDwhqzi9c54DDjbSh1Vw4BbkuxgFUgdREipn1NJLine truncated
+6 -6
View File
@@ -90,12 +90,12 @@ Both are cheap to enforce mechanically in the server's write path.
```
src/web-console/
console.mjs CLI: open | post | wait | status | stop
server.mjs the HTTP server (spawned detached by `open`)
lib.mjs paths, atomic writes, patch merge, validate()
server.mjs the HTTP server (spawned detached by `open`); routes.mjs lists its URLs
files.mjs, sessions.mjs, patches.mjs, scan.mjs, ... paths, atomic writes, patch merge, validate(), the repo scan
console.md the agent-facing contract
public/index.html markup shell only
public/app.js the client (no inline script, see CSP below)
public/app.css
public/app.js the client's entry (no inline script, see CSP below); screens/ and state.js hold the rest
public/styles/ the stylesheet, joined by the server into /app.css
public/render.js markdown tokens to DOM nodes
public/vendor/marked.esm.js pinned 15.0.7, MIT, lexer only
```
@@ -223,7 +223,7 @@ Recovery matrix:
}
```
Note `recommended` is **optional per option**. Handoff explicitly wants its inferred task offered as the recommendation; the `.gitignore` question in handoff explicitly does not ("present it, don't force it").
Note `recommended` is **optional per option**. Handoff explicitly wants its inferred task offered as the recommendation.
### 4.2 Primitives
@@ -308,7 +308,7 @@ Three panes, plus view tabs, closer to pathfinder's own vocabulary than to a gri
Built for a mixed product and engineering room reading one screen together.
- **One width variable.** `--card-width` on `:root` in `app.css` sets the column the card, the pager and the document tabs share (`max-width: min(var(--card-width), 100%)`, so a narrow window still wins); no fixed `720px` column rule is left outside a media query. Three presets, picked under *Card width* in the looks panel and saved as `looks.width`: `narrow` 720px, `comfortable` 880px (the default, and the variable's own value), `wide` 1080px, applied as `:root[data-width="…"]`. `CARD_WIDTHS` in `palette.js` is the same list for the page's validation and the server's first-paint `data-width`; **`palette.js` and `app.css` must agree**, which is the one place the number is written twice. The dashboard keeps its own 860px layout. Inside the card the `62ch` / `68ch` measure caps come off (`.card .md, .card .prompt { max-width: none; }`) so a wider card is not a narrow column in a wide frame; documents keep `.md`'s 68ch.
- **One width variable.** `--card-width` on `:root` in `styles/tokens.css` sets the column the card, the pager and the document tabs share (`max-width: min(var(--card-width), 100%)`, so a narrow window still wins); no fixed `720px` column rule is left outside a media query. Three presets, picked under *Card width* in the looks panel and saved as `looks.width`: `narrow` 720px, `comfortable` 880px (the default, and the variable's own value), `wide` 1080px, applied as `:root[data-width="…"]`. `CARD_WIDTHS` in `palette.js` is the same list for the page's validation and the server's first-paint `data-width`; **`palette.js` and `app.css` must agree**, which is the one place the number is written twice. The dashboard keeps its own 860px layout. Inside the card the `62ch` / `68ch` measure caps come off (`.card .md, .card .prompt { max-width: none; }`) so a wider card is not a narrow column in a wide frame; documents keep `.md`'s 68ch.
- **One box grows.** On the primary card, the answer box that is being typed in — a `text` question's box, a choice's *Something else* box once picked, or the note under a verdict / confirm / recap once shown — is `textarea.grow`, and the card takes the column's full height above the pager (`.card.is-primary.has-grow { flex: 1 1 auto; }`). `fitGrowBox()` in `app.js` writes the card's free height as the box's `min-height`, **never under 160px**; a `ResizeObserver` watches the main column rather than the box, so the box growing can never retrigger it, and it writes only on a change over 1px. `resize: vertical` with that moving floor makes the handle taller-only; past the fill the card scrolls. Every other box keeps its ordinary size, and the notes panel is untouched.
- **A switch per sound.** Every cue is an event in `SOUND_EVENTS` (`palette.js`), each naming its file and rank: `startSkill` (`start-skill.mp3`, played once the dashboard's **Start** is accepted) 5, `bootup` 4, `sessionStart` / `sessionEnd` (`start-stop.mp3`) 3, `question` / `skillReady` / `chatReply` (`next.mp3`) 2, `newTab` (`insert.mp3`) 1, `snore` (`sleeping.mp3`, looped by the wake-up outside the queue) 0. The queue, the held slot and the one-at-a-time rule in `app.js` work on events, one `Audio` per file shared by the events that use it. User Preferences shows a *Play sounds* master (`looks.sound`) over one box per event, saved flat as `sound<Event>` (`soundStartSkill`, …) because `looks.json` only holds flat values; `soundPrefs()` turns any missing or non-boolean switch on, so a file from before the switches keeps every sound. A cue plays only while the master and its own switch are both on; the master off greys the boxes but keeps their ticks, and ticking a box plays it.
- **Send breathes.** `#btn-send:not(:disabled)` runs `send-pulse`, a soft accent ring that spreads and fades every 2.4s; a disabled Send is still, and reduced motion switches it off.
+60 -12
View File
@@ -15,7 +15,8 @@ inside it, or add `--web` to a skill (`/plan2code-1-plan --web plan a lunch voti
- **Tabs** show the document taking shape, the build progress and, always last, **Ask**, where you can
put a quick question to the running agent.
- **Sign-off** asks for your approval at the end of a phase. You can run the code review first from
the same card.
the same card, or press **Show me it working** to have the agent start the app and show you
screenshots of the change right on the page.
**Where next.** [walkthrough.md](walkthrough.md) follows one feature from the first idea to the
last phase. The rest of this file is the reference: every card, button and rule. Prefer the terminal?
@@ -198,10 +199,34 @@ the git board, three tabs — Changes, Branches and Sync — that open on the
likely next step (Help's *The git board* topic walks through it), and asks
before every push, publish and delete. In a folder that is not a git
repository its card says *Not a git repository yet: it offers to start one*,
and clicking it still works. Click one and Planny flies while it gets ready;
and clicking it still works. **Codebase X-ray** is always available too: it
explains how and why an area works, or ranks its rough spots into
`specs/<name>/ARCHITECTURE-BRIEF-<date>.md`, and never changes code.
**Diagnose a bug** sits beside it, also always
available: it finds a bug's cause and writes it up as
`specs/<bug-name>/DIAGNOSIS-<date>.md` without fixing it. Pick such a spec in
the picker and it reads *Bug diagnosed*: Quick Task (suggested) and Plan light
up, while Document, Implement, Implement + Review and Finalize stay greyed. Once
Quick Task has fixed it, the folder reads *Bug fixed*: Quick Task offers to
archive it to `specs--completed/`, and until then the picker never opens on it
and hides it while *Hide unavailable workflows* is on. Its chip has a visible
**Delete** button in place of the hover ✕ other specs carry, and one confirm
removes the folder (any other spec also asks you to type its name). Click a card and Planny
flies while it gets ready;
a few seconds later the same page is that skill's console, already running. No
command names to remember.
Handoffs this checkout has not picked up yet follow the specs in the picker as
dashed **Handoff** chips, each with its title and age. Select one and the skill
cards give way to a preview: when it was written, its spec, the skill it came
from and its Next task. **Pick it up here** carries on in that skill and spec
in this same session (Quick Task takes over, and says so, when the skill or
spec is gone), and the chip is gone from the next dashboard. **Read it all**
opens the whole document, **Copy for a new conversation** copies a one-line
prompt that points a fresh conversation at the file, and **Delete** removes it
for good after one confirm. Handoffs from *Stop with a handoff* (below) and
from the Handoff skill land in the same place, `~/.plan2code/handoffs/`.
A freshly opened dashboard starts with Planny asleep in the middle of the page.
Click to wake him: he snores once while he gets a gentle shake side to side,
then about five seconds of him powering on to a boot-up sound (arms lifting
@@ -456,6 +481,15 @@ A finished session says so, and ends in one of three shapes:
- **Paused.** You pressed *Stop session*. The card names what was saved and
gives the command that picks it up later. Nothing else is offered.
*Stop session* offers two ways to stop (on the dashboard, where nothing has
started, it is a plain Stop). **Stop with a handoff**, the suggested one,
saves your place as usual and also has the agent write a handoff: where the
work stands and the next task, kept in `~/.plan2code/handoffs/` rather than in
your project. The paused card names the file, and the dashboard offers it as a
chip until it is picked up. **Just stop and save** saves your place and gives
the resume command, nothing more; where the step has nothing saved yet it reads
*Stop anyway*, under a warning about what is lost.
The first two also carry a **Back to the dashboard** button (beside the next
step, or as the main button under "All done"). Press it and the same page turns
back into the skill menu, in the same conversation, so the next skill starts
@@ -569,9 +603,19 @@ chimes once (if sounds are on).
When a newer Plan2Code release is out, the dashboard shows an **UPDATE
AVAILABLE** banner at the top. Click it for the details: the version you
have, the new one (linked to its Releases page) and the exact command that
updates you, with a Copy button. **×** hides the banner for this session; the
next dashboard shows it again until you update.
have, the new one (linked to its Releases page) and the command that updates
you, `plan2code update`, with a Copy button. It updates everything that was
installed (the skills, the `plan2code` command and any extras you added), with
no menu, and never uninstalls anything. If the `plan2code` command is not
installed, the dialog also shows the install command,
`npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git`, to run
instead. **×** hides the banner for this session; the next dashboard shows it
again until you update.
The `plan2code` command tells you too: before it starts your agent it prints
one line, `Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`.
It reads the same saved check, so it never waits on the network; when that
check is missing or old, it refreshes it in the background for next time.
The check uses your own git login to read the repo's release tags, once an
hour at most. If git cannot reach the repo (no git, no access, offline), you
@@ -662,6 +706,7 @@ exception being the note attachments the agent keeps for a spec, above):
| `~/.plan2code/console/sessions/<id>/` | the questions, your draft, your answers | 30 days after the session was last touched |
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
| `~/.plan2code/handoffs/<id>.md`, `<id>.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not |
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
| `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always |
| `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session |
@@ -681,7 +726,8 @@ reads), `public/meter.js` and `public/mentions.js` (the `@name` popover) — and
**Old sessions clean themselves up.** Each time a session opens, whole session
folders nobody has touched for 30 days are deleted — questions, drafts,
answers, uploads and all, paused or not — along with stray scratch files
(`.json` / `.mjs`) left at the top of `~/.plan2code/console/` for as long.
(`.json` / `.mjs`) left at the top of `~/.plan2code/console/` for as long, and
handoffs in `~/.plan2code/handoffs/` untouched for as long, both files each.
Your `looks.json` and the `console-dir` pointer are never touched, and neither
is the session being opened. Nothing of value goes with them: the page is
never the record, `specs/` in your project is.
@@ -691,7 +737,9 @@ clean up** lists, with sizes, everything in `~/.plan2code/` that is not
needed: sessions untouched for 30 days (never the one you are in), anything at
the top of `~/.plan2code/console/` other than `sessions/`, `looks.json`,
`workspaces.json`, `subagents.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` other than
`console/`, `bin/`, `launcher.json` and `models.json`. It also lists each
`console/`, `bin/`, `launcher.json`, `install.json` (what you installed, which
`plan2code update` reads), `models.json` and `handoffs/` (old handoffs go by
age, above). It also lists each
folder in the project's `specs--completed/` whose newest file is more than 30
days old: archived specs Finalize moved there. Deleting one is permanent:
`specs--completed/` is usually gitignored, so git can't restore it. A stray is listed once
@@ -730,7 +778,7 @@ this:
### Routes
The upload routes, the send, the overview read and the workspace. Like every page route, they are on `127.0.0.1`
The upload routes, the send, the overview and handoff reads, and the workspace. Like every page route, they are on `127.0.0.1`
behind the session cookie, and the ones that write also check the request's
origin.
@@ -743,6 +791,7 @@ origin.
| `POST /chat` | A Quick question `{ text, about?, images?, files?, conversation }`, or `{ reset: true, conversation }` for New conversation. Appended to the session's `chat.ndjson`. 400 `too-long` (over 4,000 characters), `image`, `file` or `bad`; 409 `offline`, `stale` or `limit` (10 per conversation). Never refused because a card send is still uncollected. |
| `POST /chat/decision` | Approve or Decline on an edit the agent proposed: `{ re, decision, text?, conversation }`. Once per proposal; does not count toward the 10. |
| `GET /overview?spec=specs/<name>` | The Overview tab's read of `<spec>/overview.md`, as `text/markdown` with `cache-control: no-store`. On the dashboard `spec` must be one of the scanned specs; elsewhere the session's own spec is used. The file's real path must stay inside the project, so `../`, absolute paths and symlinks pointing out all get 404. |
| `GET /handoff?id=<id>` | *Read it all*: the handoff's `.md` from `~/.plan2code/handoffs/`, as `text/markdown` with `cache-control: no-store`. A dashboard only, and only an id its own scan listed: a used, unknown or malformed id is 404. |
| `GET /workspace` | The Workspace dialog's list: folders, `missing`, `remote` and the agent's folder `issues`. `?check=1` re-checks every folder on disk first. |
| `POST /workspace/add` | `{ path, name?, description? }`. The path is resolved against the folder the session started in (`~` expanded) and must be a folder: 400 `not-a-folder`, `duplicate` (with its `name`; compared case-insensitively on Windows and macOS), `bad-name`, or `name-taken` with a `suggest`. Answers the new entry, `nested: true` when it sits inside another folder in the list. |
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
@@ -754,13 +803,13 @@ origin.
| | |
| --- | --- |
| Source | `src/web-console/` |
| Source | `src/web-console/` (one row per file in the files table of `.agents-docs/AGENTS-architecture.md`; a test keeps it complete) |
| Ships as | `skills/<every skill>/references/web-console/` |
| Wiring | one `additionalReferences` entry per skill in `install.js`; the dashboard's menu lives in `public/answers.js` (`SKILL_CATALOG`) |
| Agent contract | `src/web-console/console.md` (read once), its topic files (`console-*.md`), `notes/<workflow>.md`, and `building.md` / `building-review.md` for the builds; `console.mjs help <topic>` prints any of them |
| Tests | `node --test scripts/test-web-console-*.mjs` (split by area, shared setup in `scripts/web-console-test-helpers.mjs`), also run by `npm test` |
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs `puppeteer-core` and a local Chrome or Edge for the paint columns; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
| Screenshots | `node scripts/capture-screenshots.mjs` (needs `puppeteer-core` and a local Chrome or Edge) |
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs a local Chrome or Edge for the paint columns, driven through `playwright-core` from `npm install`; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
| Screenshots | `node scripts/capture-screenshots.mjs` (needs a local Chrome or Edge, driven through `playwright-core` from `npm install`; `PLAN2CODE_TEST_BROWSER=chrome|msedge` forces one) |
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only |
Edit `src/` only. `skills/` is a committed build artifact: regenerate it with
@@ -833,7 +882,6 @@ after any change a person would see on the page: a new layout, a renamed
button, a different colour.
```bash
npm i --no-save puppeteer-core # once; never added to package.json
node scripts/capture-screenshots.mjs # every screen
node scripts/capture-screenshots.mjs --only dashboard # one screen
```
+10 -5
View File
@@ -42,7 +42,7 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line
## Web Console
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. 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, 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`), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) 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`); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. 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, 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 built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) 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`); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
## Skill Scripts
@@ -67,7 +67,7 @@ Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` (and `plan2code-loop/src/utils/logger.ts`) and appear in workflow markdown files: arms down at rest, one arm waving when he is asking something, both arms up when he is celebrating. The eye is always the star.
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight colour and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `app.js` switches mood with a single class, so the drawing stays in the markup and the styling in `app.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight colour and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
```
╭───╮
@@ -86,6 +86,9 @@ When you make a mistake, get corrected, or discover something about this codebas
2. Keep it specific to this repo. General advice belongs nowhere.
3. If this fix is a workflow rather than a rule, put it in `.claude/skills/` and link it from here.
4. Include the change in the same commit and mention it in your summary.
5. A skill rule broken twice becomes a script check (a `scripts/` test or a skill-script check), not more prose.
6. Before adding a line, look for one on the same topic: sharpen or extend that one rather than adding a near-duplicate.
7. Keep the log to 17 entries at most. Over the cap, first merge entries that share a cause, then drop the lowest-value ones: one-offs unlikely to recur, rules a test or script now enforces, and entries about code that no longer exists.
## Failure log
@@ -93,10 +96,12 @@ When you make a mistake, get corrected, or discover something about this codebas
- Sync upstream only through `/sync-repo`, and verify its baseline against the real tree before porting: an earlier sync silently skipped a whole upstream release (the `3-implement-review` skill) while the recorded version froze. Update the baseline with `.claude/skills/sync-repo/set-synced.mjs`, never with a shell pipe over the decrypted body.
- After a sync merge, run `npm test` before trusting a "clean" file: when upstream and plan2code fixed the same bug, `git merge-file` keeps both copies without a conflict (a sync once left `let pattern` declared twice in `app.js`, caught only by `parse-check`).
- When extracting upstream files in Git Bash, run `git show <ref>:<path>` with `MSYS_NO_PATHCONV=1` and `C:/` style paths (never `/c/`): path conversion rewrites `origin/main:.readme/x.md` into `origin\main;.readme\x.md`, the show fails, and the merge silently runs against an empty "theirs". Check every extracted file is non-empty before merging.
- After a sync, grep the result for the upstream owner slug and company name in any case (the `/sync-repo` body lists them): the rebrand map only rewrites URLs, so a bare owner slug once slipped through into `feedback-payload.mjs` (and its test) until it was fixed by hand to `jparkerweb/plan2code`. No upstream name may appear in plain text anywhere in this repo.
- After a sync, grep the result for every upstream name the rebrand map can miss (the `/sync-repo` body lists them): the owner slug and company name in any case, the bare brand word inside identifiers and fixtures, and the ticket key followed by anything, not only digits. Each slipped through once: an owner slug in `feedback-payload.mjs` and its test (fixed by hand to `jparkerweb/plan2code`); in v2.7.0 a `KEPT_<BRAND>_ENTRIES` constant, a `<brand>Dir` option, a `"<brand>"` test folder and an owner slug in a git remote URL; in v2.8.0 git board fixtures built as `` `feature/<KEY>-${11000 + i}-…` `` template literals, which a digits-only rewrite to `ABC-<n>` misses. No upstream name may appear in plain text anywhere in this repo.
- Keep plan2code's ticket-free `commit-msg.mjs` (`<subject>`, `AI Assisted`) in every `/sync-repo`: upstream's ticket-from-branch rule was ported by mistake once and removed in v2.6.0.
- When a new first-run dialog is added to the web console, set its seen flag in `scripts/capture-screenshots.mjs`'s `looks.json` too: the Welcome dialog once covered the regenerated dashboard screenshots until `welcomeSeen: true` was added.
- After a sync, grep for the upstream brand word on its own too, not only the full product name: the rebrand map misses a bare brand word inside identifiers and fixtures (a `KEPT_<BRAND>_ENTRIES` constant, a `<brand>Dir` option, a `"<brand>"` test folder, an owner slug in a git remote URL), and v2.7.0's sync let all four through until the residual grep caught them.
- After a sync, grep for the upstream ticket key followed by anything, not only by digits: v2.8.0's git board fixtures built branch names as `` `feature/<KEY>-${11000 + i}-…` `` template literals, which a digits-only rewrite to `ABC-<n>` misses.
- Import `scripts/skill-script-helpers.mjs` in any test that builds git fixtures for a skill script or `git-repo.mjs`: it scrubs the whole test process's git config, so fixtures, imported modules and spawned scripts agree. Mixed configs broke `git plan switch` once (a global `core.autocrlf=true` checked fixtures out with CRLF the scrubbed script read as changed).
- Before deleting a test file that upstream split or removed, diff plan2code's copy against the rebranded upstream base and port the plan2code-only tests: v2.7.0's split of the web console suite would otherwise have dropped seven hardening tests (now in `scripts/test-web-console-hardening.mjs`).
- Register a new skill in `install.js` `SOURCE_PROMPTS` before running its `scripts/test-script-<name>.mjs`: importing `scripts/skill-script-helpers.mjs` rebuilds `skills/` and prunes any skill folder `install.js` does not list, so the script under test vanishes.
- When a `CHANGELOG.md` heading gets a version number, set the same number in `version.json` (with its `releaseDate`), the root `package.json` and README's `Version X.Y.Z` line in the same change, then run `npm run build:skills`. The changelog skill only touches `package.json`: v2.9.0 nearly shipped with `version.json` at 2.8.1, and README's line sat at 2.6.0 for three releases.
- When `npm test` fails only timing-bound suites (the chat stress test, then a cascade in the session suite starting at "no submitted frame within 5s") while the machine is busy, rerun those files alone, and the `node --test` list with `--test-concurrency=4`, before suspecting the change: they failed that way on untouched code under load during the web console file split.
- Post a helper as `done` or `failed` in the same turn its completion notice arrives: its row stays `running` on the Subagents tab until a post says otherwise (a build once reached its sign-off with one row spinning). A `finish` is now refused while any helper is `running`.
+51
View File
@@ -2,6 +2,57 @@
All notable changes to Plan2Code will be documented in this file.
## v2.9.0
### ✨ Added
- **building habits**: Quick Task, Implement and Implement + Review now read one shared reference file, `references/building-habits.md`, at three moments. When a bug or an unexpected failing test turns up, they find the cause first: build a command that fails on the bug before changing code (or say why they cannot, rank their guesses with the evidence and let you decide), then keep the reproduction as a regression test in the project's existing test runner. When the plan asks for it, they build test first: write the test, see it fail for the right reason, then write the code. Before a restructure meant to change no behaviour, they pin the behaviour with tests that must pass unchanged afterwards. Adapted from Matt Pocock's [`diagnose`, `tdd` and `improve-codebase-architecture`](https://github.com/mattpocock/skills) skills and pstack's debugging playbook (both MIT).
- **plan**: the testing question gains a fourth choice, **Approach**: code first (the default) or test first. Test first is recorded in the PLAN-DRAFT's Testing Strategy table, and Document then orders each task's test before its code with a `Test:` line under the task naming where the test drives the behaviour.
- **review**: reviews run in a fresh helper that never saw the build; reports say how they ran. Wherever the tool can start a helper and the web console's Subagents switch is not off, every review (`/plan2code-review`, Implement + Review's Stage 2, Implement's "review" at sign-off and Quick Task's "Review it now") hands its analysis to one helper briefed only with the spec and the change set (the new `references/reviewer-brief.md`). The main session checks every finding in the source before you see it and drops what it cannot confirm. Each report carries a **Reviewed by** line: a fresh helper (with how many findings were checked and dropped), or this session, said once as not independent. Adapted from pstack's independent reviewer and Matt Pocock's [`code-review`](https://github.com/mattpocock/skills) guidance (both MIT).
- **xray**: a new skill, **Codebase X-ray** (`/plan2code-xray`), on the dashboard under *Useful any time*. Explain an area: how it works and why it is that way, citing files and the commits and pull requests behind it (git history always, `gh` when it is installed and signed in, and it says once which sources it could not use). Or find the rough spots: files that always change together, thin wrappers, tangled boundaries and busy code with no tests, ranked with a concrete "to change X today you must touch..." example each. You tick the ones worth fixing and only those go into `specs/<name>/ARCHITECTURE-BRIEF-<date>.md`, ready for Pathfinder or Plan. A new script, `xray.mjs`, does the counting from git history. Pathfinder and Plan point at it when the code is unfamiliar. Adapted from Matt Pocock's [`improve-codebase-architecture`](https://github.com/mattpocock/skills) skill (MIT) and pstack's codebase survey, `how` and `why`.
- **diagnose**: a new skill, **Diagnose a bug** (`/plan2code-diagnose`), on the dashboard under *Useful any time*. It finds a bug's cause and writes it up without fixing it, under the find-the-cause-first habit: a command that fails on the bug first (or, when it cannot build one, its guesses ranked with the evidence), then the cause in `specs/<bug-name>/DIAGNOSIS-<date>.md`. It then offers `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big. The dashboard shows such a folder as a new spec state, **Bug diagnosed**, which lights Quick Task (suggested) and Plan and keeps Document, Implement, Implement + Review and Finalize greyed. Adapted from Matt Pocock's [`diagnose`](https://github.com/mattpocock/skills) skill and pstack's debugging playbook (both MIT).
- **quick-task**: asks "Write the test first?" when the change alters behaviour and the project already has a test runner, and names the test spot in the plan's Verify section. A bug fix starts with its reproduction.
- **show me it working**: Implement, Implement + Review, Quick Task and Finalize offer to show the change running before you approve, never required: reply `show me` in the terminal, or press **Show me it working** on the web console. The agent starts the app the way `AGENTS.md` says (working it out from the project and offering the line for `AGENTS.md` when it is missing, or asking you), looks at the change, stops what it started and records one line saying what was run and what was seen. Screenshots appear on the page only, never under `specs/`. Init and Init Update now ask how to start the app and where to view it. Adapted from pstack's proof-on-the-running-app idea (MIT).
- **web console**: a doc can show a picture. An image block (`"image": "shots/<name>.png"`) shows a PNG, JPEG or WebP the agent saved under the session's `shots/` folder; anything outside that folder, over 5 MB or not really an image is refused.
- **launcher**: `plan2code update` updates everything that was installed (the skills, the `plan2code` command and any of the status line, `plan2code-loop`, `plan2code-metrics` and `plan2code-bot`), with no menu and never uninstalling. Every global install now writes `~/.plan2code/install.json` listing what it installed, which `install.js --update` reads; with no record it updates the skills and the `plan2code` command.
- **launcher**: `plan2code` prints one line before it starts your agent when a newer release is out: `Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`. It reads the web console's saved release check, so it never waits on the network; when that check is missing or old it refreshes it in the background for the next start.
- **web console**: **Stop session** gains a second way to stop, **Stop with a handoff**. It saves the skill's place as before and also writes a Handoff document, so a quick task, a review or a half-done changelog keeps its context; the paused screen names the file.
- **dashboard**: this checkout's unused handoffs show as chips in the spec picker. **Pick it up here** carries on in the skill that stopped (a handoff from the Handoff skill carries on in Quick Task), in the same session, and the chip is gone afterwards; **Read it all**, **Copy for a new conversation** and **Delete** sit beside it.
### 🔧 Changed
- **implement**, **quick-task**, **plan**, **document**: tightened as they took on the habits, so each stays well under 15,000 characters.
- **pathfinder**: tightened to stay under 15,000 characters as it took on the X-ray pointer.
- **quick-task**, **implement**: when the cause is unclear or the fix big, they stop and suggest `/plan2code-diagnose`.
- **finalize**: its archive confirmation now reads "yes / no / show me", the last chance to look at the whole feature running before the spec moves.
- **dashboard**: Handoff is now the last card in *Useful any time*, after Git.
- **contributors**: the add-a-skill checklist in `.agents-docs/AGENTS-development-commands.md` now lists every place a new skill must be registered (it missed about a dozen).
- **contributors**: `AGENTS.md` gains a rule that a skill rule broken twice becomes a script check, not more prose.
- **web console**: the UPDATE AVAILABLE dialog now gives `plan2code update` as the command, keeping the install command beside it for a machine without the `plan2code` command. User Preferences → Cleanup never lists `~/.plan2code/install.json`.
- **docs**: README, the quick reference and the web console guide say to update with `plan2code update` (or re-run the install command).
- **handoff**: every handoff now lives in `~/.plan2code/handoffs/` (a Markdown file plus a small `.json` beside it), owned by the web console, and handoffs older than 30 days are swept when the console opens. The Handoff skill writes there with no folder or `.gitignore` question, and Cleanup never lists the folder. Handoffs written to the OS temp folder or a `handoffs/` folder before this change are not listed.
- **dashboard**: a **Bug fixed** spec has a visible **Delete** that needs one confirm, and its chip no longer repeats the "bug fixed" line.
- **web console**: the review sign-off card lists **Approve this phase** before **Show me it working**, with the approve button outlined in the accent colour.
- **web console**: a sign-off's **yes** button (Quick Task's **Build it**, Finalize's **Archive it**) is outlined in your highlight colour too, like **Approve**. So is the yes of a yes/no question (such as Plan's **Write the plan**) and a recap's **Yes, that is right**, except on a question marked dangerous, whose yes stays red.
- **web console**: **Skip this one** (and **Do not skip**) on an optional question is a small button in your highlight colour, like a comment box's **No changes**, instead of an underlined link.
- **init**, **init-update**: the *Keeping this file current* section they write into `AGENTS.md` gains three rules: a rule broken twice becomes an automated check, a new Failure log line first looks for one on the same topic to sharpen instead, and the log holds 17 entries at most (over the cap, merge entries that share a cause, then drop the lowest-value ones). Init update offers the missing rules to an existing section and tidies the log on every run, showing each merge and removal for a yes before it writes.
- **contributors**: this repo's `AGENTS.md` follows the same Failure log rules, and its three post-sync grep entries are merged into one.
- **contributors**: the web console's source is split by job: `lib.mjs`, `server.mjs`, `console.mjs`, `app.js` and `app.css` become `routes.mjs`, `static.mjs`, `cmd-*.mjs`, the by-job Node files, `public/screens/` and `public/styles/`. Nothing a person sees changes, and the page starts faster (ready in about 280 ms, was 450 ms).
- **contributors**: the per-skill and per-spec-state tables live in two data files, `public/skills.js` and `public/spec-states.js`, so adding a skill or a state is a short list in `.agents-docs/AGENTS-development-commands.md` and `npm test` names anything missed. This replaces the long add-a-skill checklist noted above.
- **contributors**: page tests drive the real console in Chrome or Edge through `playwright-core` inside `npm test` (running it needs Node 20 or newer; installed skills still need only Node 18). The screenshot and speed scripts use it too, with no hand install, and `scripts/css-snapshot.mjs` compares every computed style across a stylesheet change.
- **contributors**: a test keeps the files table in `.agents-docs/AGENTS-architecture.md` complete: every console file needs a one-line row.
- **contributors**: `post` now refuses a `finish` (exit 3) while any reported helper still shows `running`, so a finished page never keeps a spinning row. The agent contract in `console-finish.md` says to mark each helper `done` or `failed` first.
### 🗑️ Removed
- **handoff**: the Handoff skill's `handoff-path.mjs` script is retired in favour of `console.mjs handoff new`, which every skill can reach.
### 🐛 Fixed
- **web console**: a short card on the git board (a confirm such as *Delete 2 branches?*) fills the board's width instead of sitting narrow in the middle.
- **web console**: a redraw no longer throws you back to the top of the finished screen, a doc tab, the Overview or the dashboard menu (pressing **Review it now**, or an agent update landing while you read). The page kept your place only on question cards; it now keeps it for whatever is scrolling, as long as the same thing is still on screen.
- **dashboard**: a bug folder whose diagnosis Quick Task had marked `Fixed` no longer sits on the dashboard forever as *Files on disk*, pre-selected as the most recent spec with no card to clear it. The scan reports it as a new spec state, **Bug fixed**: no pipeline card lights for it, the picker never opens on it (it opens on the most recent spec still in play, or *Start from scratch*), and it is hidden while *Hide unavailable workflows* is on, dimmed otherwise. Quick Task, right after marking a diagnosis-only folder `Fixed`, offers to archive it to `specs--completed/<bug>/` with the same `specs.mjs archive` Finalize uses (a confirm card on the web console).
## v2.8.1
### 📚 Documentation
+4 -1
View File
@@ -15,7 +15,8 @@ The web console is the main way in: a local page where questions, documents, bui
| ------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------- |
| From your project (shell) | `plan2code` | Opens Claude Code, Devin or Codex on the dashboard (`--cli claude` / `devin` / `codex` to choose) |
| Inside any agent | `/plan2code` (`$plan2code` in Codex) | Opens the dashboard: a card for every skill, launched on the same page |
| Install / update | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command; re-run it to update |
| Install | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command (re-run it to update without the `plan2code` command) |
| Update | `plan2code update` | Updates everything that was installed, with no menu; never uninstalls anything |
| Straight into a skill | `/plan2code-1-plan --web` (any step) | Skips the "web console or terminal?" question and opens the page |
The install command always opens a menu. Back at your prompt with no output at all? npm could not reach the repository and hid the reason: run `git ls-remote https://github.com/jparkerweb/plan2code.git` to see it (usually the network, a proxy or the VPN).
@@ -41,6 +42,8 @@ Every command below is what a dashboard card runs. Typed on its own, each one as
| 3+review | /plan2code-3-implement-review | overview.md | Reviewed implementation ready for approval (alternative to `/plan2code-3-implement`) |
| 4 | /plan2code-4-finalize | overview.md | Archived specs |
| handoff | /plan2code-handoff | Conversation | Self-contained handoff doc (OS temp dir by default, or a folder you pick such as `handoffs/`) |
| xray | /plan2code-xray | An area, or none | An explanation citing files and commits, or `ARCHITECTURE-BRIEF-<date>.md` with the rough spots you picked |
| diagnose | /plan2code-diagnose | A bug, or none | `DIAGNOSIS-<date>.md` with the cause and its evidence, then Quick Task (or Plan for a big fix) to fix it |
| changelog | /plan2code-changelog | Your branch | `CHANGELOG.md` entries and the `package.json` version, from the default branch's latest version |
| git | /plan2code-git | Your repo | Commits (`<subject>` / `AI Assisted`), branches, pull with conflict help, push, publish |
+11 -7
View File
@@ -13,7 +13,7 @@ the next engineer all start from the same specs.
One command opens it, every step is a card, and the terminal is always there if you prefer it.
Version 2.6.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
Version 2.9.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
---
@@ -37,7 +37,7 @@ The dashboard, in a project halfway through a build. It suggests the next step f
- **Ways in.** `plan2code` (Claude Code, Devin or Codex), or type `/plan2code` in your agent (`$plan2code` in Codex).
- **No agent yet?** Install Claude Code, Codex or Devin first.
Installation needs network access and runs through the [skills CLI](https://skills.sh). To update, re-run the install command.
Installation needs network access and runs through the [skills CLI](https://skills.sh). To update, run `plan2code update` (or re-run the install command).
```bash
npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git
@@ -93,7 +93,7 @@ GitHub Copilot · Windsurf · Codex · Continue · Codeium · Zed · Amp · Open
Gemini CLI · Cline · Roo · Kilo · Goose · Trae · Qwen Code.
The installer keeps one canonical copy of each skill under `~/.agents/skills/` and links it into
agents that maintain their own directory. To update, re-run the install command.
agents that maintain their own directory. To update, run `plan2code update` (or re-run the install command).
Use the installer rather than calling `skills add` against the repository root: recursive discovery
would also find maintainer-only skills under `.claude/skills/`. The installer targets `skills/`
@@ -184,15 +184,17 @@ The dashboard's cards, and when each one lights up for the spec you pick:
| Set up this project | Reads your project and writes AGENTS.md, the guide every later step works from. | The project has no AGENTS.md yet |
| Refresh AGENTS.md | Brings AGENTS.md and its notes up to date with what the project has learned lately. | The project has an AGENTS.md |
| Pathfinder | A foggy idea becomes a clear list of decisions, settled one question at a time. | You start fresh, or the spec is still being explored |
| Plan | Requirements, technical design and your approval: the shape of what gets built. | You start fresh, or the spec has a finished Pathfinder map or a drafted plan |
| Plan | Requirements, technical design and your approval: the shape of what gets built. | You start fresh, or the spec has a finished Pathfinder map, a drafted plan or a bug diagnosis |
| Revise the plan | Requirements changed mid-build? Adjust the plan without starting over. | The spec is written up into phases and not fully built |
| Document | The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do. | The spec has a drafted plan |
| Implement | Builds the next phase, task by task, with a report and your sign-off at the end. | The spec has phases with tasks still to build |
| Implement + review | One phase built, then a careful review of the changes, then your sign-off. All in one run. | The spec has phases with tasks still to build |
| Finalize | Checks the work, writes the summary, files the specs away and suggests the commit message. | Every task in the spec is done |
| Quick task | Too small for the full process? A quick plan, then it just builds it. | Always |
| Quick task | Too small for the full process? A quick plan, then it just builds it. | Always (suggested when the spec is a diagnosed bug) |
| Review | A second opinion on the changes. Problems ranked, and you pick what gets fixed. | Always |
| Handoff | Pack this conversation into a document a fresh session can pick up cold. | Always |
| Handoff | Pack this conversation into a document a fresh session can pick up cold. Any skill's **Stop with a handoff** writes one too, and the dashboard lists them to pick up. | Always |
| Codebase X-ray | Explain how and why an area works, or find the rough spots worth fixing. | Always |
| Diagnose a bug | Find a bug's cause and write it up, without fixing it. | Always |
| Changelog | Checks the CHANGELOG version against the main branch and suggests entries for what is new. | Always |
| Git | Branches, pull, push and commits on one board, asking before anything leaves your machine. | Always (offers to start a repository outside one) |
@@ -360,7 +362,9 @@ console or the terminal; add `--web` to skip the question and go straight to the
| `/plan2code-init-update` | Fold what you learned this session back into `AGENTS.md` |
| `/plan2code-quick-task` | A small change that doesn't warrant the full sequence |
| `/plan2code-1b-revise-plan` | Requirements moved mid-build. Revise the specs, not the code |
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from |
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from, saved in `~/.plan2code/handoffs/` and listed on the dashboard to pick up |
| `/plan2code-xray` | Explain how and why an area of the code works (citing files, commits and PRs), or rank the rough spots worth fixing into a brief for Pathfinder or Plan; never edits code |
| `/plan2code-diagnose` | Find a bug's cause and write it up as `specs/<bug-name>/DIAGNOSIS-<date>.md` without fixing it, then offer `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big |
| `/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 |
+3 -1
View File
@@ -11,7 +11,7 @@
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<style>
/* The web console's palette and type (src/web-console/public/app.css), so the
/* The web console's palette and type (src/web-console/public/styles/tokens.css), so the
site and the product look like one thing, with the Plan2Code blue as the
accent: #2455a4 in light, and the console's Ocean highlight (palette.js),
which the screenshots use, in dark. System fonts only, like the console. */
@@ -307,6 +307,8 @@ footer a { color: inherit; }
<div class="util"><span class="chip">Any time</span><h3>Quick task</h3><p>Too small for the full process? A quick plan, then it just builds it.</p></div>
<div class="util"><span class="chip">Any time</span><h3>Review</h3><p>A second opinion on the changes. Problems ranked, and you pick what gets fixed.</p></div>
<div class="util"><span class="chip">Any time</span><h3>Handoff</h3><p>Pack the current session into a document a fresh session can pick up cold.</p></div>
<div class="util"><span class="chip">Any time</span><h3>Codebase X-ray</h3><p>Explains how and why an area works, or ranks the rough spots worth fixing into a brief for planning.</p></div>
<div class="util"><span class="chip">Any time</span><h3>Diagnose a bug</h3><p>Finds a bug's cause and writes it up without fixing it, then hands the fix to Quick task, or to Plan when it is big.</p></div>
<div class="util"><span class="chip">Any time</span><h3>Changelog</h3><p>Picks the next version and drafts the entries, which you edit before Git commits them.</p></div>
<div class="util"><span class="chip">Any time</span><h3>Git</h3><p>A board for branches, pull, push and commits that opens on the likely next step.</p></div>
</div>
+202 -26
View File
@@ -174,6 +174,7 @@ const SOURCE_PROMPTS = [
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
{ source: 'plan2code-review.md', target: 'review.md' },
{ source: 'plan2code-review-references' }
]
@@ -216,6 +217,7 @@ const SOURCE_PROMPTS = [
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
{ source: 'plan2code-review.md', target: 'review.md' },
{ source: 'plan2code-review-references' }
]
@@ -230,6 +232,7 @@ const SOURCE_PROMPTS = [
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'plan2code-3-implement.md', target: 'implement.md' },
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
{ source: 'plan2code-review.md', target: 'review.md' },
{ source: 'plan2code-review-references' }
]
@@ -263,6 +266,29 @@ const SOURCE_PROMPTS = [
scripts: ['specs.mjs'],
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-xray.md',
stepNumber: 'xray',
name: 'xray',
displayName: 'X-ray Mode',
description: 'Explain how and why an area of the code works, or find the rough spots worth fixing',
isUtility: true,
scripts: [],
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-diagnose.md',
stepNumber: 'diagnose',
name: 'diagnose',
displayName: 'Diagnose Mode',
description: 'Find and write up a bug\'s cause without fixing it',
isUtility: true,
scripts: ['specs.mjs'],
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' }
]
},
{
source: 'plan2code-changelog.md',
stepNumber: 'changelog',
@@ -309,6 +335,8 @@ function generateStepLabel(prompt) {
if (prompt.stepNumber === 'review') return 'Review';
if (prompt.stepNumber === 'handoff') return 'Handoff';
if (prompt.stepNumber === 'git') return 'Git';
if (prompt.stepNumber === 'xray') return 'X-ray';
if (prompt.stepNumber === 'diagnose') return 'Diagnose';
if (prompt.stepNumber === 'changelog') return 'Changelog';
if (prompt.stepNumber === 'quick') return 'Quick Task';
return `Step ${prompt.stepNumber}`;
@@ -900,9 +928,10 @@ function removeInstalledSkills(scope, { quiet = false } = {}) {
// ============================================================================
/**
* Execute installation
* Execute installation. `unattended` (plan2code update) asks nothing and skips the getting-started
* steps; `outcome` receives `skills` and `launcher` as true or false for update's per-piece report.
*/
async function install() {
async function install({ unattended = false, outcome = {} } = {}) {
displaySectionHeader(' INSTALLING SKILLS ');
if (!buildSkills(true)) {
console.log(`${COLORS.RED}${SYMBOLS.ERROR} Failed to build ${SKILLS_DIR_NAME}/ from src/${COLORS.RESET}`);
@@ -946,10 +975,13 @@ async function install() {
console.log('');
reportSkillsOutput(result);
const failed = !result.ok;
outcome.skills = !failed;
if (!failed) recordInstalled('skills');
// The `plan2code` command opens the dashboard skill, so it's only worth adding once the
// skills themselves are in place.
const launcherFailed = failed ? false : (await installLauncher({ quiet: true })) !== 0;
const launcherFailed = failed ? false : (await installLauncher({ quiet: true, unattended })) !== 0;
outcome.launcher = !failed && !launcherFailed;
// Summary
console.log(`${COLORS.CYAN}╔═══════════════════════════════════════════════════════════════════════════╗${COLORS.RESET}`);
@@ -977,7 +1009,7 @@ async function install() {
}
// The steps come first: where to start, the ways in, and what to do without an agent.
printGettingStarted({ commandInstalled: !launcherFailed });
if (!unattended) printGettingStarted({ commandInstalled: !launcherFailed });
console.log(`${COLORS.GREEN} ╭───╮${COLORS.RESET} ${COLORS.BRIGHT}All done! Happy coding!${COLORS.RESET}`);
console.log(`${COLORS.GREEN} ╲│ ${COLORS.CYAN}★${COLORS.GREEN} │╱${COLORS.RESET}`);
console.log(`${COLORS.GREEN} │ ${COLORS.BRIGHT}◡${COLORS.GREEN} │${COLORS.RESET}`);
@@ -1049,6 +1081,7 @@ function uninstallSkills() {
} else {
errors++;
}
if (errors === 0) forgetInstalled('skills');
console.log(`\n${COLORS.YELLOW}${SYMBOLS.ACTIVE} CLEANING LEGACY PATHS${COLORS.RESET}\n`);
const legacy = cleanLegacyPaths();
@@ -1520,6 +1553,7 @@ function installPlan2CodeLoop() {
}
console.log('');
recordInstalled('loop');
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-loop installed successfully!${COLORS.RESET}`);
console.log('');
console.log(`${COLORS.CYAN}Usage:${COLORS.RESET}`);
@@ -1539,6 +1573,7 @@ function uninstallPlan2CodeLoop() {
displaySectionHeader('PLAN2CODE-LOOP', '[ UNINSTALL ]');
removeGlobalSymlink();
forgetInstalled('loop');
console.log('');
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-loop uninstalled${COLORS.RESET}`);
@@ -1756,6 +1791,7 @@ function installPlan2CodeMetrics() {
}
console.log('');
recordInstalled('metrics');
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-metrics installed successfully!${COLORS.RESET}`);
console.log('');
console.log(`${COLORS.CYAN}Usage:${COLORS.RESET}`);
@@ -1772,6 +1808,7 @@ function uninstallPlan2CodeMetrics() {
displaySectionHeader('PLAN2CODE-METRICS', '[ UNINSTALL ]');
removeMetricsGlobalSymlink();
forgetInstalled('metrics');
console.log('');
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-metrics uninstalled${COLORS.RESET}`);
@@ -1795,9 +1832,10 @@ function getStatusLineSrcDir() {
/**
* Install status line (copy + configure settings).
* Async because it may prompt when a custom (non-plan2code) statusLine exists.
* Async because it may prompt when a custom (non-plan2code) statusLine exists. `unattended`
* (plan2code update) never prompts: a custom statusLine is kept as it is.
*/
async function installStatusLine({ quiet = false } = {}) {
async function installStatusLine({ quiet = false, unattended = false } = {}) {
if (!quiet) {
displaySectionHeader('CLAUDE STATUS LINE', '[ INSTALL ]');
} else {
@@ -1873,6 +1911,13 @@ async function installStatusLine({ quiet = false } = {}) {
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} Existing statusLine detected in settings.json:`);
console.log(` ${COLORS.DIM} ${existingCmd}${COLORS.RESET}`);
// The person chose that status line when they last installed; an update keeps it.
if (unattended) {
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} Kept it: scripts updated, settings.json unchanged${COLORS.RESET}`);
recordInstalled('statusline');
return 0;
}
const rl2 = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise(resolve => {
rl2.question(` ${COLORS.CYAN}Replace with Plan2Code status line?${COLORS.RESET} (Y/n): `, resolve);
@@ -1882,6 +1927,7 @@ async function installStatusLine({ quiet = false } = {}) {
if (answer.trim().toLowerCase() === 'n') {
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} Skipped — scripts installed but settings.json unchanged${COLORS.RESET}`);
console.log('');
recordInstalled('statusline');
return 0;
}
@@ -1919,6 +1965,7 @@ async function installStatusLine({ quiet = false } = {}) {
}
if (settingsOk) {
recordInstalled('statusline');
if (!quiet) {
console.log('');
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Claude Status Line installed successfully!${COLORS.RESET}`);
@@ -2000,6 +2047,7 @@ function uninstallStatusLine() {
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No status line files found${COLORS.RESET}`);
}
forgetInstalled('statusline');
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} Preserved: statusline-config.json${COLORS.RESET}`);
console.log('');
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Status line uninstalled${COLORS.RESET}`);
@@ -2217,6 +2265,7 @@ function installPlan2CodeBot() {
}
console.log('');
recordInstalled('bot');
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-bot installed successfully!${COLORS.RESET}`);
console.log('');
console.log(`${COLORS.CYAN}Usage:${COLORS.RESET}`);
@@ -2233,6 +2282,7 @@ function uninstallPlan2CodeBot() {
displaySectionHeader('PLAN2CODE-BOT', '[ UNINSTALL ]');
removeBotGlobalSymlink();
forgetInstalled('bot');
console.log('');
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-bot uninstalled${COLORS.RESET}`);
@@ -2260,7 +2310,55 @@ const MODELS_SRC = path.join(__dirname, 'src', 'launcher', 'models.json');
const MODELS_DEST = path.join(os.homedir(), '.plan2code', 'bin', 'models.json');
const LAUNCHER_DEST = path.join(os.homedir(), '.plan2code', 'bin', 'plan2code.js');
const LAUNCHER_STATE = path.join(os.homedir(), '.plan2code', 'launcher.json');
// The release notice: the launcher reads the console's cached check through this copy, and
// compares it with the version.json written beside it.
const UPDATE_CHECK_SRC = path.join(__dirname, 'src', 'web-console', 'update-check.mjs');
const UPDATE_CHECK_DEST = path.join(path.dirname(LAUNCHER_DEST), 'update-check.mjs');
const LAUNCHER_VERSION_DEST = path.join(path.dirname(LAUNCHER_DEST), 'version.json');
// What a global install put on this machine, so `plan2code update` reinstalls exactly that.
const INSTALL_RECORD = path.join(os.homedir(), '.plan2code', 'install.json');
const INSTALL_PIECES = ['skills', 'launcher', 'statusline', 'loop', 'metrics', 'bot'];
const LAUNCHER_PICK_FOLDER_FLAG = '--pick-folder';
/** `~/.plan2code/install.json` as `{ version, scope, pieces }`, or null when missing or unparsable. */
function readInstallRecord() {
try {
const record = JSON.parse(fs.readFileSync(INSTALL_RECORD, 'utf8'));
if (record && typeof record === 'object' && Array.isArray(record.pieces)) return record;
} catch {}
return null;
}
/** Temp file, then rename, so a crash never leaves a half-written record. A failure only skips the record. */
function writeInstallRecord(pieces) {
const record = {
version: projectVersion.version,
scope: 'global',
pieces: [...new Set(pieces)].filter((piece) => INSTALL_PIECES.includes(piece)).sort(),
};
const tmp = `${INSTALL_RECORD}.${process.pid}.tmp`;
try {
fs.mkdirSync(path.dirname(INSTALL_RECORD), { recursive: true });
fs.writeFileSync(tmp, JSON.stringify(record, null, 2) + '\n');
fs.renameSync(tmp, INSTALL_RECORD);
} catch {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
}
/** Add a piece after a successful global install. */
function recordInstalled(piece) {
const record = readInstallRecord();
writeInstallRecord([...(record ? record.pieces : []), piece]);
}
/** Drop a piece after its uninstall; no record means nothing to forget. */
function forgetInstalled(piece) {
const record = readInstallRecord();
if (record) writeInstallRecord(record.pieces.filter((p) => p !== piece));
}
const SHORTCUT_NAME = 'Plan2Code';
const SHORTCUT_ICON_SRC = path.join(__dirname, 'src', 'launcher', 'plan2code.ico');
const SHORTCUT_ICON_DEST = path.join(path.dirname(LAUNCHER_DEST), 'plan2code.ico');
@@ -2539,9 +2637,10 @@ async function offerDesktopShortcut(binDir) {
/**
* Install the global `plan2code` command, then offer the desktop shortcut. `quiet` prints
* compact lines for use inside the skills install instead of a section of its own.
* compact lines for use inside the skills install instead of a section of its own;
* `unattended` (plan2code update) skips the shortcut offer and leaves any shortcut as it is.
*/
async function installLauncher({ quiet = false } = {}) {
async function installLauncher({ quiet = false, unattended = false } = {}) {
if (quiet) {
console.log(`${COLORS.YELLOW}${SYMBOLS.ACTIVE} INSTALLING THE ${LAUNCHER_COMMAND.toUpperCase()} COMMAND${COLORS.RESET}`);
} else {
@@ -2559,6 +2658,8 @@ async function installLauncher({ quiet = false } = {}) {
// The curated model menu is the authors' source of truth, so it is overwritten on every install.
// Models the user added in User Preferences live in ~/.plan2code/models.json and are untouched.
fs.copyFileSync(MODELS_SRC, MODELS_DEST);
fs.copyFileSync(UPDATE_CHECK_SRC, UPDATE_CHECK_DEST);
fs.writeFileSync(LAUNCHER_VERSION_DEST, JSON.stringify(projectVersion, null, 2) + '\n');
if (process.platform !== 'win32') fs.chmodSync(LAUNCHER_DEST, 0o755);
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Installed: ${LAUNCHER_DEST}`);
} catch (error) {
@@ -2592,8 +2693,9 @@ async function installLauncher({ quiet = false } = {}) {
if (!isDirOnPath(binDir)) {
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} ${binDir} is not on your PATH — add it to use ${COLORS.BRIGHT}${LAUNCHER_COMMAND}${COLORS.RESET} from any directory`);
}
recordInstalled('launcher');
// The shortcut is a convenience on top of the command, so a failure here only warns.
await offerDesktopShortcut(binDir);
if (!unattended) await offerDesktopShortcut(binDir);
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} The ${LAUNCHER_COMMAND} command starts the agent with permission prompts off (${COLORS.CYAN}--permission-mode bypassPermissions${COLORS.RESET} in Claude Code, ${COLORS.CYAN}bypass${COLORS.RESET} in Devin, ${COLORS.CYAN}--dangerously-bypass-approvals-and-sandbox${COLORS.RESET} in Codex). Run ${COLORS.CYAN}claude /plan2code${COLORS.RESET} yourself if you want prompts.`);
console.log('');
// Inside install() the final summary prints the steps once, after everything else.
@@ -2627,7 +2729,8 @@ function uninstallLauncher() {
}
const shortcut = getShortcutFile();
if (isOurShortcut(shortcut)) remove(shortcut);
for (const file of [LAUNCHER_DEST, MODELS_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE]) {
forgetInstalled('launcher');
for (const file of [LAUNCHER_DEST, MODELS_DEST, UPDATE_CHECK_DEST, LAUNCHER_VERSION_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE, INSTALL_RECORD]) {
if (fs.existsSync(file)) remove(file);
}
try {
@@ -2642,26 +2745,99 @@ function uninstallLauncher() {
return 0;
}
// ============================================================================
// UPDATE (`plan2code update` runs the npx install with --update)
// ============================================================================
/**
* The install function for each recorded piece, in the order update runs them. Install
* functions only: an update never uninstalls anything. install() covers the skills and the
* plan2code command together.
*/
const UPDATE_STEPS = {
skills: install,
launcher: installLauncher,
statusline: installStatusLine,
loop: installPlan2CodeLoop,
metrics: installPlan2CodeMetrics,
bot: installPlan2CodeBot,
};
/**
* Reinstall whatever ~/.plan2code/install.json lists, without the menu or any prompt. Returns
* the exit code: 0 when every piece updated, 1 naming the pieces that failed.
*/
async function update({ steps = UPDATE_STEPS } = {}) {
displaySectionHeader(' UPDATING PLAN2CODE ');
console.log(`${COLORS.BLUE}${COLORS.BRIGHT}Installing:${COLORS.RESET} ${projectVersion.name} ${projectVersion.version}`);
console.log('');
const record = readInstallRecord();
const pieces = record ? record.pieces : ['skills', 'launcher'];
if (!record) {
console.log(`${COLORS.YELLOW}${SYMBOLS.INFO}${COLORS.RESET} No install record found (installed before v${projectVersion.version}); updating the skills and the plan2code command.`);
console.log('');
}
const results = {};
for (const piece of INSTALL_PIECES) {
if (!pieces.includes(piece) || piece in results) continue;
const outcome = {};
try {
const code = await steps[piece]({ quiet: true, unattended: true, outcome });
results[piece] = code === 0 ? 'updated' : 'failed: see the messages above';
} catch (error) {
results[piece] = `failed: ${error.message}`;
}
// install() returns 1 when only the command failed, so its outcome says how the skills
// themselves went; a command it put in place has updated the launcher too, and one it
// could not is retried on its own as the next piece.
if (piece === 'skills' && typeof outcome.skills === 'boolean') {
results.skills = outcome.skills ? 'updated' : 'failed: see the messages above';
}
if (piece === 'skills' && outcome.launcher === true) results.launcher = 'updated';
console.log('');
}
console.log(`${COLORS.BRIGHT}UPDATE SUMMARY${COLORS.RESET}`);
const failed = [];
for (const piece of INSTALL_PIECES.filter((p) => p in results)) {
const ok = results[piece] === 'updated';
if (!ok) failed.push(piece);
console.log(` ${ok ? COLORS.GREEN + SYMBOLS.SUCCESS : COLORS.RED + SYMBOLS.ERROR}${COLORS.RESET} ${piece}: ${results[piece]}`);
}
console.log('');
if (failed.length > 0) {
console.log(`${COLORS.RED}${SYMBOLS.ERROR} Update failed for: ${failed.join(', ')}${COLORS.RESET}\n`);
return 1;
}
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Plan2Code is up to date (v${projectVersion.version})${COLORS.RESET}\n`);
return 0;
}
// ============================================================================
// MAIN
// ============================================================================
// Non-interactive build hooks for the generated skills/ artifact.
const argv = process.argv.slice(2);
// Run only when invoked directly; requiring the file (the update tests do) is load-only.
if (require.main === module) {
// Non-interactive build hooks for the generated skills/ artifact.
const argv = process.argv.slice(2);
if (argv.includes('--build-skills')) {
process.exit(buildSkills() ? 0 : 1);
if (argv.includes('--build-skills')) {
process.exit(buildSkills() ? 0 : 1);
} else if (argv.includes('--verify-skills')) {
process.exit(verifySkillsSync() ? 0 : 1);
} else if (argv.length === 1 && argv[0] === '--update') {
update().then((code) => process.exit(code));
} else if (argv.length > 0) {
console.error(`Unknown option(s): ${argv.join(' ')}`);
console.error('Usage: node install.js [--build-skills | --verify-skills | --update]');
console.error('Run with no options for the interactive installer.');
process.exit(1);
} else {
runInteractive();
}
}
if (argv.includes('--verify-skills')) {
process.exit(verifySkillsSync() ? 0 : 1);
}
if (argv.length > 0) {
console.error(`Unknown option(s): ${argv.join(' ')}`);
console.error('Usage: node install.js [--build-skills | --verify-skills]');
console.error('Run with no options for the interactive installer.');
process.exit(1);
}
runInteractive();
module.exports = { update, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName };
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "plan2code",
"version": "2.8.1",
"version": "2.9.0",
"private": true,
"bin": {
"plan2code-install": "./install.js"
@@ -8,9 +8,10 @@
"scripts": {
"prepare": "husky",
"build:skills": "node install.js --build-skills",
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.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-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-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-script-handoff.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs"
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.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-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-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-handoffs.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-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 scripts/test-web-console-page-git.mjs"
},
"devDependencies": {
"husky": "^9.0.0"
"husky": "^9.0.0",
"playwright-core": "1.64.1"
}
}
+21 -29
View File
@@ -16,15 +16,17 @@
// fcp first contentful paint: the person sees something
// ready the session is drawn from real state (the menu, or a question)
//
// plus the bytes and request count the page cost. Needs puppeteer-core in
// node_modules and a local Chrome or Edge for the browser columns; without
// them it still reports url/cliExit and an HTTP-only waterfall.
// plus the bytes and request count the page cost. The browser columns need
// playwright-core (from `npm install`) and a local Chrome or Edge, picked by
// scripts/browser.mjs; without a browser it still reports url/cliExit and an
// HTTP-only waterfall.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { findBrowser, launchBrowser } from "./browser.mjs";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
@@ -44,20 +46,6 @@ const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER
// so a slow GitHub never colours the timings.
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
function findBrowser() {
if (args.browser === "none") return null;
if (typeof args.browser === "string") return args.browser;
const candidates = [
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/usr/bin/google-chrome",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
];
return candidates.find((p) => fs.existsSync(p)) || null;
}
// Resolves at the first stdout line carrying a url, and again at exit.
// --launch hook (default): `open` launches "the browser" the way it would for
// a person, through PLAN2CODE_BROWSER, and the hook just writes the link to
@@ -211,18 +199,22 @@ async function roundtrip() {
async function main() {
if (args.roundtrip) return roundtrip();
const browserPath = findBrowser();
let puppeteer = null;
if (browserPath) {
// --browser none: no launch at all. --browser <path>: that executable.
// Otherwise the helper's pick; a browser problem is one line, then the
// HTTP-only waterfall.
let browser = null;
let browserName = null;
if (args.browser !== "none") {
const custom = typeof args.browser === "string" ? args.browser : null;
try {
puppeteer = (await import("puppeteer-core")).default;
} catch {
console.error("puppeteer-core not installed; browser columns skipped");
browser = await launchBrowser(custom ? { executablePath: custom } : {});
const found = custom ? null : findBrowser();
browserName = found ? `${found.channel} (${found.path})` : custom;
} catch (e) {
if (!e.browserProblem) throw e;
console.error(e.message);
}
}
const browser = puppeteer
? await puppeteer.launch({ executablePath: browserPath, headless: true, args: ["--no-first-run", "--no-default-browser-check"] })
: null;
const rows = [];
// One throwaway run so disk caches and the Node binary are warm; the person
@@ -231,7 +223,7 @@ async function main() {
stopAll();
// The tab exists before the clock starts: a person's browser is already
// running, and creating a context is the harness's cost, not the page's.
const ctx = browser ? await browser.createBrowserContext() : null;
const ctx = browser ? await browser.newContext() : null;
const page = ctx ? await ctx.newPage() : null;
const { t0, urlP, exitP, openP } = runOpen();
const o = await openP;
@@ -246,7 +238,7 @@ async function main() {
page.on("response", async (res) => {
requests++;
try {
bytes += (await res.buffer()).length;
bytes += (await res.body()).length;
} catch {}
});
if (BROWSER_DELAY) await new Promise((r) => setTimeout(r, Math.max(0, o.at + BROWSER_DELAY - Date.now())));
@@ -303,7 +295,7 @@ async function main() {
};
const summary = Object.fromEntries(cols.map((k) => [k, stat(k)]));
console.log(`web console start-up, ${RUNS} runs, workflow=${WORKFLOW}, cwd=${CWD}`);
console.log(`browser: ${browser ? browserPath : "none (HTTP-only waterfall)"}`);
console.log(`browser: ${browser ? browserName : "none (HTTP-only waterfall)"}`);
console.log("metric".padEnd(10) + "median".padStart(9) + "min".padStart(9) + "max".padStart(9));
for (const k of cols) {
const s = summary[k];
+91
View File
@@ -0,0 +1,91 @@
// Picks and launches the browser for page tests and the dev scripts. Dev-only:
// lives in scripts/ so it never ships inside a skill.
//
// The first installed of Chrome then Edge, through playwright-core (a root
// devDependency); PLAN2CODE_TEST_BROWSER=chrome or msedge forces one. Every
// failure is one line in our own words, never Playwright's install hint.
import fs from "node:fs";
// The fixed places each browser installs to, probed in order on every
// platform (a path that cannot exist here is simply not found).
export const BROWSER_PATHS = {
chrome: [
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/usr/bin/google-chrome",
"/usr/bin/google-chrome-stable",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
],
msedge: [
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
"C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
"/usr/bin/microsoft-edge",
"/usr/bin/microsoft-edge-stable",
],
};
const CHANNELS = Object.keys(BROWSER_PATHS);
// Returns { channel, path } for the first browser found, or null. Either way
// findBrowser.checked lists every path this call looked at.
export function findBrowser({ env = process.env, exists = fs.existsSync } = {}) {
const forced = env.PLAN2CODE_TEST_BROWSER;
if (forced && !CHANNELS.includes(forced)) {
throw new Error(`PLAN2CODE_TEST_BROWSER must be ${CHANNELS.join(" or ")} (it is "${forced}").`);
}
findBrowser.checked = [];
for (const channel of forced ? [forced] : CHANNELS) {
for (const p of BROWSER_PATHS[channel]) {
findBrowser.checked.push(p);
if (exists(p)) return { channel, path: p };
}
}
return null;
}
findBrowser.checked = [];
// null when page tests can run here, otherwise the one line that says why
// not. `checked` defaults to the paths the last findBrowser() call probed.
export function browserProblem({ nodeVersion = process.versions.node, found, checked = findBrowser.checked } = {}) {
if (Number(nodeVersion.split(".")[0]) < 20) {
return `Page tests need Node 20 or newer (this is ${nodeVersion}). Users of Plan2Code still only need Node 18.`;
}
if (!found) {
return `Page tests need Chrome or Edge. Looked in: ${checked.join(", ")}. Install either one, or set PLAN2CODE_TEST_BROWSER.`;
}
return null;
}
// Launches the browser findBrowser() picks, headless. `options` go to
// Playwright's chromium.launch() as they are (an `executablePath` there skips
// the pick); `find` hands findBrowser() its env and exists, for tests. A
// problem rejects with an Error whose message is our one line and whose
// `browserProblem` is true, never Playwright's own launch text.
export async function launchBrowser(options = {}, find = {}) {
const found = options.executablePath ? { channel: null, path: options.executablePath } : findBrowser(find);
const problem = browserProblem({ found });
if (problem) throw Object.assign(new Error(problem), { browserProblem: true });
let chromium;
try {
({ chromium } = await import("playwright-core"));
} catch (e) {
throw Object.assign(new Error("Page tests need playwright-core: run npm install.", { cause: e }), { browserProblem: true });
}
try {
return await chromium.launch({
executablePath: found.path,
headless: true,
args: ["--no-first-run", "--no-default-browser-check"],
...options,
});
} catch (e) {
// Playwright's own text stays out of the message, but is kept as the
// cause for whoever needs to debug a real launch failure.
const line = `Page tests could not start the browser at ${found.path}. Install Chrome or Edge, or set PLAN2CODE_TEST_BROWSER.`;
throw Object.assign(new Error(line, { cause: e }), { browserProblem: true });
}
}
+197 -51
View File
@@ -3,7 +3,7 @@
// it never ships inside a skill.
//
// node scripts/capture-screenshots.mjs [--only <shot>] [--browser <path>]
// [--out <dir>]
// [--out <dir>] [--compare]
//
// Every shot is staged with no agent: a throwaway sample project called
// `task-api`, a throwaway console home (PLAN2CODE_CONSOLE_HOME), then
@@ -14,16 +14,27 @@
// it is the console's nearest to the Plan2Code blue the site and README use.
//
// Shots: dashboard, dashboard-utilities, question, doc, build, signoff, finish, ask, git.
// --compare adds workspace, stop, delete, help, prefs and cleanup: screens the
// docs never show, for checking a change by eye against a "before" set. Its
// --out must be outside docs/screenshots/, so the set is never published.
//
// Needs puppeteer-core (`npm i --no-save puppeteer-core`, never added to
// package.json) and a local Chrome or Edge. Writes nothing outside its temp
// folders and --out.
// --snapshot <file> (used by scripts/css-snapshot.mjs) takes no pictures: it
// writes every element's computed style, per screen, theme and width, to <file>.
// It sees what these shots stage: choice, multi, text, review and confirm cards;
// a checklist, list, recap or menu card is not staged, so a rule only they use
// is not covered.
//
// Needs playwright-core (a root devDependency, so `npm install` brings it) and
// a local Chrome or Edge, launched through scripts/browser.mjs. Playwright has
// no WebP screenshots, so each shot is taken over CDP. Writes nothing outside
// its temp folders and --out.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { launchBrowser } from "./browser.mjs";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
@@ -72,6 +83,82 @@ const SHOTS = {
git: { workflow: "git", posts: ["git"], repo: true },
};
// --compare only: the screens the docs never show, shot so a change to the
// console can be checked against a "before" set by eye. `open` runs on the
// page after every load and clicks through to the screen. Never published.
const COMPARE_SHOTS = {
// The confirm dialog, with the handoff choice beside plain stop.
stop: {
workflow: "implement",
posts: ["stop"],
open: async (page) => {
await page.click("#btn-stop");
await page.waitForSelector("#stop-modal[open]", { timeout: 10000 });
},
},
// The first step of a spec chip's delete.
delete: {
workflow: "dashboard",
posts: ["delete"],
open: async (page) => {
await page.locator(".spec-chip-del").first().click({ force: true });
await page.waitForSelector("#delete-modal[open]", { timeout: 10000 });
},
},
// Help on its first tab, whatever topic it opened on.
help: {
workflow: "plan",
posts: ["help"],
open: async (page) => {
await page.click("#btn-about");
await page.locator("#help-tabs .help-tab").first().click();
await page.waitForSelector("#help-modal[open]", { timeout: 10000 });
},
},
prefs: {
workflow: "plan",
posts: ["prefs"],
open: async (page) => {
await page.click("#btn-looks");
await page.waitForSelector("#looks-modal[open]", { timeout: 10000 });
},
},
// Preferences scrolled to Cleanup once its scan has answered.
cleanup: {
workflow: "plan",
posts: ["cleanup"],
open: async (page) => {
await page.click("#btn-looks");
await page.waitForSelector("#looks-modal[open]", { timeout: 10000 });
await page.locator(".looks-cleanup").scrollIntoViewIfNeeded();
await page.click("#cleanup-scan");
await page.waitForFunction(() => document.getElementById("cleanup-status").textContent.trim() !== "", null, { timeout: 15000 }).catch(() => {});
},
},
// The panel open with two folders: the project and a sibling added once.
// Last, since the console remembers the folder for the project and every
// later shot's footer would count it.
workspace: {
workflow: "plan",
posts: ["workspace"],
open: async (page) => {
const extra = makeExtraFolder();
await page.evaluate(async (dir) => {
const now = await (await fetch("/workspace", { cache: "no-store" })).json();
if ((now.folders || []).length < 2) {
await fetch("/workspace/add", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ path: dir, name: "task-web", description: "The web app that calls the API" }),
});
}
}, extra);
await page.click("#footer-where");
await page.waitForSelector("#workspace-modal[open] #workspace-list li:nth-child(2)", { timeout: 10000 });
},
},
};
// On Windows the temp dir sits under the user's profile, and the page can
// show the project's path, so the sample project goes at the drive root
// instead. Elsewhere the temp dir carries no username. Each run makes its own
@@ -89,21 +176,6 @@ function fail(message) {
process.exit(1);
}
function findBrowser() {
if (typeof args.browser === "string") return fs.existsSync(args.browser) ? args.browser : null;
const candidates = [
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
"/usr/bin/google-chrome",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
];
return candidates.find((p) => fs.existsSync(p)) || null;
}
function phaseFile(n, name, tasks, done) {
const lines = tasks.map((t, i) => `- [${done ? "x" : " "}] **Task ${n}.${i + 1}:** ${t}`).join("\n");
return `# Phase ${n}: ${name}\n\n**Status:** ${done ? "Complete" : "Not Started"}\n\n## Tasks\n\n${lines}\n`;
@@ -169,6 +241,14 @@ function makeSampleProject() {
return project;
}
// The Workspace shot's second folder, beside the sample project.
function makeExtraFolder() {
const dir = path.join(SCRATCH, "task-web");
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, "README.md"), "# task-web\n\nThe web app that lists and edits a team's tasks.\n");
return dir;
}
function git(cwd, ...gitArgs) {
const r = spawnSync("git", gitArgs, { cwd, env: ENV, encoding: "utf8" });
if (r.status !== 0) throw new Error(`git ${gitArgs.join(" ")} failed: ${(r.stderr || "").trim()}`);
@@ -225,8 +305,7 @@ function post(project, sid, name) {
}
// Opens a session for the shot and posts its payloads. Returns { sid, url }.
function stage(project, shot) {
const spec = SHOTS[shot];
function stage(project, spec) {
const r = cli(project, "open", "--workflow", spec.workflow, "--no-open");
if (r.code !== 0 || !r.out || !r.out.url) throw new Error(`open failed (${r.code}): ${r.err.trim()}`);
for (const name of spec.posts) post(project, r.out.sid, name);
@@ -236,9 +315,9 @@ function stage(project, shot) {
// Waits for the page to draw real state, then lets the animations finish
// (the dashboard's wake-up is the longest).
async function settle(page) {
await page.waitForNetworkIdle({ idleTime: 500, timeout: 15000 }).catch(() => {});
await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => {});
await page.waitForSelector(".dash-card, .card, .handoff, .ask-pane, .doc, .git-board", { timeout: 15000 }).catch(() => {});
await sleep(3500);
await sleep(args.snapshot ? 1800 : 3500);
}
async function openTab(page, label) {
@@ -251,7 +330,7 @@ async function openTab(page, label) {
async function scrollTo(page, { scrollTo: top, mustShow }) {
const problem = await page.evaluate(
(topSel, showSel) => {
([topSel, showSel]) => {
const find = (sel) =>
sel.startsWith("cmd:")
? [...document.querySelectorAll(".dash-card")].find((c) => c.querySelector(".dash-card-cmd")?.textContent.trim() === sel.slice(4))
@@ -265,24 +344,95 @@ async function scrollTo(page, { scrollTo: top, mustShow }) {
const r = show.getBoundingClientRect();
return r.top >= 0 && r.bottom <= window.innerHeight ? null : `${showSel} is not wholly in view`;
},
top,
mustShow || null
[top, mustShow || null]
);
if (problem) console.log(` warning: ${problem}`);
await sleep(300);
}
// The properties that change how a stylesheet move would look.
const SNAP_PROPS = [
"display", "position", "top", "right", "bottom", "left", "width", "height", "min-width", "max-width", "min-height", "max-height",
"margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left",
"color", "background-color", "background-image", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
"border-top-style", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-left-radius",
"font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-align", "text-transform",
"gap", "grid-template-columns", "grid-template-rows", "grid-column-start", "grid-column-end", "grid-row-start", "grid-row-end",
"flex-direction", "flex-wrap", "flex-grow", "flex-shrink", "flex-basis", "align-items", "justify-content", "align-self",
"overflow-x", "overflow-y", "opacity", "visibility", "transform", "z-index", "box-shadow", "cursor", "pointer-events", "white-space",
"content", "outline-style", "transform-origin", "fill", "stroke",
];
// Recorded after the properties above, for every element: what names its animation.
// A property a running animation is moving is recorded as "~" (it differs from run
// to run), so a rule that adds or removes an animation shows in these fields instead.
const SNAP_ANIMATION = ["animation-name", "animation-duration", "animation-delay", "animation-iteration-count", "animation-timing-function", "animation-direction", "animation-fill-mode"];
const SNAP = {};
async function snapshotNow(page) {
return page.evaluate(
([props, animation]) => {
const out = {};
const seen = new Map();
for (const el of document.querySelectorAll("*")) {
const parent = el.parentElement;
const key = parent ? (seen.get(parent) || "") : "";
const sib = parent ? [...parent.children].indexOf(el) : 0;
const cls = typeof el.className === "string" ? el.className.trim().split(/\s+/).filter(Boolean).slice(0, 3).join(".") : "";
const path = (parent ? key + ">" : "") + el.tagName.toLowerCase() + (el.id ? "#" + el.id : "") + (cls ? "." + cls : "") + "[" + sib + "]";
seen.set(el, path);
const cs = getComputedStyle(el);
const moving = new Set();
for (const a of el.getAnimations ? el.getAnimations() : []) {
for (const kf of a.effect && a.effect.getKeyframes ? a.effect.getKeyframes() : []) {
for (const k of Object.keys(kf)) if (!["offset", "easing", "composite", "computedOffset"].includes(k)) moving.add(k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()));
}
}
out[path] = props.map((p) => (moving.has(p) ? "~" : cs.getPropertyValue(p))).concat(animation.map((p) => cs.getPropertyValue(p))).join("|");
}
return out;
},
[SNAP_PROPS, SNAP_ANIMATION]
);
}
async function snapshotShot(page, name, theme) {
for (const [w, h] of [[1280, 800], [390, 844]]) {
await page.setViewportSize({ width: w, height: h });
await sleep(1500);
SNAP[`${name}/${theme}/${w}`] = await snapshotNow(page);
}
await page.setViewportSize({ width: 1280, height: 800 });
}
async function shoot(page, name) {
const written = [];
// Math.random picks Planny's mood variants; pinned so two runs draw the same page.
if (args.snapshot) await page.addInitScript(() => { Math.random = () => 0.5; });
for (const theme of THEMES) {
await page.emulateMediaFeatures([{ name: "prefers-color-scheme", value: theme }]);
await page.emulateMedia({ colorScheme: theme });
// The theme is applied at load, so reload rather than trust a live switch.
await page.reload({ waitUntil: "domcontentloaded" });
await settle(page);
if (page.__tab) await openTab(page, page.__tab);
if (page.__scroll && page.__scroll.scrollTo) await scrollTo(page, page.__scroll);
if (page.__open) {
await page.__open(page);
await sleep(600);
}
if (args.snapshot) {
await snapshotShot(page, name, theme);
continue;
}
const file = path.join(OUT, `${name}-${theme}.webp`);
await page.screenshot({ type: "webp", quality: QUALITY, path: file });
const cdp = await page.context().newCDPSession(page);
// Without a clip the capture comes out in CSS pixels; a clip of the
// viewport at scale 2 is the twice-density shot (byte for byte what
// Playwright's own PNG screenshot takes).
const clip = { x: 0, y: 0, width: 1280, height: 800, scale: 2 };
const { data } = await cdp.send("Page.captureScreenshot", { format: "webp", quality: QUALITY, captureBeyondViewport: false, clip });
await cdp.detach();
fs.writeFileSync(file, Buffer.from(data, "base64"));
const kb = Math.round(fs.statSync(file).size / 1024);
console.log(`${path.basename(file)} ${kb} KB`);
if (kb > WARN_KB) console.log(` warning: ${path.basename(file)} is over ${WARN_KB} KB`);
@@ -292,15 +442,15 @@ async function shoot(page, name) {
}
// Opens the page for a staged session and saves both themes.
async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
const ctx = await browser.createBrowserContext();
async function capture(browser, url, name, { tab, scrollTo: top, mustShow, open }) {
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
try {
const page = await ctx.newPage();
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
await page.goto(url, { waitUntil: "domcontentloaded" });
await settle(page);
page.__tab = tab || null;
page.__scroll = { scrollTo: top, mustShow };
page.__open = open || null;
return await shoot(page, name);
} finally {
await ctx.close();
@@ -310,15 +460,14 @@ async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
// The Ask shot: a question typed and sent on the page, collected with `chat`
// the way an agent would, and answered with a posted reply.
async function captureAsk(browser, project, sid, url, question) {
const ctx = await browser.createBrowserContext();
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
try {
const page = await ctx.newPage();
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
await page.goto(url, { waitUntil: "domcontentloaded" });
await settle(page);
await openTab(page, "Ask");
await page.waitForSelector("#ask-input:not([disabled])", { timeout: 10000 });
await page.type("#ask-input", question);
await page.locator("#ask-input").pressSequentially(question);
await page.evaluate(() => {
const send = [...document.querySelectorAll(".ask-composer button")].find((b) => b.textContent.trim() === "Send");
if (send) send.click();
@@ -360,17 +509,14 @@ async function captureAsk(browser, project, sid, url, question) {
}
async function main() {
const names = args.only ? [args.only] : Object.keys(SHOTS);
for (const n of names) if (!SHOTS[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(SHOTS).join(", ")}`);
let puppeteer;
try {
puppeteer = (await import("puppeteer-core")).default;
} catch {
fail("puppeteer-core is not installed. Run: npm i --no-save puppeteer-core");
const docs = path.join(ROOT, "docs", "screenshots");
const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
if (args.compare && (fold(OUT) === fold(docs) || fold(OUT).startsWith(fold(docs) + path.sep))) {
fail(`--compare never writes into ${path.relative(ROOT, docs)}: pass --out with a folder outside it.`);
}
const browserPath = findBrowser();
if (!browserPath) fail("No Chrome or Edge found. Pass one with --browser <path>.");
const table = args.compare ? { ...SHOTS, ...COMPARE_SHOTS } : SHOTS;
const names = args.only ? [args.only] : Object.keys(table);
for (const n of names) if (!table[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(table).join(", ")}`);
SCRATCH = fs.mkdtempSync(path.join(SCRATCH_ROOT, "p2c-shots-"));
HOME = path.join(SCRATCH, "console-home");
@@ -385,21 +531,21 @@ async function main() {
// and the Ocean highlight is the console's nearest to the Plan2Code blue
// the landing page uses.
fs.writeFileSync(path.join(HOME, "looks.json"), JSON.stringify({ looks: { role: "engineer", accent: "ocean", welcomeSeen: true } }));
browser = await puppeteer.launch({
executablePath: browserPath,
headless: true,
browser = await launchBrowser({
...(typeof args.browser === "string" ? { executablePath: args.browser } : {}),
args: ["--no-first-run", "--no-default-browser-check", "--mute-audio"],
});
for (const name of names) {
const where = SHOTS[name].repo ? makeGitProject() : project;
const { sid, url } = stage(where, name);
const where = table[name].repo ? makeGitProject() : project;
const { sid, url } = stage(where, table[name]);
try {
if (SHOTS[name].ask) await captureAsk(browser, where, sid, url, SHOTS[name].ask);
else await capture(browser, url, name, SHOTS[name]);
if (table[name].ask) await captureAsk(browser, where, sid, url, table[name].ask);
else await capture(browser, url, name, table[name]);
} finally {
cli(where, "stop", "--session", sid);
}
}
if (args.snapshot) fs.writeFileSync(path.resolve(String(args.snapshot)), JSON.stringify(SNAP));
} finally {
if (browser) await browser.close();
if (project) cli(project, "stop", "--all");
+10
View File
@@ -0,0 +1,10 @@
// The console's stylesheet as the tests read it: the files under
// public/styles/ joined in the server's own order, without the accent rules.
// A rule moving between files never breaks a test; only a rule that changes
// or vanishes does.
import { joinedStyles } from "../src/web-console/static.mjs";
export function joinedCss() {
return joinedStyles().toString("utf8");
}
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env node
// The cheapest check for a stylesheet move: every element's computed style, on
// every screen the console has, in both themes, at desktop and phone width.
// Dev-only, not in `npm test`. Stages the screens the way
// scripts/capture-screenshots.mjs does (its --snapshot mode), so the sample
// project and payloads are the same.
//
// node scripts/css-snapshot.mjs [--out <file>] write a snapshot
// node scripts/css-snapshot.mjs --compare <file> take one now and print every difference
//
// Take a baseline before moving any rule, then compare after each move. Two
// runs in a row on the same stylesheet report nothing: Math.random is pinned,
// a property a running animation is moving is recorded as "~" (its animation
// fields are still compared), and heights within 4px are ignored (see jitter).
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const CAPTURE = path.join(ROOT, "scripts", "capture-screenshots.mjs");
const args = {};
for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i];
if (a.startsWith("--")) args[a.slice(2)] = process.argv[i + 1] && !process.argv[i + 1].startsWith("--") ? process.argv[++i] : true;
}
function take(file) {
// The screenshot script wants a folder to exist for --compare; nothing is written to it.
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-css-snap-"));
try {
const r = spawnSync(process.execPath, [CAPTURE, "--compare", "--snapshot", file, "--out", out], { stdio: ["ignore", "inherit", "inherit"] });
if (r.status !== 0) {
console.error("the snapshot run failed");
process.exit(1);
}
} finally {
fs.rmSync(out, { recursive: true, force: true });
}
}
const NAMES = [
"display", "position", "top", "right", "bottom", "left", "width", "height", "min-width", "max-width", "min-height", "max-height",
"margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left",
"color", "background-color", "background-image", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
"border-top-style", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-left-radius",
"font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-align", "text-transform",
"gap", "grid-template-columns", "grid-template-rows", "grid-column-start", "grid-column-end", "grid-row-start", "grid-row-end",
"flex-direction", "flex-wrap", "flex-grow", "flex-shrink", "flex-basis", "align-items", "justify-content", "align-self",
"overflow-x", "overflow-y", "opacity", "visibility", "transform", "z-index", "box-shadow", "cursor", "pointer-events", "white-space",
"content", "outline-style", "transform-origin", "fill", "stroke",
];
const ANIMATION = ["animation-name", "animation-duration", "animation-delay", "animation-iteration-count", "animation-timing-function", "animation-direction", "animation-fill-mode"];
// A growing answer box at phone width settles a few pixels either way from one
// run to the next with the same stylesheet; the heights it carries up the page
// (and the transform origin, which is half of one) are not a stylesheet's doing.
const JITTER = new Set(["height", "min-height", "transform-origin"]);
function jitter(name, a, b) {
if (!JITTER.has(name)) return false;
const na = a.match(/-?\d+(?:\.\d+)?/g);
const nb = b.match(/-?\d+(?:\.\d+)?/g);
return !!na && !!nb && na.length === nb.length && na.every((n, i) => Math.abs(n - nb[i]) <= 4);
}
function compare(before, after) {
const diffs = [];
for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
const a = before[key];
const b = after[key];
if (!a || !b) {
diffs.push(`${key}: screen ${a ? "missing from the new run" : "is new"}`);
continue;
}
for (const el of new Set([...Object.keys(a), ...Object.keys(b)])) {
if (a[el] === b[el] || el.includes("p.dock-say")) continue; // the one line of Planny that types itself in, so its width moves
if (a[el] === undefined || b[el] === undefined) {
diffs.push(`${key} ${el}: element ${a[el] === undefined ? "added" : "gone"}`);
continue;
}
const x = a[el].split("|");
const y = b[el].split("|");
const names = NAMES.concat(ANIMATION);
x.forEach((v, i) => {
if (v !== y[i] && v !== "~" && y[i] !== "~" && !jitter(names[i], v, y[i])) diffs.push(`${key} ${el} ${names[i] ?? i}: ${v} -> ${y[i]}`);
});
}
}
return diffs;
}
if (args.compare === true) {
console.error("usage: node scripts/css-snapshot.mjs --compare <snapshot file> (or --out <file> to take one)");
process.exit(1);
} else if (typeof args.compare === "string") {
const tmp = path.join(os.tmpdir(), `p2c-css-snap-${process.pid}.json`);
take(tmp);
const diffs = compare(JSON.parse(fs.readFileSync(args.compare, "utf8")), JSON.parse(fs.readFileSync(tmp, "utf8")));
fs.rmSync(tmp, { force: true });
for (const d of diffs.slice(0, 200)) console.log(d);
if (diffs.length > 200) console.log(`... and ${diffs.length - 200} more`);
console.log(diffs.length ? `${diffs.length} difference(s)` : "no differences");
process.exit(diffs.length ? 1 : 0);
} else {
const out = path.resolve(typeof args.out === "string" ? args.out : "css-snapshot.json");
take(out);
console.log(`wrote ${out} (${Math.round(fs.statSync(out).size / 1024)} KB)`);
}
+127
View File
@@ -0,0 +1,127 @@
// Start a real console and open its page in a real browser, for the page tests
// (scripts/test-web-console-page-*.mjs).
//
// One browser per test file (pageSuite), a fresh console session and browser
// context per test (openSession). Sessions run against the file's own console
// home from web-console-test-helpers.mjs, in a temp project unless a test
// names one. Any uncaught error on the page fails the test that opened it, so
// a later split that breaks a screen shows as a named error, not a blank page.
import fs from "node:fs";
import path from "node:path";
import { cli, payload, until, HOME, REMEMBERED } from "./web-console-test-helpers.mjs";
import { launchBrowser } from "./browser.mjs";
// `test` is node:test's test function (or any context with .after): the
// browser is launched the first time a test asks for it and closed once the
// file is done.
export function pageSuite(test) {
let launching = null;
test.after(async () => {
if (launching) await (await launching).close();
});
return {
browser: () => (launching ??= launchBrowser()),
};
}
let projects = 0;
let payloads = 0;
// A fresh project folder under the file's console home, removed with it.
export function tempProject(files = {}) {
const dir = path.join(HOME, "projects", `p${++projects}`);
for (const [rel, text] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
fs.writeFileSync(path.join(dir, rel), text);
}
fs.mkdirSync(dir, { recursive: true });
return dir;
}
// Opens a console session the way an agent does (`console.mjs open`, then
// `post`), and its page in a new browser context. Resolves once the page has
// drawn from the session's real state, not the boot pane in the markup.
// `t` is the test's context: stop() is registered with t.after, so a failing
// test still cleans up, and a page error fails the test. `clock: true` gives
// the page Playwright's fake clock before it loads (s.page.clock), so a test
// can jump past the page's silence limits instead of sitting through them.
export async function openSession(browser, { t, workflow, payload: first, project, open = [], clock = false }) {
fs.rmSync(REMEMBERED, { force: true });
const cwd = project || tempProject();
const opened = cli(["open", "--workflow", workflow, "--no-open", ...open], { cwd }).json;
const s = {
sid: opened.sid,
session: opened.session,
url: opened.url,
project: cwd,
errors: [],
context: null,
page: null,
};
// The agent's side, run from the project like an agent would.
s.post = (patch) => {
const r = cli(["post", "--session", s.sid, "--file", payload(`page-post-${++payloads}.json`, patch)], { cwd });
if (r.status !== 0) throw new Error(`post failed (${r.status}): ${r.stderr}`);
return r.json;
};
s.wait = (seconds = 10) => {
const r = cli(["wait", "--session", s.sid, "--seconds", String(seconds)], { cwd });
return { code: r.status, ...(r.json || {}) };
};
// Whether the session's server still answers on its port.
s.answers = async () => {
try {
await fetch(new URL("/health", s.url), { signal: AbortSignal.timeout(1000) });
return true;
} catch {
return false;
}
};
let stopped = false;
s.stop = async () => {
if (stopped) return;
stopped = true;
cli(["stop", "--session", s.sid], { cwd });
if (s.context) await s.context.close().catch(() => {});
await until(async () => !(await s.answers()), 5000);
};
t.after(async () => {
await s.stop();
if (s.errors.length) throw new Error(`uncaught error on the page: ${s.errors[0]}`);
});
if (first) s.post(first);
s.context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
if (clock) await s.context.clock.install();
s.page = await s.context.newPage();
s.page.on("pageerror", (e) => s.errors.push(e.message));
await s.page.goto(s.url, { waitUntil: "domcontentloaded" });
await drawn(s.page);
return s;
}
// The page has adopted a state frame: app.js has replaced the boot pane the
// markup ships with.
export async function drawn(page) {
await page.waitForFunction(() => !document.querySelector("#main .boot-pane"), null, { timeout: 15000 });
}
// Presses Send on the page and collects the send the way an agent's `wait`
// does: the same JSON an agent receives.
export async function sendAndCollect(s) {
await s.page.click("#btn-send");
const got = s.wait(10);
if (got.code !== 0) throw new Error(`nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
return got;
}
// The card for one item id.
export const itemCard = (page, id) => page.locator(`[data-item="${id}"]`).first();
// A locator's visible text, trimmed.
export const textOf = async (locator) => (await locator.innerText()).trim();
// The scroll offset of the first element matching `selector`.
export const scrollTopOf = (page, selector) => page.$eval(selector, (el) => el.scrollTop);
+14 -2
View File
@@ -10,7 +10,19 @@ import { fileURLToPath } from "node:url";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const DIR = path.join(ROOT, "src", "web-console", "public");
const FILES = ["app.js", "answers.js", "render.js", "palette.js", "starters.js", "favicon.js"];
// Every page module (vendored code aside), found by walking public/ so a new
// screen is guarded without editing a list.
function pageModules(dir, rel = "") {
const out = [];
for (const e of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
const p = rel ? `${rel}/${e.name}` : e.name;
if (e.isDirectory()) {
if (p !== "vendor") out.push(...pageModules(dir, p));
} else if (e.name.endsWith(".js")) out.push(p);
}
return out.sort();
}
const FILES = pageModules(DIR);
let bad = 0;
for (const name of FILES) {
@@ -20,7 +32,7 @@ for (const name of FILES) {
console.log(` ok ${name}`);
} catch (err) {
// A module that parses but cannot run here (app.js touches `document` at
// import) is fine; only a parse failure is a real problem.
// import, and relative imports cannot resolve from a data: URL) is fine; only a parse failure is a real problem.
const parseFailure = err instanceof SyntaxError;
if (parseFailure) {
bad++;
+17
View File
@@ -17,3 +17,20 @@ and dark WebP images in `docs/screenshots/`.
Refresh every image with `node scripts/capture-screenshots.mjs`, or one with
`--only <shot>`.
## Comparison-only shots
`--compare` adds the screens the docs never show, so a change to the console
can be checked by eye against a "before" set. They are never published: the
script refuses `--compare` with an `--out` inside `docs/screenshots/`.
| File | Stages |
| --- | --- |
| `stop.json` | A build with a question open, behind the Stop dialog and its handoff choice |
| `delete.json` | The dashboard, behind the first step of a spec chip's Delete |
| `help.json` | A Plan question, behind Help on its first tab |
| `prefs.json` | A Plan question, behind User Preferences |
| `cleanup.json` | A Plan question, behind User Preferences scrolled to Cleanup after a scan |
| `workspace.json` | A Plan question, behind the Workspace panel with a second folder added (shot last: the console remembers the folder) |
`node scripts/capture-screenshots.mjs --compare --out <folder outside the repo>`
+21
View File
@@ -0,0 +1,21 @@
{
"workflow": "plan",
"title": "Task API",
"headline": {
"stage": "Step 3 of 7: Signing in",
"cleared": 2,
"total": 7
},
"items": [
{
"id": "q4",
"kind": "text",
"title": "How callers sign in",
"body": "Do callers sign in as a person, or as an app with a key?",
"placeholder": "For example: apps use an API key per team."
}
],
"agent": {
"status": "waiting"
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"menu": {
"note": "task-api is built up to Phase 2 of 4. Phase 3 is next.",
"recommend": "plan2code-3-implement",
"details": {
"plan2code-3-implement": "Phase 3 of 4 is next"
}
},
"agent": {
"status": "waiting"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"workflow": "plan",
"title": "Task API",
"headline": {
"stage": "Step 2 of 7: Who calls it",
"cleared": 2,
"total": 7
},
"items": [
{
"id": "q3",
"kind": "text",
"title": "Who calls the API",
"body": "Which apps call the task API first, and what does each need from it?",
"placeholder": "For example: the web app lists tasks, the mobile app only updates their status."
}
],
"agent": {
"status": "waiting"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"workflow": "plan",
"title": "Task API",
"headline": {
"stage": "Step 3 of 7: Signing in",
"cleared": 2,
"total": 7
},
"items": [
{
"id": "q4",
"kind": "text",
"title": "How callers sign in",
"body": "Do callers sign in as a person, or as an app with a key?",
"placeholder": "For example: apps use an API key per team."
}
],
"agent": {
"status": "waiting"
}
}
+36
View File
@@ -0,0 +1,36 @@
{
"workflow": "implement",
"title": "task-api: Phase 3",
"specDir": "specs/task-api",
"headline": {
"stage": "Phase 3: API endpoints",
"cleared": 2,
"total": 4
},
"docs": [
{
"id": "phase",
"title": "Phase 3 tasks",
"blocks": [
{
"id": "tasks",
"state": "settled",
"md": "- [x] **Task 3.1:** Add GET /tasks with cursor paging\n- [x] **Task 3.2:** Add POST /tasks\n- [ ] **Task 3.3:** Add PATCH /tasks/:id\n- [ ] **Task 3.4:** Add DELETE /tasks/:id"
}
]
}
],
"items": [
{
"id": "keep",
"kind": "confirm",
"title": "Tests are failing",
"body": "Two paging tests fail after Task 3.2. Fix them before going on?",
"yesLabel": "Fix them now",
"noLabel": "Note them and go on"
}
],
"agent": {
"status": "waiting"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"workflow": "plan",
"title": "Task API",
"headline": {
"stage": "Step 2 of 7: Who calls it",
"cleared": 2,
"total": 7
},
"items": [
{
"id": "q3",
"kind": "text",
"title": "Who calls the API",
"body": "Which apps call the task API first, and what does each need from it?",
"placeholder": "For example: the web app lists tasks, the mobile app only updates their status."
}
],
"agent": {
"status": "waiting"
}
}
+142
View File
@@ -0,0 +1,142 @@
// Tests for the shared browser helper (scripts/browser.mjs) and the two dev
// scripts that launch a browser through it. Run with:
// node --test scripts/test-browser-helper.mjs
//
// The unit cases hand findBrowser() a fake `exists`, so they run anywhere. The
// live cases launch a real Chrome or Edge and skip when none is installed.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
test("playwright-core is pinned exactly in the root devDependencies", () => {
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8"));
assert.equal(pkg.devDependencies["playwright-core"], "1.64.1");
});
// A fake file system holding only `present`.
const only = (...present) => (p) => present.includes(p);
test("findBrowser picks Chrome, then Edge, and honours PLAN2CODE_TEST_BROWSER", async () => {
const { findBrowser, BROWSER_PATHS } = await import("./browser.mjs");
const chrome = BROWSER_PATHS.chrome[0];
const edge = BROWSER_PATHS.msedge[0];
assert.deepEqual(findBrowser({ env: {}, exists: only(edge) }), { channel: "msedge", path: edge });
assert.deepEqual(findBrowser({ env: {}, exists: only(chrome, edge) }), { channel: "chrome", path: chrome });
assert.deepEqual(findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "msedge" }, exists: only(chrome, edge) }), { channel: "msedge", path: edge });
assert.deepEqual(findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "chrome" }, exists: only(edge) }), null);
assert.deepEqual(findBrowser.checked, BROWSER_PATHS.chrome);
assert.throws(() => findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "firefox" }, exists: only(chrome) }), (e) => /chrome/.test(e.message) && /msedge/.test(e.message));
assert.equal(findBrowser({ env: {}, exists: only() }), null);
assert.deepEqual(findBrowser.checked, [...BROWSER_PATHS.chrome, ...BROWSER_PATHS.msedge]);
});
test("browserProblem says what is missing in one line of our own words", async () => {
const { browserProblem } = await import("./browser.mjs");
const found = { channel: "chrome", path: "C:\chrome.exe" };
const oldNode = browserProblem({ nodeVersion: "18.19.0", found });
assert.equal(oldNode, "Page tests need Node 20 or newer (this is 18.19.0). Users of Plan2Code still only need Node 18.");
const checked = ["C:\a\chrome.exe", "/usr/bin/microsoft-edge"];
const none = browserProblem({ nodeVersion: "24.12.0", found: null, checked });
assert.match(none, /^Page tests need Chrome or Edge\. Looked in: /);
for (const p of checked) assert.ok(none.includes(p), `names ${p}`);
assert.ok(none.endsWith("Install either one, or set PLAN2CODE_TEST_BROWSER."));
assert.equal(browserProblem({ nodeVersion: "24.12.0", found }), null);
for (const line of [oldNode, none]) {
assert.ok(!line.includes("\n"));
assert.ok(!line.includes("playwright install"));
}
});
test("launchBrowser fails with our one line when the forced browser is missing", async () => {
const { launchBrowser, BROWSER_PATHS } = await import("./browser.mjs");
const edgeOnly = only(BROWSER_PATHS.msedge[0]);
await assert.rejects(launchBrowser({}, { env: { PLAN2CODE_TEST_BROWSER: "chrome" }, exists: edgeOnly }), (e) => {
assert.equal(e.browserProblem, true);
assert.match(e.message, /^Page tests need Chrome or Edge\. Looked in: /);
assert.ok(!e.message.includes("\n"));
return true;
});
});
test("launchBrowser opens a page in the installed browser", async (t) => {
const { launchBrowser, findBrowser } = await import("./browser.mjs");
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
const browser = await launchBrowser();
try {
const page = await browser.newPage();
await page.goto("data:text/html,<p>ok</p>");
assert.equal(await page.textContent("p"), "ok");
} finally {
await browser.close();
}
});
// Width and height from a WebP file's first chunk (lossy VP8, lossless VP8L,
// or the extended VP8X header).
function webpSize(buf) {
assert.equal(buf.toString("ascii", 0, 4), "RIFF");
assert.equal(buf.toString("ascii", 8, 12), "WEBP");
const chunk = buf.toString("ascii", 12, 16);
if (chunk === "VP8 ") return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
if (chunk === "VP8L") {
const bits = buf.readUInt32LE(21);
return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
}
if (chunk === "VP8X") return { width: buf.readUIntLE(24, 3) + 1, height: buf.readUIntLE(27, 3) + 1 };
throw new Error(`unknown WebP chunk ${chunk}`);
}
const CAPTURE = path.join(ROOT, "scripts", "capture-screenshots.mjs");
test("capture-screenshots writes both themes as 2560x1600 WebP (slow)", { timeout: 120000 }, async (t) => {
const { findBrowser } = await import("./browser.mjs");
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shots-test-"));
try {
const r = spawnSync(process.execPath, [CAPTURE, "--only", "question", "--out", out], { encoding: "utf8", timeout: 110000 });
assert.equal(r.status, 0, r.stderr || r.stdout);
for (const theme of ["light", "dark"]) {
const buf = fs.readFileSync(path.join(out, `question-${theme}.webp`));
assert.deepEqual(webpSize(buf), { width: 2560, height: 1600 });
}
} finally {
fs.rmSync(out, { recursive: true, force: true });
}
});
test("capture-screenshots --compare refuses to write into docs/screenshots", () => {
// A shot that does not exist: were the guard ever to break, the run would
// stop at "Unknown shot" (which never names docs/screenshots) rather than
// shoot every screen into the published folder.
const argv = [CAPTURE, "--compare", "--only", "__no-such-shot__", "--out", path.join(ROOT, "docs", "screenshots")];
const r = spawnSync(process.execPath, argv, { encoding: "utf8", timeout: 30000 });
assert.notEqual(r.status, 0);
const lines = r.stderr.trim().split("\n");
assert.equal(lines.length, 1, r.stderr);
assert.match(lines[0], /docs[\\/]screenshots/);
});
test("capture-screenshots --compare shoots the comparison-only screens (slow)", { timeout: 120000 }, async (t) => {
const { findBrowser } = await import("./browser.mjs");
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-compare-test-"));
try {
const r = spawnSync(process.execPath, [CAPTURE, "--compare", "--only", "help", "--out", out], { encoding: "utf8", timeout: 110000 });
assert.equal(r.status, 0, r.stderr || r.stdout);
for (const theme of ["light", "dark"]) assert.ok(fs.statSync(path.join(out, `help-${theme}.webp`)).size > 0);
} finally {
fs.rmSync(out, { recursive: true, force: true });
}
});
+188
View File
@@ -0,0 +1,188 @@
// Tests for `node install.js --update` and the install record (~/.plan2code/install.json).
// Run with: node --test scripts/test-install-update.mjs
//
// install.js reads the home directory once, at load, so HOME and USERPROFILE point at a temp
// folder before it is required. update() takes its install steps as an argument: the tests
// pass stand-ins that record their calls, so nothing reaches the skills CLI, npm or the network.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
const require = createRequire(import.meta.url);
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const INSTALL = path.join(ROOT, "install.js");
const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version;
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-install-update-"));
process.env.HOME = HOME;
process.env.USERPROFILE = HOME;
const installer = require(INSTALL);
test.after(() => fs.rmSync(HOME, { recursive: true, force: true }));
const RECORD = path.join(HOME, ".plan2code", "install.json");
function writeRecord(pieces) {
fs.mkdirSync(path.dirname(RECORD), { recursive: true });
fs.writeFileSync(RECORD, JSON.stringify({ version: "1.0.0", scope: "global", pieces }));
}
function clearRecord() {
fs.rmSync(RECORD, { force: true });
}
/** Stand-in install steps: each logs its piece and options, then returns `codes[piece]` (default 0) or throws `throws[piece]`. */
function fakeSteps({ codes = {}, throws = {}, launcherWithSkills = true } = {}) {
const calls = [];
const steps = {};
for (const piece of installer.INSTALL_PIECES) {
steps[piece] = async (options) => {
calls.push({ piece, options });
if (throws[piece]) throw new Error(throws[piece]);
let code = codes[piece] ?? 0;
if (piece === "skills") {
// As the real install(): the skills first, then the command, and 1 if either failed.
options.outcome.skills = code === 0;
options.outcome.launcher = code === 0 && launcherWithSkills;
if (code === 0 && !launcherWithSkills) code = 1;
}
return code;
};
}
return { steps, calls, ran: () => calls.map((c) => c.piece) };
}
/** Run update() with console output captured: `{ code, out }`. */
async function runUpdate(steps) {
const lines = [];
const log = console.log;
console.log = (...args) => lines.push(args.join(" "));
try {
const code = await installer.update({ steps });
return { code, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") };
} finally {
console.log = log;
}
}
test("install record: recordInstalled and forgetInstalled round trip a sorted set", () => {
clearRecord();
assert.equal(installer.INSTALL_RECORD, RECORD);
assert.equal(installer.readInstallRecord(), null);
installer.recordInstalled("loop");
installer.recordInstalled("skills");
installer.recordInstalled("skills");
installer.recordInstalled("not-a-piece");
assert.deepEqual(installer.readInstallRecord(), { version: VERSION, scope: "global", pieces: ["loop", "skills"] });
installer.forgetInstalled("loop");
assert.deepEqual(installer.readInstallRecord().pieces, ["skills"]);
installer.forgetInstalled("skills");
assert.deepEqual(installer.readInstallRecord().pieces, []);
// No temp file is left beside the record.
assert.deepEqual(fs.readdirSync(path.dirname(RECORD)), ["install.json"]);
});
test("install record: a missing or unparsable record reads as null, and forgetting needs none", () => {
clearRecord();
installer.forgetInstalled("skills");
assert.equal(fs.existsSync(RECORD), false);
fs.writeFileSync(RECORD, "{ not json");
assert.equal(installer.readInstallRecord(), null);
fs.writeFileSync(RECORD, JSON.stringify({ pieces: "skills" }));
assert.equal(installer.readInstallRecord(), null);
});
test("update: with no record it says so and updates the skills and the plan2code command", async () => {
clearRecord();
const fake = fakeSteps();
const { code, out } = await runUpdate(fake.steps);
assert.equal(code, 0, out);
assert.match(out, new RegExp(`No install record found \\(installed before v${VERSION.replace(/\./g, "\\.")}\\); updating the skills and the plan2code command\\.`));
// install() covers the command with the skills, so the launcher step does not run again.
assert.deepEqual(fake.ran(), ["skills"]);
assert.match(out, /skills: updated/);
assert.match(out, /launcher: updated/);
});
test("update: a partial record runs only the listed pieces, in order, unattended", async () => {
writeRecord(["loop", "statusline"]);
const fake = fakeSteps();
const { code, out } = await runUpdate(fake.steps);
assert.equal(code, 0, out);
assert.deepEqual(fake.ran(), ["statusline", "loop"]);
for (const call of fake.calls) assert.equal(call.options.unattended, true, call.piece);
assert.doesNotMatch(out, /No install record/);
assert.doesNotMatch(out, /skills:/);
});
test("update: a failing piece exits 1 naming it, and the others still run", async () => {
writeRecord(["skills", "launcher", "loop", "metrics", "bot"]);
const fake = fakeSteps({ codes: { loop: 1 }, throws: { metrics: "npm exploded" } });
const { code, out } = await runUpdate(fake.steps);
assert.equal(code, 1, out);
assert.deepEqual(fake.ran(), ["skills", "loop", "metrics", "bot"]);
assert.match(out, /loop: failed: /);
assert.match(out, /metrics: failed: npm exploded/);
assert.match(out, /bot: updated/);
assert.match(out, /Update failed for: loop, metrics/);
});
test("update: when the skills install leaves the command out, the launcher step runs on its own", async () => {
writeRecord(["skills", "launcher"]);
const fake = fakeSteps({ launcherWithSkills: false });
const { code, out } = await runUpdate(fake.steps);
assert.equal(code, 0, out);
assert.deepEqual(fake.ran(), ["skills", "launcher"]);
// install() returned 1 for the command alone: the skills still read as updated.
assert.match(out, /skills: updated/);
assert.match(out, /launcher: updated/);
});
test("update: a command that fails on the retry is the only piece named", async () => {
writeRecord(["skills", "launcher"]);
const fake = fakeSteps({ launcherWithSkills: false, codes: { launcher: 1 } });
const { code, out } = await runUpdate(fake.steps);
assert.equal(code, 1, out);
assert.match(out, /skills: updated/);
assert.match(out, /Update failed for: launcher\b/);
});
test("update: the real status line step keeps a custom statusLine without asking", async () => {
const claudeDir = path.join(HOME, ".claude");
const settingsFile = path.join(claudeDir, "settings.json");
fs.mkdirSync(claudeDir, { recursive: true });
const settings = JSON.stringify({ statusLine: { type: "command", command: "my-own-status-line" } }, null, 2);
fs.writeFileSync(settingsFile, settings);
clearRecord();
// stdin is not a TTY here: a prompt would hang the test until it times out.
const log = console.log;
console.log = () => {};
let code;
try {
code = await installer.UPDATE_STEPS.statusline({ quiet: true, unattended: true });
} finally {
console.log = log;
}
assert.equal(code, 0);
assert.equal(fs.readFileSync(settingsFile, "utf8"), settings);
assert.ok(fs.existsSync(path.join(claudeDir, "plan2code-statusline.js")));
assert.deepEqual(installer.readInstallRecord().pieces, ["statusline"]);
});
test("update: every step is an install function, never an uninstall", () => {
assert.deepEqual(Object.keys(installer.UPDATE_STEPS), installer.INSTALL_PIECES);
for (const [piece, fn] of Object.entries(installer.UPDATE_STEPS)) {
assert.match(fn.name, /^install/, piece);
}
});
test("install.js: --update is in the usage line, and an unknown option still exits 1", () => {
const result = spawnSync(process.execPath, [INSTALL, "--bogus"], { encoding: "utf8" });
assert.equal(result.status, 1);
assert.ok(result.stderr.includes("Usage: node install.js [--build-skills | --verify-skills | --update]"), result.stderr);
});
+89 -5
View File
@@ -20,13 +20,28 @@ const LAUNCHER = path.join(ROOT, "src", "launcher", "plan2code.js");
const IS_WINDOWS = process.platform === "win32";
const NOTICE = "will use the model you last used in it";
/** A temp home and a bin dir holding stand-ins for `clis`; each writes its args to <bin>/<cli>.json. */
function sandbox(clis) {
/**
* A temp home and a bin dir holding stand-ins for `clis`; each writes its args to <bin>/<cli>.json.
* `installed: "X.Y.Z"` runs an installed copy instead, as install.js lays it out: the launcher,
* models.json and update-check.mjs in <home>/.plan2code/bin/ beside a version.json saying X.Y.Z.
*/
function sandbox(clis, { installed } = {}) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-launcher-"));
const home = path.join(dir, "home");
const bin = path.join(dir, "bin");
fs.mkdirSync(home);
fs.mkdirSync(bin);
const consoleHome = path.join(home, ".plan2code", "console");
let launcher = LAUNCHER;
if (installed) {
const binCopy = path.join(home, ".plan2code", "bin");
fs.mkdirSync(binCopy, { recursive: true });
launcher = path.join(binCopy, "plan2code.js");
fs.copyFileSync(LAUNCHER, launcher);
fs.copyFileSync(path.join(path.dirname(LAUNCHER), "models.json"), path.join(binCopy, "models.json"));
fs.copyFileSync(path.join(ROOT, "src", "web-console", "update-check.mjs"), path.join(binCopy, "update-check.mjs"));
fs.writeFileSync(path.join(binCopy, "version.json"), JSON.stringify({ name: "Plan2Code", version: installed }));
}
const recorder = path.join(bin, "record.js");
fs.writeFileSync(
recorder,
@@ -45,21 +60,31 @@ function sandbox(clis) {
return {
home,
stateFile: path.join(home, ".plan2code", "launcher.json"),
cacheFile: path.join(consoleHome, "update-check.json"),
run: (args, env = {}) =>
spawnSync(process.execPath, [LAUNCHER, ...args], {
spawnSync(process.execPath, [launcher, ...args], {
cwd: dir,
input: "",
encoding: "utf8",
env: { ...process.env, PATH: bin, HOME: home, USERPROFILE: home, ...env },
env: { ...process.env, PATH: bin, HOME: home, USERPROFILE: home, PLAN2CODE_CONSOLE_HOME: consoleHome, ...env },
}),
argsOf: (cli) => {
const file = path.join(bin, `${cli}.json`);
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
},
cleanup: () => fs.rmSync(dir, { recursive: true, force: true }),
// A detached release-check refresh may still be writing its cache; retry rather than fail.
cleanup: () => fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }),
};
}
const NOTICE_LINE = /is out \(you have v/;
/** Write the console's cached release check, `ageMs` old. */
function writeCache(box, latest, ageMs = 0) {
fs.mkdirSync(path.dirname(box.cacheFile), { recursive: true });
fs.writeFileSync(box.cacheFile, JSON.stringify({ checkedAt: Date.now() - ageMs, latest }));
}
test("launcher: Claude Code gets the prompt first, then bypassPermissions and the forwarded args", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
@@ -263,6 +288,65 @@ test("launcher: the CLI's non-zero exit code is passed through", (t) => {
assert.equal(result.status, 7, result.stderr);
assert.notEqual(box.argsOf("claude"), null);
});
test("launcher: update runs the npx install and starts no agent", (t) => {
const box = sandbox(["npx", "claude"]);
t.after(box.cleanup);
const result = box.run(["update"]);
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /Updating Plan2Code\.\.\./);
const args = box.argsOf("npx");
assert.ok(args, "npx was not run");
assert.ok(args.includes("--update"), args.join(" "));
assert.ok(args.includes("git+https://github.com/jparkerweb/plan2code.git"), args.join(" "));
assert.equal(box.argsOf("claude"), null);
});
test("launcher: update passes npx's exit code through", (t) => {
const box = sandbox(["npx"]);
t.after(box.cleanup);
assert.equal(box.run(["update"], { P2C_TEST_EXIT: "3" }).status, 3);
});
test("launcher: release notice prints from a fresh cache", (t) => {
const box = sandbox(["claude"], { installed: "1.0.0" });
t.after(box.cleanup);
writeCache(box, "9.9.9");
const result = box.run([]);
assert.equal(result.status, 0, result.stderr);
assert.ok(result.stdout.includes("Plan2Code v9.9.9 is out (you have v1.0.0). Run: plan2code update"), result.stdout);
assert.notEqual(box.argsOf("claude"), null);
});
test("launcher: no notice when current, stale or missing, and the start does not wait", (t) => {
// PATH holds only the stand-ins, so the detached refresh finds no git: nothing may wait on it.
const cases = [
["current", (box) => writeCache(box, "1.0.0")],
["stale", (box) => writeCache(box, "9.9.9", 2 * 60 * 60 * 1000)],
["missing", () => {}],
];
for (const [name, setup] of cases) {
const box = sandbox(["claude"], { installed: "1.0.0" });
t.after(box.cleanup);
setup(box);
const started = Date.now();
const result = box.run([]);
const took = Date.now() - started;
assert.equal(result.status, 0, `${name}: ${result.stderr}`);
assert.doesNotMatch(result.stdout, NOTICE_LINE, name);
assert.notEqual(box.argsOf("claude"), null, name);
assert.ok(took < 5000, `${name}: the start took ${took} ms`);
}
});
test("launcher: compareVersions orders X.Y.Z numerically and refuses anything else", () => {
const { compareVersions } = require(LAUNCHER);
assert.equal(compareVersions("1.9.0", "1.10.0"), -1);
assert.equal(compareVersions("2.0.0", "2.0.0"), 0);
assert.equal(compareVersions("3.0.0", "2.9.9"), 1);
assert.equal(compareVersions("1.0.0", null), null);
assert.equal(compareVersions("v1.0.0", "1.0.0"), null);
});
test("launcher: renderBanner draws Planny and the name, colored only through paint", () => {
const { renderBanner, paint } = require(LAUNCHER);
const plain = renderBanner(paint(false));
-55
View File
@@ -1,55 +0,0 @@
// Tests for plan2code-handoff's scripts/handoff-path.mjs.
//
// 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 { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
/* =========================================================== handoff-path.mjs */
test("handoff-path: timestamped name, no overwrite, git ignore check", () => {
const repo = tmp("handoff");
gitInit(repo);
const H = (...a) => runScript("plan2code-handoff", "handoff-path.mjs", a, { cwd: repo });
const first = H("--dir", "handoffs");
assert.equal(first.code, 0, first.stderr);
assert.equal(path.basename(first.json.path), "2026-08-03-1405-handoff.md");
assert.equal(first.json.created, true);
assert.equal(first.json.git.inRepo, true);
assert.equal(first.json.git.ignored, false);
assert.match(first.json.warning, /handoffs\//);
fs.writeFileSync(first.json.path, "x");
assert.equal(path.basename(H("--dir", "handoffs").json.path), "2026-08-03-1405-2-handoff.md");
write(repo, ".gitignore", "handoffs/\n");
assert.equal(H("--dir", "handoffs").json.git.ignored, true);
const temp = H();
assert.equal(temp.json.git.inRepo, false);
assert.equal(temp.json.git.ignored, null);
const dry = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "later", "--dry-run"], { cwd: repo });
assert.equal(dry.json.created, false);
assert.ok(!fs.existsSync(path.join(repo, "later")));
});
/* ================================================= verification regressions */
test("handoff-path: the repo root itself is never the line to ignore", () => {
const repo = tmp("handoff2");
gitInit(repo);
const j = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "."], { cwd: repo }).json;
assert.equal(j.git.inRepo, true);
assert.equal(j.git.ignoreLine, "*-handoff.md");
});
test("handoff-path: --dir naming an existing file is refused", () => {
const repo = tmp("handoff3");
write(repo, "notes.txt", "x");
const r = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "notes.txt"], { cwd: repo });
assert.equal(r.code, 5);
assert.equal(r.json.ok, false);
assert.equal(r.json.error, "not-a-folder");
assert.match(r.json.next, /--dir temp/);
assert.equal(runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "notes.txt", "--dry-run"], { cwd: repo }).code, 5, "dry-run refuses it too");
});
+113
View File
@@ -0,0 +1,113 @@
// Tests for plan2code-xray's scripts/xray.mjs.
//
// 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 { execFileSync } from "node:child_process";
import { runScript, tmp, write, gitInit } from "./skill-script-helpers.mjs";
const X = (cwd, args, env) => runScript("plan2code-xray", "xray.mjs", args, { cwd, env });
// One fixture for the file: a.js and b.js always change together, hot.js
// changes in most commits and has no test, the others are tested, and
// old1.js and old2.js changed together before they were deleted.
let fixture;
function repo() {
if (fixture) return fixture;
const dir = tmp("xray");
const g = gitInit(dir);
const commit = (msg, files) => {
for (const [rel, content] of Object.entries(files)) write(dir, rel, content);
g("add", "-A");
g("commit", "-q", "-m", msg);
};
commit("Start", { "a.js": "a1\n", "b.js": "b1\n", "hot.js": "h1\n", "c.js": "c1\n", "tests/a.test.js": "t\n", "tests/b.test.js": "t\n", "tests/c.test.js": "t\n" });
commit("Change a and b (#12)", { "a.js": "a2\n", "b.js": "b2\n", "hot.js": "h2\n", "package-lock.json": "{}\n" });
commit("Change a and b again", { "a.js": "a3\n", "b.js": "b3\n", "hot.js": "h3\n", "package-lock.json": "{ }\n" });
commit("Change hot and c", { "hot.js": "h4\nmore\n", "c.js": "c2\n" });
commit("Change hot alone", { "hot.js": "h5\nmore\n", "dist/out.js": "x\n" });
// Without hot.js, so a-b (support 1) outranks a-hot and b-hot on support, not on name.
commit("Change a and b only", { "a.js": "a4\n", "b.js": "b4\n" });
for (let i = 1; i <= 3; i++) commit(`Change the old pair ${i}`, { "old1.js": `o${i}\n`, "old2.js": `p${i}\n` });
g("rm", "-q", "old1.js", "old2.js");
g("commit", "-q", "-m", "Delete the old pair");
fixture = dir;
return dir;
}
// PATH with git (and node) but no gh: git's own exec dir holds a git binary
// on every platform, so the directory that also holds gh is never needed.
function pathWithoutGh() {
const gitDir = execFileSync("git", ["--exec-path"], { encoding: "utf8" }).trim();
const dirs = [path.resolve(gitDir)];
const nodeDir = path.dirname(process.execPath);
const hasGh = ["gh", "gh.exe"].some((n) => fs.existsSync(path.join(nodeDir, n)));
if (!hasGh) dirs.push(nodeDir);
const value = dirs.join(path.delimiter);
// Windows keys env case-insensitively but a child gets both spellings: set both.
return { PATH: value, Path: value };
}
test("xray hotspots: the always-together pair ranks first, the hot file without a test is listed", () => {
const r = X(repo(), ["hotspots"]);
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.ok, true);
assert.deepEqual(r.json.window, { commits: 10, capped: false });
assert.deepEqual(r.json.churn[0], { file: "hot.js", commits: 5 });
assert.ok(!r.json.churn.some((c) => c.file === "package-lock.json" || c.file.startsWith("dist/")), "lockfiles and dist/ are skipped");
assert.deepEqual(r.json.pairs[0], { a: "a.js", b: "b.js", together: 4, support: 1 });
assert.ok(r.json.pairs[1].support < 1, JSON.stringify(r.json.pairs));
assert.ok(r.json.pairs.every((p) => p.together >= 3));
const untested = r.json.untested.map((u) => u.file);
assert.ok(untested.includes("hot.js"), JSON.stringify(r.json.untested));
for (const tested of ["a.js", "b.js", "c.js"]) assert.ok(!untested.includes(tested), `${tested} has a test`);
});
test("xray hotspots: files deleted since drop out of churn and pairs", () => {
const r = X(repo(), ["hotspots"]);
assert.equal(r.code, 0, r.stderr);
const named = [...r.json.churn.map((c) => c.file), ...r.json.pairs.flatMap((p) => [p.a, p.b])];
assert.ok(!named.some((f) => f.startsWith("old")), JSON.stringify(named));
});
test("xray hotspots: --max-commits below the history sets capped", () => {
const r = X(repo(), ["hotspots", "--max-commits", "2"]);
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.window, { commits: 2, capped: true });
assert.equal(X(repo(), ["hotspots", "--top", "1"]).json.churn.length, 1);
});
test("xray history: commits, blame and gh missing when gh is not on PATH", () => {
const r = X(repo(), ["history", "hot.js"], pathWithoutGh());
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.path, "hot.js");
assert.equal(r.json.commits.length, 5);
assert.equal(r.json.commits[0].subject, "Change hot alone");
assert.equal(r.json.commits[0].author, "Test");
assert.match(r.json.commits[0].hash, /^[0-9a-f]{40}$/);
assert.equal(r.json.blame.lines, 2);
assert.deepEqual(r.json.blame.authors, [{ author: "Test", lines: 2, share: 1 }]);
assert.match(r.json.blame.oldest, /^\d{4}-\d{2}-\d{2}$/);
assert.deepEqual(r.json.prs, [{ number: 12, subject: "Change a and b (#12)", title: null, summary: null }]);
assert.deepEqual(r.json.sources, { git: true, blame: true, gh: "missing" });
});
test("xray: a folder outside any repository is exit 3 not-a-repo", () => {
const plain = tmp("xray-plain");
for (const args of [["hotspots"], ["history", "x.js"]]) {
const r = X(plain, args);
assert.equal(r.code, 3);
assert.equal(r.json.ok, false);
assert.equal(r.json.error, "not-a-repo");
assert.match(r.json.next, /explain mode/);
}
});
test("xray: --help documents the exit codes", () => {
const r = X(repo(), ["--help"]);
assert.equal(r.code, 0);
assert.match(r.stdout, /Exit:/);
});
+218
View File
@@ -29,6 +29,17 @@ test("every skill with scripts ships common.mjs and version.json; dashboard ship
assert.equal(JSON.parse(fs.readFileSync(path.join(SKILLS, "plan2code-4-finalize", "scripts", "version.json"), "utf8")).version, v);
});
test("the Handoff skill writes through the console's handoff new, with no folder or gitignore step", () => {
const skill = fs.readFileSync(path.join(SKILLS, "plan2code-handoff", "SKILL.md"), "utf8");
assert.match(skill, /console\.mjs" handoff new/);
assert.doesNotMatch(skill, /handoff-path\.mjs/);
assert.doesNotMatch(skill, /--dir temp/);
assert.doesNotMatch(skill, /\.gitignore/);
// handoff-path.mjs is retired: the build ships only the shared specs.mjs.
assert.ok(!fs.existsSync(path.join(SKILLS, "plan2code-handoff", "scripts", "handoff-path.mjs")), "handoff-path.mjs is not shipped");
assert.ok(fs.existsSync(path.join(SKILLS, "plan2code-handoff", "scripts", "specs.mjs")), "specs.mjs still is");
});
test("every script a SKILL.md (or a reference it ships) runs exists beside it, and answers --help", () => {
for (const skill of fs.readdirSync(SKILLS)) {
const dir = path.join(SKILLS, skill);
@@ -115,6 +126,27 @@ test("specs list: active specs with state, drafts and archives, never specs--com
assert.equal(r.json.hasAgents, true);
});
test("specs list: a folder holding only Diagnose's write-up is diagnosed", () => {
const root = specFixture();
write(root, "specs/csv-drops-rows/DIAGNOSIS-20261016.md", "# Diagnosis: CSV drops rows\n\n**Status:** Diagnosed\n");
const r = runScript("plan2code-diagnose", "specs.mjs", ["list", "--root", root]);
assert.equal(r.code, 0, r.stderr);
const bug = r.json.specs.find((s) => s.name === "csv-drops-rows");
assert.equal(bug.state, "diagnosed");
assert.equal(bug.detail, "bug diagnosed, not fixed");
assert.equal(bug.phaseFiles, 0);
});
test("specs list: a diagnosis Quick Task marked Fixed is a fixed bug", () => {
const root = specFixture();
write(root, "specs/csv-drops-rows/DIAGNOSIS-20261016.md", "# Diagnosis: CSV drops rows\n\n**Status:** Fixed\n");
const r = runScript("plan2code-quick-task", "specs.mjs", ["list", "--root", root]);
assert.equal(r.code, 0, r.stderr);
const bug = r.json.specs.find((s) => s.name === "csv-drops-rows");
assert.equal(bug.state, "fixed");
assert.equal(bug.detail, "bug fixed");
});
test("specs status: checklist formats, groups, task markers, numbering, totals, checks", () => {
const root = specFixture();
const r = runScript("plan2code-3-implement", "specs.mjs", ["status", "specs/lunch-vote/overview.md", "--root", root]);
@@ -140,6 +172,25 @@ test("specs status: checklist formats, groups, task markers, numbering, totals,
assert.deepEqual(j.pending.map((p) => p.number), [2, 3, 4]);
});
test("specs status: a plain ` - Test:` sub-bullet under a task is not counted or flagged", () => {
const plain = specFixture();
const withTests = specFixture();
// The shape Document writes: a task line followed directly by a non-checkbox sub-bullet.
for (const [n, ids] of [[2, ["2.1", "2.2"]], [3, ["3.1", "3.4"]]]) {
const rel = `specs/lunch-vote/phase-${n}.md`;
let text = read(withTests, rel);
for (const id of ids) text = text.replace(`**Task ${id}:** Do ${id}\n`, `**Task ${id}:** Do ${id}\n - Test: through \`POST /votes\`\n`);
assert.match(text, /\n - Test: through/);
write(withTests, rel, text);
}
const status = (root) => runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
const a = status(plain);
const b = status(withTests);
assert.deepEqual(b.phases.map((p) => p.tasks), a.phases.map((p) => p.tasks));
assert.deepEqual(b.totals, a.totals);
assert.deepEqual(b.checks, a.checks);
});
test("specs status: the implement selection table", () => {
const root = specFixture();
const ov = (m1, m2, m3, m4) => OVERVIEW.replace("- [x] **[Phase 1", `- [${m1}] **[Phase 1`).replace("- [/] [Phase 2", `- [${m2}] [Phase 2`).replace("- [ ] **Phase 3", `- [${m3}] **Phase 3`).replace("- [ ] [Phase 4", `- [${m4}] [Phase 4`);
@@ -473,6 +524,173 @@ test("specs: --set cannot override computed fields; empty overview exists; uncou
assert.ok(!e.checks.some((c) => c.code === "no-overview"));
});
// A spec with nothing for check to find: a checklist row per phase file,
// sequential task numbers, a Test-first sub-bullet and plain-bullet criteria.
function cleanSpec(root) {
write(root, "specs/clean/overview.md", "# Clean\n\n## Phase Checklist\n\n- [ ] [Phase 1: Data model](./phase-1.md)\n- [ ] [Phase 2: API](./phase-2.md)\n");
write(root, "specs/clean/phase-1.md", phase(1, "Not Started", [[" ", "1.1"], [" ", "1.2"]]).replace("**Task 1.1:** Do 1.1\n", "**Task 1.1:** Do 1.1\n - Test: through `POST /votes`\n"));
write(root, "specs/clean/phase-2.md", phase(2, "Not Started", [[" ", "2.1"]]));
return root;
}
test("specs check: a well-formed spec passes", () => {
const root = cleanSpec(specFixture());
assert.match(read(root, "specs/clean/phase-1.md"), /\n - Test: through/);
const r = runScript("plan2code-2-document", "specs.mjs", ["check", "clean", "--root", root]);
assert.equal(r.code, 0, r.stdout);
assert.equal(r.json.ok, true);
assert.equal(r.json.errors, 0);
assert.deepEqual(r.json.checked, ["specs/clean/overview.md", "specs/clean/phase-1.md", "specs/clean/phase-2.md"]);
assert.deepEqual(r.json.problems, []);
});
test("specs check: a bad task line, a checklist row with no phase file, a loop token and a bare metric word each fail", () => {
const root = cleanSpec(specFixture());
write(root, "specs/clean/overview.md", read(root, "specs/clean/overview.md") + "- [ ] [Phase 3: Docs](./phase-3.md)\n");
write(root, "specs/clean/phase-1.md", read(root, "specs/clean/phase-1.md").replace("- [ ] **Task 1.2:** Do 1.2", "- [ ] Task 1.2 without the bold"));
write(root, "specs/clean/phase-2.md", read(root, "specs/clean/phase-2.md") + "\n## Notes\n\nPrint TASK_COMPLETE when done. Risk: 3 of 5.\n");
const r = runScript("plan2code-2-document", "specs.mjs", ["check", "clean", "--root", root]);
assert.equal(r.code, 4, r.stdout);
assert.equal(r.json.ok, false);
assert.equal(r.json.error, "check-failed");
assert.match(r.json.next, /rerun check/);
assert.match(r.stderr, /^error: check found \d+ errors?\.\nnext: /);
const errs = r.json.problems.filter((p) => p.level === "error");
assert.equal(r.json.errors, errs.length);
const by = (code) => errs.filter((p) => p.code === code);
assert.deepEqual(by("bad-task-line").map((p) => p.file), ["specs/clean/phase-1.md"]);
assert.deepEqual(by("missing-phase-file").map((p) => p.file), ["specs/clean/overview.md"]);
assert.deepEqual(by("loop-token").map((p) => p.file), ["specs/clean/phase-2.md"]);
assert.deepEqual(by("metric-word").map((p) => p.file), ["specs/clean/phase-2.md"]);
for (const p of r.json.problems) assert.deepEqual(Object.keys(p), ["level", "file", "code", "message"]);
assert.equal(runScript("plan2code-2-document", "specs.mjs", ["check", "nope", "--root", root]).code, 3);
// A status problem names the phase file by its real name, not phase-N.md.
fs.renameSync(path.join(root, "specs/clean/phase-2.md"), path.join(root, "specs/clean/phase-2-api.md"));
write(root, "specs/clean/phase-2-api.md", phase(2, "Not Started", [[" ", "2.2"]]));
const named = runScript("plan2code-2-document", "specs.mjs", ["check", "clean", "--root", root]).json;
assert.deepEqual(named.problems.filter((p) => p.code === "task-numbering").map((p) => p.file), ["specs/clean/phase-2-api.md"]);
});
// A draft in the shape Plan's Phase 7 writes, with every heading Document reads.
const COMPLETE_DRAFT = `# Lunch vote - Implementation Plan
**Created:** 2026-08-01
**Status:** Complete
**Confidence:** 92% (Requirements-clarity 24/25 · Feasibility-technical 23/25 · Integration-points 23/25 · Risk-assessment 22/25)
## 1. Executive Summary
A lunch vote.
## 2. Requirements
### 2.1 Functional Requirements
- [ ] FR-1: People vote
### 2.4 Testing Strategy
| Type | Phase Testing | Coverage |
|------|---------------|----------|
## 3. Tech Stack
Node.
## 4. Architecture
One server.
## 5. Implementation Phases
### Phase 1: Votes
Build the vote (FR-1).
## 6. Risks and Mitigations
| Risk | Likelihood | Impact | Mitigation |
## 7. Success Criteria
- [ ] Votes count
## 9. Assumptions
- People eat lunch
## Planning Metrics
<!-- METRICS_JSON {"confidence": 92, "confidence_breakdown": {"requirements": 24, "risk": 22}} -->
`;
test("specs check-draft: a complete draft passes", () => {
const root = specFixture();
write(root, "specs/lunch-vote/PLAN-DRAFT-20260801.md", COMPLETE_DRAFT);
for (const arg of ["lunch-vote", "specs/lunch-vote/PLAN-DRAFT-20260801.md"]) {
const r = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", arg, "--root", root]);
assert.equal(r.code, 0, r.stdout);
assert.equal(r.json.errors, 0);
assert.equal(r.json.warnings, 0);
assert.equal(r.json.status, "Complete");
assert.deepEqual(r.json.checked, ["specs/lunch-vote/PLAN-DRAFT-20260801.md"]);
}
// A newer -prev copy is archived, never the one checked.
write(root, "specs/lunch-vote/PLAN-DRAFT-20260802-prev.md", "# old\n");
assert.equal(runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "lunch-vote", "--root", root]).code, 0);
// Untraced requirements only warn.
write(root, "specs/lunch-vote/PLAN-DRAFT-20260801.md", COMPLETE_DRAFT.replace("Build the vote (FR-1).", "Build the vote."));
const w = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "lunch-vote", "--root", root]);
assert.equal(w.code, 0, w.stdout);
assert.deepEqual(w.json.problems.map((p) => [p.level, p.code]), [["warn", "untraced-requirements"]]);
});
test("specs check-draft: a missing section, a bad status, no metrics, a loop token each fail", () => {
const root = specFixture();
const check = (text) => {
write(root, "specs/lunch-vote/PLAN-DRAFT-20260801.md", text);
const r = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "lunch-vote", "--root", root]);
assert.equal(r.code, 4, r.stdout);
assert.equal(r.json.error, "check-draft-failed");
return r.json.problems.filter((p) => p.level === "error").map((p) => p.code);
};
const noTech = check(COMPLETE_DRAFT.replace("## 3. Tech Stack", "## 3. Tools"));
assert.deepEqual(noTech, ["missing-section"]);
assert.deepEqual(check(COMPLETE_DRAFT.replace("**Status:** Complete", "**Status:** Finished")), ["bad-status"]);
assert.deepEqual(check(COMPLETE_DRAFT.replace("**Status:** Complete\n", "")), ["bad-status"]);
assert.deepEqual(check(COMPLETE_DRAFT.replace(/## Planning Metrics\n<!--.*-->\n/, "")), ["no-metrics"]);
assert.deepEqual(check(COMPLETE_DRAFT.replace('{"confidence": 92,', '{"confidence": 92')), ["no-metrics"]);
assert.deepEqual(check(COMPLETE_DRAFT.replace("METRICS_JSON {", "METRICS_JSON{")), ["no-metrics"], "the collector needs whitespace after METRICS_JSON");
assert.deepEqual(check(COMPLETE_DRAFT.replace("### Phase 1: Votes", "Phase 1, votes")), ["no-phases"]);
assert.deepEqual(check(COMPLETE_DRAFT.replace("Node.", "Node. Then say PHASE_COMPLETE.")), ["loop-token"]);
assert.deepEqual(check(COMPLETE_DRAFT.replace("One server.", "One server. Integration: 4 services.")), ["metric-word"]);
const missing = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "specs/lunch-vote/PLAN-DRAFT-nope.md", "--root", root]);
assert.equal(missing.code, 3);
assert.equal(runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "idea-only", "--root", root]).json.error, "no-draft");
});
test("specs check-draft: a pathfinder draft at Resume at Phase 4 is checked lightly", () => {
const root = specFixture();
const draft = "# Idea - Implementation Plan\n\n*Written by /plan2code-0-pathfinder.*\n\n**Status:** Phase 3 Complete - Resume at Phase 4\n\n## 1. Executive Summary\n\nTBD\n";
write(root, "specs/idea-only/PLAN-DRAFT-20260801.md", draft);
const r = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "idea-only", "--root", root]);
assert.equal(r.code, 0, r.stdout);
assert.deepEqual(r.json.problems, [], "no section, phase or metrics checks before Plan's Phase 4");
// Status, loop tokens and every metric pattern still apply, confidence included.
write(root, "specs/idea-only/PLAN-DRAFT-20260801.md", draft + "\n**Confidence:** 80%\n\nSay WORK_COMPLETE.\n");
const bad = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "idea-only", "--root", root]);
assert.equal(bad.code, 4);
assert.deepEqual(bad.json.problems.map((p) => p.code).sort(), ["loop-token", "metric-word"]);
});
test("common.mjs exports the shared loop-token and scrape patterns", async () => {
const common = await import(new URL(`file:///${path.join(SKILLS, "plan2code-2-document", "scripts", "common.mjs").replace(/\\/g, "/")}`).href);
assert.ok(common.LOOP_TOKENS instanceof RegExp);
assert.ok(common.LOOP_TOKENS.test("then TASK_COMPLETE"));
assert.equal(common.SCRAPE.length, 6);
assert.deepEqual(common.scrapeHits("Risk: 3"), ['bare Risk + number: "Risk: 3"']);
assert.deepEqual(common.scrapeHits("Risk-assessment 22/25"), []);
});
test("commit-msg: a repo with no commits, stray arguments, and paths quoted for every shell", () => {
const repo = tmp("commit2");
gitInit(repo, "feature/ABC-12-x");
+1 -1
View File
@@ -29,7 +29,7 @@ import {
unreadDot,
} from "../src/web-console/public/chat.js";
import { WEIGHTS } from "../src/web-console/public/meter.js";
import { readChat } from "../src/web-console/lib.mjs";
import { readChat } from "../src/web-console/inbox.mjs";
import {
ROOT,
CONSOLE_CLI,
+2 -1
View File
@@ -9,7 +9,8 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { readChat, terminalLine } from "../src/web-console/lib.mjs";
import { terminalLine } from "../src/web-console/sessions.mjs";
import { readChat } from "../src/web-console/inbox.mjs";
import {
ROOT,
CONSOLE_CLI,
+10 -3
View File
@@ -12,7 +12,10 @@ import path from "node:path";
import { execFileSync, spawn } from "node:child_process";
import http from "node:http";
import { meterView } from "../src/web-console/public/meter.js";
import { cwdHash, readLedger, repoRoots, STATE_LOCK_FILE, validate, WORKSPACE_FILE } from "../src/web-console/lib.mjs";
import { STATE_LOCK_FILE } from "../src/web-console/files.mjs";
import { cwdHash, readLedger, repoRoots } from "../src/web-console/sessions.mjs";
import { validate } from "../src/web-console/patches.mjs";
import { WORKSPACE_FILE } from "../src/web-console/workspace.mjs";
import {
ROOT,
CONSOLE_CLI,
@@ -47,7 +50,11 @@ test("helpers: a dashboard hop clears them, a same-workflow or paused resume kee
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]);
assert.equal(readState(s.session).helpers.length, 2, "a resume into the same workflow keeps them");
assert.equal(postPatch(s, { finish: { headline: "Paused at Task 2" } }).status, 0);
// A finish is refused while a helper still shows as running, so the pause settles them.
assert.equal(
postPatch(s, { helpers: [reportedHelper("h1", { state: "done" }), reportedHelper("h2", { state: "failed" })], finish: { headline: "Paused at Task 2" } }).status,
0
);
cli(["open", "--resume", s.sid, "--no-open"]);
const resumed = readState(s.session);
assert.equal("finish" in resumed, false, "the pause came down");
@@ -240,7 +247,7 @@ test("stop never kills a live process that does not answer /health as ours", ()
const bystander = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
const sidForged = "20000101-000000-beef01";
// Under the test home, as the CLI sees it: this process has no override of
// its own, and lib.mjs would name the real runtime dir.
// its own, and files.mjs would name the real runtime dir.
const dir = path.join(HOME, "runtime", cwdHash(repoRoots(ROOT).project));
fs.mkdirSync(dir, { recursive: true });
const forged = path.join(dir, `${sidForged}.json`);
+11 -17
View File
@@ -495,30 +495,24 @@ test("git board view: a .gitignore-only pick commits just .gitignore, and never
assert.equal(gitReply("commit", { files: ["a.js"], ignore: ["dist/"] }), "Commit this file: a.js. Add dist/ to .gitignore.");
});
test("git board host: app.js draws the board only through drawGitBoard, and the server serves the view", () => {
const app = fs.readFileSync(new URL("../src/web-console/public/app.js", import.meta.url), "utf8");
test("git board host: the host draws the board only through drawGitBoard, and the server serves the view", () => {
const host = fs.readFileSync(new URL("../src/web-console/public/screens/git-host.js", import.meta.url), "utf8");
for (const gone of ["gitActionBar", "gitBranches", "smallButton", "gitHeader", "gitCommitPanel"]) {
assert.ok(!app.includes(`function ${gone}(`), `app.js no longer defines ${gone}()`);
assert.ok(!host.includes(`function ${gone}(`), `git-host.js no longer defines ${gone}()`);
}
const drawCalls = [...app.matchAll(/\bdrawGitBoard\(/g)].length;
const drawCalls = [...host.matchAll(/\bdrawGitBoard\(/g)].length;
assert.equal(drawCalls, 1, "one call to drawGitBoard");
const host = app.slice(app.indexOf("function renderGitBoard("), app.indexOf("function rememberGitTabScroll("));
assert.ok(host.includes("drawGitBoard("), "renderGitBoard is the one that calls it");
const server = fs.readFileSync(new URL("../src/web-console/server.mjs", import.meta.url), "utf8");
const body = host.slice(host.indexOf("function renderGitBoard("), host.indexOf("function rememberGitTabScroll("));
assert.ok(body.includes("drawGitBoard("), "renderGitBoard is the one that calls it");
const server = fs.readFileSync(new URL("../src/web-console/static.mjs", import.meta.url), "utf8");
const servable = server.slice(server.indexOf("const SERVABLE = new Set(["), server.indexOf("]);", server.indexOf("const SERVABLE = new Set([")));
assert.ok(servable.includes('"git-board-view.js"'), "SERVABLE includes git-board-view.js");
assert.ok(servable.includes('"screens/git-host.js"'), "SERVABLE includes screens/git-host.js");
});
test("git board host: the always-on commit table keeps the person's ticks, and a click re-seeds them", () => {
const app = fs.readFileSync(new URL("../src/web-console/public/app.js", import.meta.url), "utf8");
const send = app.slice(app.indexOf("async function sendGit("), app.indexOf("const gitOn = {"));
assert.match(send, /board\.ticks = null;\s*board\.ignore = new Set\(\);/, "a click drops the old picks");
const commit = app.slice(app.indexOf("function openCommit("), app.indexOf("function openCleanup("));
assert.ok(!commit.includes("commitTicks("), "opening the panel never re-seeds over their ticks");
assert.ok(commit.includes("tablePicks(git)"), "a detached commit carries the table's picks");
const panel = app.slice(app.indexOf("function openPanel("), app.indexOf("const closePanel ="));
assert.match(panel, /opts\.commit && !opts\.files\) return openCreate\(git, \{ \.\.\.opts, \.\.\.tablePicks\(git\) \}\)/, "Start a branch takes what is ticked");
});
// The commit table's ticks and the click that re-seeds them are page tests now
// ("the commit table keeps the person's ticks across an agent post, and a click
// re-seeds them" and its neighbours in test-web-console-page-git.mjs).
test("git board docs: the agent prose, Help topic and readme describe the tabbed board", () => {
const read = (p) => fs.readFileSync(new URL(p, import.meta.url), "utf8");
+13 -21
View File
@@ -14,12 +14,11 @@ import { spawnSync } from "node:child_process";
// is exactly why this lives in its own file.
import {
cardAvailability,
CONSOLE_WORKFLOWS,
GIT_INIT_NOTE,
resumeCommand,
SKILL_CATALOG,
START_POSES,
} from "../src/web-console/public/answers.js";
import { SKILLS } from "../src/web-console/public/skills.js";
import { breakdownFrom, pointsFrom } from "../src/web-console/public/meter.js";
import {
BRANCH_TYPES,
@@ -38,7 +37,7 @@ import {
refreshedLine,
} from "../src/web-console/public/git-board.js";
import { prUrl } from "../src/web-console/public/pr-url.js";
import { PROTECTED_CONSOLE_FILES, readLedger } from "../src/web-console/lib.mjs";
import { PROTECTED_CONSOLE_FILES, readLedger } from "../src/web-console/sessions.mjs";
import {
CONSOLE_CLI,
HOME,
@@ -290,8 +289,6 @@ test("git: the Git card is never greyed, and its resume command is /plan2code-gi
assert.deepEqual(cardAvailability(entry, { hasAgents: true, isGit: true, pending: 0 }, null), { on: true });
assert.deepEqual(cardAvailability(entry, { hasAgents: true, isGit: true, pending: null }, null), { on: true });
assert.equal(resumeCommand({ workflow: "git" }), "/plan2code-git");
assert.ok(CONSOLE_WORKFLOWS.includes("/plan2code-git"));
assert.ok(START_POSES.includes("git"));
});
test("git: the Git card's copy, place and availability are pinned (FR-58, FR-59)", async () => {
@@ -303,7 +300,11 @@ test("git: the Git card's copy, place and availability are pinned (FR-58, FR-59)
);
assert.equal(entry.group, "extra");
assert.equal(entry.chip, "Utility");
assert.equal(SKILL_CATALOG.at(-1), entry, "the Git card is last");
// The card order is skills.js's order.
const order = SKILLS.filter((s) => s.card).map((s) => s.skill);
assert.equal(order.indexOf("plan2code-git") + 1, order.indexOf("plan2code-handoff"), "the Git card comes right before Handoff");
assert.equal(order.at(-1), "plan2code-handoff", "the Handoff card is last");
assert.deepEqual(SKILL_CATALOG.map((e) => e.skill), order, "the catalog draws in that order");
for (const isGit of [true, false, undefined]) {
for (const pending of [0, 3, null]) {
const scan = { hasAgents: true, pending, ...(isGit === undefined ? {} : { isGit }) };
@@ -326,12 +327,10 @@ test("git: the board stays locked from a click until the agent's next post, not
assert.equal(boardAwaiting({ sentAt, updatedAt: "2026-10-10T05:15:51.000Z", cardsAwaiting: 2 }), true);
assert.equal(boardAwaiting({ sentAt, cardsAwaiting: 1, adrift: true }), false, "an agent gone quiet releases the lock");
const app = fs.readFileSync(new URL("../src/web-console/public/app.js", import.meta.url), "utf8");
assert.match(app, /const gitMode = \(\) =>[^;]*gitAwaiting\(\)/, "the busy mode includes gitAwaiting()");
assert.match(app, /const gitLocked = \(\) => gitMode\(\) !== "idle";/, "gitLocked is anything but idle");
const send = app.slice(app.indexOf("async function sendGit("), app.indexOf("function renderGitBoard("));
assert.match(send, /local\.gitSentAt = Date\.now\(\);\s*save\(\);/, "a board click records when it was sent, and saves it");
assert.match(app, /sentAt: local\.gitSentAt[\s\S]{0,80}updatedAt: S\.updatedAt[\s\S]{0,80}cardsAwaiting: awaitingReply\(\)\.length/);
// gitMode, gitLocked and the click's gitSentAt are page tests now (the board
// stays locked in test-web-console-page-git.mjs); what feeds them is here.
const selectors = fs.readFileSync(new URL("../src/web-console/public/selectors.js", import.meta.url), "utf8");
assert.match(selectors, /sentAt: page\.local\.gitSentAt[\s\S]{0,80}updatedAt: page\.S\.updatedAt[\s\S]{0,80}cardsAwaiting: awaitingReply\(\)\.length/);
});
/* ------------------------------------------- the git board's pure helpers */
@@ -562,19 +561,12 @@ test("git board: boardPrLink builds the link for a pushed feature branch only",
test("git board: the page draws it from git-board.js, with no inline styles", () => {
const dir = path.join(path.dirname(CONSOLE_CLI), "public");
const app = fs.readFileSync(path.join(dir, "app.js"), "utf8");
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
const view = fs.readFileSync(path.join(dir, "git-board-view.js"), "utf8");
assert.match(app, /^import [^;]+ from "\.\/git-board\.js";/m, "app.js imports git-board.js");
assert.match(app, /^import [^;]+ from "\.\/git-board-view\.js";/m, "app.js imports git-board-view.js");
for (const m of ["git-board.js", "git-board-view.js", "pr-url.js"]) assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
assert.match(app, /const isGitBoard = \(\) => S && S\.workflow === "git" && S\.git;/);
assert.match(app, /i: "__git", type: "git", op/, "a click is one __git action");
const selectors = fs.readFileSync(path.join(dir, "selectors.js"), "utf8");
assert.match(selectors, /const isGitBoard = \(\) => page\.S && page\.S\.workflow === "git" && page\.S\.git;/);
assert.match(view, /a\.rel = "noopener"/, "the PR link opens with rel=noopener");
const start = app.indexOf("/* ------------------------------------------------------------ git board */");
const end = app.indexOf("/* ------------------------------------------------------------- welcome */");
assert.ok(start > 0 && end > start);
assert.doesNotMatch(app.slice(start, end), /setAttribute\(\s*["']style["']|\.style\./, "the board sets no inline styles");
assert.doesNotMatch(view, /setAttribute\(\s*["']style["']|\.style\./, "nor does its view");
});
+503
View File
@@ -0,0 +1,503 @@
// Web console tests, the handoff store: ids, writing, listing, marking,
// removing and sweeping ~/.plan2code/handoffs/, and the console commands
// built on it.
// Run with: node --test scripts/test-web-console-handoffs.mjs
//
// Shared setup (a per-process console home, the CLI runner, fixtures) lives in
// web-console-test-helpers.mjs; see the comment at its top. Every handoff here
// lands in its throwaway HANDOFFS_DIR, never the real home folder.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { CONSOLE_CLI, ENV, HANDOFFS_DIR, cli, safeJson, sessionUrl } from "./web-console-test-helpers.mjs";
process.env.PLAN2CODE_HANDOFFS_DIR = HANDOFFS_DIR;
const store = await import("../src/web-console/handoffs.mjs");
const { HANDOFF_ID, handoffsDir, isHandoffId } = store;
test("isHandoffId takes only a bare handoff id", () => {
assert.ok(isHandoffId("2026-10-17-1152-handoff"));
assert.ok(isHandoffId("2026-10-17-1152-handoff-3"));
for (const bad of ["../x", "2026-10-17-1152-handoff.md", "a/2026-10-17-1152-handoff", "", null, undefined, 7, {}]) {
assert.equal(isHandoffId(bad), false, String(bad));
}
assert.ok(HANDOFF_ID.test("2026-10-17-1152-handoff"));
});
test("handoffsDir follows PLAN2CODE_HANDOFFS_DIR at call time", () => {
assert.equal(handoffsDir(), HANDOFFS_DIR);
const saved = process.env.PLAN2CODE_HANDOFFS_DIR;
try {
process.env.PLAN2CODE_HANDOFFS_DIR = path.join(HANDOFFS_DIR, "elsewhere");
assert.equal(handoffsDir(), path.join(HANDOFFS_DIR, "elsewhere"));
} finally {
process.env.PLAN2CODE_HANDOFFS_DIR = saved;
}
});
// A link at `at`: a file symlink to `file` where the machine allows one, else
// a junction to the folder `dir`, which needs no privilege on Windows and
// which lstat reports as a link all the same. False when neither can be made.
function link(file, dir, at) {
try {
fs.symlinkSync(file, at, "file");
return true;
} catch (err) {
if (err.code !== "EPERM") throw err;
}
try {
fs.symlinkSync(dir, at, "junction");
return true;
} catch {
return false;
}
}
// A clean folder per test that writes handoffs, and the pinned clock it asks for.
function fresh(nowPinned) {
fs.rmSync(HANDOFFS_DIR, { recursive: true, force: true });
if (nowPinned === undefined) delete process.env.PLAN2CODE_NOW;
else process.env.PLAN2CODE_NOW = nowPinned;
}
const WORKTREE = path.join(HANDOFFS_DIR, "..", "repo");
const REC = {
worktree: WORKTREE,
project: WORKTREE,
spec: "specs/lunch-vote",
workflow: "quick-task",
skill: "plan2code-quick-task",
title: "Lunch vote",
fromStop: true,
};
test("newHandoff claims the next free id for the minute and writes only the .json", () => {
fresh("2026-10-17 11:52");
try {
const a = store.newHandoff(REC);
const b = store.newHandoff({ ...REC, spec: undefined, fromStop: false });
assert.equal(a.id, "2026-10-17-1152-handoff");
assert.equal(b.id, "2026-10-17-1152-handoff-2");
assert.equal(a.path, path.join(HANDOFFS_DIR, a.id + ".md"));
assert.equal(fs.existsSync(a.path), false, "the agent writes the .md");
const meta = JSON.parse(fs.readFileSync(path.join(HANDOFFS_DIR, a.id + ".json"), "utf8"));
assert.deepEqual(Object.keys(meta), ["v", "id", "title", "worktree", "project", "spec", "workflow", "skill", "written", "fromStop", "usedAt"]);
assert.deepEqual(
{ ...meta, written: undefined },
{ v: 1, id: a.id, title: "Lunch vote", worktree: WORKTREE, project: WORKTREE, spec: "specs/lunch-vote", workflow: "quick-task", skill: "plan2code-quick-task", written: undefined, fromStop: true, usedAt: null }
);
assert.ok(!Number.isNaN(Date.parse(meta.written)));
assert.deepEqual(a.meta, meta);
assert.equal(b.meta.spec, null);
assert.equal(b.meta.fromStop, false);
} finally {
fresh();
}
});
test("newHandoff refuses a bad workflow, skill or spec and leaves no file", () => {
fresh("2026-10-17 11:52");
try {
for (const [field, value] of [["workflow", "Quick Task"], ["workflow", undefined], ["skill", "../x"], ["spec", "../x"], ["spec", "specs/a/b"]]) {
assert.throws(() => store.newHandoff({ ...REC, [field]: value }), new RegExp(field));
}
assert.deepEqual(fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR) : [], []);
} finally {
fresh();
}
});
test("readHandoffMeta round-trips, markHandoffUsed stamps usedAt and leaves the .md alone", () => {
fresh("2026-10-17 11:52");
try {
const { id, path: md, meta } = store.newHandoff(REC);
fs.writeFileSync(md, "# Handoff: Lunch vote\n");
const before = fs.readFileSync(md);
assert.deepEqual(store.readHandoffMeta(id), meta);
const used = store.markHandoffUsed(id, new Date("2026-10-18T09:00:00Z"));
assert.equal(used.usedAt, "2026-10-18T09:00:00.000Z");
assert.deepEqual(store.readHandoffMeta(id), used);
assert.deepEqual(fs.readFileSync(md), before);
assert.equal(store.readHandoffMeta("../x"), null);
assert.equal(store.readHandoffMeta("2026-10-17-1152-handoff-9"), null);
assert.equal(store.markHandoffUsed("2026-10-17-1152-handoff-9"), null);
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-17-1152-handoff-7.json"), "not json");
assert.equal(store.readHandoffMeta("2026-10-17-1152-handoff-7"), null);
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-17-1152-handoff-8.json"), JSON.stringify({ ...meta, v: 2 }));
assert.equal(store.readHandoffMeta("2026-10-17-1152-handoff-8"), null);
} finally {
fresh();
}
});
test("readHandoffMeta refuses a linked .json", (t) => {
fresh("2026-10-17 11:52");
try {
const { meta } = store.newHandoff(REC);
const linkId = "2026-10-17-1152-handoff-5";
const outside = path.join(HANDOFFS_DIR, "..", "outside-dir");
fs.mkdirSync(outside, { recursive: true });
if (!link(path.join(HANDOFFS_DIR, meta.id + ".json"), outside, path.join(HANDOFFS_DIR, linkId + ".json"))) {
t.skip("this machine can make neither a symlink nor a junction");
return;
}
assert.equal(store.readHandoffMeta(linkId), null);
} finally {
fresh();
}
});
// A handoff with a document, as the agent would leave it.
function written(rec, md, when) {
const h = store.newHandoff(rec, when);
if (md !== null) fs.writeFileSync(h.path, md);
return h;
}
const DOC = `# Handoff: Lunch vote
## Context
Some context.
## Next task
Wire the vote button
to the tally, then test it.
## Notes
x
`;
test("listHandoffs lists only this checkout's unused handoffs that have both files, newest first", () => {
fresh();
try {
const mine = written(REC, DOC, new Date("2026-10-17T10:00:00Z"));
const newer = written({ ...REC, title: "Second" }, "# Handoff - Second try\n\n## Next task\n\n" + "word ".repeat(80) + "\n", new Date("2026-10-17T12:00:00Z"));
written({ ...REC, worktree: path.join(HANDOFFS_DIR, "..", "other") }, DOC, new Date("2026-10-17T10:01:00Z"));
const used = written(REC, DOC, new Date("2026-10-17T10:02:00Z"));
store.markHandoffUsed(used.id);
// A .json with no .md, and a .md with no .json.
written(REC, null, new Date("2026-10-17T10:03:00Z"));
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-01-0900-handoff.md"), DOC);
const list = store.listHandoffs(WORKTREE);
assert.deepEqual(list.map((h) => h.id), [newer.id, mine.id]);
assert.deepEqual(list[1], {
id: mine.id,
title: "Lunch vote",
next: "Wire the vote button to the tally, then test it.",
written: mine.meta.written,
spec: "specs/lunch-vote",
skill: "plan2code-quick-task",
workflow: "quick-task",
});
assert.equal(list[0].title, "Second try");
assert.equal(list[0].next.length, 280);
assert.ok(list[0].next.endsWith("…"));
} finally {
fresh();
}
});
test("listHandoffs falls back to the stored title and lists nothing for a missing folder", () => {
fresh();
try {
assert.deepEqual(store.listHandoffs(WORKTREE), []);
const h = written(REC, "No heading here.\n", new Date("2026-10-17T10:00:00Z"));
assert.deepEqual(store.listHandoffs(WORKTREE).map((x) => [x.id, x.title, x.next]), [[h.id, "Lunch vote", ""]]);
// Only the word "Handoff" is a prefix: "Handoffs" is part of the title.
const plural = written(REC, "# Handoffs page redesign\n", new Date("2026-10-17T09:00:00Z"));
assert.equal(store.listHandoffs(WORKTREE).find((x) => x.id === plural.id).title, "Handoffs page redesign");
} finally {
fresh();
}
});
test("listHandoffs matches the worktree whatever its case on win32 and darwin", { skip: process.platform !== "win32" && process.platform !== "darwin" }, () => {
fresh();
try {
const h = written(REC, DOC, new Date("2026-10-17T10:00:00Z"));
assert.deepEqual(store.listHandoffs(WORKTREE.toUpperCase()).map((x) => x.id), [h.id]);
} finally {
fresh();
}
});
test("removeHandoff removes both files, or a lone one, and refuses anything else", () => {
fresh();
try {
const both = written(REC, DOC, new Date("2026-10-17T10:00:00Z"));
assert.deepEqual(store.removeHandoff(both.id), { ok: true, removed: [both.id + ".md", both.id + ".json"] });
assert.deepEqual(fs.readdirSync(HANDOFFS_DIR), []);
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-01-0900-handoff.md"), DOC);
assert.deepEqual(store.removeHandoff("2026-10-01-0900-handoff").removed, ["2026-10-01-0900-handoff.md"]);
const lone = written(REC, null, new Date("2026-10-17T10:01:00Z"));
assert.deepEqual(store.removeHandoff(lone.id).removed, [lone.id + ".json"]);
assert.throws(() => store.removeHandoff("../evil"), /not a handoff id: \.\.\/evil/);
assert.throws(() => store.removeHandoff("2026-10-01-0900-handoff"), /there is no handoff 2026-10-01-0900-handoff/);
} finally {
fresh();
}
});
test("removeHandoff refuses a linked .md and leaves everything in place", (t) => {
fresh();
try {
const h = written(REC, null, new Date("2026-10-17T10:00:00Z"));
const outside = path.join(HANDOFFS_DIR, "..", "outside.md");
const outsideDir = path.join(HANDOFFS_DIR, "..", "outside-dir");
fs.writeFileSync(outside, "keep me");
fs.mkdirSync(outsideDir, { recursive: true });
fs.writeFileSync(path.join(outsideDir, "keep.txt"), "keep me too");
if (!link(outside, outsideDir, h.path)) {
t.skip("this machine can make neither a symlink nor a junction");
return;
}
assert.throws(() => store.removeHandoff(h.id), /link/);
assert.ok(fs.existsSync(path.join(HANDOFFS_DIR, h.id + ".json")));
assert.ok(fs.lstatSync(h.path).isSymbolicLink(), "the link itself stays");
assert.equal(fs.readFileSync(outside, "utf8"), "keep me");
assert.equal(fs.readFileSync(path.join(outsideDir, "keep.txt"), "utf8"), "keep me too");
} finally {
fresh();
}
});
test("staleHandoffs lists only month-old handoffs and removeHandoffs takes both files", async () => {
fresh();
try {
const old = written(REC, DOC, new Date("2026-09-01T10:00:00Z"));
const recent = written(REC, DOC, new Date("2026-10-16T10:00:00Z"));
const oldMdOnly = "2026-08-01-0900-handoff";
fs.writeFileSync(path.join(HANDOFFS_DIR, oldMdOnly + ".md"), DOC);
fs.writeFileSync(path.join(HANDOFFS_DIR, "notes.txt"), "not mine");
const DAY = 24 * 60 * 60 * 1000;
const age = (file, days) => {
const t = (Date.now() - days * DAY) / 1000;
fs.utimesSync(file, t, t);
};
age(path.join(HANDOFFS_DIR, old.id + ".json"), 31);
age(old.path, 31);
age(path.join(HANDOFFS_DIR, recent.id + ".json"), 1);
age(path.join(HANDOFFS_DIR, oldMdOnly + ".md"), 40);
age(path.join(HANDOFFS_DIR, "notes.txt"), 90);
const stale = store.staleHandoffs(Date.now(), 30 * DAY);
assert.deepEqual(stale.sort(), [oldMdOnly, old.id].sort());
assert.deepEqual((await store.removeHandoffs([...stale, "../evil", "notes.txt"])).sort(), [oldMdOnly, old.id].sort());
assert.deepEqual(fs.readdirSync(HANDOFFS_DIR).sort(), [recent.id + ".json", recent.id + ".md", "notes.txt"].sort());
} finally {
fresh();
}
});
/* ------------------------------------------------------- console commands */
// A throwaway git checkout to run the CLI in, so repoRoots() names it.
const REPO = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-handoff-repo-"));
spawnSync("git", ["init", "-q", REPO], { env: ENV });
const REPO_REAL = fs.realpathSync.native(REPO);
function run(args) {
const res = spawnSync(process.execPath, [CONSOLE_CLI, ...args], { env: ENV, encoding: "utf8", cwd: REPO });
return { status: res.status, stderr: res.stderr, json: safeJson(res.stdout) };
}
test("handoff new claims a handoff for this checkout and prints where to write it", () => {
fresh();
try {
const res = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--spec", "specs/lunch-vote", "--title", "Lunch vote", "--from-stop"]);
assert.equal(res.status, 0, res.stderr);
assert.equal(res.json.ok, true);
assert.ok(store.isHandoffId(res.json.id));
assert.equal(path.dirname(res.json.path), HANDOFFS_DIR);
assert.ok(res.json.path.endsWith(".md"));
assert.equal(fs.existsSync(res.json.path), false);
const meta = JSON.parse(fs.readFileSync(path.join(HANDOFFS_DIR, res.json.id + ".json"), "utf8"));
assert.equal(meta.worktree, REPO_REAL);
assert.equal(meta.project, REPO_REAL);
assert.equal(meta.spec, "specs/lunch-vote");
assert.equal(meta.fromStop, true);
assert.deepEqual(res.json.meta, meta);
} finally {
fresh();
}
});
test("handoff new refuses bad usage with 2 and a bad value with 3", () => {
fresh();
try {
assert.equal(run(["handoff", "new", "--workflow", "quick-task"]).status, 2);
assert.equal(run(["handoff", "new", "--skill", "plan2code-quick-task"]).status, 2);
assert.equal(run(["handoff", "list"]).status, 2);
assert.equal(run(["handoff"]).status, 2);
const bad = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--spec", "../x"]);
assert.equal(bad.status, 3);
assert.equal(bad.json.ok, false);
assert.match(bad.json.message, /spec/);
assert.deepEqual(fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR) : [], []);
} finally {
fresh();
}
});
test("delete-handoff removes both files and refuses a bad id or no flag", () => {
fresh();
try {
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
fs.writeFileSync(made.path, DOC);
const done = run(["delete-handoff", "--handoff", made.id]);
assert.equal(done.status, 0, done.stderr);
assert.deepEqual(done.json, { ok: true, removed: [made.id + ".md", made.id + ".json"] });
assert.deepEqual(fs.readdirSync(HANDOFFS_DIR), []);
const bad = run(["delete-handoff", "--handoff", "../evil"]);
assert.equal(bad.status, 3);
assert.equal(bad.json.ok, false);
assert.match(bad.json.message, /not a handoff id/);
assert.equal(run(["delete-handoff"]).status, 2);
assert.equal(run(["delete-handoff", "--handoff"]).status, 2);
} finally {
fresh();
}
});
/* ------------------------------------------------- the dashboard's scan */
// Open a dashboard in REPO (and stop it after), returning its state and a getter for pages.
async function withDashboard(fn) {
const opened = run(["open", "--no-open", "--workflow", "dashboard"]);
assert.equal(opened.status, 0, opened.stderr);
const s = sessionUrl(opened.json.url);
const get = (pathname) => fetch(`${s.base}${pathname}`, { headers: { cookie: s.cookie, connection: "close" } });
try {
return await fn({ sid: opened.json.sid, session: opened.json.session, get });
} finally {
run(["stop", "--session", opened.json.sid]);
}
}
const readStateOf = (session) => JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
test("a dashboard open scans this checkout's handoffs and the folder; other workflows do not", async () => {
fresh();
try {
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"]).json;
fs.writeFileSync(made.path, DOC);
await withDashboard(({ session }) => {
const scan = readStateOf(session).scan;
assert.equal(scan.handoffs.length, 1);
assert.equal(scan.handoffs[0].id, made.id);
assert.equal(scan.handoffs[0].title, "Lunch vote");
assert.equal(scan.handoffs[0].next, "Wire the vote button to the tally, then test it.");
assert.equal(scan.handoffsDir, HANDOFFS_DIR);
});
const quick = run(["open", "--no-open", "--workflow", "quick-task"]);
try {
assert.equal(readStateOf(quick.json.session).scan, undefined, "no scan, so no handoffs, off the dashboard");
} finally {
run(["stop", "--session", quick.json.sid]);
}
} finally {
fresh();
}
});
test("GET /handoff serves a scanned handoff's document and nothing else", async () => {
fresh();
try {
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"]).json;
fs.writeFileSync(made.path, DOC);
const unscanned = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
fs.writeFileSync(unscanned.path, DOC);
await withDashboard(async ({ get }) => {
// The two above were both on disk when the dashboard opened, so use a third made afterwards as "unscanned".
const later = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
fs.writeFileSync(later.path, DOC);
const ok = await get(`/handoff?id=${made.id}`);
assert.equal(ok.status, 200);
assert.match(ok.headers.get("content-type"), /^text\/markdown/);
assert.equal(ok.headers.get("cache-control"), "no-store");
assert.equal(await ok.text(), DOC);
assert.equal((await get(`/handoff?id=${later.id}`)).status, 404, "valid but not scanned");
assert.equal((await get("/handoff?id=../x")).status, 404);
assert.equal((await get("/handoff")).status, 404);
});
// A used handoff drops out of the next scan, so it is no longer served.
store.markHandoffUsed(made.id);
await withDashboard(async ({ get }) => {
assert.equal((await get(`/handoff?id=${made.id}`)).status, 404, "used");
});
} finally {
fresh();
}
});
test("a __pickup round trip prints the hop, marks the handoff used, and the next dashboard scan drops it", async () => {
fresh();
try {
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"]).json;
fs.writeFileSync(made.path, DOC);
const opened = run(["open", "--no-open", "--workflow", "dashboard"]);
const s = sessionUrl(opened.json.url);
try {
const res = await fetch(`${s.base}/submit`, {
method: "POST",
headers: { "content-type": "application/json", cookie: s.cookie, connection: "close" },
body: JSON.stringify({ actions: [{ i: "__pickup", type: "pickup", handoff: made.id }], reply: "pick up" }),
});
assert.equal(res.status, 200);
const got = run(["wait", "--session", opened.json.sid, "--seconds", "10"]);
assert.equal(got.status, 0, got.stderr);
assert.match(got.json.resume, /--workflow quick-task$/);
assert.equal(got.json.handoffFile, made.path);
assert.ok(JSON.parse(fs.readFileSync(path.join(HANDOFFS_DIR, made.id + ".json"), "utf8")).usedAt, "the .json now has usedAt");
assert.ok(fs.existsSync(made.path), "the document stays until the sweep");
const back = run(["open", "--resume", opened.json.sid, "--no-open", "--workflow", "dashboard"]);
assert.equal(back.status, 0, back.stderr);
assert.deepEqual(readStateOf(opened.json.session).scan.handoffs, [], "a used handoff is no longer listed");
} finally {
run(["stop", "--session", opened.json.sid]);
}
} finally {
fresh();
}
});
test("a __delete with a handoff round-trips like a spec delete: no resume, no skillFile", async () => {
fresh();
try {
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
fs.writeFileSync(made.path, DOC);
const opened = run(["open", "--no-open", "--workflow", "dashboard"]);
const s = sessionUrl(opened.json.url);
try {
const res = await fetch(`${s.base}/submit`, {
method: "POST",
headers: { "content-type": "application/json", cookie: s.cookie, connection: "close" },
body: JSON.stringify({ actions: [{ i: "__delete", type: "delete", handoff: made.id }], reply: "delete it" }),
});
assert.equal(res.status, 200);
const got = run(["wait", "--session", opened.json.sid, "--seconds", "10"]);
assert.equal(got.status, 0, got.stderr);
assert.equal(got.json.actions[0].handoff, made.id);
assert.equal(got.json.resume, undefined);
assert.equal(got.json.skillFile, undefined);
assert.equal(got.json.handoffFile, undefined);
} finally {
run(["stop", "--session", opened.json.sid]);
}
} finally {
fresh();
}
});
test.after(() => fs.rmSync(REPO, { recursive: true, force: true }));
+45 -1
View File
@@ -7,7 +7,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { parseArgs } from "../src/web-console/lib.mjs";
import { parseArgs } from "../src/web-console/files.mjs";
import { BASE, cli, consoleSession, cookieFor, ENV, HOME, payload, ROOT } from "./web-console-test-helpers.mjs";
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
@@ -182,3 +182,47 @@ test("a fresh open whose --file is refused leaves no session folder behind", ()
const after = fs.readdirSync(sessionsDir).filter((n) => !before.has(n));
assert.deepEqual(after, [], "no orphan session folders");
});
// Show me it working: an image block may only point at a picture the agent
// saved directly inside the session's shots/ folder, and only a real one.
test("an image block outside the session's shots folder, or not an image, is refused", () => {
const s = consoleSession(["--file", payload("shots-safety.json", BASE)]);
try {
const shots = path.join(s.session, "shots");
fs.mkdirSync(shots, { recursive: true });
const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(32)]);
const outside = path.join(HOME, "outside-shot.png");
fs.writeFileSync(outside, png);
fs.writeFileSync(path.join(s.session, "beside.png"), png);
fs.writeFileSync(path.join(shots, "renamed.png"), "just some text, not a picture\n");
fs.writeFileSync(path.join(shots, "huge.png"), Buffer.concat([png, Buffer.alloc(6 * 1024 * 1024)]));
const cases = [
["../../outside-shot.png", /outside the session's shots\/ folder/],
[outside, /outside the session's shots\/ folder/],
["beside.png", /outside the session's shots\/ folder/],
["shots/missing.png", /does not exist/],
["shots/renamed.png", /not a PNG image/],
["shots/huge.png", /larger than 5 MB/],
];
let linked = false;
try {
fs.symlinkSync(outside, path.join(shots, "link.png"), "file");
linked = true;
} catch {
// Windows without the symlink privilege: the realpath check is still covered by the cases above.
}
if (linked) cases.push(["shots/link.png", /outside the session's shots\/ folder/]);
for (const [image, why] of cases) {
const patch = { docs: [{ id: "shown", title: "Shown", blocks: [{ id: "b1", image, alt: "The page" }] }] };
const res = cli(["post", "--session", s.sid, "--file", payload("shots-bad.json", patch)], { expectFail: true });
assert.equal(res.status, 3, image);
assert.match(res.stderr, why, image);
}
const both = { docs: [{ id: "shown", title: "Shown", blocks: [{ id: "b1", image: "shots/renamed.png", md: "x" }] }] };
const res = cli(["post", "--session", s.sid, "--file", payload("shots-both.json", both)], { expectFail: true });
assert.equal(res.status, 3);
assert.match(res.stderr, /cannot also carry "md" or "file"/);
} finally {
cli(["stop", "--session", s.sid]);
}
});
+13
View File
@@ -783,6 +783,19 @@ test("a finish is refused while its command still has a placeholder", () => {
assert.match(res.stderr, /placeholder/);
});
// The Subagents tab would otherwise spin on a helper long after the session ended.
test("a finish is refused while a reported helper still shows as running", () => {
const helper = (state, result) => ({ id: "h1", title: "Check the tests", ask: "Run them.", state, ...(result ? { result } : {}) });
const running = cli(["post", "--session", sid, "--file", payload("fin-h-run.json", { helpers: [helper("running")], finish: { headline: "Done", command: "/x" } })], {
expectFail: true,
});
assert.equal(running.status, 3);
assert.match(running.stderr, /still shows as running/);
assert.match(running.stderr, /"h1"/);
const settled = cli(["post", "--session", sid, "--file", payload("fin-h-done.json", { helpers: [helper("done", "All pass.")], finish: { headline: "Done", command: "/x" } })]);
assert.equal(settled.status, 0);
});
test("a finish faces the same jargon and completion-marker scan as everything else", () => {
const jargon = cli(
["post", "--session", sid, "--file", payload("fin-j.json", { finish: { headline: "The grilling is over", command: "/x" } })],
+307 -48
View File
@@ -32,6 +32,7 @@ import {
sortAttachments,
cardAvailability,
cardPresentation,
defaultSpec,
CATALOG_GROUPS,
CONTINUE_IN_CONSOLE,
CONSOLE_WORKFLOWS,
@@ -46,6 +47,13 @@ import {
handoffShape,
handoffText,
launchReply,
launchTarget,
deleteAction,
deleteReply,
chipDetail,
deleteSummary,
FIXED_REASON,
isDeletableSpecDir,
MAX_NOTE_IMAGES,
noteAction,
noteReplyLines,
@@ -61,6 +69,14 @@ import {
SPEC_STATE_LABELS,
STALE_MS,
STOP_REPLY,
STOP_HANDOFF_REPLY,
stopAction,
pickupAction,
pickupReply,
deleteHandoffAction,
deleteHandoffReply,
handoffCopyText,
handoffAge,
verdictLabel,
verdictText,
lastOpenCard,
@@ -131,29 +147,33 @@ import {
import {
appendLedger,
attachmentName,
chatReplyLines,
checkDocument,
initialWorkspace,
insideGitRepo,
pendingFiles,
latestOpenCaps,
pendingWorkspaceChanges,
PROTECTED_CONSOLE_FILES,
readLedger,
repoRoots,
} from "../src/web-console/sessions.mjs";
import { scanProject, removeSpec, SPEC_STATES } from "../src/web-console/scan.mjs";
import { validate } from "../src/web-console/patches.mjs";
import { chatReplyLines } from "../src/web-console/inbox.mjs";
import {
initialWorkspace,
pendingWorkspaceChanges,
readWorkspaceCursor,
WORKSPACE_FILE,
writeWorkspaceCursor,
} from "../src/web-console/workspace.mjs";
import {
latestOpenCaps,
readSubagentCursor,
readSubagentSetting,
readWorkspaceCursor,
resetSubagentCursor,
writeSubagentCursor,
writeSubagentSetting,
repoRoots,
scanProject,
SPEC_STATES,
validate,
WORKSPACE_FILE,
writeWorkspaceCursor,
} from "../src/web-console/lib.mjs";
} from "../src/web-console/settings.mjs";
import { ROOT, HOME, cli, PDF, postPatch, ask } from "./web-console-test-helpers.mjs";
import { joinedCss } from "./css-helpers.mjs";
// Someone who worked the whole session in the browser should land back in it.
// Every Plan2Code skill ships a console, so the sentence goes on all of
@@ -206,34 +226,17 @@ test("every console workflow the page names ships the console", () => {
assert.ok(fs.existsSync(path.join(dir, "console.mjs")), `${skill} must bundle the console`);
assert.ok(fs.existsSync(path.join(dir, "building.md")), `${skill} must bundle building.md`);
}
// And the other way round: a skill that ships the console but is missing
// from the list would hand off a bare command, and its next session would
// ask the interface question of someone who was already in the browser.
for (const skill of fs.readdirSync(path.join(ROOT, "skills"))) {
if (!fs.existsSync(path.join(ROOT, "skills", skill, "references", "web-console"))) continue;
assert.ok(CONSOLE_WORKFLOWS.includes("/" + skill), `${skill} ships the console but is not in CONSOLE_WORKFLOWS`);
}
});
// The dashboard draws its cards from the page's own catalog, so the catalog
// is the contract: every card has to be a skill that really installs, every
// installed skill has to be a card (a skill that is missing launches nothing),
// and every card's workflow has to be one the console names.
test("the dashboard catalog is exactly the set of installable skills", () => {
// The dashboard draws its cards from the page's own catalog, so every card
// has to be filled in and launch into a real SKILL.md. Which skills have a
// card is held against install.js in test-web-console-skills.mjs.
test("every dashboard card is filled in and launches a real skill", () => {
const skillsDir = path.join(ROOT, "skills");
const installed = fs.readdirSync(skillsDir).filter((d) => fs.statSync(path.join(skillsDir, d)).isDirectory());
const cataloged = SKILL_CATALOG.map((e) => e.skill);
// The dashboard itself is the hub, not a card.
assert.ok(!cataloged.includes("plan2code"), "the dashboard does not launch itself");
assert.ok(!SKILL_CATALOG.some((e) => e.skill === "plan2code"), "the dashboard does not launch itself");
for (const skill of installed) {
if (skill === "plan2code") continue;
assert.ok(cataloged.includes(skill), `${skill} installs but has no card on the dashboard`);
}
for (const e of SKILL_CATALOG) {
assert.ok(installed.includes(e.skill), `${e.skill} is a card but does not install`);
assert.ok(CONSOLE_WORKFLOWS.includes(e.command), `${e.command} must be a console workflow`);
assert.ok(CATALOG_GROUPS.some((g) => g.id === e.group), `${e.skill}: unknown group ${e.group}`);
for (const field of ["workflow", "chip", "title", "blurb"]) {
assert.ok(e[field] && String(e[field]).trim(), `${e.skill}.${field} must be filled in`);
@@ -573,6 +576,42 @@ test("the stop request cannot be mistaken for a brief request", () => {
assert.doesNotMatch(STOP_REPLY, /\b(brief|recap|minutes)\b/i);
});
test("handoff helpers: actions carry only the id, replies and copy text are plain, ages round at the boundaries", () => {
const h = { id: "2026-10-17-1152-handoff", title: "Lunch vote" };
assert.deepEqual(pickupAction(h), { i: "__pickup", type: "pickup", handoff: h.id });
assert.deepEqual(deleteHandoffAction(h), { i: "__delete", type: "delete", handoff: h.id });
assert.equal(pickupReply(h), 'Pick up the handoff "Lunch vote" right here in this session.');
assert.equal(deleteHandoffReply(h), 'Delete the handoff "Lunch vote" for good, right here in this session.');
const file = "/home/sam/.plan2code/handoffs/2026-10-17-1152-handoff.md";
assert.equal(handoffCopyText(file), `Read the handoff at ${file} and carry on with its Next task.`);
for (const line of [pickupReply(h), deleteHandoffReply(h), handoffCopyText(file)]) {
assert.ok(!line.includes("—"), "no em dash");
assert.doesNotMatch(line, /(brief|recap|minutes)/i);
}
const now = Date.parse("2026-10-17T12:00:00Z");
const ago = (ms) => handoffAge(new Date(now - ms).toISOString(), now);
assert.equal(ago(0), "just now");
assert.equal(ago(59 * 1000), "just now");
assert.equal(ago(60 * 1000), "1 min ago");
assert.equal(ago(59 * 60 * 1000), "59 min ago");
assert.equal(ago(60 * 60 * 1000), "1 h ago");
assert.equal(ago(23 * 3600 * 1000), "23 h ago");
assert.equal(ago(24 * 3600 * 1000), "1 day ago");
assert.equal(ago(3 * 24 * 3600 * 1000), "3 days ago");
assert.equal(handoffAge("not a date", now), "");
});
test("the stop-with-a-handoff request is its own plain line, and stopAction sets the flag only when asked", () => {
assert.notEqual(STOP_HANDOFF_REPLY, STOP_REPLY);
assert.match(STOP_HANDOFF_REPLY, /handoff/i);
assert.doesNotMatch(STOP_HANDOFF_REPLY, /\b(brief|recap|minutes)\b/i);
assert.ok(!STOP_HANDOFF_REPLY.includes("—"), "no em dash in a line that rides to the agent");
assert.ok(!("handoff" in stopAction({})), "a plain stop carries no handoff key");
assert.deepEqual(stopAction({}), { i: "__stop", type: "stop" });
assert.equal(stopAction({ handoff: true }).handoff, true);
assert.equal(stopAction({ handoff: true }).type, "stop");
});
// Nineteen highlight colors, four shades each, two themes: far too many to
// trust to eyeballing, and a failure here is a label nobody can read.
const hexLum = (h) => {
@@ -634,6 +673,15 @@ test("the project scan reads each spec's pipeline stage off its files", () => {
"PLAN-DRAFT-20260923.md": "# draft\n\n**Status:** Phase 3 Complete - Resume at Phase 4\n",
"pathfinder/map.md": "**Status:** Cleared\n",
});
// The other Status forms specs.mjs accepts read the same, CRLF included.
fakeSpec(root, "planned-bold-colon", { "PLAN-DRAFT-20260923.md": "# draft\n\n**Status**: Complete\n" });
fakeSpec(root, "draft-mid-plan-bold-colon", {
"PLAN-DRAFT-20260923.md": "# draft\r\n\r\n**Status**: Phase 3 Complete - Resume at Phase 4\r\n",
});
fakeSpec(root, "mapped-bold-colon", {
"pathfinder/map.md": "**Status**: Cleared\n",
"pathfinder/questions/00-a.md": "State: resolved\n",
});
fakeSpec(root, "documented", {
"overview.md": "# spec\n",
"phase-1.md": "- [ ] Task one\n- [ ] Task two\n",
@@ -648,6 +696,19 @@ test("the project scan reads each spec's pipeline stage off its files", () => {
"phase-1.md": "- [x] Task one\n- [x] Task two\n",
});
fakeSpec(root, "weird", { "DESIGN.md": "# notes\n" });
fakeSpec(root, "diagnosed", { "DIAGNOSIS-20261016.md": "# Diagnosis: rows go missing\n\n**Status:** Diagnosed\n" });
// Once planning starts on a diagnosed bug, the usual states win.
fakeSpec(root, "diagnosed-then-planned", {
"DIAGNOSIS-20261016.md": "# Diagnosis\n\n**Status:** Diagnosed\n",
"PLAN-DRAFT-20261017.md": "# draft\n\n**Status:** Complete\n",
});
// Quick Task marks the write-up Fixed: a finished bug, not loose files.
fakeSpec(root, "diagnosed-then-fixed", { "DIAGNOSIS-20261016.md": "# Diagnosis\n\n**Status:** Fixed\n" });
// A fixed bug someone then started planning around is mid-plan again.
fakeSpec(root, "fixed-then-conversation", {
"DIAGNOSIS-20261016.md": "# Diagnosis\n\n**Status:** Fixed\n",
"PLAN-CONVERSATION-20261017.md": "# conversation\n",
});
fs.writeFileSync(path.join(root, "AGENTS.md"), "# agents\n");
const scan = scanProject(root);
@@ -658,10 +719,17 @@ test("the project scan reads each spec's pipeline stage off its files", () => {
["mapped", "mapped"],
["planned", "planned"],
["draft-mid-plan", "mapped"],
["planned-bold-colon", "planned"],
["draft-mid-plan-bold-colon", "mapped"],
["mapped-bold-colon", "mapped"],
["documented", "documented"],
["building", "building"],
["built", "built"],
["weird", "unrecognized"],
["diagnosed", "diagnosed"],
["diagnosed-then-planned", "planned"],
["diagnosed-then-fixed", "fixed"],
["fixed-then-conversation", "mapped"],
]) {
assert.ok(byName[name], `spec ${name} was scanned`);
assert.equal(byName[name].state, state, `spec ${name}`);
@@ -671,6 +739,12 @@ test("the project scan reads each spec's pipeline stage off its files", () => {
assert.equal(byName.exploring.detail, "1 of 2 decisions made");
assert.equal(byName.building.detail, "1 of 2 tasks done");
assert.equal(byName["draft-mid-plan"].detail, "plan draft, resume at Phase 4");
assert.equal(byName["draft-mid-plan-bold-colon"].detail, "plan draft, resume at Phase 4");
assert.equal(byName.diagnosed.detail, "bug diagnosed, not fixed");
assert.equal(byName["diagnosed-then-fixed"].detail, "bug fixed");
for (const state of SPEC_STATES) assert.ok(SPEC_STATE_LABELS[state], `state ${state} has a picker label`);
assert.equal(SPEC_STATE_LABELS.diagnosed, "Bug diagnosed");
assert.equal(SPEC_STATE_LABELS.fixed, "Bug fixed");
// A pathfinder folder with no map yet is still mid-exploration; a map
// whose status line is missing or unreadable is too.
@@ -689,6 +763,130 @@ test("the project scan reads each spec's pipeline stage off its files", () => {
}
});
// Deleting a spec from the dashboard: the page offers only folders it can
// name exactly, and the agent's `delete-spec` refuses anything else on disk.
test("isDeletableSpecDir takes exactly specs/<one name>", () => {
for (const ok of ["specs/lunch-vote", "specs/codebase-health", "specs/a b"]) {
assert.equal(isDeletableSpecDir(ok), true, ok);
}
for (const bad of [
"specs/../x",
"specs/..",
"specs/.",
"specs/.hidden",
"specs/a/b",
"specs/",
"specs",
"specs--completed/x",
"/specs/x",
"C:/specs/x",
"specs\\x",
"other/x",
"",
undefined,
null,
]) {
assert.equal(isDeletableSpecDir(bad), false, String(bad));
}
});
test("a delete is a session action naming the folder, and its reply says it is for good", () => {
const spec = { dir: "specs/lunch-vote", name: "lunch-vote", state: "building", detail: "1 of 2 tasks done", files: 3, touched: 1 };
assert.deepEqual(deleteAction(spec), { i: "__delete", type: "delete", spec: "specs/lunch-vote" });
const reply = deleteReply(spec);
assert.match(reply, /specs\/lunch-vote\//);
assert.match(reply, /for good/);
assert.doesNotMatch(reply, /\b(brief|recap|minutes)\b/i);
const sum = deleteSummary(spec);
assert.equal(sum.folder, "specs/lunch-vote/");
assert.equal(sum.stage, `${SPEC_STATE_LABELS.building}: 1 of 2 tasks done`);
assert.equal(sum.files, "3 files");
assert.equal(sum.touched, 1);
assert.equal(deleteSummary({ ...spec, files: 1 }).files, "1 file");
assert.equal(deleteSummary({ ...spec, files: undefined }).files, "");
assert.equal(deleteSummary({ ...spec, detail: "" }).stage, SPEC_STATE_LABELS.building);
});
test("a fixed bug says so once: on its chip, in the delete dialog and on its greyed cards", () => {
const fixed = { dir: "specs/old-bug", name: "old-bug", state: "fixed", detail: "bug fixed", files: 1, touched: 1 };
assert.equal(deleteSummary(fixed).stage, "Bug fixed");
const building = { dir: "specs/lunch-vote", name: "lunch-vote", state: "building", detail: "1 of 2 tasks done" };
assert.equal(deleteSummary(building).stage, `${SPEC_STATE_LABELS.building}: 1 of 2 tasks done`);
assert.equal(chipDetail(fixed), "");
assert.equal(chipDetail(building), "1 of 2 tasks done");
assert.equal(chipDetail({ ...building, detail: undefined }), "");
assert.match(FIXED_REASON, /Delete button/);
assert.doesNotMatch(FIXED_REASON, /✕/);
});
test("scanProject counts each spec's files", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-scan-files-"));
try {
fakeSpec(root, "three", { "overview.md": "# o\n", "phase-1.md": "- [ ] **Task 1.1:** a\n", "pathfinder/map.md": "# m\n" });
fakeSpec(root, "one", { "DESIGN.md": "# d\n" });
const byName = Object.fromEntries(scanProject(root).specs.map((s) => [s.name, s]));
assert.equal(byName.three.files, 3);
assert.equal(byName.one.files, 1);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test("removeSpec deletes one spec folder and refuses everything else", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-remove-spec-"));
const outside = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-remove-outside-"));
try {
fakeSpec(root, "keep", { "overview.md": "# keep\n" });
fakeSpec(root, "gone", { "overview.md": "# gone\n", "pathfinder/map.md": "# m\n" });
fs.mkdirSync(path.join(root, "specs--completed", "old"), { recursive: true });
fs.writeFileSync(path.join(outside, "precious.md"), "do not touch\n");
assert.deepEqual(removeSpec(root, "specs/gone"), { ok: true, removed: "specs/gone" });
assert.equal(fs.existsSync(path.join(root, "specs", "gone")), false);
assert.equal(fs.existsSync(path.join(root, "specs", "keep", "overview.md")), true);
for (const bad of ["specs/../specs--completed/old", "specs--completed/old", "specs/keep/pathfinder", "specs/missing", "specs"]) {
assert.throws(() => removeSpec(root, bad), Error, bad);
}
assert.equal(fs.existsSync(path.join(root, "specs--completed", "old")), true);
// A spec folder that is a link to somewhere else is refused, and what it
// points at survives.
fs.symlinkSync(outside, path.join(root, "specs", "linked"), "junction");
assert.throws(() => removeSpec(root, "specs/linked"), /outside|link/i);
assert.equal(fs.existsSync(path.join(outside, "precious.md")), true);
// A file named like a spec is not a spec folder.
fs.writeFileSync(path.join(root, "specs", "note.md"), "x\n");
assert.throws(() => removeSpec(root, "specs/note.md"), /folder/i);
} finally {
fs.rmSync(root, { recursive: true, force: true });
fs.rmSync(outside, { recursive: true, force: true });
}
});
test("delete-spec removes a spec from the worktree it runs in, and exits 3 with the reason when it refuses", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-delete-cli-"));
try {
fakeSpec(root, "scratch", { "overview.md": "# s\n" });
const done = cli(["delete-spec", "--spec", "specs/scratch"], { cwd: root });
assert.equal(done.status, 0, done.stderr);
assert.equal(done.json.ok, true);
assert.equal(done.json.removed, "specs/scratch");
assert.equal(fs.existsSync(path.join(root, "specs", "scratch")), false);
const refused = cli(["delete-spec", "--spec", "specs/../AGENTS.md"], { cwd: root, expectFail: true });
assert.equal(refused.status, 3);
assert.equal(refused.json.ok, false);
assert.ok(refused.json.message);
const usage = cli(["delete-spec"], { cwd: root, expectFail: true });
assert.equal(usage.status, 2);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
// The dashboard's Git card offers to start a repository when the folder
// is not one. The scan answers that from the filesystem, never from a git
// process, and a linked worktree (a .git file, not a folder) must count.
@@ -864,6 +1062,49 @@ test("the dashboard matrix lights only the cards a spec state allows", () => {
assert.equal(on("plan2code-1b-revise-plan", scan, sel("built")), false);
assert.equal(on("plan2code-4-finalize", scan, sel("built")), true);
// A diagnosed bug: Quick Task (its next step) and Plan, never the build steps.
for (const skill of ["plan2code-quick-task", "plan2code-1-plan", "plan2code-review", "plan2code-diagnose"]) {
assert.equal(on(skill, scan, sel("diagnosed")), true, `${skill} on for a diagnosed bug`);
}
for (const skill of [
"plan2code-0-pathfinder",
"plan2code-1b-revise-plan",
"plan2code-2-document",
"plan2code-3-implement",
"plan2code-3-implement-review",
"plan2code-4-finalize",
]) {
assert.equal(on(skill, scan, sel("diagnosed")), false, `${skill} off for a diagnosed bug`);
}
assert.equal(cardAvailability(entry("plan2code-quick-task"), scan, sel("diagnosed")).next, true);
assert.ok(!cardAvailability(entry("plan2code-1-plan"), scan, sel("diagnosed")).next);
assert.ok(!cardAvailability(entry("plan2code-quick-task"), scan, sel("building")).next);
// Quick Task carries the folder only for a diagnosed bug; spec cards always do.
assert.equal(launchTarget(entry("plan2code-quick-task"), sel("diagnosed")).dir, "specs/x");
assert.equal(launchTarget(entry("plan2code-quick-task"), sel("building")), null);
assert.equal(launchTarget(entry("plan2code-1-plan"), sel("diagnosed")).dir, "specs/x");
assert.equal(launchTarget(entry("plan2code-review"), sel("diagnosed")), null);
assert.equal(launchTarget(entry("plan2code-1-plan"), null), null);
// A fixed bug is finished: no pipeline card, and Quick Task starts fresh.
for (const skill of [
"plan2code-0-pathfinder",
"plan2code-1-plan",
"plan2code-1b-revise-plan",
"plan2code-2-document",
"plan2code-3-implement",
"plan2code-3-implement-review",
"plan2code-4-finalize",
]) {
const av = cardAvailability(entry(skill), scan, sel("fixed"));
assert.equal(av.on, false, `${skill} off for a fixed bug`);
assert.ok(av.reason, `${skill} says why it is off for a fixed bug`);
}
assert.equal(on("plan2code-quick-task", scan, sel("fixed")), true);
assert.ok(!cardAvailability(entry("plan2code-quick-task"), scan, sel("fixed")).next);
assert.equal(launchTarget(entry("plan2code-quick-task"), sel("fixed")), null);
// A greyed card always says why, and a selected spec's next step is marked.
assert.ok(cardAvailability(entry("plan2code-3-implement"), scan, sel("exploring")).reason);
assert.equal(cardAvailability(entry("plan2code-3-implement"), scan, sel("documented")).next, true);
@@ -903,6 +1144,29 @@ test("dashboard card presentation follows the current picker selection", () => {
assert.equal(planned.detail, "plan drafted");
});
test("the picker never opens on a fixed bug", () => {
const fixed = { dir: "specs/old-bug", name: "old-bug", state: "fixed", detail: "bug fixed" };
const live = { dir: "specs/lunch-vote", name: "lunch-vote", state: "documented", detail: "2 phases, 8 tasks ready" };
assert.equal(defaultSpec([fixed, live]), live);
assert.equal(defaultSpec([live, fixed]), live);
assert.equal(defaultSpec([fixed]), null);
assert.equal(defaultSpec([]), null);
assert.equal(defaultSpec(undefined), null);
// The agent's recommendation describes the default pick, not the fixed bug
// the server listed first.
const entry = (skill) => SKILL_CATALOG.find((e) => e.skill === skill);
const scan = { hasAgents: true, specs: [fixed, live] };
const menu = { recommend: "plan2code-3-implement", details: { "plan2code-3-implement": "Phase 1 of 2 is next" } };
const shown = cardPresentation(entry("plan2code-3-implement"), scan, live, menu);
assert.equal(shown.recommended, true);
assert.equal(shown.detail, "Phase 1 of 2 is next");
// Only fixed bugs on disk: the default is "start from scratch".
const onlyFixed = { hasAgents: true, specs: [fixed] };
const fresh = cardPresentation(entry("plan2code-0-pathfinder"), onlyFixed, null, { recommend: "plan2code-0-pathfinder" });
assert.equal(fresh.recommended, true);
});
test("the launch reply names the picked spec", () => {
const e = SKILL_CATALOG.find((x) => x.skill === "plan2code-3-implement");
assert.equal(
@@ -1071,6 +1335,8 @@ const CONSOLE_WORKFLOW_LIST = [
"review",
"finalize",
"handoff",
"xray",
"diagnose",
];
test("STARTER_SETS: 3 to 4 starters a set, one without context at least, known lead roles, unique ids", () => {
@@ -1493,7 +1759,6 @@ test("skip: the last open card goes to Send, a middle one to the next unstaged,
test("page: the Workspace dialog, meter pill and new modules are in the page, with no inline styles or scripts", () => {
const dir = path.join(ROOT, "src", "web-console", "public");
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
const app = fs.readFileSync(path.join(dir, "app.js"), "utf8");
for (const id of [
"workspace-modal",
"workspace-title",
@@ -1520,7 +1785,6 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
assert.ok(pill[0].includes('class="meter-track"') && pill[0].includes('class="meter-fill"'));
for (const m of ["workspace.js", "meter.js", "mentions.js", "favicon.js"]) {
assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
assert.match(app, new RegExp(`^import [^;]+ from "\\./${m.replace(".", "\\.")}";`, "m"), `app.js imports ${m}`);
}
// The CSP refuses style attributes and inline script: the new markup has neither.
const added = [
@@ -1532,23 +1796,18 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
assert.doesNotMatch(block, /<script/i);
assert.doesNotMatch(block, /\son[a-z]+=/i, "no inline event handlers");
}
assert.doesNotMatch(app, /setAttribute\(\s*["']style["']/, "no style attributes set from script");
});
test("page: the footer label opens the workspace instead of copying", () => {
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
assert.ok(app.includes('$("footer-where").addEventListener("click", openWorkspace)'));
assert.doesNotMatch(app, /\$\("footer-where"\)\.addEventListener\("blur"/, "the copied-state blur handler is gone");
assert.ok(app.includes('"Open workspace: " + label'));
assert.ok(app.includes("footerLabel(") && app.includes("FOOTER_TIERS"));
// The dashboard keeps the footer for the workspace label, minus the summary and Send.
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
assert.ok(app.includes('foot.classList.toggle("is-dash", Boolean(isDashboard() && !finish()))'));
assert.doesNotMatch(app, /foot\.hidden = Boolean\(isDashboard\(\)/, "the dashboard no longer hides the whole footer");
const css = joinedCss();
assert.match(css, /\.footer\.is-dash \.footer-summary,\s*\.footer\.is-dash \.footer-actions \{ display: none; \}/);
assert.match(css, /\.footer\.is-dash \.footer-where:not\(\[hidden\]\) \{ display: block;/, "narrow screens keep the label on the dashboard");
// Every typing place offers @name suggestions.
assert.equal((app.match(/attachMentions\((ta|input)\);/g) || []).length, 4, "Ask, card note, notes panel, text answer");
// Every typing place offers @name suggestions: the Ask pane and the notes panel
// (screens/ask.js) and the card note and text answer (screens/cards.js).
const read = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", f), "utf8");
const count = (text) => (text.match(/attachMentions\((ta|input)\);/g) || []).length;
assert.equal(count(read("ask.js")) + count(read("cards.js")), 4, "Ask, card note, notes panel, text answer");
});
// The quoted flags between -NoProfile and -EncodedCommand, whichever quote style.
@@ -1806,7 +2065,7 @@ test("subagents: the store round-trips per project and workflow under the consol
try {
const project = path.join(home, "My Repo");
const script = `
const lib = await import(${JSON.stringify(new URL("../src/web-console/lib.mjs", import.meta.url).href)});
const lib = await import(${JSON.stringify(new URL("../src/web-console/settings.mjs", import.meta.url).href)});
const project = ${JSON.stringify(project)};
lib.saveSubagentStoreEntry(project, "implement", { on: true, instruction: "Mine", max: 5 });
const flipped = project.replace(/My Repo$/, "MY REPO");
+188
View File
@@ -0,0 +1,188 @@
// Page tests for the Ask tab: a Quick question and the agent's reply, the
// starters, a retry after a failed send, a new conversation, a picture attached
// to a note, and the Subagents tab. Run with:
// node --test scripts/test-web-console-page-ask.mjs
//
// Each test drives the real console in a real Chrome or Edge through
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
// session per test.
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, itemCard, textOf } from "./page-test-helpers.mjs";
import { reportedHelper } from "./web-console-test-helpers.mjs";
const suite = pageSuite(test);
// A plan session on the person's turn: one text question, the agent listening.
const PLAN_QUESTION = {
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
agent: { status: "waiting" },
};
// A real 1x1 PNG. The page decodes and re-encodes every picture before it
// uploads, so the fake JPEG the server tests use would be refused here.
const PNG = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
"base64"
);
// The one send `wait` hands the agent; fails the test when nothing arrived.
function collect(s) {
const got = s.wait(10);
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
return got;
}
// The questions in a send's chat entries (the first send also carries the
// conversation's start, which is not a question).
const messages = (got) => got.chat.filter((e) => e.kind === "message");
// Opens the Ask tab and returns its question box.
async function openAsk(s) {
await s.page.locator("nav").getByRole("button", { name: "Ask", exact: true }).click();
const box = s.page.locator("#ask-input");
await box.waitFor();
return box;
}
// Types a question and presses Send in the Ask pane.
async function askQuestion(s, text) {
const box = s.page.locator("#ask-input");
await box.fill(text);
await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click();
}
// What a person sees break: a question typed in Ask that never reaches the
// agent, or an answer that never shows.
test("a Quick question typed in Ask reaches the agent under chat, and the agent's reply shows in the pane", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openAsk(s);
await askQuestion(s, "Where does the export live?");
const got = collect(s);
assert.equal(got.type, "chat");
const [asked, ...more] = messages(got);
assert.equal(more.length, 0, "one question, one message");
assert.equal(asked.text, "Where does the export live?");
assert.match(got.reply, /^Quick question: Where does the export live\?$/m);
// The question is in the pane, and the box is empty for the next one.
await s.page.locator(".ask-row.person").getByText("Where does the export live?").waitFor();
assert.equal(await s.page.locator("#ask-input").inputValue(), "");
s.post({ chat: { replies: [{ id: "r1", re: asked.seq, conversation: 1, md: "It lives in `exports/`." }] } });
const reply = s.page.locator(".ask-row.agent");
await reply.getByText("It lives in").waitFor();
assert.match(await textOf(reply), /exports\//);
assert.match(await textOf(s.page.locator(".ask-counter")), /1/);
});
// What a person sees break: starters that send for them, or that are missing
// from an empty conversation.
test("an empty Ask offers starters, a click only fills the box, and nothing is sent until Send", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
const box = await openAsk(s);
const starters = s.page.locator(".ask-starters .ask-starter");
await starters.first().waitFor();
assert.ok((await starters.count()) >= 1, "no starter questions are offered");
const first = (await textOf(starters.first())).trim();
await starters.first().click();
assert.equal(await box.inputValue(), first, "the starter fills the box");
assert.equal(s.wait(1).code === 0, false, "a starter click sent something");
await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click();
assert.deepEqual(messages(collect(s)).map((e) => e.text), [first]);
// With a question in the list the starters are gone.
await s.page.locator(".ask-starters").waitFor({ state: "detached" });
});
// What a person sees break: a question lost when the network hiccups, or
// sent twice when they press Retry.
test("a failed send shows Not sent with Retry, and Retry delivers the question once", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openAsk(s);
// The page's own request fails as a dropped connection would.
await s.page.route("**/chat", (route) => route.abort());
await askQuestion(s, "Is the header row kept?");
const row = s.page.locator(".ask-row.person.pending");
await row.getByText("Not sent").waitFor();
assert.equal(s.wait(1).code === 0, false, "a failed send reached the agent");
await s.page.unroute("**/chat");
await row.getByRole("button", { name: "Retry" }).click();
const got = collect(s);
assert.deepEqual(messages(got).map((e) => e.text), ["Is the header row kept?"]);
await s.page.locator(".ask-row.person:not(.pending)").getByText("Is the header row kept?").waitFor();
assert.equal(s.wait(1).code === 0, false, "the question was sent twice");
});
// What a person sees break: New conversation that leaves the old rows, or
// that does not start the next question in a fresh conversation.
test("New conversation clears the pane back to the starters, and the next question belongs to the new conversation", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openAsk(s);
await askQuestion(s, "First question");
const first = collect(s);
assert.equal(messages(first)[0].conversation, 1);
await s.page.locator(".ask-row.person:not(.pending)").waitFor();
await s.page.getByRole("button", { name: "New conversation" }).click();
await s.page.locator(".ask-row").waitFor({ state: "detached" });
await s.page.locator(".ask-starters").waitFor();
await askQuestion(s, "Second question");
const second = collect(s);
assert.deepEqual(messages(second).map((e) => e.text), ["Second question"]);
assert.equal(messages(second)[0].conversation, 2);
});
// What a person sees break: a picture that shows in the tray but never goes
// to the agent, or goes without the note it belongs to.
test("a picture attached to a note uploads, and the send carries it in the note's images entry", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await itemCard(s.page, "q1").waitFor();
const aside = s.page.locator("#aside");
await aside.locator('input[type="file"]').setInputFiles({ name: "shot.png", mimeType: "image/png", buffer: PNG });
await aside.locator(".attach-thumb.is-ready").waitFor();
await aside.locator("#thread-q1").fill("See the screenshot.");
await s.page.click("#btn-send");
const got = collect(s);
const note = got.actions.find((a) => a.i === "q1" && a.type === "comment");
assert.ok(note, `a note action for q1: ${JSON.stringify(got.actions)}`);
assert.equal(note.text, "See the screenshot.");
assert.equal(note.images.length, 1);
assert.equal(note.images[0].name, "shot.png");
assert.ok(note.images[0].path, "the image names the file the console saved");
});
// What a person sees break: the Subagents tab missing once helpers are
// reported, or showing the wrong state.
test("posting helpers adds a Subagents tab that lists each with its state and result", async (t) => {
const s = await openSession(await suite.browser(), {
t,
workflow: "implement",
payload: { agent: { status: "working", activity: "Task 1 of 2" }, items: PLAN_QUESTION.items },
});
const tab = s.page.locator("nav").getByRole("button", { name: /^Subagents/ });
assert.equal(await tab.count(), 0, "no tab before any helper is reported");
s.post({
helpers: [
reportedHelper("h1", { title: "Read the store helpers", state: "running" }),
reportedHelper("h2", { title: "Check the tests", state: "done", result: "All 9 pass." }),
],
});
await tab.waitFor();
await tab.click();
const card = s.page.locator("#main .sa-card");
await card.getByRole("heading", { name: "Subagents" }).waitFor();
const rows = card.locator(".sa-row");
assert.equal(await rows.count(), 2);
const running = rows.filter({ hasText: "Read the store helpers" });
const done = rows.filter({ hasText: "Check the tests" });
assert.match(await textOf(running.locator(".sa-pill")), /running/i);
assert.match(await textOf(done.locator(".sa-pill")), /done/i);
assert.match(await textOf(done), /All 9 pass\./);
assert.match(await textOf(running), /Find the callers of applyPatch/);
});
+689
View File
@@ -0,0 +1,689 @@
// Page tests for question cards: every kind answered on the page and sent, the
// sign-off card, and a redraw keeping your place. Run with:
// node --test scripts/test-web-console-page-cards.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 { gitInit } from "./skill-script-helpers.mjs";
import { pageSuite, openSession, tempProject, sendAndCollect, itemCard, scrollTopOf } from "./page-test-helpers.mjs";
const suite = pageSuite(test);
test("a session with nothing posted yet shows its starting screen, and stop ends its server", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
assert.match(await s.page.innerText("#main"), /Starting Plan/);
assert.equal(await s.page.locator("#main .pose-stage").count(), 1);
await s.stop();
assert.equal(await s.answers(), false, "the server still answers after stop()");
});
test("a text answer typed on the page reaches the agent as it was typed", async (t) => {
const s = await openSession(await suite.browser(), {
t,
workflow: "plan",
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }] },
});
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
const got = await sendAndCollect(s);
assert.equal(got.type, "submit");
assert.deepEqual(
got.actions.map(({ i, type, text }) => ({ i, type, text })),
[{ i: "q1", type: "answer", text: "audit-export" }]
);
assert.match(got.reply, /audit-export/);
});
// The agent's side of one question: settle what came before, post `item`
// alone, and wait for its card.
async function ask(s, item) {
s.post({ settle: true, items: [item] });
const card = itemCard(s.page, item.id);
await card.waitFor();
return card;
}
// The answer an agent reads for item `id`, without the routing fields.
function answerTo(got, id) {
const action = got.actions.find((a) => a.i === id);
assert.ok(action, `the send carries an answer to ${id}: ${JSON.stringify(got.actions)}`);
const { i, type, kind, ...answer } = action;
assert.equal(type, "answer");
return answer;
}
const opt = (k, text) => ({ k, text, detail: `The ${text.toLowerCase()} option.` });
test("every kind of question card sends the answer shape the agent reads", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
let card = await ask(s, { id: "c1", kind: "choice", title: "Export format", body: "Which format?", options: [opt("A", "CSV"), opt("B", "JSON")] });
await card.getByLabel("JSON").check();
let got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "c1"), { k: "B" });
assert.equal(got.reply, "Export format: B");
card = await ask(s, { id: "c2", kind: "choice", title: "Where it goes", body: "Where?", allowOther: true, options: [opt("A", "Email"), opt("B", "Slack")] });
await card.getByRole("radio", { name: "Something else, in your own words" }).check();
await card.locator("textarea").fill("A shared drive");
got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "c2"), { text: "A shared drive" });
assert.equal(got.reply, "Where it goes: A shared drive");
card = await ask(s, { id: "m1", kind: "multi", title: "Columns", body: "Which?", options: [opt("1", "Date"), opt("2", "User"), opt("3", "Action")], presets: [{ label: "Date and user", ks: ["1", "2"] }] });
await card.getByRole("button", { name: "Date and user" }).click();
await card.getByLabel("Action").check();
await card.locator("textarea").fill("and the IP");
got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "m1"), { ks: ["1", "2", "3"], text: "and the IP" });
assert.equal(got.reply, "Columns: 1, 2, 3; and the IP");
card = await ask(s, { id: "t1", kind: "text", title: "What to call it", body: "A name.", pattern: "^[a-z][a-z0-9-]*$", patternHint: "Lowercase letters, digits and hyphens.", placeholder: "For example: audit-export" });
const field = card.locator("input[type=text]");
// The suggestion is the placeholder without its "For example:" lead-in.
await card.getByRole("button", { name: "Autofill suggestion" }).click();
assert.equal(await field.inputValue(), "audit-export");
await field.fill("Audit Export");
await card.getByText("Lowercase letters, digits and hyphens.").waitFor();
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "a value that breaks the pattern is not sendable");
await field.fill("audit-export");
got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "t1"), { text: "audit-export" });
assert.equal(got.reply, "What to call it: audit-export");
card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
await card.getByRole("button", { name: "Yes" }).click();
got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "y1"), { yes: true });
assert.equal(got.reply, "Keep going: yes");
card = await ask(s, { id: "r1", kind: "recap", title: "What we decided", body: "Is this right?", summary: "- CSV\n- Mondays" });
await card.getByRole("button", { name: "Yes, that is right" }).click();
got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "r1"), { ok: true });
assert.equal(got.reply, "What we decided: confirmed");
card = await ask(s, { id: "k1", kind: "checklist", title: "Set up access", body: "Only you can do these.", steps: ["Create the app", "Paste its key"] });
await card.locator("input[type=checkbox]").first().check();
await card.getByRole("button", { name: "All done" }).click();
got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "k1"), { done: [0], state: "done" });
assert.equal(got.reply, "Set up access: all done; did steps 1");
card = await ask(s, { id: "n1", kind: "menu", title: "What next", body: "Pick one.", options: [opt("1", "Keep planning"), opt("2", "Stop here")] });
await card.getByLabel("Stop here").check();
got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "n1"), { k: "2" });
assert.equal(got.reply, "What next: 2");
const rows = [
{ id: "a", title: "Read the data", body: "x" },
{ id: "b", title: "Write the file", body: "y" },
];
card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Reorder or rename.", rows });
await card.getByRole("button", { name: "No changes" }).click();
got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "l1"), { text: "no changes" });
assert.equal(got.reply, "The steps: no changes");
card = await ask(s, { id: "l2", kind: "list", title: "The steps again", body: "Reorder or rename.", rows });
await card.locator("input[type=text]").first().fill("Read the audit log");
got = await sendAndCollect(s);
assert.deepEqual(
answerTo(got, "l2").rows.map((r) => [r.id, r.title]),
[["a", "Read the audit log"], ["b", "Write the file"]]
);
assert.equal(got.reply, "The steps again: the list: Read the audit log, then Write the file; renamed Read the data to Read the audit log");
s.post({ settle: true, items: [{ id: "x1", kind: "notice", title: "Heads up", body: "The export runs **nightly**." }] });
await s.page.getByText("The export runs").waitFor();
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "a notice alone gives nothing to send");
});
test("a sign-off card opens its document, and each verdict reaches the agent", async (t) => {
const s = await openSession(await suite.browser(), {
t,
workflow: "implement",
payload: {
docs: [{ id: "report", title: "Completion report", blocks: [{ id: "b1", state: "settled", md: "## Summary\n\nPhase 3 adds the /tasks endpoints." }] }],
},
});
const signoff = (id, extra = {}) => ({
id,
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" },
{ id: "discard", label: "Throw it away", danger: true },
],
...extra,
});
let card = await ask(s, signoff("so1"));
await card.getByRole("button", { name: /Read .*Completion report.* in full/ }).click();
await s.page.getByText("Phase 3 adds the /tasks endpoints.").waitFor();
assert.ok(await s.page.getByText("Phase 3 adds the /tasks endpoints.").isVisible(), "the report is on screen");
// The danger verdict is marked as such: here the class is the behaviour.
await s.page.locator("#views").getByRole("button", { name: /^Questions/ }).click();
card = itemCard(s.page, "so1");
assert.match(await card.getByRole("button", { name: "Throw it away" }).getAttribute("class"), /danger/);
assert.doesNotMatch(await card.getByRole("button", { name: "Approve this phase" }).getAttribute("class"), /danger/);
await card.getByRole("button", { name: "Approve this phase" }).click();
let got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "so1"), { verdict: "approve" });
card = await ask(s, signoff("so2"));
await card.getByRole("button", { name: "I want changes" }).click();
await card.locator("textarea").fill("Keep the header row.");
got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "so2"), { verdict: "changes", text: "Keep the header row." });
});
const longText = (n) => Array.from({ length: n }, (_, i) => `Paragraph ${i + 1}. The export runs every night and keeps a year of rows.`).join("\n\n");
// The agent posts something unrelated, and the page redraws: wait until the
// new title is drawn.
async function unrelatedPost(s, title) {
s.post({ title });
await s.page.waitForFunction((want) => document.getElementById("title").textContent.includes(want), title);
}
test("a redraw keeps your place: the scroll and the focused field survive an agent post", async (t) => {
const s = await openSession(await suite.browser(), {
t,
workflow: "plan",
payload: {
items: [{ id: "q1", kind: "text", title: "What to call it", body: longText(40) }],
docs: [{ id: "map", title: "What we've agreed", blocks: [{ id: "b1", state: "settled", md: longText(80) }] }],
},
});
// Reading a question part-way down: the card scrolls itself.
const card = itemCard(s.page, "q1");
await card.evaluate((el) => (el.scrollTop = 400));
assert.equal(await card.evaluate((el) => el.scrollTop), 400, "the question card scrolls");
await unrelatedPost(s, "Audit export, take two");
assert.equal(await itemCard(s.page, "q1").evaluate((el) => el.scrollTop), 400);
// Typing in its answer box: the box keeps the focus and the caret, and the
// card stays where it was.
const field = itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
await field.click();
await field.pressSequentially("audit-ex");
await field.evaluate((el) => el.setSelectionRange(3, 3));
const typingAt = await itemCard(s.page, "q1").evaluate((el) => el.scrollTop);
await unrelatedPost(s, "Audit export, take three");
const after = itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
assert.deepEqual(await after.evaluate((el) => [el === document.activeElement, el.value, el.selectionStart]), [true, "audit-ex", 3]);
assert.equal(await itemCard(s.page, "q1").evaluate((el) => el.scrollTop), typingAt);
// On a doc: the column scrolls.
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
await s.page.getByText("Paragraph 80.").waitFor();
await s.page.locator("#main").evaluate((el) => (el.scrollTop = 900));
const docBefore = await scrollTopOf(s.page, "#main");
assert.ok(docBefore > 0, "the doc column scrolls");
await unrelatedPost(s, "Audit export, take four");
assert.equal(await scrollTopOf(s.page, "#main"), docBefore);
});
// The progress line under the title, once the page has drawn `want`.
async function progressSays(s, want) {
await s.page.waitForFunction((w) => document.getElementById("progress-text").textContent === w, want, { timeout: 5000 }).catch(() => {});
return (await s.page.innerText("#progress-text")).trim();
}
// One answered question, so a question workflow has something to count.
const answered = { id: "a1", kind: "text", title: "What to call it", body: "A name.", status: "answered", answer: { text: "audit-export" } };
const open = { id: "o1", kind: "text", title: "Who uses it", body: "Who?" };
test("a build's header counts its tasks, 0 done included, and a question workflow counts its answers", async (t) => {
for (const workflow of ["implement", "implement-review", "quick-task"]) {
const s = await openSession(await suite.browser(), {
t,
workflow,
payload: { headline: { stage: "Phase 3", cleared: 3, total: 9 }, items: [answered] },
});
assert.equal(await progressSays(s, "3 of 9 done"), "3 of 9 done", `${workflow} counts its tasks`);
s.post({ headline: { cleared: 0 } });
assert.equal(await progressSays(s, "0 of 9 done"), "0 of 9 done", `${workflow}: 0 done is 0 done, not the answered card`);
// A build between counts (a review starting at total 0) shows its stage.
s.post({ headline: { stage: "Reviewing the phase", cleared: 0, total: 0 }, items: [open] });
assert.equal(await progressSays(s, "Reviewing the phase"), "Reviewing the phase", `${workflow} shows its stage at total 0`);
assert.equal(await s.page.locator("#progress-bar").isHidden(), true, `${workflow}: no track for a stage`);
await s.stop();
}
// A question workflow that set a total and never moved `cleared` fills as
// cards are answered, and at total 0 counts its cards instead of the stage.
const s = await openSession(await suite.browser(), {
t,
workflow: "plan",
payload: { headline: { stage: "Charting", cleared: 0, total: 4 }, items: [answered] },
});
assert.equal(await progressSays(s, "1 of 4 answered"), "1 of 4 answered");
s.post({ headline: { total: 0 }, items: [open] });
assert.equal(await progressSays(s, "1 of 2 answered"), "1 of 2 answered");
});
test("an answer typed over several lines reaches the agent under its title, never as reply lines of its own", async (t) => {
const s = await openSession(await suite.browser(), {
t,
workflow: "plan",
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }] },
});
await itemCard(s.page, "q1").locator("textarea").fill("audit-export\nIdea name: not a heading");
const got = await sendAndCollect(s);
assert.equal(answerTo(got, "q1").text, "audit-export\nIdea name: not a heading");
assert.ok(got.reply.includes("What to call it: audit-export\n Idea name: not a heading"), `the second line is not indented under its title: ${JSON.stringify(got.reply)}`);
});
test("a redraw keeps the place of the dashboard, the waiting screen and the finished screen, and a new question starts at its top", async (t) => {
// The dashboard's menu scrolls itself.
let s = await openSession(await suite.browser(), { t, workflow: "dashboard" });
await s.page.setViewportSize({ width: 1280, height: 420 });
await s.page.getByRole("button", { name: "Skip the intro" }).click();
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
if (await welcomeDone.isVisible()) await welcomeDone.click();
await welcomeDone.waitFor({ state: "hidden" });
await s.page.locator("#main > .dash").evaluate((el) => (el.scrollTop = 150));
assert.equal(await scrollTopOf(s.page, "#main > .dash"), 150, "the dashboard scrolls");
await unrelatedPost(s, "Dashboard, take two");
assert.equal(await scrollTopOf(s.page, "#main > .dash"), 150, "the dashboard lost its place");
await s.stop();
// A build with nothing to ask yet: the waiting screen, and then its finish.
s = await openSession(await suite.browser(), {
t,
workflow: "implement",
payload: { headline: { stage: "Phase 1", cleared: 0, total: 3 }, agent: { status: "working", activity: "Task 1 of 3: the reader" } },
});
await s.page.setViewportSize({ width: 1280, height: 300 });
const pane = "#main > .waiting-pane";
await s.page.locator(pane).waitFor();
await s.page.locator(pane).evaluate((el) => (el.scrollTop = 60));
const waitingAt = await scrollTopOf(s.page, pane);
assert.ok(waitingAt > 0, "the waiting screen scrolls");
await unrelatedPost(s, "Phase 1, take two");
assert.equal(await scrollTopOf(s.page, pane), waitingAt, "the waiting screen lost its place");
s.post({ finish: { headline: "Phase 1 is done", body: longText(30), command: "/plan2code-3-implement specs/audit-export/overview.md" } });
await s.page.locator("#main").getByRole("heading", { name: "Phase 1 is done" }).waitFor();
const end = "#main > .card";
await s.page.locator(end).evaluate((el) => (el.scrollTop = 300));
assert.equal(await scrollTopOf(s.page, end), 300, "the finished screen scrolls");
await unrelatedPost(s, "Phase 1, take three");
assert.equal(await scrollTopOf(s.page, end), 300, "the finished screen lost its place");
await s.stop();
// Part-way down one question, a new one arrives: it starts at its top.
s = await openSession(await suite.browser(), {
t,
workflow: "plan",
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: longText(40) }] },
});
await itemCard(s.page, "q1").evaluate((el) => (el.scrollTop = 400));
s.post({ items: [{ id: "q2", kind: "text", title: "Who uses it", body: longText(40) }] });
await itemCard(s.page, "q2").waitFor();
assert.equal(await itemCard(s.page, "q2").evaluate((el) => el.scrollTop), 0, "the new question opened part-way down");
});
// The accent colour as the browser resolves it, and a button's outline colour,
// so "wears the accent" is read off the screen, not off a class name.
const accentOf = (page) =>
page.evaluate(() => {
const probe = document.createElement("i");
probe.style.color = "var(--accent)";
document.body.appendChild(probe);
const colour = getComputedStyle(probe).color;
probe.remove();
return colour;
});
const outlineOf = (button) => button.evaluate((b) => getComputedStyle(b).borderTopColor);
const warnOf = (page) =>
page.evaluate(() => {
const probe = document.createElement("i");
probe.style.color = "var(--warn)";
document.body.appendChild(probe);
const colour = getComputedStyle(probe).color;
probe.remove();
return colour;
});
// What a person sees break: the way forward on a sign-off card looks like any
// other choice.
test("on a sign-off card, approve and yes are outlined in the accent until picked, and the others are not", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "implement" });
const accent = await accentOf(s.page);
const review = (id, verdicts) => ({ id, kind: "review", title: "Sign off " + id, body: "Read it.", verdicts });
let card = await ask(s, review("so1", [{ id: "approve", label: "Approve this phase" }, { id: "changes", label: "I want changes" }]));
const approve = card.getByRole("button", { name: "Approve this phase" });
assert.equal(await outlineOf(approve), accent, "an unpicked approve is outlined in the accent");
assert.notEqual(await outlineOf(card.getByRole("button", { name: "I want changes" })), accent, "the other verdict is not");
await approve.click();
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
assert.equal(await approve.evaluate((b) => getComputedStyle(b).backgroundColor), accent, "picked, approve fills with the accent");
card = await ask(s, review("so2", [{ id: "yes", label: "Build it" }, { id: "no", label: "Not yet" }]));
assert.equal(await outlineOf(card.getByRole("button", { name: "Build it" })), accent, "an unpicked yes is outlined too");
assert.notEqual(await outlineOf(card.getByRole("button", { name: "Not yet" })), accent);
});
// What a person sees break: Skip this one turns into a full-size button, or
// the quick answer under a note box does.
test("Skip this one and a comment box's quick answer are the same small accent button", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
const rows = [{ id: "a", title: "Read the data", body: "x" }];
const card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Rename.", required: false, rows });
const skip = card.getByRole("button", { name: "Skip this one" });
const quick = card.getByRole("button", { name: "No changes" });
const look = (b) => b.evaluate((x) => { const c = getComputedStyle(x); return [c.fontSize, c.paddingTop, c.paddingLeft, c.color]; });
assert.deepEqual(await look(skip), await look(quick), "the two chips look alike");
const [size, , , colour] = await look(skip);
assert.equal(size, "12px", "small, not a full-size button");
assert.equal(colour, await accentOf(s.page), "in the accent");
});
// What a person sees break: a safe yes looks like any button, or a risky yes
// stops warning.
test("a confirm's safe yes and a recap's yes are outlined in the accent, and a dangerous yes stays red", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
const accent = await accentOf(s.page);
const warn = await warnOf(s.page);
let card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
const yes = card.getByRole("button", { name: "Yes" });
assert.equal(await outlineOf(yes), accent, "a safe, unpicked yes wears the accent");
assert.notEqual(await outlineOf(card.getByRole("button", { name: "No" })), accent, "the no does not");
await yes.click();
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
assert.equal(await yes.evaluate((b) => getComputedStyle(b).backgroundColor), accent, "picked, it fills");
card = await ask(s, { id: "y2", kind: "confirm", title: "Delete it", body: "Really?", danger: true });
assert.equal(await outlineOf(card.getByRole("button", { name: "Yes" })), warn, "a dangerous yes stays red");
card = await ask(s, { id: "r1", kind: "recap", title: "What we decided", body: "Right?", summary: "- CSV" });
assert.equal(await outlineOf(card.getByRole("button", { name: "Yes, that is right" })), accent, "the recap's yes wears the accent");
});
// What a person sees break: a long question runs off the window with nothing
// to say there is more, or the fade stays on at the very end.
test("a card cut by the window fades at its bottom edge while there is more below", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
await s.page.setViewportSize({ width: 1280, height: 420 });
const card = await ask(s, { id: "q1", kind: "text", title: "What to call it", body: longText(40) });
const fades = () => card.evaluate((el) => { const c = getComputedStyle(el); return (c.maskImage || c.webkitMaskImage || "none") !== "none"; });
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); return c && c.scrollHeight > c.clientHeight + 4; });
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); const m = getComputedStyle(c); return (m.maskImage || m.webkitMaskImage || "none") !== "none"; });
assert.equal(await fades(), true, "a cut card fades at the bottom");
await card.evaluate((el) => (el.scrollTop = el.scrollHeight));
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); const m = getComputedStyle(c); return (m.maskImage || m.webkitMaskImage || "none") === "none"; });
assert.equal(await fades(), false, "at the end, the fade is gone");
});
// What a person sees break: a rename typed in a list is lost when the agent
// posts or Ctrl+Enter sends before the field was left.
test("a list rename is staged as it is typed, so Ctrl+Enter or an agent post never drops it", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
const rows = [{ id: "a", title: "Read the data", body: "x" }, { id: "b", title: "Write the file", body: "y" }];
const card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Rename.", rows });
const first = card.locator("input.row-title").first();
await first.click();
await first.fill("Read the audit log");
// The field is still focused: it has not changed or blurred.
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
await unrelatedPost(s, "Steps, take two");
assert.equal(await itemCard(s.page, "l1").locator("input.row-title").first().inputValue(), "Read the audit log", "the agent post kept the typed name");
await itemCard(s.page, "l1").locator("input.row-title").first().focus();
await s.page.keyboard.press("Control+Enter");
const got = s.wait(10);
assert.equal(got.code, 0, "Ctrl+Enter sent");
assert.deepEqual(answerTo(got, "l1").rows.map((r) => [r.id, r.title]), [["a", "Read the audit log"], ["b", "Write the file"]]);
});
// What a person sees break: a send the agent already collected still shows as
// being with the agent, locking a question it left open.
test("a send made before the last collection is never shown as still with the agent", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
const card = await ask(s, { id: "q1", kind: "text", title: "What to call it", body: "A name." });
// Sent from another tab: this page never learns of it except from the session.
await s.page.evaluate(() =>
fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [{ i: "q1", type: "answer", kind: "text", text: "audit-export" }], reply: "What to call it: audit-export" }),
})
);
const lock = card.getByText(/Plan2Code is working on it|Waiting for Plan2Code to pick this up/);
await lock.waitFor();
assert.equal(await card.locator("textarea").count(), 0, "before the agent collects it, the card is locked");
// The agent collects it, leaves the question open and waits again.
assert.equal(s.wait(10).code, 0);
s.post({ agent: { status: "waiting" } });
await card.locator("textarea").waitFor();
assert.equal(await lock.count(), 0, "after the collection, it is not shown as sent");
});
// What a person sees break: a note box on a card above the git board grows and
// squeezes the board, or the card is cut short under it.
test("a note box over the git board grows no box, and the card flows at its own height", async (t) => {
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
const g = gitInit(dir);
g("add", "-A");
g("commit", "-q", "-m", "First commit");
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
const confirm = { id: "y1", kind: "confirm", title: "Save these changes", body: "Commit them?" };
const git = await openSession(await suite.browser(), {
t,
workflow: "git",
project: dir,
payload: { reread: true, board: { describe: "export-more" }, items: [confirm] },
});
await git.page.getByRole("tablist").waitFor();
const gitCard = itemCard(git.page, "y1");
await gitCard.waitFor();
const note = gitCard.locator("textarea").first();
const gitBox = await note.evaluate((el) => ({ min: el.style.minHeight, height: el.offsetHeight }));
assert.equal(gitBox.min, "", "no height was filled in for the note box");
assert.ok(gitBox.height < 120, `the note box keeps its ordinary height over the board: ${gitBox.height}`);
assert.ok(await gitCard.evaluate((el) => el.scrollHeight <= el.clientHeight + 1), "the card is not shrunk under the board");
// The same card away from the board does fill the free height of the card.
const plan = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: [confirm] } });
const planBox = plan.page.locator('[data-item="y1"] textarea').first();
await planBox.waitFor();
await plan.page.waitForFunction(() => document.querySelector('[data-item="y1"] textarea').offsetHeight >= 160);
assert.ok((await planBox.evaluate((el) => el.offsetHeight)) > gitBox.height, "away from the board, the note box grows");
});
const three = ["First", "Second", "Third"].map((name, n) => ({ id: `q${n + 1}`, kind: "text", title: `${name} question`, body: `Body ${n + 1}.` }));
// What a person sees break: Previous and Next stop walking the open questions.
test("Previous and Next walk the questions still waiting, and the ends have no button", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: three } });
const pager = s.page.getByRole("navigation", { name: "Move between the questions waiting" });
const shown = () => s.page.locator("#main [data-item]").first().getAttribute("data-item");
await pager.getByText("1 of 3 waiting").waitFor();
assert.equal(await pager.getByRole("button", { name: /Previous/ }).count(), 0, "nothing before the first");
await pager.getByRole("button", { name: /Next.*Second question/ }).click();
await pager.getByText("2 of 3 waiting").waitFor();
assert.equal(await shown(), "q2");
await pager.getByRole("button", { name: /Next.*Third question/ }).click();
await pager.getByText("3 of 3 waiting").waitFor();
assert.equal(await pager.getByRole("button", { name: /Next/ }).count(), 0, "nothing after the last");
await pager.getByRole("button", { name: /Previous.*Second question/ }).click();
await pager.getByText("2 of 3 waiting").waitFor();
assert.equal(await shown(), "q2");
});
// What a person sees break: Skip this one does nothing, or leaves you on the
// card you skipped.
test("Skip this one on an optional card moves on, and the skip reaches the agent", async (t) => {
const items = three.map((q, n) => ({ ...q, required: n !== 2 ? false : true }));
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items } });
const card = itemCard(s.page, "q1");
await card.getByRole("button", { name: "Skip this one" }).click();
await s.page.waitForFunction(() => document.querySelector("#main [data-item]")?.dataset.item === "q2");
assert.equal(await itemCard(s.page, "q3").getByRole("button", { name: "Skip this one" }).count(), 0, "a required card cannot be skipped");
await itemCard(s.page, "q2").locator("textarea").fill("Ana");
await s.page.getByRole("navigation", { name: "Move between the questions waiting" }).getByRole("button", { name: /Next/ }).click();
await itemCard(s.page, "q3").locator("textarea").fill("Bo");
const got = await sendAndCollect(s);
assert.deepEqual(
got.actions.map(({ i, type, text }) => ({ i, type, text })),
[{ i: "q1", type: "skip", text: undefined }, { i: "q2", type: "answer", text: "Ana" }, { i: "q3", type: "answer", text: "Bo" }]
);
});
// What a person sees break: an answered question can be edited again, or says
// nothing about what was answered.
test("a settled card is a record: your answer in words, the options as marks, and no form", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
s.post({
settle: true,
items: [
{ id: "c1", kind: "choice", title: "Export format", body: "Which?", options: [opt("A", "CSV"), opt("B", "JSON")], status: "answered", answer: { k: "B" } },
{ id: "q9", kind: "text", title: "Still open", body: "Next." },
],
});
await s.page.locator("#sidebar").getByRole("button", { name: /Export format/ }).click();
const card = itemCard(s.page, "c1");
await card.waitFor();
const record = card.locator(".answered");
assert.match(await record.innerText(), /Your answer[\s\S]*JSON/i);
assert.match(await record.innerText(), /Locked\./);
assert.equal(await card.locator("input, textarea").count(), 0, "a record has no inputs");
});
// What a person sees break: a card still takes edits after Send, or never
// opens again when the agent hands it back.
test("a sent card locks, and the agent's next post on it unlocks it", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: [three[0]] } });
const card = itemCard(s.page, "q1");
await card.locator("textarea").fill("Ana");
await s.page.click("#btn-send");
const lock = card.getByText(/Plan2Code is working on it|Waiting for Plan2Code to pick this up/);
await lock.waitFor();
assert.match(await card.locator(".answered").innerText(), /Sent[\s\S]*Ana/i);
assert.equal(await card.locator("textarea").count(), 0, "no form while the agent has it");
s.wait(10);
s.post({ items: [{ id: "q1", status: "reopened", thread: [{ who: "agent", text: "Which Ana?" }] }], agent: { status: "waiting" } });
await card.locator("textarea").waitFor();
assert.equal(await lock.count(), 0, "the next post gives the card back");
});
// What a person sees break: the "something else" box takes the words but the
// pick sent is still the listed option, or the pick is lost on a switch back.
test("Something else in your own words replaces the pick, and picking an option again drops the words", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
const card = await ask(s, { id: "c1", kind: "choice", title: "Where", body: "Where?", options: [opt("A", "Email"), opt("B", "Slack")] });
await card.getByLabel("Email").check();
const other = card.getByRole("radio", { name: "Something else, in your own words" });
await other.check();
await card.locator("textarea.other-text").fill("A shared drive");
assert.equal(await card.getByLabel("Email").isChecked(), false, "the options and the other share one group");
await card.getByLabel("Slack").check();
await other.check();
assert.equal(await card.locator("textarea.other-text").inputValue(), "A shared drive", "the words survive a switch");
const got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "c1"), { text: "A shared drive" });
});
// What a person sees break: a note typed on a card is dropped by the verdict,
// or is lost when the verdict comes first.
test("a note's comment field rides along with the answer, typed before or after the pick", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
let card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
await card.getByLabel("Anything to add?").fill("Only on weekdays.");
await card.getByRole("button", { name: "Yes" }).click();
let got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "y1"), { yes: true, text: "Only on weekdays." });
assert.equal(got.reply, "Keep going: yes; Only on weekdays.");
card = await ask(s, { id: "y2", kind: "confirm", title: "And this", body: "Also?" });
await card.getByRole("button", { name: "No" }).click();
await card.getByLabel("Anything to add?").fill("Not this quarter.");
got = await sendAndCollect(s);
assert.deepEqual(answerTo(got, "y2"), { yes: false, text: "Not this quarter." });
});
/* ----------------------------------------------------------------- docs */
// What a person sees break: a guess reads like a decision, or a draft does.
test("a doc tags an assumed block and a draft block, and shows a file block's text", async (t) => {
const project = tempProject({ "notes/facts.md": "The export keeps **a year** of rows.\n" });
const s = await openSession(await suite.browser(), {
t,
workflow: "plan",
project,
payload: {
docs: [
{
id: "map",
title: "What we've agreed",
blocks: [
{ id: "b1", state: "settled", md: "Runs nightly." },
{ id: "b2", state: "assumed", md: "Output is CSV." },
{ id: "b3", state: "draft", md: "Maybe a weekly digest." },
{ id: "b4", file: "notes/facts.md" },
],
},
],
},
});
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
const block = (id) => s.page.locator(`#main [data-block="${id}"]`);
await block("b4").waitFor();
assert.equal(await block("b1").innerText(), "Runs nightly.", "a settled block has no tag");
assert.match(await block("b2").innerText(), /^assumed for now, still open\s+Output is CSV\.$/i);
assert.match(await block("b3").innerText(), /^draft\s+Maybe a weekly digest\.$/i);
assert.match(await block("b4").innerText(), /The export keeps a year of rows\./, "the file's text is on the page");
});
// What a person sees break: Download hands over something other than the
// document, or loses which parts are still guesses.
test("Download offers a Markdown file with the doc's title, blocks and marks", async (t) => {
const s = await openSession(await suite.browser(), {
t,
workflow: "plan",
payload: {
docs: [{ id: "map", title: "What we've agreed", blocks: [{ id: "b1", state: "settled", md: "Runs nightly." }, { id: "b2", state: "assumed", md: "Output is CSV." }] }],
},
});
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
const [download] = await Promise.all([s.page.waitForEvent("download"), s.page.getByRole("button", { name: "Download" }).click()]);
assert.equal(download.suggestedFilename(), "what-we-ve-agreed.md");
const chunks = [];
for await (const c of await download.createReadStream()) chunks.push(c);
assert.equal(Buffer.concat(chunks).toString("utf8"), "# What we've agreed\n\nRuns nightly.\n\n> **Assumed for now, still open.**\n\nOutput is CSV.");
});
// What a person sees break: the brief button turns up where no playbook
// answers it, or sends a different range than the one picked.
test("a pathfinder session offers Write a brief, and the picked range reaches the agent", async (t) => {
const plain = await openSession(await suite.browser(), { t, workflow: "plan" });
assert.equal(await plain.page.locator("#btn-brief").isHidden(), true, "no brief button outside pathfinder");
await plain.stop();
const s = await openSession(await suite.browser(), { t, workflow: "pathfinder", payload: { agent: { status: "waiting" } } });
await s.page.getByRole("button", { name: "Write a brief" }).first().click();
const dialog = s.page.locator("#brief-modal");
await dialog.getByLabel("This week").check();
await dialog.getByRole("button", { name: "Write the brief" }).click();
await dialog.waitFor({ state: "hidden" });
const got = s.wait(10);
assert.equal(got.code, 0, "a brief request was sent");
assert.deepEqual(got.actions.map(({ i, type, range }) => ({ i, type, range })), [{ i: "__brief", type: "brief", range: "this week" }]);
assert.equal(got.reply, "Write a brief for this week.");
});
+447
View File
@@ -0,0 +1,447 @@
// Page tests for the dashboard: a spec in the picker, a card picked and
// started, the launch send the agent collects, and its `resume` turning the
// page into the launched skill's starting screen. Run with:
// node --test scripts/test-web-console-page-dashboard.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 fs from "node:fs";
import path from "node:path";
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs";
import { cli, until, CONSOLE_CLI, HOME } from "./web-console-test-helpers.mjs";
const suite = pageSuite(test);
// A project that is set up (AGENTS.md) with one spec holding a Plan draft.
// A PLAN-DRAFT whose Status line says only "Draft" (no "Resume at Phase N")
// scans as `planned`, which the picker labels "Ready to document". Plan is
// still lit for it (only exploring, fixed and documented-or-later grey Plan
// out); Document is the state's own next step.
const DRAFT_PROJECT = {
"AGENTS.md": "# AGENTS.md\n\nA small demo project.\n",
"specs/demo/PLAN-DRAFT-20261017.md": "# Plan draft: demo\n\n**Status:** Draft\n\nA lunch vote for the team.\n",
};
// What a real agent posts on the dashboard (plan2code.md, "The menu"): its
// judgment on top of the scan, then it waits.
const MENU = {
menu: {
note: "One spec on disk, with a plan drafted.",
recommend: "plan2code-2-document",
details: { "plan2code-2-document": "Plan drafted" },
},
agent: { status: "waiting" },
};
// The one send `wait` hands the agent; fails the test when nothing arrived.
function collect(s) {
const got = s.wait(10);
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
return got;
}
test("a Plan launch from the dashboard carries the picked spec, and its resume turns the page to Starting Plan", async (t) => {
const project = tempProject(DRAFT_PROJECT);
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
const main = await toTheMenu(s);
// The picker shows the spec with its state, and opens on it.
const chip = main.getByRole("button").filter({ hasText: /^demo/ });
await chip.waitFor();
// The state is drawn in capitals, so the match ignores case.
const chipText = await textOf(chip);
assert.match(chipText, /Ready to document/i, "the spec chip names its state");
assert.match(chipText, /plan drafted/, "the spec chip says how far it got");
assert.equal(await chip.getAttribute("aria-current"), "true", "the picker opens on the only spec");
// The Plan card is lit for this spec; picking it asks to confirm.
const planCard = main.getByRole("button").filter({ has: s.page.locator("code", { hasText: /^\/plan2code-1-plan$/ }) });
assert.equal(await planCard.isEnabled(), true, "the Plan card is greyed for a drafted plan");
await planCard.click();
await main.getByRole("button", { name: "Start Plan" }).click();
const got = collect(s);
assert.equal(got.type, "submit");
const launch = got.actions.find((a) => a.i === "__launch");
assert.ok(launch, `the send carries a launch: ${JSON.stringify(got.actions)}`);
assert.deepEqual(
{ i: launch.i, skill: launch.skill, workflow: launch.workflow, spec: launch.spec },
{ i: "__launch", skill: "plan2code-1-plan", workflow: "plan", spec: "specs/demo" }
);
// `resume` is the one command to run, naming the session, workflow and spec.
const head = `node "${CONSOLE_CLI}" `;
assert.ok(got.resume.startsWith(head), `resume runs this console: ${got.resume}`);
const args = got.resume.slice(head.length).split(" ");
assert.deepEqual(args, ["open", "--resume", s.sid, "--no-open", "--workflow", "plan", "--spec", "specs/demo"]);
// `skillFile` is offered only when the skill's SKILL.md sits beside the
// console's own folder, as in an install. Run from this repo's source tree
// (src/web-console/), that is a plan2code-1-plan/ folder next to the repo,
// which does not exist, so the send leaves it out (console-launches.md:
// "absent outside an install").
assert.equal("skillFile" in got, false, `a source-tree launch names no skillFile: ${got.skillFile}`);
// The agent runs `resume` first: the page leaves the menu for Plan's
// starting screen while the skill is read.
const r = cli(args, { cwd: s.project });
assert.equal(r.status, 0, `resume failed: ${r.stderr}`);
await main.getByRole("heading", { name: "Starting Plan" }).waitFor();
});
// A project holding one fixed bug (a diagnosis Quick Task marked Fixed) and
// one drafted plan. The fixed bug is touched last, so it is the newest spec on
// disk: the picker must still open on the plan, since a finished spec is never
// the default.
function fixedProject() {
const project = tempProject({
...DRAFT_PROJECT,
"specs/old-bug/DIAGNOSIS-20261017.md": "# Diagnosis: old bug\n\n**Status:** Fixed\n\nThe save button lost its handler.\n",
});
const later = new Date(Date.now() + 60_000);
fs.utimesSync(path.join(project, "specs/old-bug/DIAGNOSIS-20261017.md"), later, later);
return project;
}
// Past Planny's wake-up and, on this console home's first run, the Welcome,
// to the menu.
async function toTheMenu(s) {
const skip = s.page.getByRole("button", { name: "Skip the intro" });
await skip.click();
await skip.waitFor({ state: "hidden" });
const main = s.page.locator("#main");
const heading = main.getByRole("heading", { name: "What are we doing today?" });
await heading.waitFor();
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
if (await welcomeDone.isVisible()) {
await welcomeDone.click();
await welcomeDone.waitFor({ state: "hidden" });
}
return main;
}
// Sets the picker's "Hide unavailable workflows" switch. Looks are kept per
// console home, so each test sets the one it needs rather than trusting the
// default.
async function hideUnavailable(main, on) {
const box = main.getByRole("switch", { name: "Hide unavailable workflows" });
if ((await box.isChecked()) !== on) await main.getByText("Hide unavailable workflows").click();
assert.equal(await box.isChecked(), on);
}
const chipFor = (main, name) => main.getByRole("button").filter({ hasText: new RegExp(`^${name}`) });
test("a fixed bug is hidden while unavailable workflows are, dimmed when they show, and never the picker's default", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: fixedProject() });
const main = await toTheMenu(s);
// Hidden while the switch is on.
await hideUnavailable(main, true);
const demo = chipFor(main, "demo");
await demo.waitFor();
assert.equal(await demo.getAttribute("aria-current"), "true", "the picker opens on the plan, not the newer fixed bug");
assert.equal(await chipFor(main, "old-bug").count(), 0, "the fixed bug's chip is hidden while unavailable workflows are");
// Switched off: the chip shows, labelled and dimmed, and still not picked.
await hideUnavailable(main, false);
const bug = chipFor(main, "old-bug");
await bug.waitFor();
assert.match(await textOf(bug), /Bug fixed/i, "the chip names its state");
assert.doesNotMatch(await textOf(bug), /bug fixed\s+bug fixed/i, "the scan's detail does not repeat the label");
assert.equal(await bug.getAttribute("aria-current"), "false", "the fixed bug is not picked");
const opacity = await bug.evaluate((b) => Number(getComputedStyle(b).opacity));
assert.ok(opacity < 1, `the fixed bug's chip is dimmed (opacity ${opacity})`);
assert.equal(await demo.getAttribute("aria-current"), "true", "the plan stays picked");
});
test("a fixed bug's Delete asks once with no name to type, while any other spec asks for its name", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: fixedProject() });
const main = await toTheMenu(s);
await hideUnavailable(main, false);
await chipFor(main, "old-bug").waitFor();
const dialog = s.page.locator("#delete-modal");
const go = s.page.locator("#delete-go");
const nameStep = s.page.locator("#delete-confirm");
// Any other spec: the first press only reveals the name step.
await main.getByRole("button", { name: "Delete the spec demo" }).click({ force: true });
await dialog.waitFor();
assert.equal(await textOf(go), "Delete this spec…");
await go.click();
await nameStep.waitFor();
assert.equal(await go.isDisabled(), true, "the final button waits for the name");
await s.page.keyboard.press("Escape");
await dialog.waitFor({ state: "hidden" });
// The fixed bug: a visible Delete, its own warning, and one press sends it.
const del = main.getByRole("button", { name: "Delete the spec old-bug" });
assert.equal(await textOf(del), "Delete", "a fixed bug's Delete is a labelled button");
await del.click();
await dialog.waitFor();
assert.match(await textOf(s.page.locator("#delete-warn")), /The bug is fixed, so this only clears the write-up/);
assert.equal(await textOf(go), "Delete it");
assert.equal(await nameStep.isHidden(), true, "no name step for a fixed bug");
await go.click();
const got = collect(s);
assert.equal(await nameStep.isHidden(), true, "the name step never showed");
const action = got.actions.find((a) => a.i === "__delete");
assert.deepEqual({ type: action?.type, spec: action?.spec }, { type: "delete", spec: "specs/old-bug" });
});
// ---------------------------------------------------------------------------
// The picker's switching, the first-open wake-up, handoffs, the update banner,
// the workspace scope, and the pose that carries a launch into the work.
const lightOf = (main, command) => main.getByRole("button").filter({ has: main.page().locator("code", { hasText: new RegExp(`^${command}$`) }) });
const pickedChip = (main, name) => main.locator('button[aria-current="true"]', { hasText: new RegExp(`^${name}`) });
// What a person would see break: picking another target leaves the launch
// aimed at the old spec, or the cards lit for it.
test("picking Start from scratch instead of a spec greys Document, and a launch then carries no spec", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
const main = await toTheMenu(s);
const document = lightOf(main, "/plan2code-2-document");
await pickedChip(main, "demo").waitFor();
assert.equal(await document.isEnabled(), true, "Document is lit for the drafted spec");
// From scratch there is no draft to document: the card greys.
await chipFor(main, "Start from scratch").click();
await pickedChip(main, "Start from scratch").waitFor();
assert.equal(await document.isDisabled(), true, "Document is greyed with no spec picked");
assert.equal(await chipFor(main, "demo").getAttribute("aria-current"), "false");
// Back on the spec it is lit again; then from scratch once more to launch.
await chipFor(main, "demo").click();
await pickedChip(main, "demo").waitFor();
assert.equal(await document.isEnabled(), true, "Document is lit again for the spec");
await chipFor(main, "Start from scratch").click();
await pickedChip(main, "Start from scratch").waitFor();
await lightOf(main, "/plan2code-1-plan").click();
await main.getByRole("button", { name: "Start Plan" }).click();
const launch = collect(s).actions.find((a) => a.i === "__launch");
assert.equal(launch.skill, "plan2code-1-plan");
assert.ok(!launch.spec, `a launch from scratch names no spec: ${JSON.stringify(launch)}`);
});
// What a person would see break: the intro cannot be skipped, or it replays
// on every reload of the same tab.
test("Skip the intro ends the first-open wake-up at once, and a reload of the tab does not play it again", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
const skip = s.page.getByRole("button", { name: "Skip the intro" });
await skip.waitFor();
await toTheMenu(s);
assert.equal(await skip.isVisible(), false);
await s.page.reload({ waitUntil: "domcontentloaded" });
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
assert.equal(await skip.isVisible(), false, "the intro does not play again in this tab");
});
// A project with no spec, only a handoff written for it (the Handoff skill's
// file pair under the test's own handoffs folder), removed with the test.
const HANDOFF_DOC = "# Handoff: Lunch vote\n\n## Next task\n\nWire the vote button to the tally.\n\n## Notes\n\nA long body line.\n";
function handoffProject(t) {
const project = tempProject({ "AGENTS.md": "# AGENTS.md\n\nA small demo project.\n" });
const made = cli(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"], { cwd: project }).json;
fs.writeFileSync(made.path, HANDOFF_DOC);
t.after(() => {
fs.rmSync(made.path, { force: true });
fs.rmSync(made.path.replace(/\.md$/, ".json"), { force: true });
});
return { project, made };
}
async function openHandoffMenu(t) {
const { project, made } = handoffProject(t);
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
const main = await toTheMenu(s);
const chip = chipFor(main, "Lunch vote");
await chip.waitFor();
return { s, main, chip, made };
}
// What a person would see break: a handoff is not offered when it is all the
// project has, or picking it still shows the skill cards beside the preview.
test("a handoff shows as a dashed Handoff chip even with no spec, and picking it swaps the cards for a preview of four buttons", async (t) => {
const { main, chip } = await openHandoffMenu(t);
assert.match(await textOf(chip), /Handoff/i, "the chip is labelled Handoff");
assert.equal(await chip.getAttribute("aria-current"), "false", "a handoff is offered, not picked for you");
assert.equal(await chip.evaluate((b) => getComputedStyle(b).borderTopStyle), "dashed", "the chip's border is dashed");
assert.ok(await lightOf(main, "/plan2code-1-plan").isVisible(), "the cards show before a handoff is picked");
await chip.click();
assert.equal(await chip.getAttribute("aria-current"), "true");
await main.getByRole("heading", { name: "Lunch vote" }).waitFor();
assert.match(await textOf(main), /Wire the vote button to the tally\./, "the preview quotes the Next task");
for (const name of ["Pick it up here", "Read it all", "Copy for a new conversation", "Delete"]) {
assert.equal(await main.getByRole("button", { name, exact: true }).count(), 1, `the preview has ${name}`);
}
assert.equal(await lightOf(main, "/plan2code-1-plan").count(), 0, "the skill cards give way to the preview");
assert.equal(await main.getByRole("switch", { name: "Hide unavailable workflows" }).count(), 0, "and so does their toggle");
});
// What a person would see break: Pick it up here sends nothing, or sends more
// than the handoff's id.
test("Pick it up here sends a pickup naming the handoff, and the page turns to its launch screen", async (t) => {
const { s, main, chip, made } = await openHandoffMenu(t);
await chip.click();
await main.getByRole("button", { name: "Pick it up here" }).click();
const got = collect(s);
const pick = got.actions.find((a) => a.i === "__pickup");
assert.deepEqual({ type: pick?.type, handoff: pick?.handoff }, { type: "pickup", handoff: made.id });
assert.match(got.resume, /--workflow quick-task$/, "the CLI read the handoff's own workflow");
await main.getByRole("heading", { name: "Waking up Lunch vote" }).waitFor();
});
// What a person would see break: Read it all opens nothing, or Copy puts the
// wrong words on the clipboard.
test("Read it all opens the handoff's text, and Copy puts a prompt naming its file on the clipboard", async (t) => {
const { s, main, chip, made } = await openHandoffMenu(t);
await s.context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: new URL(s.url).origin });
await chip.click();
await main.getByRole("button", { name: "Read it all" }).click();
const reader = s.page.locator("#handoff-modal");
await reader.getByText("A long body line.").waitFor();
await s.page.keyboard.press("Escape");
await reader.waitFor({ state: "hidden" });
const copy = main.getByRole("button", { name: "Copy for a new conversation" });
await copy.click();
await main.getByRole("button", { name: "Copied" }).waitFor();
const text = await s.page.evaluate(() => navigator.clipboard.readText());
assert.match(text, /^Read the handoff at .*\.md and carry on with its Next task\.$/);
assert.ok(text.includes(made.id), `the prompt names the handoff's file: ${text}`);
});
// What a person would see break: Delete asks for a name, or sends a spec
// delete instead of the handoff's.
test("a handoff's Delete asks once in its own dialog and sends a delete naming the handoff", async (t) => {
const { s, main, chip, made } = await openHandoffMenu(t);
await chip.click();
await main.getByRole("button", { name: "Delete", exact: true }).click();
const dialog = s.page.locator("#delete-modal");
await dialog.waitFor();
assert.equal(await textOf(s.page.locator("#delete-title")), "Delete this handoff?");
assert.equal(await s.page.locator("#delete-warn-handoff").isVisible(), true, "the warning says where handoffs live");
assert.equal(await s.page.locator("#delete-confirm").isHidden(), true, "no name to type");
await s.page.locator("#delete-go").click();
const action = collect(s).actions.find((a) => a.i === "__delete");
assert.deepEqual({ type: action?.type, handoff: action?.handoff, spec: action?.spec }, { type: "delete", handoff: made.id, spec: undefined });
});
// A newer release on record, so a console that boots now has an update to
// announce (the check reads this file for an hour instead of asking the
// network). The file is put back as the suite had it.
function aNewerReleaseExists(t) {
const file = path.join(HOME, "update-check.json");
const before = fs.readFileSync(file, "utf8");
fs.writeFileSync(file, JSON.stringify({ checkedAt: Date.now(), latest: "99.0.0" }));
t.after(() => fs.writeFileSync(file, before));
}
// What a person would see break: the banner shows on a build's page, or the
// dashboard never offers it.
test("the update banner shows on the dashboard only, and its dismiss hides it", async (t) => {
aNewerReleaseExists(t);
const browser = await suite.browser();
const build = await openSession(browser, { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
const dash = await openSession(browser, { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
const main = await toTheMenu(dash);
const banner = main.getByRole("button", { name: /UPDATE AVAILABLE · v99\.0\.0/ });
await banner.waitFor();
// The build's server booted under the same record; a later frame has landed
// on its page by the time this text shows, and it still has no banner.
build.post({ agent: { status: "working", activity: "Task 1 of 1, one more look" } });
await build.page.getByText("Task 1 of 1, one more look").first().waitFor();
assert.equal(await build.page.getByText("UPDATE AVAILABLE").count(), 0, "a build's page has no banner");
await main.getByRole("button", { name: "Dismiss until next time" }).click();
await banner.waitFor({ state: "hidden" });
});
// What a person would see break: two dashboard tabs of one session, on
// different picks, keep taking the workspace's folders back from each other.
test("two dashboard tabs on different picks leave the workspace scope with the last pick and ask for it no more", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
const mainA = await toTheMenu(s);
const second = await s.context.newPage();
second.on("pageerror", (e) => s.errors.push(e.message));
await second.goto(s.url, { waitUntil: "domcontentloaded" });
const mainB = await toTheMenu({ page: second });
const asks = { a: 0, b: 0 };
s.page.on("request", (r) => r.method() === "POST" && r.url().endsWith("/workspace/scope") && asks.a++);
second.on("request", (r) => r.method() === "POST" && r.url().endsWith("/workspace/scope") && asks.b++);
const scopeOf = () => s.page.evaluate(async () => (await (await fetch("/workspace?check=1", { cache: "no-store" })).json()).scope || "");
assert.equal(await scopeOf(), "specs/demo", "both tabs opened on the spec");
// The second tab moves to Start from scratch: its folders become the project's own.
await chipFor(mainB, "Start from scratch").click();
await pickedChip(mainB, "Start from scratch").waitFor();
assert.ok(await until(async () => (await scopeOf()) === ""), "the scope followed the second tab");
// The first tab keeps its pick and takes a frame from the agent after the change.
s.post({ menu: { ...MENU.menu, note: "A second look from the agent." } });
await mainA.getByText("A second look from the agent.").waitFor();
assert.equal(await pickedChip(mainA, "demo").count(), 1, "the first tab still has its own pick");
assert.equal(asks.a, 0, "the tab that did not move never asked for its own scope back");
assert.equal(asks.b, 1, "the tab that moved asked once");
assert.equal(await scopeOf(), "", "the scope stays with the last pick");
});
// What a person would see break: Planny is rebuilt on every screen change, so
// his animation restarts as the launch becomes the work.
test("the pose pane a launch shows is the very element the starting and waiting screens keep, and the waiting pane shows the agent's activity", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
const main = await toTheMenu(s);
await lightOf(main, "/plan2code-1-plan").click();
await main.getByRole("button", { name: "Start Plan" }).click();
// The launching screen, with its pose; mark that exact element.
const pane = s.page.locator("#main > [data-pose]");
await pane.waitFor();
const pose = await pane.getAttribute("data-pose");
await pane.evaluate((el) => (el.__sameElement = true));
// The agent resumes the session as Plan: the starting screen reuses the pane.
const got = collect(s);
const args = got.resume.slice(`node "${CONSOLE_CLI}" `.length).split(" ");
assert.equal(cli(args, { cwd: s.project }).status, 0);
await main.getByRole("heading", { name: "Starting Plan" }).waitFor();
assert.equal(await pane.getAttribute("data-pose"), pose, "the same pose carries into the starting screen");
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "the pane was kept, not rebuilt");
// The agent starts work and says what it is doing: the waiting screen shows it,
// still in the same pane.
s.post({ agent: { status: "working", activity: "Reading the plan draft" } });
await main.getByText("Reading the plan draft").waitFor();
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "the pane survives into the waiting screen");
s.post({ agent: { status: "working", activity: "Writing the first questions" } });
await main.getByText("Writing the first questions").waitFor();
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "and survives each state frame after it");
});
// What a person would see break: a quick-task build points at a Plan tab that
// does not open, or another skill's page gains a pointer it has no list for.
test("a quick-task build's waiting pane points at its Plan tab, and a plan session with the same tab gets no pointer", async (t) => {
const plan = { id: "plan", title: "Plan", blocks: [{ id: "steps", state: "settled", md: "## Steps\n\n- [ ] **1.** Wire the vote button" }] };
const working = { agent: { status: "working", activity: "Step 1 of 1" } };
const s = await openSession(await suite.browser(), { t, workflow: "quick-task", payload: { docs: [plan], ...working } });
const pane = s.page.locator("#main > .waiting-pane");
await pane.waitFor();
const jump = pane.getByRole("button", { name: "Plan", exact: true });
await jump.waitFor();
await jump.click();
await s.page.locator("#main").getByText("Wire the vote button").waitFor();
const other = await openSession(await suite.browser(), { t, workflow: "plan", payload: { docs: [plan], ...working } });
const otherPane = other.page.locator("#main > .waiting-pane");
await otherPane.waitFor();
assert.equal(await otherPane.getByRole("button", { name: "Plan", exact: true }).count(), 0, "a plan session has no live task list to point at");
});
+314
View File
@@ -0,0 +1,314 @@
// Page tests for the git board: the Changes, Branches and Sync tabs drawn
// from a real repository, each tab's content on show when it is picked. Run
// with:
// node --test scripts/test-web-console-page-git.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. The fixture repo is built under the scrubbed git config
// that skill-script-helpers.mjs sets for the whole process, so the console's
// own snapshot reads it the way the fixture wrote it.
import { gitInit } from "./skill-script-helpers.mjs";
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { pageSuite, openSession, tempProject, textOf, itemCard } from "./page-test-helpers.mjs";
import { until } from "./web-console-test-helpers.mjs";
const suite = pageSuite(test);
// A repo with one commit on main, a second branch, and one file changed on
// the tree since that commit.
function gitProject() {
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
const g = gitInit(dir);
g("add", "-A");
g("commit", "-q", "-m", "First commit");
g("branch", "feature/export-csv");
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
return dir;
}
// What a real Git skill posts once the board is up (notes/git.md): a reread,
// so the console snapshots the repo, and the description of what changed.
const BOARD = { reread: true, board: { describe: "export-more" } };
test("the git board shows Changes, Branches and Sync, and each tab shows its own content", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: BOARD });
const { page } = s;
const tab = (label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
const panel = page.getByRole("tabpanel");
await page.getByRole("tablist").waitFor();
assert.deepEqual(
(await page.getByRole("tab").allInnerTexts()).map((x) => x.trim().split(/\s/)[0]),
["Changes", "Branches", "Sync"]
);
await tab("Changes").click();
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent.startsWith("Changes"));
await panel.getByText("src/app.js", { exact: true }).waitFor();
assert.match(await textOf(panel), /src\/app\.js/);
await tab("Branches").click();
await panel.getByText("feature/export-csv").first().waitFor();
const branches = await textOf(panel);
assert.match(branches, /feature\/export-csv/);
assert.doesNotMatch(branches, /src\/app\.js/, "the Branches tab still shows the changed files");
await tab("Sync").click();
await panel.getByText(/nothing to sync/).waitFor();
const sync = await textOf(panel);
assert.match(sync, /No remote yet, so nothing to sync/);
assert.doesNotMatch(sync, /feature\/export-csv/, "the Sync tab still lists the branches");
});
test("each git tab keeps its own scroll place, across a tab switch and an agent post", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: BOARD });
const { page } = s;
await page.getByRole("tablist").waitFor();
await page.setViewportSize({ width: 1280, height: 260 });
const tab = (label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
const column = () => page.locator("#main").evaluate((el) => el.scrollTop);
await tab("Changes").click();
await page.getByRole("tabpanel").getByText("src/app.js", { exact: true }).waitFor();
await page.locator("#main").evaluate((el) => (el.scrollTop = 120));
const changesAt = await column();
assert.ok(changesAt > 0, "the board's column scrolls");
// Another tab opens at its own place, not where Changes was left.
await tab("Branches").click();
await page.getByRole("tabpanel").getByText("feature/export-csv").first().waitFor();
assert.equal(await column(), 0, "Branches opened at the place Changes was left");
await tab("Changes").click();
await page.getByRole("tabpanel").getByText("src/app.js", { exact: true }).waitFor();
assert.equal(await column(), changesAt, "Changes lost its place across the switch");
// An agent post redraws the board: still the same place.
s.post({ title: "Git, take two" });
await page.waitForFunction(() => document.getElementById("title").textContent.includes("Git, take two"));
assert.equal(await column(), changesAt, "Changes lost its place across a redraw");
});
// The agent is sitting in `wait`, so the board is the person's to use. A fresh
// session has the agent working, which locks every button but the tabs.
const READY = { ...BOARD, agent: { status: "waiting" } };
// A repo with one commit, then two changes on the tree: src/app.js edited and
// notes.md new. `branch` checks out a branch of its own (or "detached" a bare
// commit), so the commit panel is the next step; on main the next step is to
// start a branch. `remotes` names the remotes to add.
function changesProject({ branch = null, remotes = [] } = {}) {
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
const g = gitInit(dir);
g("add", "-A");
g("commit", "-q", "-m", "First commit");
g("branch", "feature/export-csv");
for (const name of remotes) {
const bare = tempProject();
g("init", "-q", "--bare", bare);
g("remote", "add", name, bare);
}
if (branch === "detached") g("checkout", "-q", "--detach");
else if (branch) g("checkout", "-q", "-b", branch);
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
fs.writeFileSync(path.join(dir, "notes.md"), "Notes.\n");
return dir;
}
const confirmCard = { id: "y1", kind: "confirm", title: "Save these changes", body: "Commit them?" };
const tabButton = (page, label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
const tickBox = (page, file) => page.getByLabel(`Commit ${file}`);
// The Branches tab's Switch button, for the one other branch.
const switchButton = (page) => page.getByRole("tabpanel").getByRole("button", { name: "Switch" });
// The board's step button, in the strip above the tab's content.
const stepButton = (page, name) => page.locator(".git-step-actions").getByRole("button", { name });
// Whether the board's own controls (not its tabs or the pointer to another
// tab) are all off, or at least one is on. Whatever tab the board has moved to,
// a locked board has every one of them disabled.
const boardControls = (page) => page.locator(".git-panel-tab").locator("button, input[type=checkbox], select");
const usable = async (page) => {
const off = await boardControls(page).evaluateAll((all) => all.filter((x) => !x.classList.contains("git-hint")).map((x) => x.disabled));
return off.some((x) => !x);
};
// The board redraws a moment after its cause, so each check gets time to settle.
const settles = (control, enabled) => until(async () => (await control.isEnabled()) === enabled, 8000);
const settlesUsable = (page, want) => until(async () => (await usable(page)) === want, 8000);
const titled = (page, text) => page.waitForFunction((x) => document.getElementById("title").textContent.includes(x), text);
test("the commit dialog sends the ticked files as one __git action, with its reply sentence", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject({ branch: "feature/x" }), payload: READY });
const { page } = s;
await page.getByRole("tablist").waitFor();
await stepButton(page, "Commit 2 files").click();
const panel = page.locator(".git-panel");
await panel.getByRole("button", { name: "Close" }).waitFor();
await tickBox(page, "notes.md").uncheck();
await panel.getByRole("button", { name: "Commit 1 file" }).click();
const got = s.wait(10);
assert.equal(got.code, 0, "the agent collected the click");
assert.deepEqual(got.actions, [{ i: "__git", type: "git", op: "commit", files: ["src/app.js"], ignore: [] }]);
assert.equal(got.reply, "Commit this file: src/app.js.");
});
test("a board click is exactly one __git action", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
const { page } = s;
await tabButton(page, "Branches").click();
await switchButton(page).click();
const got = s.wait(10);
assert.equal(got.code, 0);
assert.equal(got.actions.length, 1, "one click, one action");
assert.equal(got.actions[0].i, "__git");
assert.equal(got.actions[0].type, "git");
assert.equal(got.reply, "Switch to feature/export-csv.");
assert.notEqual(s.wait(1).code, 0, "nothing else was sent beside it");
});
test("the board stays locked from a click until the agent's next post, not just until it is collected", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
const { page } = s;
await tabButton(page, "Branches").click();
assert.ok(await settlesUsable(page, true), "the board is the person's before any click");
await switchButton(page).click();
assert.ok(await settlesUsable(page, false), "locked from the click");
// The agent has the click now (it is running git), and the board still waits.
assert.equal(s.wait(10).code, 0);
await new Promise((r) => setTimeout(r, 1500));
assert.equal(await usable(page), false, "collected is not yet answered");
// The agent's next post lets the board go.
s.post({ title: "Switched", agent: { status: "waiting" } });
await titled(page, "Switched");
assert.ok(await settlesUsable(page, true), "the agent's post gave the board back");
});
test("an open card of the agent's holds the board, and a notice does not", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
const { page } = s;
assert.ok(await settlesUsable(page, true));
s.post({ items: [{ id: "n1", kind: "notice", title: "Heads up", body: "Nothing to act on." }], agent: { status: "waiting" } });
await page.getByText("Heads up", { exact: true }).waitFor();
assert.equal(await usable(page), true, "a notice leaves the board alone");
s.post({ items: [confirmCard], agent: { status: "waiting" } });
await itemCard(page, "y1").waitFor();
assert.ok(await settlesUsable(page, false), "a question card holds the board");
});
test("the git board lets go of a working agent that went adrift", async (t) => {
const working = { agent: { status: "working", activity: "Looking at the repo" } };
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), clock: true, payload: { ...BOARD, ...working } });
const { page } = s;
assert.equal(await usable(page), false, "a working agent holds the board");
// Nobody has listened for longer than the adrift limit. The board only
// redraws on a post, and the agent is still "working" in it: the lock must
// not outlive the agent.
await page.clock.fastForward(200_000);
s.post({ title: "Still on it", ...working });
await titled(page, "Still on it");
assert.ok(await settlesUsable(page, true), "an agent gone quiet gave the board back");
});
test("the commit table keeps the person's ticks across an agent post, and a click re-seeds them", async (t) => {
const dir = changesProject({ branch: "feature/x" });
const s = await openSession(await suite.browser(), { t, workflow: "git", project: dir, payload: READY });
const { page } = s;
await tabButton(page, "Changes").click();
await tickBox(page, "notes.md").uncheck();
// An agent post redraws the board: the person's tick stays off.
s.post({ title: "Still looking", agent: { status: "waiting" } });
await titled(page, "Still looking");
assert.equal(await tickBox(page, "notes.md").isChecked(), false, "an agent post put the tick back");
assert.equal(await tickBox(page, "src/app.js").isChecked(), true);
// Their click goes out with the one file. Then the agent commits it and a new file turns up.
await page.locator(".git-panel-actions").getByRole("button", { name: "Commit 1 file" }).click();
assert.deepEqual(s.wait(10).actions[0].files, ["src/app.js"]);
const g = gitInit(dir, "feature/x");
g("add", "src/app.js");
g("commit", "-q", "-m", "Edit app");
fs.writeFileSync(path.join(dir, "later.md"), "Later.\n");
s.post({ reread: true, title: "Committed", agent: { status: "waiting" } });
await titled(page, "Committed");
await tabButton(page, "Changes").click();
await tickBox(page, "later.md").waitFor();
assert.equal(await tickBox(page, "notes.md").isChecked(), true, "the click dropped the old picks, so the table was seeded afresh");
});
test("starting a branch for the changes carries the files ticked in the commit table", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject(), payload: READY });
const { page } = s;
await tabButton(page, "Changes").click();
await tickBox(page, "notes.md").uncheck();
await stepButton(page, /^Start a branch for/).click();
const panel = page.locator(".git-panel");
await panel.getByRole("heading", { name: "New branch for this commit" }).waitFor();
const create = panel.getByRole("button", { name: "Create", exact: true });
assert.ok(await settles(create, true), "a free name is composed from the description");
await create.click();
const got = s.wait(10);
assert.equal(got.code, 0);
assert.equal(got.actions.length, 1);
assert.equal(got.actions[0].op, "create");
assert.equal(got.actions[0].then, "commit");
assert.deepEqual(got.actions[0].files, ["src/app.js"], "the unticked file stayed out");
assert.match(got.reply, /^Create \S+ from main\. Then commit this file: src\/app\.js\.$/);
});
test("a commit with no branch to land on carries the ticked files into the new branch", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject({ branch: "detached" }), payload: READY });
const { page } = s;
await tabButton(page, "Changes").click();
await tickBox(page, "notes.md").uncheck();
// The step is on the Branches tab, and its Commit button finds no branch to commit on.
await tabButton(page, "Branches").click();
await stepButton(page, "Commit 2 files").click();
const panel = page.locator(".git-panel");
await panel.getByRole("heading", { name: "New branch for this commit" }).waitFor();
const create = panel.getByRole("button", { name: "Create", exact: true });
assert.ok(await settles(create, true));
await create.click();
const got = s.wait(10);
assert.equal(got.code, 0);
assert.equal(got.actions[0].op, "create");
assert.deepEqual(got.actions[0].files, ["src/app.js"]);
assert.match(got.reply, /Then commit this file: src\/app\.js\.$/);
});
test("Publish names a remote only when there is exactly one", async (t) => {
const browser = await suite.browser();
const published = async (remotes) => {
const s = await openSession(browser, { t, workflow: "git", project: changesProject({ branch: "feature/x", remotes }), payload: READY });
await tabButton(s.page, "Sync").click();
await s.page.locator(".git-sync-actions").getByRole("button", { name: "Publish" }).click();
const got = s.wait(10);
assert.equal(got.code, 0);
await s.stop();
return got;
};
const one = await published(["origin"]);
assert.equal(one.actions[0].remote, "origin");
assert.equal(one.reply, "Publish to origin.");
const two = await published(["origin", "backup"]);
assert.equal(Object.hasOwn(two.actions[0], "remote"), false, "with two remotes the agent is the one to ask which");
assert.equal(two.reply, "Publish.");
});
test("over the git board a note box grows with its text, and the no-repo note only points above when a card is there", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
s.post({ items: [confirmCard], agent: { status: "waiting" } });
const note = itemCard(s.page, "y1").locator("textarea").first();
await note.waitFor();
const before = await note.evaluate((el) => el.offsetHeight);
await note.fill(Array.from({ length: 8 }, (_, n) => `Line ${n + 1} of a longer note.`).join("\n"));
const after = await note.evaluate((el) => el.offsetHeight);
assert.ok(after > before + 40, `the note box grew with its text: ${before} to ${after}`);
// A folder that is no repository: the note points up only once there is a card up there.
const bare = await openSession(await suite.browser(), { t, workflow: "git", payload: { reread: true, agent: { status: "waiting" } } });
const aside = bare.page.locator(".git-note");
await aside.waitFor();
assert.match(await textOf(aside), /will ask what to do here in a moment/);
bare.post({ items: [confirmCard], agent: { status: "waiting" } });
await itemCard(bare.page, "y1").waitFor();
assert.match(await textOf(aside), /asks above what to do/);
});
+247
View File
@@ -0,0 +1,247 @@
// Page tests for Help, the first-run Welcome and the update notice's modal. Run
// with:
// node --test scripts/test-web-console-page-help.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. Help's prose stays untested; these cover how the dialog
// behaves.
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, tempProject, textOf, drawn } from "./page-test-helpers.mjs";
import { HOME } from "./web-console-test-helpers.mjs";
import { HELP_TABS } from "../src/web-console/public/help.js";
const suite = pageSuite(test);
// The console home's saved looks, shared by every session of this file. Each
// test that cares sets it first and the file is removed once the test is done.
const LOOKS_FILE = path.join(HOME, "looks.json");
function savedLooks(t, looks) {
if (looks) fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks }));
else fs.rmSync(LOOKS_FILE, { force: true });
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
}
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
// A plan session on the person's turn: one text question and the agent listening.
const PLAN_QUESTION = {
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
agent: { status: "waiting" },
};
// The dashboard, past Planny's wake-up. The Welcome may be on top of it. The
// wake-up plays once per tab, so a reloaded page has no intro to skip.
async function toTheDashboard(s) {
const heading = s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" });
const skip = s.page.getByRole("button", { name: "Skip the intro" });
await skip.or(heading).first().waitFor();
if (await skip.isVisible()) await skip.click();
await heading.waitFor();
}
const helpModal = (s) => s.page.locator("#help-modal");
const tabButton = (s, id) => s.page.locator("#help-tab-" + id);
const selectedTab = (s) => s.page.locator('#help-tabs [role="tab"][aria-selected="true"]');
const focusedId = (s) => s.page.evaluate(() => document.activeElement && document.activeElement.id);
async function openHelp(s) {
await s.page.click("#btn-about");
await helpModal(s).waitFor();
}
test("Help opens on a tab, moves between tabs with the arrow, Home and End keys, and closes with Escape", async (t) => {
savedLooks(t, { welcomeSeen: true });
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
// Built on first open: the tab buttons are not in the page before it.
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), 0, "Help is built before it is opened");
await openHelp(s);
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), HELP_TABS.length, "one tab button per Help topic");
// A plain workflow page opens on the first topic, with focus on its tab.
const ids = HELP_TABS.map((x) => x.id);
assert.equal(await selectedTab(s).count(), 1, "exactly one tab is selected");
assert.equal(await selectedTab(s).getAttribute("id"), "help-tab-" + ids[0]);
assert.equal(await focusedId(s), "help-tab-" + ids[0], "focus starts on the selected tab");
// Roving focus: only the selected tab is in the tab order, and its panel is the one shown.
const onlySelected = async (id) => {
assert.equal(await selectedTab(s).getAttribute("id"), "help-tab-" + id);
assert.equal(await focusedId(s), "help-tab-" + id, `focus is on ${id}`);
assert.equal(await tabButton(s, id).getAttribute("tabindex"), "0");
assert.equal(await s.page.locator('#help-tabs [role=tab][tabindex="0"]').count(), 1, "one tab stop");
assert.equal(await s.page.locator("#help-panel-" + id).isVisible(), true, `${id}'s panel is shown`);
assert.equal(await s.page.locator('#help-panels [role=tabpanel]:not([hidden])').count(), 1, "one panel is shown");
};
await onlySelected(ids[0]);
await s.page.keyboard.press("ArrowDown");
await onlySelected(ids[1]);
await s.page.keyboard.press("ArrowRight");
await onlySelected(ids[2]);
await s.page.keyboard.press("ArrowUp");
await onlySelected(ids[1]);
await s.page.keyboard.press("End");
await onlySelected(ids[ids.length - 1]);
await s.page.keyboard.press("ArrowDown");
await onlySelected(ids[0]);
await s.page.keyboard.press("ArrowUp");
await onlySelected(ids[ids.length - 1]);
await s.page.keyboard.press("Home");
await onlySelected(ids[0]);
// A click picks a tab too.
await tabButton(s, ids[3]).click();
await onlySelected(ids[3]);
await s.page.keyboard.press("Escape");
await helpModal(s).waitFor({ state: "hidden" });
assert.equal(await focusedId(s), "btn-about", "focus goes back to the Help button");
// Reopened, the built dialog is reused: no second set of tabs.
await openHelp(s);
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), HELP_TABS.length);
});
test("Help shows the live connection line and the version as a safe link to the Releases page", async (t) => {
savedLooks(t, { welcomeSeen: true });
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openHelp(s);
const live = s.page.locator("#about-live");
assert.match(await textOf(live), /^Right now: both halves are talking to each other\./);
assert.equal(await live.evaluate((n) => n.classList.contains("is-good")), true);
const link = s.page.locator("#help-version a");
await link.waitFor();
assert.match(await textOf(link), /^Plan2Code v\d+\.\d+\.\d+/, "the link names the installed version");
assert.equal(await link.getAttribute("href"), RELEASES_URL);
assert.equal(await link.getAttribute("rel"), "noopener noreferrer");
assert.equal(await link.getAttribute("target"), "_blank");
// The line is written on open: a finished session says so the next time.
await s.page.keyboard.press("Escape");
await helpModal(s).waitFor({ state: "hidden" });
s.post({ finish: { headline: "The plan is written", command: "/plan2code-2-document" } });
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor();
await openHelp(s);
assert.match(await textOf(live), /^Right now: the session is finished/);
});
test("a click on Help's backdrop closes it, and a click inside it does not", async (t) => {
savedLooks(t, { welcomeSeen: true });
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openHelp(s);
await s.page.locator("#help-title").click();
assert.equal(await helpModal(s).isVisible(), true, "a click inside closed Help");
// The top-left corner of the page is the backdrop, well outside the dialog.
await s.page.mouse.click(4, 4);
await helpModal(s).waitFor({ state: "hidden" });
});
test("Ctrl+Enter does not send while Help is open, and sends once it is closed", async (t) => {
savedLooks(t, { welcomeSeen: true });
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.locator('[data-item="q1"]').first().locator("textarea, input[type=text]").first().fill("audit-export");
await openHelp(s);
await s.page.keyboard.press("Control+Enter");
await s.page.keyboard.press("Meta+Enter");
assert.equal(s.wait(1).code === 0, false, "something was sent from behind Help");
assert.equal(await helpModal(s).isVisible(), true, "the key closed Help");
await s.page.keyboard.press("Escape");
await helpModal(s).waitFor({ state: "hidden" });
await s.page.keyboard.press("Control+Enter");
const got = s.wait(10);
assert.equal(got.code, 0, "Ctrl+Enter sends nothing with Help closed");
assert.deepEqual(
got.actions.map(({ i, type }) => ({ i, type })),
[{ i: "q1", type: "answer" }]
);
});
test("the Welcome shows on a first dashboard, saves that it was seen, and Help's Show the welcome again brings it back", async (t) => {
savedLooks(t, null);
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
await toTheDashboard(s);
const welcome = s.page.locator("#welcome-modal");
await welcome.waitFor();
assert.equal(await s.page.locator("#welcome-title").isVisible(), true);
await s.page.getByRole("button", { name: "Start building" }).click();
await welcome.waitFor({ state: "hidden" });
// Saved with the other looks, so it holds for the next page too.
await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).welcomeSeen === true);
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
await toTheDashboard(s);
await s.page.waitForTimeout(800);
assert.equal(await welcome.isVisible(), false, "the Welcome came back on a later page");
// Help's first topic offers it again, and Help steps aside for it.
// (On the dashboard Help opens on the dashboard topic, so go to the first.)
await openHelp(s);
await tabButton(s, HELP_TABS[0].id).click();
await s.page.getByRole("button", { name: "Show the welcome again" }).click();
await welcome.waitFor();
assert.equal(await helpModal(s).isVisible(), false, "Help stayed open under the Welcome");
await s.page.keyboard.press("Escape");
await welcome.waitFor({ state: "hidden" });
});
test("the Welcome stays away when the person has seen it, and off the dashboard", async (t) => {
const browser = await suite.browser();
savedLooks(t, { welcomeSeen: true });
const seen = await openSession(browser, { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
await toTheDashboard(seen);
await seen.page.waitForTimeout(800);
assert.equal(await seen.page.locator("#welcome-modal").isVisible(), false, "a seen Welcome showed again");
// Unseen, but a workflow page is not a first dashboard.
savedLooks(t, null);
const plan = await openSession(browser, { t, workflow: "plan", payload: PLAN_QUESTION });
await plan.page.waitForTimeout(800);
assert.equal(await plan.page.locator("#welcome-modal").isVisible(), false, "the Welcome showed on a workflow page");
});
// A newer release on record, so a console that boots now has an update to
// announce (the check reads this file for an hour instead of asking the
// network). The file is put back as the suite had it.
function aNewerReleaseExists(t) {
const file = path.join(HOME, "update-check.json");
const before = fs.readFileSync(file, "utf8");
fs.writeFileSync(file, JSON.stringify({ checkedAt: Date.now(), latest: "99.0.0" }));
t.after(() => fs.writeFileSync(file, before));
}
test("the update banner opens a modal with the exact update commands, and its dismissal is remembered for the session", async (t) => {
savedLooks(t, { welcomeSeen: true });
aNewerReleaseExists(t);
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
await toTheDashboard(s);
const main = s.page.locator("#main");
await main.getByRole("button", { name: /UPDATE AVAILABLE · v99\.0\.0/ }).click();
const modal = s.page.locator("#update-modal");
await modal.waitFor();
assert.match(await textOf(s.page.locator("#update-versions")), /^Version v99\.0\.0 is out/);
const releases = s.page.locator("#update-versions a");
assert.equal(await releases.getAttribute("href"), RELEASES_URL);
assert.equal(await releases.getAttribute("rel"), "noopener noreferrer");
assert.equal(await textOf(s.page.locator("#update-command code")), "plan2code update");
assert.equal(
await textOf(s.page.locator("#update-fallback code")),
"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"
);
await s.page.locator("#update-done").click();
await modal.waitFor({ state: "hidden" });
// The ×: gone now, remembered under this session's key, and still gone after a reload.
await main.getByRole("button", { name: "Dismiss until next time" }).click();
await main.getByRole("button", { name: /UPDATE AVAILABLE/ }).waitFor({ state: "hidden" });
assert.equal(await s.page.evaluate((k) => sessionStorage.getItem(k), "p2c-update-dismissed:" + s.sid), "99.0.0");
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
await toTheDashboard(s);
assert.equal(await main.getByRole("button", { name: /UPDATE AVAILABLE/ }).count(), 0, "the banner came back after a reload");
});
+156
View File
@@ -0,0 +1,156 @@
// Page tests for User Preferences: the saved looks (highlight and theme), the
// launcher's model menus and the Cleanup tab. Run with:
// node --test scripts/test-web-console-page-prefs.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 fs from "node:fs";
import path from "node:path";
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, textOf, drawn } from "./page-test-helpers.mjs";
import { HOME, MODELS_DIR, backdate } from "./web-console-test-helpers.mjs";
import { formatBytes } from "../src/web-console/public/answers.js";
const suite = pageSuite(test);
// A plan session on the person's turn: one text question and the agent listening.
const PLAN_QUESTION = {
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
agent: { status: "waiting" },
};
// The console home's saved looks are shared by every session of this file, so
// each test starts with none and leaves none.
const LOOKS_FILE = path.join(HOME, "looks.json");
function noSavedLooks(t) {
fs.rmSync(LOOKS_FILE, { force: true });
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
}
const root = (s, attr) => s.page.evaluate((a) => document.documentElement.getAttribute(a), attr);
// The highlight the page paints with: an inline override while it is not the default.
const accentVar = (s) => s.page.evaluate(() => document.documentElement.style.getPropertyValue("--accent"));
const swatch = (s, id) => s.page.locator(`#looks-swatches [data-accent="${id}"]`);
// The page as the server first sends it, before any script has run: the saved
// theme and highlight are in the markup so a reload never flashes the defaults.
async function firstPaintAttrs(s) {
const html = await (await s.context.request.get(s.url)).text();
const tag = html.match(/<html\b[^>]*>/i)[0];
return { theme: tag.match(/data-theme="([^"]*)"/)?.[1] ?? null, accent: tag.match(/data-looks-accent="([^"]*)"/)?.[1] ?? null };
}
test("the violet highlight and dark theme chosen in preferences stick across a reload, and Back to default clears them", async (t) => {
noSavedLooks(t);
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
assert.equal(await root(s, "data-theme"), null, "the theme starts on the system's");
await s.page.click("#btn-looks");
await s.page.locator("#looks-modal[open]").waitFor();
await swatch(s, "violet").click();
await s.page.locator('input[name="looks-theme"][value="dark"]').check();
await s.page.waitForFunction(() => document.documentElement.getAttribute("data-theme") === "dark");
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "true");
assert.equal(await accentVar(s), "#a785e2", "the dark violet is painted");
// Saved on the server (looks.json), not only in this tab.
await s.page.waitForFunction(async () => {
const saved = (await (await fetch("/looks")).json()).looks || {};
return saved.accent === "violet" && saved.theme === "dark";
});
await s.page.click("#looks-done");
// What the server sends first, and what the page settles on, both keep the choice.
assert.deepEqual(await firstPaintAttrs(s), { theme: "dark", accent: "violet" }, "the first paint carries the saved looks");
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
assert.equal(await root(s, "data-theme"), "dark", "the theme did not stick");
await s.page.waitForFunction(() => document.documentElement.style.getPropertyValue("--accent") === "#a785e2");
await s.page.click("#btn-looks");
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "true", "the violet swatch is not the chosen one after a reload");
assert.equal(await s.page.locator('input[name="looks-theme"][value="dark"]').isChecked(), true);
// Back to default returns both, here and for the next page.
await s.page.click("#looks-reset");
await s.page.waitForFunction(() => !document.documentElement.hasAttribute("data-theme"));
assert.equal(await accentVar(s), "", "the chosen highlight is still painted");
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "false");
assert.equal(await s.page.locator('input[name="looks-theme"][value="system"]').isChecked(), true);
await s.page.waitForFunction(async () => {
const saved = (await (await fetch("/looks")).json()).looks || {};
return saved.theme === "system" && saved.accent !== "violet";
});
assert.deepEqual(await firstPaintAttrs(s), { theme: null, accent: null }, "the first paint still carries the old looks");
});
test("the launcher's model menus have Claude, Devin and Codex tabs, and a model id typed on the Codex tab is saved", async (t) => {
noSavedLooks(t);
// The file the launcher reads: put back as the suite had it (no file).
t.after(() => fs.rmSync(path.join(MODELS_DIR, "models.json"), { force: true }));
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.click("#btn-looks");
const tabs = s.page.getByRole("group", { name: "Which agent" });
for (const name of ["Claude", "Devin", "Codex"]) assert.equal(await tabs.getByRole("button", { name, exact: true }).count(), 1, `a ${name} tab`);
const pressed = async () => (await tabs.locator('button[aria-pressed="true"]').allInnerTexts()).map((x) => x.trim());
assert.deepEqual(await pressed(), ["Claude"], "the menus open on Claude");
await tabs.getByRole("button", { name: "Codex", exact: true }).click();
assert.deepEqual(await pressed(), ["Codex"]);
await s.page.click("#models-add");
const id = s.page.locator("#models-user").getByRole("textbox", { name: "Model id" });
await id.fill("gpt-test-codex-1");
await id.press("Tab");
await s.page.locator("#models-status").filter({ hasText: /^Saved\./ }).waitFor();
const saved = await s.page.evaluate(async () => (await (await fetch("/models")).json()).user);
assert.deepEqual(saved.codex.map((m) => m.id), ["gpt-test-codex-1"], "the id was not saved under Codex");
assert.deepEqual([saved.claude, saved.devin], [[], []], "the id leaked into another agent's menu");
// Back on Claude the typed id is not listed; on Codex it is, after a reload.
await tabs.getByRole("button", { name: "Claude", exact: true }).click();
assert.equal(await s.page.locator("#models-user .models-row").count(), 0);
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
await s.page.click("#btn-looks");
await s.page.locator("#models-tab-codex").click();
await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).waitFor();
assert.equal(await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).inputValue(), "gpt-test-codex-1");
});
test("Cleanup scans the console home and lists an old session folder with its size", async (t) => {
noSavedLooks(t);
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
// Made after the session opens: opening sweeps old sessions away. A session
// is old when nothing in it has been touched for 30 days.
const sid = "20250801-101010-aaaaaa";
const dir = path.join(HOME, "sessions", sid);
fs.mkdirSync(dir, { recursive: true });
const state = path.join(dir, "state.json");
fs.writeFileSync(state, "x".repeat(3000));
backdate(state);
backdate(dir);
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
await s.page.click("#btn-looks");
const list = s.page.locator("#cleanup-list");
assert.equal(await list.locator(".cleanup-row").count(), 0, "Cleanup lists things before a scan");
assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true, "Delete is offered before a scan");
await s.page.click("#cleanup-scan");
const row = list.locator(".cleanup-row").filter({ hasText: sid });
await row.waitFor();
assert.match(await textOf(row), new RegExp(`^Session ${sid}`));
const size = await textOf(row.locator(".cleanup-size"));
assert.match(size, /^\d/, "the row names a size");
assert.ok(size === formatBytes(3000) || /^[\d.,]+\s*(kB|KB|MB|B)\b/.test(size), `the size reads as a size: ${size}`);
assert.match(await textOf(list.locator(".cleanup-summary")), /1 old session/);
assert.match(await textOf(s.page.locator("#cleanup-status")), /^Found \d+ items?\./);
assert.equal(await s.page.locator("#cleanup-delete").isVisible(), true, "Delete these is offered once something is found");
// The scan only looks.
assert.equal(fs.existsSync(dir), true, "a scan deleted the folder");
// Closing preferences forgets the scan: a reopened dialog starts clean.
await s.page.click("#looks-done");
await s.page.click("#btn-looks");
assert.equal(await list.locator(".cleanup-row").count(), 0, "the old scan is still listed");
assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true);
});
+497
View File
@@ -0,0 +1,497 @@
// Page tests for how a session ends and comes back: the finished screen and
// its buttons, Stop and Stop with a handoff, and a page that loses its server
// and finds it again after a resume. Run with:
// node --test scripts/test-web-console-page-session.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, drawn, textOf, tempProject } from "./page-test-helpers.mjs";
import { cli, until } from "./web-console-test-helpers.mjs";
import { STOP_HANDOFF_REPLY, HOME_REPLY } from "../src/web-console/public/answers.js";
// How long the page waits without contact before it calls itself offline:
// the page's own constant, so this file never drifts from it.
import { GONE_AFTER_MS } from "../src/web-console/public/screens/core.js";
const suite = pageSuite(test);
// The banner the page raises when it loses its server mid-session.
const LOST_CONTACT = /Lost contact with Plan2Code\. Nothing you have typed is lost\./;
// A plan session on the person's turn, the way an agent opens one: one text
// question and the agent listening.
const PLAN_QUESTION = {
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
agent: { status: "waiting" },
};
// The agent's side of `stop`, leaving the browser context open (s.stop()
// closes it, which would hide what the page does next).
async function stopServer(s) {
cli(["stop", "--session", s.sid], { cwd: s.project });
assert.ok(await until(async () => !(await s.answers()), 5000), "the server still answers after stop");
}
// The one send `wait` hands the agent; fails the test when nothing arrived.
function collect(s) {
const got = s.wait(10);
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
return got;
}
// Local helper: checks `fn` keeps returning true for `ms`. A sleep would
// prove nothing; this fails the moment the page shows what it must not.
async function holds(fn, ms) {
const end = Date.now() + ms;
while (Date.now() < end) {
if (!(await fn())) return false;
await new Promise((r) => setTimeout(r, 100));
}
return true;
}
test("the finished screen shows the next command with --web, copies it, turns Send off, and Back to the dashboard reaches the agent", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: new URL(s.url).origin });
s.post({
settle: true,
finish: {
headline: "The plan is written",
body: "Everything is under `specs/audit-export/`. Read `PLAN.md` first.",
command: "/plan2code-2-document",
dashboard: true,
},
});
const main = s.page.locator("#main");
await main.getByRole("heading", { name: "The plan is written" }).waitFor();
const shown = main.locator("code").filter({ hasText: /^\/plan2code-2-document --web$/ });
assert.equal(await shown.count(), 1, "the command is shown once, with --web appended");
// The Copy that belongs to this command: the innermost block holding both,
// whatever wraps them.
// (`has` is matched inside each candidate, so these start from the page.)
const code = s.page.locator("code").filter({ hasText: /^\/plan2code-2-document --web$/ });
const copy = s.page.getByRole("button", { name: "Copy", exact: true });
await main.locator("*", { has: code }).filter({ has: copy }).last().getByRole("button", { name: "Copy", exact: true }).click();
await s.page.waitForFunction(async () => (await navigator.clipboard.readText()) === "/plan2code-2-document --web");
assert.equal(await s.page.evaluate(() => navigator.clipboard.readText()), "/plan2code-2-document --web");
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "Send is still on after the finish");
await main.getByRole("button", { name: "Back to the dashboard" }).click();
const got = collect(s);
assert.equal(got.type, "submit");
assert.deepEqual(
got.actions.map(({ i, type }) => ({ i, type })),
[{ i: "__dashboard", type: "dashboard" }]
);
});
test("Stop session, confirmed, sends __stop with no handoff", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.click("#btn-stop");
await s.page.locator("#stop-go").click();
const got = collect(s);
assert.equal(got.type, "submit");
const stop = got.actions.find((a) => a.i === "__stop");
assert.deepEqual(stop, { i: "__stop", type: "stop" });
});
test("Stop with a handoff sends __stop with handoff, and the paused finish and stop that follow end on the paused screen, not an error", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.click("#btn-stop");
const handoff = s.page.locator("#stop-handoff");
assert.equal(await handoff.isVisible(), true, "the handoff choice is offered off the dashboard");
await handoff.click();
const got = collect(s);
assert.equal(got.type, "submit");
const stop = got.actions.find((a) => a.i === "__stop");
assert.deepEqual(stop, { i: "__stop", type: "stop", handoff: true });
// What the agent does next (console-stop.md): a paused finish without
// --wait and no dashboard, then `stop`.
s.post({
settle: true,
finish: {
headline: "Paused at the naming question",
body: "Your place is saved, and a handoff is waiting on the dashboard. The naming question is still open.",
command: "/plan2code-1-plan",
},
});
const main = s.page.locator("#main");
await main.getByRole("heading", { name: "Paused at the naming question" }).waitFor();
await stopServer(s);
// The page needs GONE_AFTER_MS without contact before it would call the
// server lost. Through that window and past it, the paused screen stays.
const settled = async () =>
!LOST_CONTACT.test(await s.page.locator("#banner").innerText()) &&
!(await s.page.locator("#planny").getAttribute("class")).includes("is-gone");
assert.ok(await holds(settled, GONE_AFTER_MS + 3000), "the page raised a lost-contact state after a paused finish");
assert.match(await main.innerText(), /Session paused/i);
assert.match(await textOf(s.page.locator("#agent-text")), /^Paused\./);
assert.ok(await main.locator("code").filter({ hasText: /^\/plan2code-1-plan --web$/ }).count(), "the resume command is gone");
});
test("a page that loses its server goes offline, and after a resume it shows the session again with the unsent answer still typed", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
const field = () => itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
await field().fill("audit-export");
// Typed, not sent: the page mirrors it to the server's draft.json, which
// is what a page on a new port reads back (localStorage is per origin).
const draftFile = path.join(s.session, "draft.json");
assert.ok(
await until(() => fs.existsSync(draftFile) && fs.readFileSync(draftFile, "utf8").includes("audit-export"), 5000),
"the typed answer never reached the server's draft"
);
await stopServer(s);
await s.page.waitForFunction(() => document.getElementById("planny").classList.contains("is-gone"), null, {
timeout: GONE_AFTER_MS + 10000,
});
assert.match(await textOf(s.page.locator("#agent-text")), /^Not connected\. Your answers are saved\./);
assert.match(await s.page.locator("#banner").innerText(), LOST_CONTACT);
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "Send is on with no server");
const resumed = cli(["open", "--resume", s.sid, "--workflow", "plan", "--no-open"], { cwd: s.project }).json;
assert.ok(resumed && resumed.url, "the resume printed no url");
await s.page.goto(resumed.url, { waitUntil: "domcontentloaded" });
await drawn(s.page);
await itemCard(s.page, "q1").getByText("What to call it").first().waitFor();
assert.equal(await field().inputValue(), "audit-export", "the unsent answer was lost across the resume");
assert.equal(await s.page.locator("#planny").evaluate((n) => n.classList.contains("is-gone")), false);
});
// The status line beside Planny, and its "What to check" button when it has
// one. The button opens Help on the stuck tab.
const statusLine = (s) => s.page.locator("#agent-text");
const whatToCheck = (s) => statusLine(s).getByRole("button", { name: "What to check" });
async function lineSays(s, re) {
await s.page.waitForFunction((src) => new RegExp(src).test(document.getElementById("agent-text").textContent), re.source, { timeout: 10000 });
return textOf(statusLine(s));
}
test("the quiet, not running and not connected lines offer What to check, opening Help on the stuck tab, and the plain lines do not", async (t) => {
const s = await openSession(await suite.browser(), {
t,
workflow: "implement",
clock: true,
payload: { headline: { stage: "Phase 1", cleared: 0, total: 3 }, agent: { status: "working", activity: "Task 1 of 3: the reader" } },
});
// Working, and heard from just now: the plain working line.
await lineSays(s, /Task 1 of 3: the reader/);
assert.equal(await whatToCheck(s).count(), 0, "the working line is plain");
// Quiet for 30 s: the approval hint, with the button.
await s.page.clock.fastForward(40_000);
await lineSays(s, /waiting on an approval in your terminal/);
assert.equal(await whatToCheck(s).count(), 1, "the approval hint carries What to check");
// Quiet for two minutes: still working, and the button stays.
await s.page.clock.fastForward(100_000);
await lineSays(s, /^Still working on it\./);
assert.equal(await whatToCheck(s).count(), 1, "the quiet working line carries What to check");
// Back to real time, and the agent asks something: the person's turn is plain.
await s.page.clock.setSystemTime(Date.now());
s.post({ items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } });
await lineSays(s, /^Your turn: 1 question waiting\./);
assert.equal(await whatToCheck(s).count(), 0, "the your-turn line is plain");
// Nobody listening for three minutes: not running, with the button.
await s.page.clock.fastForward(200_000);
await lineSays(s, /^Plan2Code is not running right now\./);
assert.equal(await whatToCheck(s).count(), 1, "the not running line carries What to check");
await whatToCheck(s).click();
await s.page.locator("#help-modal[open]").waitFor();
assert.equal(await s.page.locator("#help-tab-stuck").getAttribute("aria-selected"), "true", "Help opened on the stuck tab");
await s.page.keyboard.press("Escape");
await s.page.locator("#help-modal[open]").waitFor({ state: "detached" });
// Answered and sent, never collected, and nobody listening: the saved line.
await s.page.clock.setSystemTime(Date.now());
s.post({ agent: { status: "waiting" } });
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
await s.page.click("#btn-send");
await lineSays(s, /^Sent\. Waiting for Plan2Code\./);
assert.equal(await whatToCheck(s).count(), 0, "the sent line is plain");
await s.page.clock.fastForward(200_000);
await lineSays(s, /^Plan2Code is not running\. Your answers are saved and waiting for it\./);
assert.equal(await whatToCheck(s).count(), 1, "the saved-and-waiting line carries What to check");
// No server at all: not connected, with the button.
await stopServer(s);
for (let i = 0; i < 20 && !(await s.page.locator("#planny.is-gone").count()); i++) {
await s.page.clock.fastForward(GONE_AFTER_MS);
await new Promise((r) => setTimeout(r, 250));
}
await lineSays(s, /^Not connected\. Your answers are saved\./);
assert.equal(await whatToCheck(s).count(), 1, "the not connected line carries What to check");
});
test("an answered finish offer comes back unanswered on a later finish, once the first finish has gone", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
const finishWith = (headline) => s.post({ finish: { headline, command: "/plan2code-3-implement specs/audit-export/overview.md", dashboard: true } });
const main = s.page.locator("#main");
finishWith("Phase 1 is done");
await main.getByRole("heading", { name: "Phase 1 is done" }).waitFor();
await main.getByRole("button", { name: "Back to the dashboard" }).click();
assert.deepEqual(collect(s).actions.map(({ i }) => i), ["__dashboard"]);
await lineSays(s, /^Opening the dashboard…/);
// The agent takes the press somewhere that clears the finish, and a later
// phase ends: that finish starts with its own offer unanswered.
s.post({ finish: null, agent: { status: "working", activity: "Task 1 of 1" } });
await lineSays(s, /Task 1 of 1/);
finishWith("Phase 2 is done");
await main.getByRole("heading", { name: "Phase 2 is done" }).waitFor();
await lineSays(s, /^Done\. Head back to the dashboard, or close this tab\./);
assert.equal(await main.getByRole("button", { name: "Back to the dashboard" }).count(), 1, "the later finish offers the way back again");
});
test("a finished session never puts a sent answer back on its form", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await itemCard(s.page, "q1").locator("textarea").fill("audit-export");
await s.page.click("#btn-send");
collect(s);
// Collected and left open, then the session ends: nothing more can be sent,
// so the answer stays sent rather than coming back to edit. It would show
// once the finish goes away (a review taken up), as an answer ready to send.
s.post({ finish: { headline: "The plan is written", command: "/plan2code-2-document" }, agent: { status: "waiting" } });
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor();
s.post({ finish: null, agent: { status: "waiting" } });
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor({ state: "detached" });
const q1 = s.page.locator("#sidebar").getByRole("button", { name: /What to call it/ });
await q1.click();
await itemCard(s.page, "q1").waitFor();
const mark = q1.locator(".rail-mark");
assert.notEqual(await mark.getAttribute("title"), "ready to send", "the sent answer came back on the form");
const box = itemCard(s.page, "q1").locator("textarea");
assert.notEqual((await box.count()) ? await box.inputValue() : "", "audit-export", "the sent answer is back in its box");
});
test("the footer keeps its workspace label on the dashboard, and the label opens the Workspace dialog", async (t) => {
const project = tempProject();
const name = path.basename(project);
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", project });
// Past Planny's wake-up and, on this console home's first run, the Welcome.
await s.page.getByRole("button", { name: "Skip the intro" }).click();
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
if (await welcomeDone.isVisible()) await welcomeDone.click();
await welcomeDone.waitFor({ state: "hidden" });
const foot = s.page.locator("footer.footer");
const where = s.page.locator("#footer-where");
await where.waitFor();
// The dashboard drops the summary and Send, never the label.
assert.equal(await foot.evaluate((f) => f.classList.contains("is-dash")), true, "the dashboard's footer is marked is-dash");
assert.equal(await s.page.locator("#footer-summary").isVisible(), false, "the summary shows on the dashboard");
assert.equal(await s.page.locator("#btn-send").isVisible(), false, "Send shows on the dashboard");
assert.match(await textOf(where), new RegExp(`^${name}`), "the label names the project");
assert.equal(await where.getAttribute("title"), "Open workspace");
assert.match(await where.getAttribute("aria-label"), new RegExp(`^Open workspace: ${name}`));
// A click opens the Workspace dialog on the session's folders; leaving the
// label leaves it as it was (no copied state to undo).
await where.click();
await s.page.locator("#workspace-modal[open]").waitFor();
assert.match(await textOf(s.page.locator("#workspace-list")), new RegExp(name));
await s.page.keyboard.press("Escape");
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
await s.page.locator("body").click({ position: { x: 5, y: 5 } });
assert.match(await textOf(where), new RegExp(`^${name}`), "the label changed after a click away");
});
test("a workflow page uses its modules: the full footer, the session meter, @ suggestions and the tab icon", async (t) => {
const project = tempProject();
const name = path.basename(project);
const s = await openSession(await suite.browser(), { t, workflow: "plan", project, payload: PLAN_QUESTION });
// Off the dashboard the footer is whole (workspace.js names the label).
assert.equal(await s.page.locator("footer.footer").evaluate((f) => f.classList.contains("is-dash")), false);
assert.equal(await s.page.locator("#btn-send").isVisible(), true);
// meter.js: the pill shows once a frame carries the meter.
await s.page.locator("#meter-pill").waitFor();
assert.ok((await textOf(s.page.locator("#meter-words"))).length, "the meter pill has no words");
// mentions.js: an @ in a text box offers the workspace's folders.
const box = itemCard(s.page, "q1").locator("textarea");
await box.click();
await box.pressSequentially("See @");
await s.page.locator("#mention-pop").waitFor();
assert.match(await textOf(s.page.locator("#mention-pop")), new RegExp(name));
// favicon.js: the person's move puts a bar on the tab icon.
await s.page.waitForFunction(() => document.querySelector('link[rel="icon"][type="image/svg+xml"]').href.startsWith("data:image/svg+xml"));
});
// The dashboard, past Planny's wake-up and the first-run Welcome.
async function pastTheIntro(s) {
const skip = s.page.getByRole("button", { name: "Skip the intro" });
await skip.click();
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
if (await welcomeDone.isVisible()) await welcomeDone.click();
await welcomeDone.waitFor({ state: "hidden" });
}
// What a person sees break: a handoff offered where there is nothing to hand off.
test("the stop dialog offers a handoff in a workflow and one plain Stop on the dashboard", async (t) => {
const plan = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
await plan.page.click("#btn-stop");
const modal = plan.page.locator("#stop-modal");
await modal.waitFor();
assert.match(await textOf(modal), /Stop with a handoff/);
assert.match(await textOf(modal.locator("#stop-go")), /Just stop and save/);
const dash = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } } });
await pastTheIntro(dash);
await dash.page.click("#btn-stop");
await dash.page.locator("#stop-modal").waitFor();
assert.equal(await dash.page.locator("#stop-handoff").isVisible(), false, "the dashboard offers a handoff");
assert.match(await textOf(dash.page.locator("#stop-go")), /Stop\s+Ends the console session\./);
assert.doesNotMatch(await textOf(dash.page.locator("#stop-modal")), /Stop with a handoff/);
});
// What the agent would misread: a handoff stop that carries the plain stop's words.
test("Stop with a handoff sends its own reply line beside the stop, and a plain stop sends another", async (t) => {
const handoff = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
await handoff.page.click("#btn-stop");
await handoff.page.locator("#stop-handoff").click();
const got = collect(handoff);
assert.deepEqual(got.actions.find((a) => a.i === "__stop"), { i: "__stop", type: "stop", handoff: true });
assert.ok(got.reply.includes(STOP_HANDOFF_REPLY), `the handoff stop's words: ${got.reply}`);
const plain = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
await plain.page.click("#btn-stop");
await plain.page.locator("#stop-go").click();
const sent = collect(plain);
assert.equal(sent.actions.find((a) => a.i === "__stop").handoff, undefined);
assert.ok(!sent.reply.includes(STOP_HANDOFF_REPLY), "a plain stop asked for a handoff");
});
// A finish that offers a review, a commit and the dashboard, on a build.
const OFFERS = { headline: "Quick task done", command: "/plan2code-5-git", review: true, commit: true, dashboard: true };
const closeGuide = (s) => s.page.getByRole("region", { name: "Before you close this" });
// What a person sees break: "Safe to close" printed under "Review requested", or the review offer coming back after a reload.
test("Before you close this shows while a review is on offer, goes while it is asked, and the asked offer stays locked after a reload", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "quick-task", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
s.post({ finish: OFFERS });
const main = s.page.locator("#main");
const reviewNow = main.getByRole("button", { name: "Review it now" });
await reviewNow.waitFor();
assert.equal(await closeGuide(s).count(), 1, "a review only on offer must not hide the guide");
assert.match(await textOf(main), /The review is optional\./);
await reviewNow.click();
const got = collect(s);
assert.deepEqual(got.actions.map(({ i, type }) => ({ i, type })), [{ i: "__review", type: "review" }]);
await main.getByRole("button", { name: "Review requested…" }).waitFor();
assert.equal(await closeGuide(s).count(), 0, "the guide shows while a review is starting");
assert.equal(await main.getByRole("button", { name: "No thanks, I am done" }).count(), 0);
// The press is remembered: the buttons do not come back on a reload.
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
await main.getByRole("button", { name: "Review requested…" }).waitFor();
assert.equal(await main.getByRole("button", { name: "Review it now" }).count(), 0);
assert.equal(await closeGuide(s).count(), 0, "the guide came back on a reload");
});
// What a person sees break: the guide missing while a commit or the dashboard
// is starting (it would say "start a new one" under "Opening Git"), or missing
// once they said they are done or the server is gone.
test("Before you close this goes while a commit or the dashboard is starting, and stays once they are done or the server is gone", async (t) => {
const browser = await suite.browser();
const finishPage = async (opts) => {
const s = await openSession(browser, { t, workflow: "quick-task", ...opts, payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
s.post({ finish: OFFERS });
await s.page.locator("#main").getByRole("heading", { name: "Quick task done" }).waitFor();
assert.equal(await closeGuide(s).count(), 1, "a plain finish shows the guide");
return s;
};
const cases = [
["Commit it now", "__commit", "Opening Git…", 0],
["Back to the dashboard", "__dashboard", "Opening the dashboard…", 0],
["No thanks, I am done", "__done", null, 1],
];
for (const [button, id, asked, guides] of cases) {
const s = await finishPage({});
await s.page.locator("#main").getByRole("button", { name: button }).click();
assert.deepEqual(collect(s).actions.map((a) => a.i), [id]);
if (asked) await s.page.locator("#main").getByRole("button", { name: asked }).waitFor();
assert.equal(await closeGuide(s).count(), guides, `the guide after ${button}`);
}
// A review asked, then the server gone: nothing is starting any more.
const gone = await finishPage({ clock: true });
await gone.page.locator("#main").getByRole("button", { name: "Review it now" }).click();
collect(gone);
assert.equal(await closeGuide(gone).count(), 0);
await stopServer(gone);
for (let i = 0; i < 20 && !(await gone.page.locator("#planny.is-gone").count()); i++) {
await gone.page.clock.fastForward(GONE_AFTER_MS);
await new Promise((r) => setTimeout(r, 250));
}
await closeGuide(gone).waitFor();
});
// What a person sees break: a finished screen with no Before you close this,
// a pause that promises the wrong thing, or the guide's own text going wrong.
test("every finished shape shows Before you close this with its three rows, and a pause names the resume command", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
const main = s.page.locator("#main");
const shapes = [
["A skill next", { command: "/plan2code-4-finalize" }, /A new session starts from clean context/, /Paste the command above in the new session, or start from the dashboard with \/plan2code\./],
["A terminal command next", { command: "git status" }, /A new session starts from clean context/, /Run the command above in your terminal, then start the next step/],
["Nothing left", {}, /A new session starts from clean context/, /In the new session, start from the dashboard with \/plan2code\./],
["Paused here", { command: "/plan2code-3-implement specs/x/overview.md" }, /Your saved place is picked up by the resume command above\./, /Paste the command above/],
];
for (const [headline, rest, fresh, carry] of shapes) {
s.post({ finish: { headline, ...rest } });
await main.getByRole("heading", { name: headline }).waitFor();
const guide = closeGuide(s);
assert.equal(await guide.count(), 1, `${headline}: one guide`);
assert.equal(await guide.locator("li").count(), 3, `${headline}: three rows`);
const text = await textOf(guide);
for (const label of ["Before you close this", "Safe to close", "Start fresh", "Carry on"]) assert.ok(text.includes(label), `${headline}: says "${label}"`);
assert.match(text, fresh, `${headline}: the Start fresh sentence`);
assert.match(text, carry, `${headline}: the Carry on sentence`);
assert.ok(!text.includes("—"), `${headline}: the guide carries an em dash`);
}
// With a stop warning up, a pause's command starts the work again.
s.post({ stopWarning: "Answers since the last save will not be kept." });
await closeGuide(s).getByText(/The command above starts it again\./).waitFor();
assert.equal(await s.page.locator("#btn-home").isVisible(), false, "a finished screen carries its own way back");
});
// What a person sees break: the triangle leaving answers behind, or sending a
// finish-style stop instead of the way home.
test("the top bar's back triangle asks first, then sends __dashboard with the typed answers and the home reply", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
await s.page.click("#btn-home");
const modal = s.page.locator("#home-modal");
await modal.waitFor();
assert.match(await textOf(modal), /Leave this workflow\?/);
assert.match(await textOf(modal.locator("#home-blurb")), /The answer you have ready goes with it\./);
await modal.locator("#home-cancel").click();
await modal.waitFor({ state: "hidden" });
assert.equal(s.wait(1).code === 0, false, "Cancel sent something");
await s.page.click("#btn-home");
await modal.locator("#home-go").click();
const got = collect(s);
assert.deepEqual(got.actions.map(({ i, type }) => ({ i, type })), [{ i: "q1", type: "answer" }, { i: "__dashboard", type: "dashboard" }]);
assert.ok(got.reply.includes("audit-export") && got.reply.endsWith(HOME_REPLY), `the reply carries the answer, then the home line: ${got.reply}`);
await s.page.waitForFunction(() => document.getElementById("btn-home").disabled);
});
// What a person sees break: Back to default in Preferences does nothing.
test("Back to default in Preferences returns the theme to follow the system and clears the chosen look", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.click("#btn-looks");
await s.page.locator('input[name="looks-theme"][value="dark"]').check();
await s.page.waitForFunction(() => document.documentElement.getAttribute("data-theme") === "dark");
await s.page.click("#looks-reset");
await s.page.waitForFunction(() => !document.documentElement.hasAttribute("data-theme"));
assert.equal(await s.page.locator('input[name="looks-theme"][value="system"]').isChecked(), true, "the system choice is ticked again");
});
@@ -0,0 +1,94 @@
// Page tests for the Workspace dialog and @mentions: adding a folder from the
// footer label, what the next send tells the agent, and picking a folder from
// the list an @ opens in a note. Run with:
// node --test scripts/test-web-console-page-workspace.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 } from "./page-test-helpers.mjs";
import { tempFolder } from "./web-console-test-helpers.mjs";
const suite = pageSuite(test);
// A plan session on the person's turn: one text question, the agent listening.
const PLAN_QUESTION = {
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
agent: { status: "waiting" },
};
// A folder named `datasets` in its own temp parent, so its @name is known.
function datasetsFolder() {
const dir = path.join(tempFolder(), "datasets");
fs.mkdirSync(dir, { recursive: true });
return dir;
}
// Opens Workspace from the footer label and adds `dir` by typing its path.
async function addFolderFromDialog(s, dir) {
await s.page.locator("#footer-where").click();
await s.page.locator("#workspace-modal[open]").waitFor();
await s.page.locator("#workspace-path").fill(dir);
await s.page.locator("#workspace-add").click();
await s.page.locator("#workspace-add-msg.is-good").waitFor();
}
// What a person sees break: a folder that does not show in the dialog, or
// that the agent is never told about.
test("a folder added in Workspace is listed with its @name, and the next send tells the agent in its reply", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
const dir = datasetsFolder();
await addFolderFromDialog(s, dir);
assert.equal(await textOf(s.page.locator("#workspace-add-msg")), "Added as @datasets.");
const rows = s.page.locator("#workspace-list .ws-entry");
assert.equal(await rows.count(), 2, "the project's own folder and the new one");
const added = rows.filter({ hasText: "@datasets" });
assert.equal(await added.count(), 1);
assert.equal(await textOf(added.locator(".ws-path")), dir);
assert.equal(await added.locator(".ws-original").count(), 0, "only the first folder is the original");
assert.equal(await rows.first().locator(".ws-original").count(), 1);
assert.equal(await s.page.locator("#workspace-path").inputValue(), "", "the path box empties after an add");
await s.page.locator("#workspace-done").click();
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
await s.page.click("#btn-send");
const got = s.wait(10);
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code})`);
assert.ok(got.reply.includes("audit-export"), `the answer is in the reply: ${got.reply}`);
assert.ok(got.reply.includes("Workspace: added @datasets"), `the Workspace line: ${got.reply}`);
assert.ok(got.reply.includes(dir), `the Workspace line names the path: ${got.reply}`);
});
// What a person sees break: an @ that offers nothing, or a pick that leaves
// the box as it was.
test("an @ in a note offers the workspace's folders, and picking one writes its @name into the note", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await addFolderFromDialog(s, datasetsFolder());
await s.page.locator("#workspace-done").click();
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
const note = s.page.locator("#aside #thread-q1");
await note.click();
await note.pressSequentially("Look in @da");
const pop = s.page.locator("#mention-pop");
await pop.waitFor();
const options = pop.locator(".mention-opt");
assert.deepEqual(await options.allTextContents(), ["@datasets"], "only the folder that matches what was typed");
await options.first().click();
await pop.waitFor({ state: "detached" });
assert.equal(await note.inputValue(), "Look in @datasets ");
// A bare @ lists every folder, the project's own first.
await note.pressSequentially("and @");
await pop.waitFor();
assert.equal(await pop.locator(".mention-opt").count(), 2);
await s.page.keyboard.press("Escape");
await pop.waitFor({ state: "detached" });
});
+10 -45
View File
@@ -13,11 +13,12 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { applyPatch, validate, blankState } from "../src/web-console/lib.mjs";
import { applyPatch, validate, blankState } from "../src/web-console/patches.mjs";
import { rebasingBranch } from "../src/web-console/git-repo.mjs";
import { indentReply, noteReplyLines, agentRepliedAfterSend } from "../src/web-console/public/answers.js";
import { chatView } from "../src/web-console/public/chat.js";
import { ROOT, CONSOLE_CLI, ENV, cli, payload, readState, postPatch, EXPORT_A, openSession } from "./web-console-test-helpers.mjs";
import { joinedCss } from "./css-helpers.mjs";
const choice = (id, extra = {}) => ({
id,
@@ -32,8 +33,7 @@ const choice = (id, extra = {}) => ({
});
const waitFor = (s, seconds = 10) => cli(["wait", "--session", s.sid, "--seconds", String(seconds)]);
const runCli = (args, opts = {}) => spawnSync(process.execPath, [CONSOLE_CLI, ...args], { env: ENV, encoding: "utf8", ...opts });
const app = () => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
const css = () => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
const css = () => joinedCss();
/* ------------------------------------------------------------ settling */
@@ -195,7 +195,6 @@ test("a rebase in progress names the branch it is rewriting", () => {
test("a typed line never starts a reply line of its own", () => {
assert.equal(indentReply("a\nIdea name: foo\r\n Image: C:\\x"), "a\n Idea name: foo\n Image: C:\\x");
assert.deepEqual(noteReplyLines("Q", "one\ntwo", []), ["Note on Q: one\n two"]);
assert.match(app(), /replyLines\.push\(`\$\{item\.title\}: \$\{indentReply\(tok\)\}`\)/);
});
test("an approved edit stops saying 'please wait' once the agent has answered it", () => {
@@ -211,32 +210,17 @@ test("an approved edit stops saying 'please wait' once the agent has answered it
assert.equal(chatView(frame).rows[1].done, true);
});
test("a build's own count wins, 0 done included; a question workflow still fills as cards are answered", () => {
const chrome = app().slice(app().indexOf("function renderChrome("), app().indexOf("// Planny and the line beside him"));
assert.match(chrome, /if \(Number\(h\.total\) > 0\)/);
assert.match(chrome, /building \? Math\.max\(0, Number\(h\.cleared\) \|\| 0\) : Number\(h\.cleared\) \|\| answeredCount\(\)/);
assert.match(chrome, /else if \(building && h\.stage\)/, "a review starting at total 0 shows its stage");
});
test("the git board: Publish names a remote only when there is one, and an open card holds the board", () => {
const js = app();
test("the git board: Publish names a remote only when there is one, and Continue is always offered", () => {
const view = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board-view.js"), "utf8");
const action = view.slice(view.indexOf("function runStep("), view.indexOf("function stepButton("));
assert.match(action, /remotes\.length === 1/);
const at = js.indexOf("const gitMode = ");
assert.match(js.slice(at, js.indexOf(";", at)), /myTurn\(\)\.some\(\(i\) => i\.kind !== "notice"\)/);
const banner = view.slice(view.indexOf("function opBlock("), view.indexOf("function prBlock("));
assert.ok(!/if \(conflicted\.every/.test(banner), "Continue is always offered; plan continue checks the files itself");
});
test("a card cut by the window fades at its bottom edge while there is more below", () => {
assert.match(app(), /function markMore\(\)[\s\S]*?classList\.toggle\("has-more"/);
assert.match(css(), /\.main > \.card\.has-more \{[\s\S]*?mask-image/);
});
test("kept attachments are served read-only from the session's spec, by their exact name shape", () => {
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
const route = server.slice(server.indexOf('pathname.startsWith("/attachments/")'), server.indexOf('pathname.startsWith("/uploads/")'));
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
const route = server.slice(server.indexOf("function attachment("), server.indexOf("function shot("));
assert.match(route, /req\.method !== "GET"/);
assert.match(server, /const KEPT_ROUTE = new RegExp\(`\^\/attachments\/\(\[a-z0-9-\]\{1,40\}-\[0-9a-f-\]\{8\}/);
const kept = server.slice(server.indexOf("function keptPath("), server.indexOf("function uploadPath("));
@@ -274,12 +258,6 @@ test("a plain reopen (status and a thread reply only) moves the sent note into t
assert.ok(card.thread.some((m) => m.who === "user" && m.text === "Add a dry-run flag."));
});
test("a list rename is staged as it is typed, so Ctrl+Enter or an agent post never drops it", () => {
const js = app();
const list = js.slice(js.indexOf("function buildList("), js.indexOf("function buildList(") + 6000);
assert.match(list, /title\.addEventListener\("input", \(\) => \{[\s\S]*?stageQuiet\(item\.id/);
});
test("the git board's Publish reply names no remote when it sent none, and key chips show only for short keys", async () => {
const { gitReply } = await import("../src/web-console/public/git-board.js");
assert.equal(gitReply("publish", {}), "Publish.");
@@ -292,25 +270,17 @@ test("the git board's Publish reply names no remote when it sent none, and key c
});
test("a skip is recorded as one, collected with the send, and settles as skipped", () => {
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
assert.match(server, /\.\.\.\(type === "skip" \? \{ skipped: true \} : \{\}\)/);
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-post-wait.mjs"), "utf8");
assert.match(cli, /a\.type === "answer" \|\| a\.type === "skip"/);
});
test("a send made before the last collection is never shown as still with the agent", () => {
const js = app();
const fn = js.slice(js.indexOf("const sendCollected = "), js.indexOf("const submittedInFlight = "));
assert.match(fn, /String\(sub\.at\) <= String\(c\.at\)/);
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-post-wait.mjs"), "utf8");
assert.match(cli, /collected: \{ at: result\.consumedAt \|\| nowIso\(\), ids \}/, "the collection time, which every earlier send precedes");
});
test("two dashboards on different specs never trade the workspace back and forth", () => {
const js = app();
assert.match(js, /wantScope !== scopeMine\) syncWorkspaceScope\(\)/);
});
/* -------------------------------------------------------------- round 3 */
test("a branch whose remote copy was deleted offers Publish again, not Pull or Push", async () => {
@@ -331,13 +301,8 @@ test("a branch whose remote copy was deleted offers Publish again, not Pull or P
assert.equal(acts.publish.enabled, true);
});
test("a finished session never puts a sent answer back on its form", () => {
const js = app();
assert.match(js, /if \(effort && !finish\(\) && isOpen\(item\)/);
});
test("keep names a copy from the upload's real path, so an 8.3 spelling reuses the same copy", () => {
const src = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
const src = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-small.mjs"), "utf8");
assert.match(src, /attachmentName\(\{ upload: real\(upload\), name: args\.name \}\)/);
});
+137 -9
View File
@@ -34,10 +34,12 @@ import {
STRAY_GRACE_MS,
staleSessions,
terminalLine,
validate,
} from "../src/web-console/lib.mjs";
} from "../src/web-console/sessions.mjs";
import { validate } from "../src/web-console/patches.mjs";
import { joinedCss } from "./css-helpers.mjs";
import {
ROOT,
HANDOFFS_DIR,
HOME,
ENV,
cookieFor,
@@ -434,6 +436,9 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
backdate(path.join(plan2code, "busy"));
kept.push(busy);
stray(path.join(plan2code, "notes.txt"));
// Handoffs are Plan2Code's own, however old: swept by age on open, never offered here.
backdate(put(path.join(plan2code, "handoffs", "2025-01-01-0900-handoff.md")));
backdate(path.join(plan2code, "handoffs"));
// In use right now: a held lock and a temp between its write and rename.
const live = [put(path.join(consoleDir, "workspaces.json.lock"), ""), put(path.join(plan2code, "models.json.123.tmp"))];
kept.push(...live);
@@ -448,6 +453,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
"root:notes.txt",
"session:20250801-101010-aaaaaa",
]);
assert.equal(items.some((i) => i.id === "root:handoffs"), false, "the handoffs folder is never a stray");
assert.equal(STRAY_GRACE_MS, 60 * 60 * 1000);
assert.equal(items.find((i) => i.id === "console:p1.json").bytes, 5);
assert.equal(items.find((i) => i.id === "root:console-dev").kind, "folder");
@@ -523,7 +529,7 @@ test("cleanup lists the project's completed specs untouched for 30 days, and rem
test("User Preferences: wider, its body scrolls and the button bar stays put, without touching dialogs that borrow .looks", () => {
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
const css = joinedCss();
const dialog = html.match(/<dialog class="modal looks prefs" id="looks-modal"[^>]*>([\s\S]*?)<\/dialog>/);
assert.ok(dialog, "the Preferences dialog carries the prefs class");
const body = dialog[1].indexOf('<div class="prefs-body">');
@@ -659,6 +665,20 @@ test("open reports a month-old session under swept and removes it after printing
assert.equal(fs.existsSync(oldDir), false);
});
test("open reports a month-old handoff under swept.handoffs and removes both its files", async () => {
const id = "2025-01-01-0900-handoff";
fs.mkdirSync(HANDOFFS_DIR, { recursive: true });
const files = [path.join(HANDOFFS_DIR, id + ".md"), path.join(HANDOFFS_DIR, id + ".json")];
fs.writeFileSync(files[0], "# Handoff: old\n");
fs.writeFileSync(files[1], "{}");
for (const f of files) backdate(f);
const res = cli(["open", "--workflow", "plan", "--no-open"]);
cli(["stop", "--session", res.json.sid]);
assert.deepEqual(res.json.swept.handoffs, [id]);
for (let i = 0; i < 20 && files.some((f) => fs.existsSync(f)); i++) await new Promise((r) => setTimeout(r, 100));
assert.deepEqual(files.filter((f) => fs.existsSync(f)), []);
});
test("post and wait hand back the terminal line; the collected result on disk does not carry it", async () => {
const res = cli(["open", "--file", payload("tl.json", BASE), "--no-open"]);
const s = sessionUrl(res.json.url);
@@ -703,12 +723,6 @@ test("notes/quick-task.md has a quick-task build tick the Plan tab's steps live"
assert.ok(section.includes("- [x] **1.** Step one"));
});
test("the waiting pane points a quick-task build at its Plan tab", () => {
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
const fn = js.slice(js.indexOf("function renderWaiting("), js.indexOf("function renderNotice("));
assert.ok(fn.includes('S.workflow === "quick-task" && docs().find((d) => d.id === "plan")'));
});
test("notes/quick-task.md has the finished quick task offer Back to the dashboard as well as the review", () => {
const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "quick-task.md"), "utf8");
const section = md.slice(md.indexOf("## Quick task (`quick-task`)"));
@@ -716,3 +730,117 @@ test("notes/quick-task.md has the finished quick task offer Back to the dashboar
assert.ok(bullet.includes('"dashboard": true'));
assert.ok(bullet.includes("Review it now"));
});
// Show me it working: a screenshot saved under <session>/shots/ posts as an
// image block and is served back; nothing else is reachable through /shots/.
test("an image block under the session's shots folder round-trips, and /shots/ serves nothing else", async () => {
const res = cli(["open", "--workflow", "implement", "--no-open"]);
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
const cookie = cookieFor(m[1], m[2]);
try {
const shots = path.join(res.json.session, "shots");
fs.mkdirSync(shots, { recursive: true });
const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(32, 7)]);
fs.writeFileSync(path.join(shots, "home-page.png"), png);
const patch = { docs: [{ id: "shown", title: "Shown working", blocks: [{ id: "s1", image: "shots/home-page.png", alt: "The home page with the new button" }] }] };
cli(["post", "--session", res.json.sid, "--file", payload("shots-ok.json", patch)]);
const block = readState(res.json.session).docs.find((d) => d.id === "shown").blocks[0];
assert.equal(block.image, "shots/home-page.png", "stored session-relative");
assert.equal(block.md, undefined);
// Its alt text is a caption, held to the same vocabulary rule as a title.
const jargon = { docs: [{ id: "shown", blocks: [{ id: "s1", image: "shots/home-page.png", alt: "Grilling the home page" }] }] };
const refused = cli(["post", "--session", res.json.sid, "--file", payload("shots-jargon.json", jargon)], { expectFail: true });
assert.equal(refused.status, 3);
assert.match(refused.stderr, /alt text contains internal vocabulary/);
// A changed picture or caption is a new version of the doc.
const before = readState(res.json.session).docs.find((d) => d.id === "shown").version;
const recaption = { docs: [{ id: "shown", blocks: [{ id: "s1", image: "shots/home-page.png", alt: "The home page, after the fix" }] }] };
cli(["post", "--session", res.json.sid, "--file", payload("shots-recaption.json", recaption)]);
assert.equal(readState(res.json.session).docs.find((d) => d.id === "shown").version, before + 1);
const got = await fetch(m[1] + "/shots/home-page.png", { headers: { cookie } });
assert.equal(got.status, 200);
assert.equal(got.headers.get("content-type"), "image/png");
assert.equal(got.headers.get("cache-control"), "no-store");
assert.deepEqual(Buffer.from(await got.arrayBuffer()), png);
const anon = await fetch(m[1] + "/shots/home-page.png");
assert.equal(anon.status, 403, "the cookie is still required");
await anon.arrayBuffer();
// Raw request lines: fetch would fold the `..` away before sending.
const raw = (p) =>
new Promise((resolve, reject) => {
const req = http.request({ host: "127.0.0.1", port: Number(new URL(m[1]).port), path: p, headers: { cookie } }, (r) => {
r.resume();
r.on("end", () => resolve(r.statusCode));
});
req.on("error", reject);
req.end();
});
for (const p of ["/shots/../state.json", "/shots/..%2fstate.json", "/shots/missing.png", "/shots/home-page.png?x=1"]) {
assert.equal(await raw(p), 404, p);
}
} finally {
cli(["stop", "--session", res.json.sid]);
}
});
// /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 () => {
const { CSS_ORDER, asset, etagOf } = await import("../src/web-console/static.mjs");
const dir = path.join(ROOT, "src", "web-console", "public", "styles");
const res = cli(["open", "--workflow", "review", "--no-open"]);
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
const cookie = cookieFor(m[1], m[2]);
try {
const r = await fetch(m[1] + "/app.css", { headers: { cookie } });
assert.equal(r.status, 200);
assert.match(r.headers.get("content-type"), /^text\/css/);
const body = await r.text();
// One newline between files: each file's own last newline is that one.
const joined = CSS_ORDER.map((f) => fs.readFileSync(path.join(dir, f), "utf8").replace(/\n$/, "")).join("\n") + "\n";
assert.ok(body.startsWith(joined), "the body opens with the files, in CSS_ORDER, one newline between");
const accents = body.slice(joined.length);
assert.match(accents, /^\n*\/\* Generated by server\.mjs from palette\.js/, "the accent rules come last");
assert.ok(accents.includes(`:root[data-looks-accent="violet"]`));
// The tests' helper joins through the server's own function, so the two agree.
assert.equal(body, joinedCss() + accents, "joinedCss() plus the accent rules is the body the server returns");
// The ETag is a hash of the whole body, so a change to any one file moves it.
assert.equal(r.headers.get("etag"), etagOf(Buffer.from(body)));
assert.equal(asset("app.css").etag, etagOf(Buffer.from(body)));
for (const f of CSS_ORDER) {
const text = fs.readFileSync(path.join(dir, f), "utf8").replace(/\n$/, "");
assert.notEqual(etagOf(Buffer.from(body.replace(text, text + "\n/* changed */"))), r.headers.get("etag"), `a change to ${f} moves the ETag`);
}
for (const f of CSS_ORDER) {
const own = await fetch(m[1] + "/styles/" + f, { headers: { cookie } });
assert.equal(own.status, 404, `/styles/${f} is not served on its own`);
await own.arrayBuffer();
}
} finally {
cli(["stop", "--session", res.json.sid]);
}
});
// The skills the build writes carry public/styles/ with every file in CSS_ORDER,
// and a console started from that tree serves the same /app.css as this one.
test("the built skills tree serves the same /app.css as the source console", async (t) => {
const { CSS_ORDER, asset } = await import("../src/web-console/static.mjs");
const built = path.join(ROOT, "skills", "plan2code", "references", "web-console");
// npm test builds first; a bare run of this file may not have.
if (!fs.existsSync(path.join(built, "console.mjs"))) return t.skip("skills/ is not built: run npm run build:skills");
for (const f of CSS_ORDER) assert.ok(fs.existsSync(path.join(built, "public", "styles", f)), `the build is missing public/styles/${f}`);
const out = execFileSync(process.execPath, [path.join(built, "console.mjs"), "open", "--workflow", "review", "--no-open"], { env: ENV, encoding: "utf8", cwd: ROOT });
const json = JSON.parse(out.trim().split("\n").pop());
const m = json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
try {
const res = await fetch(m[1] + "/app.css", { headers: { cookie: cookieFor(m[1], m[2]) } });
assert.equal(res.status, 200);
assert.equal(await res.text(), asset("app.css").body.toString("utf8"));
} finally {
execFileSync(process.execPath, [path.join(built, "console.mjs"), "stop", "--session", json.sid], { env: ENV, cwd: ROOT });
}
});
+62 -42
View File
@@ -24,10 +24,8 @@ import {
noteReplyLines,
staleLaunchFeedback,
REVIEW_REPLY,
SKILL_CATALOG,
START_POSES,
startPose,
STOP_REPLY,
STOP_HANDOFF_REPLY,
threadText,
threadWho,
turnGate,
@@ -37,13 +35,9 @@ import { ACCENTS, CARD_WIDTHS, SOUND_EVENTS, soundKey, soundPrefs } from "../src
import { HELP_TABS, helpTabFor, helpKeyTarget } from "../src/web-console/public/help.js";
import { RED_AT, YELLOW_AT } from "../src/web-console/public/meter.js";
import { REMOTE_FOLD } from "../src/web-console/public/git-board.js";
import {
applyPatch,
readLedger,
SESSION_MAX_AGE_MS,
sweepUploads,
UPLOAD_MAX_AGE_MS,
} from "../src/web-console/lib.mjs";
import { readLedger, SESSION_MAX_AGE_MS, sweepUploads, UPLOAD_MAX_AGE_MS } from "../src/web-console/sessions.mjs";
import { applyPatch } from "../src/web-console/patches.mjs";
import { joinedCss } from "./css-helpers.mjs";
import {
ROOT,
HOME,
@@ -225,6 +219,23 @@ test("a launch request round-trips with the skill the dashboard resumes as", asy
assert.ok(state.items.every((i) => i.id !== "__launch"), "a launch must not become a question");
});
// A delete from the dashboard's picker is a send like a launch, but no hop:
// the agent stays the dashboard, so it carries no resume and no skill file.
test("a delete request round-trips with the spec folder and no resume", async () => {
await post("/submit", {
actions: [{ i: "__delete", type: "delete", spec: "specs/lunch-vote" }],
reply: "Delete the spec folder specs/lunch-vote/ for good, right here in this session.",
});
const res = cli(["wait", "--session", sid, "--seconds", "10"]);
assert.equal(res.status, 0);
assert.equal(res.json.actions[0].i, "__delete");
assert.equal(res.json.actions[0].spec, "specs/lunch-vote");
assert.equal(res.json.resume, undefined);
assert.equal(res.json.skillFile, undefined);
const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
assert.ok(state.items.every((i) => i.id !== "__delete"), "a delete must not become a question");
});
// Back to the dashboard is a send like the review button: it names no
// question, it is refused while an earlier send is uncollected, and the agent
// answers it by resuming the same session as the dashboard.
@@ -371,6 +382,24 @@ test("a stop request carries the staged answers, reaches the agent as a send, an
assert.equal((await ping()).pendingStop, false);
});
// "Stop with a handoff" is the same send with `handoff: true` on the action.
// The source tree has no built Handoff skill beside it, so no handoffSkill.
test("a handoff stop keeps its flag, reports as a stop until collected, and names no skill file in the source tree", async () => {
const ping = async () => (await post("/ping", {})).json();
const before = await ping();
await post("/submit", {
rev: before.rev,
actions: [{ i: "__stop", type: "stop", handoff: true }],
reply: STOP_HANDOFF_REPLY,
});
assert.equal((await ping()).pendingStop, true, "an uncollected handoff stop shows on the heartbeat");
const res = cli(["wait", "--session", sid, "--seconds", "5"]);
assert.equal(res.status, 0);
assert.equal(res.json.actions[0].handoff, true, "the flag reaches the agent");
assert.equal(res.json.handoffSkill, undefined, "no built skill beside the source tree");
assert.equal((await ping()).pendingStop, false);
});
// The top bar's triangle is a stop that lands on the menu: the staged answers
// and `__dashboard` go as one send with no finish on the page, the agent gets
// both at once, and the resume through the dashboard blanks the skill's page.
@@ -439,8 +468,7 @@ test("the way home follows Stop's turn rules and hides where it has no job", ()
test("the page carries the way home: the triangle, its confirm, and the wiring", () => {
const dir = path.join(ROOT, "src", "web-console", "public");
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
const app = fs.readFileSync(path.join(dir, "app.js"), "utf8");
const css = fs.readFileSync(path.join(dir, "app.css"), "utf8");
const css = joinedCss();
assert.ok(html.indexOf('id="btn-home"') < html.indexOf('id="btn-stop"'), "the triangle sits left of Stop session");
assert.match(html, /id="btn-home"[\s\S]{0,200}aria-label="Back to the dashboard"/, "the icon button has a name");
for (const id of ["home-modal", "home-blurb", "home-warn", "home-cancel", "home-go"]) {
@@ -448,8 +476,6 @@ test("the page carries the way home: the triangle, its confirm, and the wiring",
}
assert.ok(html.includes("Leave this workflow?"));
assert.match(css, /\.home-btn path\s*\{\s*fill:\s*var\(--accent\)/, "the triangle is filled with the highlight color");
assert.ok(app.includes('{ i: "__dashboard", type: "dashboard" }'), "the confirm sends __dashboard");
assert.ok(app.includes("stagedPayload()") && app.includes("HOME_REPLY"), "the staged answers ride along with the reply line");
});
test("the way home cannot be mistaken for a brief request", () => {
@@ -462,11 +488,24 @@ test("console-stop.md, building.md and the dashboard prompt teach the mid-workfl
assert.ok(stopMd.includes("## Back to the dashboard, mid-workflow"));
assert.ok(stopMd.includes(HOME_REPLY), "console-stop.md quotes the reply line the agent will see");
assert.match(stopMd, /No `finish` and no `stop` in between/);
assert.match(read("src", "web-console", "console.md"), /`__stop`, `__dashboard` \(no finish up\) \| `console-stop\.md`/, "console.md's action table sends a mid-workflow __dashboard there");
assert.ok(stopMd.includes("## Stop with a handoff"));
for (const word of ["handoff new", "--from-stop", "handoffSkill"]) assert.ok(stopMd.includes(word), `console-stop.md names ${word}`);
assert.match(read("src", "web-console", "console.md"), /`__stop` \(plain, or with `handoff: true`\), `__dashboard` \(no finish up\) \| `console-stop\.md`/, "console.md's action table sends a handoff stop and a mid-workflow __dashboard there");
assert.ok(read("src", "web-console", "building.md").includes("mid-build `__dashboard`"));
assert.ok(read("src", "plan2code.md").includes("mid-workflow from the top bar's triangle"));
});
test("console-launches.md and the dashboard prompt teach the handoff pick-up and delete", () => {
const read = (...p) => fs.readFileSync(path.join(ROOT, ...p), "utf8");
const launches = read("src", "web-console", "console-launches.md");
for (const word of ["__pickup", "handoffFile", "delete-handoff", "handoffsDir", "fallback"]) {
assert.ok(launches.includes(word), `console-launches.md names ${word}`);
}
assert.ok(launches.includes("handoffs, handoffsDir"), "console-launches.md lists the scan fields");
const prompt = read("src", "plan2code.md");
for (const word of ["__pickup", "delete-handoff"]) assert.ok(prompt.includes(word), `src/plan2code.md names ${word}`);
});
// The server serves a hardcoded allow-list, so a new module that nobody adds
// to it 404s, the import fails, and the page never starts: a blank console
// with the default title and one line in the browser's console. Every module
@@ -474,9 +513,12 @@ test("console-stop.md, building.md and the dashboard prompt teach the mid-workfl
test("every module the page imports is actually served", async () => {
const dir = path.join(ROOT, "src", "web-console", "public");
const wanted = new Set(["app.js"]);
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".js"))) {
// The modules beside app.js and the screens under screens/, each import
// resolved from the file that makes it (a screen's "../state.js" is state.js).
const files = [...fs.readdirSync(dir).filter((f) => f.endsWith(".js")), ...fs.readdirSync(path.join(dir, "screens")).map((f) => `screens/${f}`)];
for (const f of files) {
const src = fs.readFileSync(path.join(dir, f), "utf8");
for (const m of src.matchAll(/^\s*import\b[^"']*["']\.\/([^"']+)["']/gm)) wanted.add(m[1]);
for (const m of src.matchAll(/^\s*import\b[^"']*["'](\.\.?\/[^"']+)["']/gm)) wanted.add(path.posix.join(path.posix.dirname(f), m[1]));
}
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
for (const m of html.matchAll(/<link rel="modulepreload" href="\/([^"]+)"/g)) wanted.add(m[1]);
@@ -564,28 +606,6 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at
assert.doesNotMatch(html, /rel="icon"[^>]*href="data:/);
});
// Each skill's starting and waiting screens clone its pose from index.html.
// A pose with no drawing silently falls back to the flight, and a style
// attribute in one would be refused by the CSP, so hold the markup to the list.
test("every skill has a pose drawn in the page, with no inline styles", () => {
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
const tpl = html.match(/<template id="start-poses">([\s\S]*?)<\/template>/);
assert.ok(tpl, "index.html has the start-poses template");
const drawn = [...tpl[1].matchAll(/data-pose="([^"]+)"/g)].map((m) => m[1]);
assert.deepEqual(drawn.sort(), [...START_POSES].sort());
assert.doesNotMatch(tpl[1], /\sstyle=/);
for (const pose of START_POSES) {
assert.ok(SKILL_CATALOG.some((e) => e.workflow === pose), `${pose} is a real workflow`);
assert.equal(startPose(pose), pose);
}
assert.equal(startPose("implement-review"), "implement");
assert.equal(startPose("revise-plan"), "plan");
assert.equal(startPose("init-update"), "init");
for (const e of SKILL_CATALOG) assert.ok(startPose(e.workflow), `${e.workflow} has a pose`);
assert.equal(startPose("dashboard"), null);
assert.equal(startPose(undefined), null);
});
/* ---------------------------------------------------------------- help */
@@ -749,9 +769,9 @@ const helpFacts = () => ({
maxDocMb: MAX_DOC_BYTES / 1024 / 1024,
imageEdge: IMAGE_LONG_EDGE,
cleanupDays: SESSION_MAX_AGE_MS / 86400000,
goneSeconds: sourceConst("public/app.js", /const GONE_AFTER_MS = ([^;]+);/, "GONE_AFTER_MS") / 1000,
adriftMinutes: sourceConst("public/app.js", /const ADRIFT_MS = ([^;]+);/, "ADRIFT_MS") / 60000,
maxUploadMb: sourceConst("public/app.js", /const MAX_UPLOAD_BYTES = ([^;]+);/, "MAX_UPLOAD_BYTES") / 1024 / 1024,
goneSeconds: sourceConst("public/screens/core.js", /const GONE_AFTER_MS = ([^;]+);/, "GONE_AFTER_MS") / 1000,
adriftMinutes: sourceConst("public/selectors.js", /const ADRIFT_MS = ([^;]+);/, "ADRIFT_MS") / 60000,
maxUploadMb: sourceConst("public/uploads.js", /const MAX_UPLOAD_BYTES = ([^;]+);/, "MAX_UPLOAD_BYTES") / 1024 / 1024,
idleMinutes: sourceConst("server.mjs", /const IDLE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "IDLE_MS") / 60000,
maxLifeHours: sourceConst("server.mjs", /const MAX_LIFE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "MAX_LIFE_MS") / 3600000,
closedTabMinutes: sourceConst("server.mjs", /\(IDLE_MS - ([^)]+)\)/, "the closed-tab shutdown") / 60000,
+325
View File
@@ -0,0 +1,325 @@
// Web console tests, the shape of the source: no console file grows past
// 3,000 lines, and the files lib.mjs split into stand on their own.
// Run with: node --test scripts/test-web-console-shape.mjs
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { pathToFileURL } from "node:url";
import { ROOT } from "./web-console-test-helpers.mjs";
const CONSOLE_DIR = path.join(ROOT, "src", "web-console");
const MAX_LINES = 3000;
// Every .mjs, .js and .css file under `dir` (vendored code aside), as paths
// relative to it with forward slashes.
function sourceFiles(dir, rel = "") {
const out = [];
for (const e of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
const p = rel ? `${rel}/${e.name}` : e.name;
if (e.isDirectory()) {
if (p !== "public/vendor") out.push(...sourceFiles(dir, p));
} else if (/\.(mjs|js|css)$/.test(e.name)) out.push(p);
}
return out;
}
// A file's line count, as `wc -l` gives it for a file ending in a newline.
function lineCount(text) {
return text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
}
// The lines that name each file over the limit.
function oversized(dir) {
return sourceFiles(dir)
.map((p) => [p, lineCount(fs.readFileSync(path.join(dir, p), "utf8"))])
.filter(([p, n]) => n > MAX_LINES)
.map(([p, n]) => `${p} is ${n} lines, over the ${MAX_LINES}-line limit: split it by job`);
}
test("shape: no console file is over 3,000 lines", () => {
assert.deepEqual(oversized(CONSOLE_DIR), []);
});
test("shape: the size check names the file that is too big", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shape-"));
try {
fs.mkdirSync(path.join(dir, "public", "vendor"), { recursive: true });
fs.writeFileSync(path.join(dir, "big.mjs"), "x\n".repeat(MAX_LINES + 1));
fs.writeFileSync(path.join(dir, "edge.css"), "x\n".repeat(MAX_LINES));
fs.writeFileSync(path.join(dir, "small.js"), "x\n");
fs.writeFileSync(path.join(dir, "public", "vendor", "huge.js"), "x\n".repeat(MAX_LINES * 2));
assert.deepEqual(oversized(dir), [`big.mjs is ${MAX_LINES + 1} lines, over the ${MAX_LINES}-line limit: split it by job`]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("shape: files.mjs still finds the console's own folder", async () => {
const { HERE, PUBLIC_DIR } = await import("../src/web-console/files.mjs");
assert.equal(path.basename(HERE), "web-console");
assert.equal(PUBLIC_DIR, path.join(HERE, "public"));
});
test("shape: lib.mjs is gone, and every file it split into is there", () => {
assert.equal(fs.existsSync(path.join(CONSOLE_DIR, "lib.mjs")), false, "src/web-console/lib.mjs still exists");
for (const f of SPLIT_FILES) {
const text = fs.readFileSync(path.join(CONSOLE_DIR, f), "utf8");
assert.match(text, /^\/\/ Plan2Code Web Console - \S.*\.\n/, `${f} opens with a one-line job comment`);
}
});
// Every page file but the entry (app.js) only defines things, so each one
// loads under plain Node with no page around it. Imported alone in a fresh
// process: one that reaches for `document` or `window` at load, or runs
// anything else that throws, is named with its first error line. One that
// starts a timer or a listener throws nothing but never exits: it is named too.
const LOAD_TIMEOUT_MS = 5000;
function pageLoadFailures(pub) {
return sourceFiles(pub)
.filter((p) => p.endsWith(".js") && p !== "app.js" && (!p.includes("/") || p.startsWith("screens/")))
.flatMap((p) => {
const url = pathToFileURL(path.join(pub, p)).href;
const r = spawnSync(process.execPath, ["--input-type=module", "-e", `await import(${JSON.stringify(url)});`], {
encoding: "utf8",
timeout: LOAD_TIMEOUT_MS,
});
if (r.error && r.error.code === "ETIMEDOUT") return [`${p} does not load on its own: still running after load (a timer or listener started at module scope)`];
if (r.status === 0) return [];
const line = r.stderr.split("\n").find((l) => /Error/.test(l)) || r.stderr.trim().split("\n")[0];
return [`${p} does not load on its own: ${line.trim()}`];
});
}
test("shape: every page file but app.js only defines things, and loads under plain Node", () => {
assert.deepEqual(pageLoadFailures(path.join(CONSOLE_DIR, "public")), []);
});
test("shape: the define-only check names a page file that touches the page at load", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-define-only-"));
try {
fs.mkdirSync(path.join(dir, "screens"));
fs.mkdirSync(path.join(dir, "vendor"));
fs.writeFileSync(path.join(dir, "package.json"), '{ "type": "module" }\n');
fs.writeFileSync(path.join(dir, "app.js"), "document.title = 'the entry may';\n");
fs.writeFileSync(path.join(dir, "fine.js"), "export const title = () => document.title;\n");
fs.writeFileSync(path.join(dir, "screens", "eager.js"), "export const title = document.title;\n");
fs.writeFileSync(path.join(dir, "screens", "ticks.js"), "setInterval(() => {}, 1000);\n");
fs.writeFileSync(path.join(dir, "vendor", "lib.js"), "window.x = 1;\n");
const failures = pageLoadFailures(dir);
assert.equal(failures.length, 2, failures.join("\n"));
assert.match(failures.find((f) => f.startsWith("screens/eager.js")), /does not load on its own: ReferenceError: document is not defined/);
assert.match(failures.find((f) => f.startsWith("screens/ticks.js")), /does not load on its own: still running after load/);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
// A screen reaches the rest of the page through ../state.js and the pure
// modules beside it, never through another screen: only core.js (the render
// loop, which draws every screen) imports screens, and only app.js (the
// entry) imports core.js. Each import that breaks that is named.
function pageImportProblems(pub) {
const problems = [];
for (const p of sourceFiles(pub).filter((f) => f.endsWith(".js") && (!f.includes("/") || f.startsWith("screens/")))) {
const text = fs.readFileSync(path.join(pub, p), "utf8");
for (const m of text.matchAll(/^\s*(?:import|export)\b[^;]*?\bfrom\s*["']([^"']+)["']|\bimport\(\s*["']([^"']+)["']\s*\)|^\s*import\s*["']([^"']+)["']/gm)) {
const spec = m[1] || m[2] || m[3];
if (!spec.startsWith(".")) continue;
const target = path.posix.join(path.posix.dirname(p), spec);
if (target === "screens/core.js" && p !== "app.js") problems.push(`${p} imports ${spec}: only app.js imports core.js`);
else if (p.startsWith("screens/") && p !== "screens/core.js" && target.startsWith("screens/"))
problems.push(`${p} imports ${spec}: a screen imports ../state.js and the modules beside it, never another screen`);
}
}
return problems;
}
test("shape: a screen never imports another screen, and only app.js imports core.js", () => {
assert.deepEqual(pageImportProblems(path.join(CONSOLE_DIR, "public")), []);
});
test("shape: the import check names a screen that imports another, and any file but app.js importing core.js", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-imports-"));
try {
fs.mkdirSync(path.join(dir, "screens"));
const put = (rel, text) => fs.writeFileSync(path.join(dir, rel), text);
put("app.js", 'import { render } from "./screens/core.js";\n');
put("state.js", "export const page = {};\n");
put("render.js", "export const el = () => null;\n");
put("screens/core.js", 'import { a } from "./a.js";\nimport { page } from "../state.js";\n');
put("screens/a.js", 'import { b } from "./b.js";\nimport { page } from "../state.js";\nimport { el } from "../render.js";\n');
put("screens/b.js", 'import { page } from "../state.js";\n');
put("screens/c.js", 'import { render } from "./core.js";\n');
put("helper.js", 'import { render } from "./screens/core.js";\n');
put("screens/d.js", 'import "./b.js";\n');
assert.deepEqual(pageImportProblems(dir).sort(), [
"helper.js imports ./screens/core.js: only app.js imports core.js",
"screens/a.js imports ./b.js: a screen imports ../state.js and the modules beside it, never another screen",
"screens/c.js imports ./core.js: only app.js imports core.js",
"screens/d.js imports ./b.js: a screen imports ../state.js and the modules beside it, never another screen",
]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
// The page's CSP refuses style attributes, so one set from script is dropped
// on the floor in the browser. Every page module, wherever a split moves the
// code that draws.
test("shape: no page module sets a style attribute from script", () => {
const pub = path.join(CONSOLE_DIR, "public");
const offenders = sourceFiles(pub)
.filter((p) => p.endsWith(".js"))
.filter((p) => /setAttribute\(\s*["']style["']/.test(fs.readFileSync(path.join(pub, p), "utf8")));
assert.deepEqual(offenders, []);
});
// Every URL the server's old `if` chain matched, in its order, so a route lost
// or moved in routes.mjs fails here by name: several match by prefix, and the
// token gate sits after the first two. SERVABLE stands for the page's own files
// and WORKSPACE_EDITS for /workspace/add, /edit and /remove. The git board has
// no routes of its own: its buttons are sends (`__git`), through /submit.
const ROUTE_ORDER = [
"/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/cleanup", "/upload",
"/attachments/", "/shots/", "/uploads/", "/submit", "/chat", "/chat/decision", "/workspace",
"WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/cancel", "/ping", "/bye",
];
test("shape: routes.mjs lists every URL the server answers, in order", () => {
const routes = fs.readFileSync(path.join(CONSOLE_DIR, "routes.mjs"), "utf8");
const start = routes.indexOf("const ROUTES = [");
const list = routes.slice(start, routes.indexOf("\n];", start));
const entries = list
.split("\n")
.filter((line) => /^\s*\{/.test(line))
.map((line) => (line.match(/path: "([^"]*)"|startsWith\("([^"]*)"\)|\b(SERVABLE|WORKSPACE_EDITS)\b/) || []).slice(1).find(Boolean));
assert.deepEqual(entries, ROUTE_ORDER);
const edits = routes.match(/const WORKSPACE_EDITS = \{([^}]*)\}/)[1];
for (const p of ["/workspace/add", "/workspace/edit", "/workspace/remove"]) assert.ok(edits.includes(`"${p}"`), `${p} is a workspace edit`);
});
// Each file split out of lib.mjs, imported first and alone in a fresh
// process: a module-scope read of a value from a file still loading (an
// import cycle) throws here, naming the file, before it reaches a real run.
const SPLIT_FILES = ["files.mjs", "sessions.mjs", "scan.mjs", "patches.mjs", "inbox.mjs", "workspace.mjs", "settings.mjs"];
test("shape: every file split out of lib.mjs loads first and alone", () => {
for (const f of SPLIT_FILES) {
const url = pathToFileURL(path.join(CONSOLE_DIR, f)).href;
const r = spawnSync(process.execPath, ["--input-type=module", "-e", `await import(${JSON.stringify(url)});`], { encoding: "utf8" });
assert.equal(r.status, 0, `${f} does not load on its own: ${r.stderr.trim().split("\n").find((l) => /Error/.test(l)) || r.stderr}`);
}
});
// app.js is the entry and nothing else, so no test may read it as text: what a
// screen does is tested by driving the page, and what a screen file holds is
// read from that screen. A statement that both reads a file and names app.js
// is a read (a fetch of /app.js, or a fixture file called app.js, is not).
const SCRIPTS_DIR = path.join(ROOT, "scripts");
// parse-check.mjs only parses the entry, so it may name it.
const MAY_NAME_APP_JS = new Set(["parse-check.mjs"]);
// One statement that reads and names app.js, or a read helper handed it
// (`web("app.js")`, `publicSource("public/app.js")`), or a path to it
// under public/, in any file that also reads files.
function appJsReaders(dir) {
return fs
.readdirSync(dir)
.filter((f) => f.endsWith(".mjs") && f !== "test-web-console-shape.mjs" && !MAY_NAME_APP_JS.has(f))
.filter((f) => {
const text = fs.readFileSync(path.join(dir, f), "utf8");
const oneStatement = text
.split(";")
.some((statement) => /\b(readFileSync|readFile|publicSource)\s*\(/.test(statement) && /["'/]app\.js["']/.test(statement));
const handedToAHelper = /\w\(\s*["'](?:(?:src\/web-console\/)?public\/)?app\.js["']\s*\)/.test(text);
const publicPath = /["']public["']\s*,\s*["']app\.js["']|\bpublic\/app\.js/.test(text) && /\breadFile(Sync)?\b/.test(text);
return oneStatement || handedToAHelper || publicPath;
})
.map((f) => `${f} reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it`);
}
test("shape: no test in scripts/ reads public/app.js as text", () => {
assert.deepEqual(appJsReaders(SCRIPTS_DIR), []);
});
test("shape: the app.js check names the test file that reads it", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shape-"));
try {
fs.writeFileSync(path.join(dir, "test-fine.mjs"), 'const r = await fetch(base + "/app.js");\nfs.appendFileSync(path.join(d, "src", "app.js"), "x");\n');
assert.deepEqual(appJsReaders(dir), []);
fs.writeFileSync(path.join(dir, "test-reads-it.mjs"), 'const app = fs.readFileSync(path.join(ROOT, "public", "app.js"), "utf8");\n');
assert.deepEqual(appJsReaders(dir), ["test-reads-it.mjs reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it"]);
fs.rmSync(path.join(dir, "test-reads-it.mjs"));
fs.writeFileSync(path.join(dir, "test-alias.mjs"), 'const web = (f) => fs.readFileSync(path.join(ROOT, "public", f), "utf8");\nconst app = web("app.js");\n');
assert.deepEqual(appJsReaders(dir), ["test-alias.mjs reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it"]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
// The stylesheet is many files under public/styles/, joined by the server into
// the one /app.css the page asks for. CSS_ORDER is the one place the cascade
// order is stated: every file in it exists, each once, and no file in the folder
// is left out of it or served on its own.
test("shape: CSS_ORDER names every file in public/styles/ once, and none is served on its own", async () => {
const { CSS_ORDER, SERVABLE } = await import("../src/web-console/static.mjs");
const dir = path.join(CONSOLE_DIR, "public", "styles");
assert.ok(CSS_ORDER.length > 0, "CSS_ORDER lists files");
assert.equal(new Set(CSS_ORDER).size, CSS_ORDER.length, "no file is listed twice");
for (const f of CSS_ORDER) assert.ok(fs.existsSync(path.join(dir, f)), `CSS_ORDER lists ${f}, which is not in public/styles/`);
const onDisk = fs.readdirSync(dir).filter((f) => f.endsWith(".css")).sort();
assert.deepEqual([...CSS_ORDER].sort(), onDisk, "public/styles/ holds exactly the files CSS_ORDER lists");
for (const rel of SERVABLE) assert.ok(!rel.startsWith("styles/") && !CSS_ORDER.includes(rel), `${rel} must not be served on its own`);
});
// The files table in AGENTS-architecture.md gives every console file a row,
// so a contributor finds where a job lives without searching. A row's first
// cell names the file by its path under src/web-console/ (backticked; one cell
// may name several files, joined by "·").
const ARCHITECTURE_DOC = path.join(ROOT, ".agents-docs", "AGENTS-architecture.md");
// The paths the files table names, from the first cell of each table row.
function tableFiles(markdown) {
const named = new Set();
for (const line of markdown.split("\n")) {
if (!line.startsWith("|")) continue;
const cell = line.split("|")[1] || "";
for (const m of cell.matchAll(/`([^`]+)`/g)) named.add(m[1]);
}
return named;
}
// One line per console file with no row in the table.
function undocumented(dir, markdown) {
const named = tableFiles(markdown);
return sourceFiles(dir)
.filter((p) => !named.has(p))
.map((p) => `${p} has no row in the files table of AGENTS-architecture.md: add one with its one-line job`);
}
test("shape: every console file has a row in the files table of AGENTS-architecture.md", () => {
const problems = undocumented(CONSOLE_DIR, fs.readFileSync(ARCHITECTURE_DOC, "utf8"));
assert.deepEqual(problems, []);
});
test("shape: the docs-table check names a file with no row, and passes one that has it", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-docs-table-"));
try {
fs.mkdirSync(path.join(dir, "public"));
fs.writeFileSync(path.join(dir, "a.mjs"), "");
fs.writeFileSync(path.join(dir, "public", "b.js"), "");
const table = "| File | Role |\n|---|---|\n| `a.mjs` | the first |\n";
assert.deepEqual(undocumented(dir, table), [
"public/b.js has no row in the files table of AGENTS-architecture.md: add one with its one-line job",
]);
assert.deepEqual(undocumented(dir, `${table}| \`public/b.js\` · \`x.js\` | the second |\n`), []);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
+247
View File
@@ -0,0 +1,247 @@
// Web console tests, the skill list: public/skills.js holds every per-skill
// fact the console uses, and the older tables are lookups on it.
// Run with: node --test scripts/test-web-console-skills.mjs
import test from "node:test";
import assert from "node:assert/strict";
import {
SKILLS,
skillFor,
skillByName,
isBuild,
isPhased,
isMetered,
subagentsFor,
takesTemplates,
labelFor,
} from "../src/web-console/public/skills.js";
import { CONSOLE_WORKFLOWS, SKILL_CATALOG, START_POSES, WORKFLOW_LABEL, dashNoteKind, onInitialPick, startPose, startingHint } from "../src/web-console/public/answers.js";
import { LAUNCH_COUNTED, PROGRESS_WORKFLOWS } from "../src/web-console/public/meter.js";
import { BUILD_WORKFLOWS } from "../src/web-console/public/labels.js";
import { helpTabFor } from "../src/web-console/public/help.js";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createRequire } from "node:module";
import { ROOT, cli, poseTemplate } from "./web-console-test-helpers.mjs";
import { SUBAGENT_WORKFLOWS } from "../src/web-console/public/subagents.js";
import { TEMPLATE_WORKFLOWS } from "../src/web-console/public/starters.js";
// meter.js keeps its answers-row names private: what they were when the list
// moved, written out. A skill added since has no row here, and only has to
// have a name.
const NAMES_AT_THE_MOVE = {
dashboard: "the dashboard",
pathfinder: "Pathfinder",
plan: "Plan",
"revise-plan": "Revise plan",
document: "Document",
implement: "Implement",
"implement-review": "Implement + Review",
review: "Review",
"quick-task": "Quick task",
init: "Init",
"init-update": "Init update",
finalize: "Finalize",
handoff: "Handoff",
git: "Git",
changelog: "Changelog",
xray: "X-ray",
diagnose: "Diagnose",
};
const CARD_FIELDS = ["group", "chip", "title", "blurb", "about", "spec"];
test("every skill the console knows has one entry, the dashboard included", () => {
const workflows = SKILLS.map((s) => s.workflow);
assert.deepEqual([...workflows].sort(), Object.keys(WORKFLOW_LABEL).sort());
assert.equal(new Set(workflows).size, workflows.length, "one entry per workflow");
assert.deepEqual(SKILLS.map((s) => s.command).sort(), [...CONSOLE_WORKFLOWS].sort());
// The cards come first, in the dashboard's order.
const carded = SKILLS.filter((s) => s.card);
assert.deepEqual(carded.map((s) => s.skill), SKILL_CATALOG.map((e) => e.skill));
assert.equal(skillFor("dashboard").skill, "plan2code");
assert.equal(skillFor("dashboard").card, null, "the dashboard is the hub, not a card");
});
// The older exports (WORKFLOW_LABEL, SKILL_CATALOG, LAUNCH_COUNTED and the
// rest) are now built from SKILLS, so this checks the wiring: each one still
// says what its entry says. It proved the move when the tables were still
// written by hand; the meter names and the build flags, which have no
// importable twin, are held to their values at the move.
test("the derived exports agree with each entry", () => {
for (const s of SKILLS) {
const w = s.workflow;
for (const f of ["skill", "workflow", "label", "name"]) assert.ok(typeof s[f] === "string" && s[f].trim(), `${w}: ${f} must be filled in`);
assert.equal(s.command, "/" + s.skill, `${w}: command`);
assert.equal(s.label, WORKFLOW_LABEL[w], `${w}: label`);
if (Object.hasOwn(NAMES_AT_THE_MOVE, w)) assert.equal(s.name, NAMES_AT_THE_MOVE[w], `${w}: name`);
assert.equal(s.pose, startPose(w), `${w}: pose`);
assert.equal(s.metered, LAUNCH_COUNTED.has(w), `${w}: metered`);
assert.equal(s.subagents, SUBAGENT_WORKFLOWS[w] ? SUBAGENT_WORKFLOWS[w].instruction : null, `${w}: subagents`);
assert.equal(s.templates, TEMPLATE_WORKFLOWS.includes(w), `${w}: templates`);
if (Object.hasOwn(NAMES_AT_THE_MOVE, w)) {
assert.equal(s.builds, ["implement", "implement-review", "quick-task"].includes(w), `${w}: builds`);
assert.equal(s.phased, ["implement", "implement-review"].includes(w), `${w}: phased`);
}
const entry = SKILL_CATALOG.find((e) => e.workflow === w);
if (!entry) {
assert.equal(s.card, null, `${w}: no card`);
continue;
}
assert.equal(entry.skill, s.skill, `${w}: skill`);
assert.equal(entry.command, s.command, `${w}: card command`);
for (const f of CARD_FIELDS) assert.equal(s.card[f], entry[f], `${w}: card.${f}`);
}
// Every pose in the page's list belongs to an entry.
for (const pose of START_POSES) assert.ok(SKILLS.some((s) => s.pose === pose), `${pose} belongs to a skill`);
for (const w of PROGRESS_WORKFLOWS) assert.ok(isPhased(w), `${w} counts its tasks`);
});
test("the entries are frozen data", () => {
assert.ok(Object.isFrozen(SKILLS));
for (const s of SKILLS) {
assert.ok(Object.isFrozen(s), `${s.workflow} is frozen`);
if (s.card) assert.ok(Object.isFrozen(s.card), `${s.workflow}.card is frozen`);
}
});
test("the lookups answer by workflow or skill name, and say nothing for an unknown one", () => {
assert.equal(skillFor("implement-review").skill, "plan2code-3-implement-review");
assert.equal(skillByName("plan2code-git").workflow, "git");
assert.equal(skillByName("plan2code").workflow, "dashboard");
assert.equal(labelFor("xray"), "X-ray");
assert.equal(subagentsFor("review"), SUBAGENT_WORKFLOWS.review.instruction);
for (const unknown of ["nope", undefined, null, "", "constructor", "__proto__"]) {
assert.equal(skillFor(unknown), null);
assert.equal(skillByName(unknown), null);
assert.equal(labelFor(unknown), null);
assert.equal(subagentsFor(unknown), null);
for (const is of [isBuild, isPhased, isMetered, takesTemplates]) assert.equal(is(unknown), false);
}
});
// Which workflows labels.js and help.js count as builds, as they stood when the
// sets moved onto skills.js: labels.js leaves Quick Task out, help.js keeps it.
test("the two build sets hold what they held before", () => {
assert.deepEqual([...BUILD_WORKFLOWS].sort(), ["implement", "implement-review"]);
assert.deepEqual(SKILLS.filter((s) => isBuild(s.workflow)).map((s) => s.workflow).sort(), ["implement", "implement-review", "quick-task"]);
// help.js keeps its set private: Help opens on its Building tab for exactly these.
const onBuild = SKILLS.map((s) => s.workflow).filter((workflow) => helpTabFor({ workflow }) === "build");
assert.deepEqual(onBuild.sort(), ["implement", "implement-review", "quick-task"]);
assert.equal(helpTabFor({ workflow: "nope" }), "about");
});
/* ------------------------------------------- tests that name what was missed */
// Each check below is a pure function of a skill list, so a test can hand it a
// copy with one thing wrong and see the message name the skill.
// Each skill's starting screen clones its pose from index.html. A pose with no
// drawing silently falls back to the flight, and a drawing no skill uses is
// dead markup.
function poseProblems(skills, drawn) {
const problems = [];
for (const s of skills) {
if (s.card && !s.pose) problems.push(`${s.skill} has a card but no pose`);
if (s.pose && !drawn.includes(s.pose)) problems.push(`${s.skill} names pose "${s.pose}", which index.html does not draw`);
}
for (const pose of drawn) {
if (!skills.some((s) => s.pose === pose)) problems.push(`index.html draws pose "${pose}", which belongs to no skill`);
}
return problems;
}
// Every workflow the console can open has its notes behind `console.mjs help`.
function helpProblems(skills, topics) {
return skills.filter((s) => !Object.hasOwn(topics, s.workflow)).map((s) => `${s.skill} (${s.workflow}) has no help topic in console.mjs`);
}
// The skills with a card, plus the dashboard, are exactly what install.js builds.
function installProblems(skills, installed) {
const named = skills.filter((s) => s.card || s.workflow === "dashboard").map((s) => s.skill);
return [
...named.filter((n) => !installed.includes(n)).map((n) => `${n} is in skills.js but not in install.js SOURCE_PROMPTS`),
...installed.filter((n) => !named.includes(n)).map((n) => `${n} is in install.js SOURCE_PROMPTS but has no card in skills.js`),
];
}
const drawnPoses = () => [...poseTemplate().matchAll(/data-pose="([^"]+)"/g)].map((m) => m[1]);
const helpTopics = () => cli(["help", "topics"]).json.topics;
// install.js reads the home directory at load: point it at a temp one, as the
// install tests do. Requiring it never runs its CLI (that waits on require.main).
function installedSkills() {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-skills-"));
const saved = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE };
process.env.HOME = home;
process.env.USERPROFILE = home;
try {
const { SOURCE_PROMPTS, generateSkillName } = createRequire(import.meta.url)(path.join(ROOT, "install.js"));
return SOURCE_PROMPTS.map(generateSkillName);
} finally {
for (const [k, v] of Object.entries(saved)) v === undefined ? delete process.env[k] : (process.env[k] = v);
fs.rmSync(home, { recursive: true, force: true });
}
}
test("every skill's pose is drawn in the page, and every drawn pose belongs to a skill", () => {
const drawn = drawnPoses();
assert.deepEqual(poseProblems(SKILLS, drawn), []);
assert.doesNotMatch(poseTemplate(), /\sstyle=/, "a style attribute would be refused by the CSP");
// Variants borrow their pose; the dashboard keeps the flight.
assert.equal(startPose("implement-review"), "implement");
assert.equal(startPose("revise-plan"), "plan");
assert.equal(startPose("init-update"), "init");
assert.equal(startPose("dashboard"), null);
assert.equal(startPose(undefined), null);
const broken = SKILLS.map((s) => (s.workflow === "xray" ? { ...s, pose: "x-ray-glasses" } : s));
assert.deepEqual(poseProblems(broken, drawn), [
'plan2code-xray names pose "x-ray-glasses", which index.html does not draw',
'index.html draws pose "xray", which belongs to no skill',
]);
const poseless = SKILLS.map((s) => (s.workflow === "git" ? { ...s, pose: null } : s));
assert.deepEqual(poseProblems(poseless, drawn), ["plan2code-git has a card but no pose", 'index.html draws pose "git", which belongs to no skill']);
});
test("every workflow in the skill list has a help topic", () => {
const topics = helpTopics();
assert.deepEqual(helpProblems(SKILLS, topics), []);
const extra = [...SKILLS, { skill: "plan2code-made-up", workflow: "made-up" }];
assert.deepEqual(helpProblems(extra, topics), ["plan2code-made-up (made-up) has no help topic in console.mjs"]);
});
test("the skill list and install.js agree on which skills exist", () => {
const installed = installedSkills();
assert.ok(installed.includes("plan2code"), "read SOURCE_PROMPTS");
assert.deepEqual(installProblems(SKILLS, installed), []);
const extra = [...SKILLS, { skill: "plan2code-made-up", workflow: "made-up", card: {} }];
assert.deepEqual(installProblems(extra, installed), ["plan2code-made-up is in skills.js but not in install.js SOURCE_PROMPTS"]);
assert.deepEqual(installProblems(SKILLS, [...installed, "plan2code-orphan"]), ["plan2code-orphan is in install.js SOURCE_PROMPTS but has no card in skills.js"]);
});
test("dashboard note: the agent's note shows only on the spec the picker opened on", () => {
const a = { dir: "specs/a" };
const b = { dir: "specs/b" };
assert.equal(onInitialPick(a, a), true);
assert.equal(onInitialPick(a, b), false);
assert.equal(onInitialPick(a, null), false);
assert.equal(onInitialPick(null, null), true, "no spec at all: scratch is the opening pick");
assert.equal(onInitialPick(null, a), false);
});
test("dashboard note: the agent's note, the looking-over line and the neutral line", () => {
const menu = { note: "Phase 2 is next." };
assert.equal(dashNoteKind({ menu, hasMenu: true, onInitial: true, working: false }), "agent");
assert.equal(dashNoteKind({ menu, hasMenu: true, onInitial: false, working: false }), "neutral", "another pick, another line");
assert.equal(dashNoteKind({ menu: { note: " " }, hasMenu: true, onInitial: true, working: true }), "neutral", "a blank note is no note");
assert.equal(dashNoteKind({ menu: {}, hasMenu: false, onInitial: true, working: true }), "looking");
assert.equal(dashNoteKind({ menu: {}, hasMenu: false, onInitial: true, working: false }), "neutral");
});
test("starting screen: the hint stays calm for ninety seconds, then points at the terminal", () => {
assert.match(startingHint(0), /fills in by itself/);
assert.match(startingHint(90000), /fills in by itself/, "ninety seconds is still calm");
assert.match(startingHint(90001), /terminal has the play-by-play/);
});
+106 -122
View File
@@ -13,6 +13,7 @@ import path from "node:path";
// (it touches `document` at module scope and starts a session on import), which
// is exactly why this lives in its own file.
import { cardAvailability, SKILL_CATALOG } from "../src/web-console/public/answers.js";
import { SKILLS } from "../src/web-console/public/skills.js";
import { HELP_TABS } from "../src/web-console/public/help.js";
import { FAVICON_BODY, FAVICON_COLORS, faviconState, faviconSvg } from "../src/web-console/public/favicon.js";
import {
@@ -24,8 +25,9 @@ import {
latestTag,
} from "../src/web-console/update-check.mjs";
import { runHint } from "../src/web-console/public/render.js";
import { applyPatch } from "../src/web-console/lib.mjs";
import { applyPatch } from "../src/web-console/patches.mjs";
import { ROOT, cli, helpTemplate, sessionUrl } from "./web-console-test-helpers.mjs";
import { joinedCss } from "./css-helpers.mjs";
test("favicon: the dot follows the status line -- busy, ready, attention, plain", () => {
// Anything with the spinning ring is busy, even a finished screen opening the dashboard.
@@ -82,7 +84,7 @@ test("runHint: command words (git included) get the hint, the rest nothing", ()
});
test("a reused item id does not inherit the previous answer's submitted record", async () => {
const { applyPatch } = await import("../src/web-console/lib.mjs");
const { applyPatch } = await import("../src/web-console/patches.mjs");
const before = { items: [{ id: "q7", kind: "choice", title: "A", body: "old", status: "open", submitted: { at: "t", text: "old answer" } }] };
const reworded = applyPatch(before, { items: [{ id: "q7", kind: "choice", title: "B", body: "new", status: "open" }] });
assert.equal(reworded.items[0].submitted, undefined);
@@ -100,7 +102,7 @@ test("a reused item id does not inherit the previous answer's submitted record",
});
test("unansweredChat lists delivered Quick questions that still have no reply", async () => {
const { unansweredChat, appendChat, writeCursor } = await import("../src/web-console/lib.mjs");
const { unansweredChat, appendChat, writeCursor } = await import("../src/web-console/inbox.mjs");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-chat-"));
appendChat(dir, { kind: "reset", conversation: 1, workflow: "dashboard", reason: "start" });
appendChat(dir, { kind: "message", conversation: 1, text: "run it" });
@@ -248,9 +250,72 @@ test("update check: the frame carries update only when a newer release is cached
}
});
test("stop modal: handoff choice first, plain stop second, Keep going last, styled and wired", () => {
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
const html = web("index.html");
const css = joinedCss();
const dialog = html.match(/<dialog class="modal" id="stop-modal"[^>]*>([\s\S]*?)<\/dialog>/);
assert.ok(dialog, "index.html has the stop modal");
const body = dialog[1];
const at = (id) => body.indexOf(`id="${id}"`);
assert.ok(at("stop-handoff") >= 0 && at("stop-handoff") < at("stop-go") && at("stop-go") < at("stop-cancel"), "handoff, plain stop, Keep going, in that order");
assert.ok(body.includes("Stop with a handoff") && body.includes("Just stop and save"));
assert.doesNotMatch(body, /\sstyle=|<script/i);
assert.match(css, /\.stop-choice/, "app.css styles the choices");
assert.match(css, /\.stop-choice:focus-visible/, "and gives them a focus outline");
const help = helpTemplate().match(/<section class="help-panel" data-tab="finishing">([\s\S]*?)<\/section>/);
assert.ok(help && help[1].includes("Stop with a handoff") && help[1].includes("Just stop and save") && help[1].includes("~/.plan2code/handoffs/"), "Help names both choices and where handoffs land");
});
// The dashboard's handoff chips, preview and their four actions. What they
// do on the page is held by the page tests in test-web-console-page-dashboard.mjs;
// this keeps the style, the modal markup and the Help.
test("dashboard handoffs: the style, the read dialog and the delete warning ship, and Help explains the chips", () => {
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
const css = joinedCss();
const html = web("index.html");
assert.match(css, /\.spec-chip\.is-handoff/, "app.css styles handoff chips");
assert.match(css, /\.handoff-preview\b/, "and the preview panel");
const modal = html.match(/<dialog class="modal handoff-read" id="handoff-modal"[^>]*>([\s\S]*?)<\/dialog>/);
assert.ok(modal, "index.html has #handoff-modal");
assert.doesNotMatch(modal[1], /\sstyle=|<script/i);
assert.ok(html.includes('id="delete-warn-handoff"'), "the delete dialog carries the handoff warning");
const panel = helpTemplate().match(/<section class="help-panel" data-tab="dashboard">([\s\S]*?)<\/section>/);
assert.ok(panel && panel[1].includes("Pick it up here") && panel[1].includes("30-day sweep"), "Help explains handoff chips");
});
// The sign-off card: Approve comes before Show me it working, and an unpicked
// approve verdict is outlined in the accent.
test("sign-off: approve leads show, and the approve button wears the accent", () => {
const doc = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", f), "utf8");
for (const f of ["notes/implement.md", "building-review.md"]) {
const text = doc(f);
const approve = text.indexOf('{ "id": "approve", "label": "Approve this phase" }');
const show = text.indexOf('{ "id": "show", "label": "Show me it working" }');
assert.ok(approve > 0 && show > approve, `${f} lists Approve this phase before Show me it working`);
}
assert.match(joinedCss(), /\.btn\.is-approve\s*\{[^}]*border-color:\s*var\(--accent\)/, "is-approve borders in the accent");
});
// A fixed bug's chip: a visible Delete, one confirm, and "bug fixed" said once.
// What the fixed bug's chip and Delete do on the page is held by the page tests
// in test-web-console-page-dashboard.mjs; this keeps the style and the Help.
test("bug fixed delete: the Delete button is styled and Help explains the one confirm", () => {
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
const css = joinedCss();
assert.match(css, /\.spec-chip-del-label\s*\{/, "app.css styles the Delete button");
assert.match(css, /\.spec-chip-del-label:focus-visible/, "and gives it a focus outline");
const panel = helpTemplate().match(/<section class="help-panel" data-tab="dashboard">([\s\S]*?)<\/section>/);
assert.ok(panel && /fixed\s+bug[\s\S]*?Delete[\s\S]*?one\s+confirm/i.test(panel[1]), "Help says a fixed bug has its own Delete and needs one confirm");
});
test("update banner: the modal is in the page, with the exact command and no inline styles or scripts", () => {
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
const dash = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "dashboard.js"), "utf8");
const dialog = html.match(/<dialog class="modal" id="update-modal" aria-labelledby="update-title">([\s\S]*?)<\/dialog>/);
assert.ok(dialog, "index.html has the update modal");
assert.doesNotMatch(dialog[1], /\sstyle=/);
@@ -260,32 +325,26 @@ test("update banner: the modal is in the page, with the exact command and no inl
assert.match(panel[1], /UPDATE AVAILABLE/, "the dashboard topic explains the banner");
assert.doesNotMatch(panel[1], /\sstyle=/);
assert.doesNotMatch(panel[1], /<script/i);
assert.ok(app.includes('"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"'), "app.js copies the exact command");
assert.ok(dash.includes('"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"'), "the dashboard copies the exact command");
});
test("update banner: built only on the dashboard, dismissed per session, and Help's version links to Releases", () => {
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
const start = app.indexOf("function renderDashboard(main) {");
assert.ok(start >= 0, "app.js has renderDashboard");
const end = app.indexOf("\n}\n", start);
const body = app.slice(start, end);
assert.match(body, /"dash-nudge update-banner"/, "renderDashboard builds the banner");
const outside = app.slice(0, start) + app.slice(end);
assert.doesNotMatch(outside, /update-banner/, "no other code builds it");
assert.match(app, /"p2c-update-dismissed:" \+ S\.sid/, "the dismissal is keyed by the session id");
assert.match(app, /const RELEASES_URL = "https:\/\/github\.com\/jparkerweb\/plan2code\/releases\/";/);
assert.match(app, /\.rel = "noopener noreferrer";/);
const help = app.match(/async function renderHelpVersion\(\) \{([\s\S]*?)\n\}/);
assert.ok(help, "app.js has renderHelpVersion");
assert.match(help[1], /releasesLink\(/, "the help version is a Releases link");
const dash = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "dashboard.js"), "utf8");
const render = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "render.js"), "utf8");
assert.match(dash, /"p2c-update-dismissed:" \+ page\.S\.sid/, "the dismissal is keyed by the session id");
assert.match(render, /const RELEASES_URL = "https:\/\/github\.com\/jparkerweb\/plan2code\/releases\/";/);
assert.match(render, /\.rel = "noopener noreferrer";/);
});
// The Changelog card sits left of Git, the last card. It is always clickable,
// and a launch from it resumes the session under its own workflow.
test("the Changelog card comes just before Git, Git is last, and Changelog is always on", () => {
const skills = SKILL_CATALOG.map((e) => e.skill);
assert.equal(skills.indexOf("plan2code-changelog") + 1, skills.indexOf("plan2code-git"));
assert.equal(skills[skills.length - 1], "plan2code-git");
// The Changelog card sits left of Git, which sits left of Handoff, the last
// card. It is always clickable, and a launch from it resumes the session under
// its own workflow.
test("the Changelog card comes just before Git, Handoff is last, and Changelog is always on", () => {
// The card order is skills.js's order.
const skills = SKILLS.filter((s) => s.card).map((s) => s.skill);
assert.equal(skills.indexOf("plan2code-changelog") + 1, skills.indexOf("plan2code-git"), "Changelog sits just before Git");
assert.equal(skills.indexOf("plan2code-git") + 1, skills.indexOf("plan2code-handoff"), "Git sits just before Handoff");
assert.equal(skills.at(-1), "plan2code-handoff", "Handoff is last");
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-changelog");
assert.equal(entry.workflow, "changelog");
assert.equal(entry.command, "/plan2code-changelog");
@@ -315,93 +374,33 @@ test("help: the stuck tab is second, with a callout and four symptom rows before
assert.match(panel, /<svg class="help-callout-icon"[^>]*aria-hidden="true"/, "the icon is decoration");
});
// Every say(...) call in a source slice, as its top-level arguments (raw
// source text). String-aware, so commas and brackets inside a line are text.
function sayCalls(source) {
const calls = [];
let at = 0;
while ((at = source.indexOf("say(", at)) !== -1) {
if (/[\w.]/.test(source[at - 1] || "")) {
at += 4;
continue;
}
const args = [];
let depth = 0;
let quote = null;
let start = at + 4;
let i = start;
for (; i < source.length; i++) {
const ch = source[i];
if (quote) {
if (ch === "\\") i++;
else if (ch === quote) quote = null;
continue;
}
if (ch === '"' || ch === "'" || ch === "`") quote = ch;
else if ("([{".includes(ch)) depth++;
else if (")]}".includes(ch)) {
if (depth === 0) break;
depth--;
} else if (ch === "," && depth === 0) {
args.push(source.slice(start, i).trim());
start = i + 1;
}
}
const last = source.slice(start, i).trim();
if (last) args.push(last);
calls.push(args);
at = i;
}
return calls;
}
test("status line: the quiet, Not running and Not connected lines offer What to check, opening Help on the stuck tab", () => {
const app = publicSource("app.js");
assert.equal(HELP_TABS.findIndex((t) => t.id === "stuck"), 1, "the stuck tab is second");
const opener = app.match(/function openHelpOn\(id\) \{([\s\S]*?)\n\}/);
assert.ok(opener, "app.js has openHelpOn");
assert.match(opener[1], /HELP_TABS\.some\(/, "openHelpOn only opens a tab that exists");
const render = app.slice(app.indexOf("function renderStatus()"), app.indexOf("/* ---------------------------------------------------------------- brief */"));
const sayDef = render.slice(render.indexOf("const say = ("), render.indexOf("text.replaceChildren("));
assert.match(sayDef, /help\.textContent = "What to check"/);
assert.match(sayDef, /help\.addEventListener\("click", \(\) => openHelpOn\("stuck"\)\)/, "the button opens Help on the stuck tab");
const calls = sayCalls(render.slice(render.indexOf("text.replaceChildren(")));
const checked = calls.filter((args) => args[4] && args[4] !== "false");
for (const needle of ["Not connected. Your answers are saved.", "Still working on it.", "is not running. Your answers are saved", "is not running right now."]) {
assert.ok(checked.some((args) => args.join(",").includes(needle)), `"${needle}" carries What to check`);
}
assert.ok(checked.some((args) => args[4] === "Boolean(hint)"), "the approval hint carries What to check");
// Nothing else does: the finished, working and adrift lines stay plain.
assert.equal(checked.length, 4, `four calls pass check, got: ${checked.map((a) => a[1]).join(" | ")}`);
test("help: privacy names the handoffs folder and preferences says Cleanup never offers it", () => {
const tpl = helpTemplate();
const privacy = tpl.match(/<section class="help-panel" data-tab="privacy">([\s\S]*?)<\/section>/)[1];
const kept = privacy.slice(privacy.indexOf("<h4>What is kept, and where</h4>"));
assert.match(kept, /(<code>)?~\/\.plan2code\/handoffs\/(<\/code>)?/, "privacy lists ~/.plan2code/handoffs/");
assert.doesNotMatch(
kept,
/Everything lives under\s+<code>~\/\.plan2code\/console\/<\/code>/,
"the lead no longer says everything lives under the console folder"
);
const prefs = tpl.match(/<section class="help-panel" data-tab="prefs">([\s\S]*?)<\/section>/)[1];
const cleanup = prefs.slice(prefs.indexOf("<strong>Cleanup</strong>"), prefs.indexOf("<strong>Back to default</strong>"));
assert.match(cleanup, /handoffs/, "the Cleanup text names the handoffs folder");
assert.match(cleanup, /never\s+offered/, "the Cleanup text says the handoffs folder is never offered for removal");
});
test("finished screen: Before you close this waits while a hand-off they asked for is starting", () => {
const app = publicSource("app.js");
const handoff = app.slice(app.indexOf("function renderHandoff("));
const body = handoff.slice(0, handoff.indexOf("\n}\n"));
assert.match(body, /if \(!closeGuideHeld\(\)\) card\.appendChild\(renderCloseGuide\(shape, fin\)\)/);
const held = app.match(/function closeGuideHeld\(\) \{([\s\S]*?)\n\}/);
assert.ok(held, "app.js has closeGuideHeld");
const run = (gone, afterBuild, pending) =>
new Function("gone", "local", "reviewPending", held[1])(gone, { afterBuild }, () => pending);
for (const kind of ["review", "commit", "dashboard"]) {
assert.equal(run(false, kind, null), true, `held while ${kind} is starting`);
}
assert.equal(run(false, null, "asked"), true, "held while a review is asked");
assert.equal(run(false, null, "open"), false, "shown while the review is only on offer");
assert.equal(run(false, null, null), false, "shown on a plain finish");
assert.equal(run(false, "done", null), false, "shown once they said they are done");
assert.equal(run(true, "review", null), false, "shown once the server is gone: nothing is starting");
// The press re-renders the page, and so does the finish going away, so the
// panel follows the state.
const send = app.slice(app.indexOf("async function sendAfterBuild("), app.indexOf("/* ------------------------------------------------------------- dashboard */"));
assert.match(send, /local\.afterBuild = kind;[\s\S]*finally \{\s*render\(\);/);
assert.match(app, /if \(!finish\(\) && local\.afterBuild\) \{\s*local\.afterBuild = null;/);
test("help: the stuck tab is second, and openHelpOn only opens a tab that exists", () => {
const app = publicSource("screens/help-dialog.js");
assert.equal(HELP_TABS.findIndex((t) => t.id === "stuck"), 1, "the stuck tab is second");
const opener = app.match(/function openHelpOn\(id\) \{([\s\S]*?)\n\}/);
assert.ok(opener, "help-dialog.js has openHelpOn");
assert.match(opener[1], /HELP_TABS\.some\(/, "openHelpOn only opens a tab that exists");
});
test("models: Codex is a model CLI on the server and the page, with its own tab", () => {
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
const app = publicSource("app.js");
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
const app = publicSource("screens/looks.js");
const html = publicSource("index.html");
const list = (src) => JSON.parse(src.match(/const MODEL_CLIS = (\[[^\]]*\]);/)[1]);
assert.deepEqual(list(server), ["claude", "devin", "codex"]);
@@ -415,22 +414,7 @@ test("models: Codex is a model CLI on the server and the page, with its own tab"
for (const cli of list(server)) assert.ok(Array.isArray(shipped[cli]), `the launcher's models.json has ${cli}`);
});
test("finished screen: every shape shows Before you close this, with three rows", () => {
const app = publicSource("app.js");
const handoff = app.slice(app.indexOf("function renderHandoff("));
assert.match(handoff.slice(0, handoff.indexOf("\n}\n")), /card\.appendChild\(renderCloseGuide\(shape, fin\)\)/);
const guide = app.slice(app.indexOf("function renderCloseGuide("), app.indexOf("function renderHandoff("));
for (const label of ["Safe to close", "Start fresh", "Carry on", "Before you close this"]) {
assert.ok(guide.includes(label), `the guide says "${label}"`);
}
assert.match(guide, /shape === "paused"/, "a pause changes the Start fresh sentence");
assert.match(guide, /resume command/);
});
test("getting started: the new help, status and finished-screen strings carry no em dash", () => {
const app = publicSource("app.js");
const guide = app.slice(app.indexOf("const GUIDE_ICONS"), app.indexOf("function renderHandoff("));
assert.ok(!guide.includes(EM), "the close guide has no em dash");
const tpl = helpTemplate();
const stuck = tpl.match(/<section class="help-panel" data-tab="stuck">([\s\S]*?)<\/section>/)[1];
const fresh = stuck.slice(0, stuck.indexOf("<h4>Not running, or not connected?</h4>"));
+408
View File
@@ -0,0 +1,408 @@
// Web console tests, the spec states: public/spec-states.js defines every
// state the dashboard scan can report, and the labels, next steps and card
// rules are lookups on it.
// Run with: node --test scripts/test-web-console-spec-states.mjs
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { SPEC_STATES as TABLE, stateFor } from "../src/web-console/public/spec-states.js";
import { SKILLS } from "../src/web-console/public/skills.js";
import { SKILL_CATALOG, cardAvailability, defaultSpec } from "../src/web-console/public/answers.js";
import { scanProject } from "../src/web-console/scan.mjs";
// What the picker labels each state and which card each state lights, as
// answers.js's SPEC_STATE_LABELS and NEXT_FOR_STATE said before the table.
const LABELS = {
diagnosed: "Bug diagnosed",
fixed: "Bug fixed",
exploring: "Exploring",
mapped: "Ready to plan",
planned: "Ready to document",
documented: "Ready to build",
building: "Building",
built: "Ready to finalize",
unrecognized: "Files on disk",
};
const NEXT = {
diagnosed: "plan2code-quick-task",
fixed: null,
exploring: "plan2code-0-pathfinder",
mapped: "plan2code-1-plan",
planned: "plan2code-2-document",
documented: "plan2code-3-implement",
building: "plan2code-3-implement",
built: "plan2code-4-finalize",
unrecognized: null,
};
test("spec states: each state keeps its label and next step, and only fixed is finished", () => {
assert.deepEqual(Object.keys(TABLE), Object.keys(LABELS), "the states, in the scan's order");
for (const [name, label] of Object.entries(LABELS)) {
const s = stateFor(name);
assert.ok(s, `${name} is in the table`);
assert.equal(s.label, label, `${name}'s label`);
assert.equal(s.next, NEXT[name], `${name}'s next step`);
assert.equal(s.finished, name === "fixed", `${name}'s finished flag`);
}
assert.equal(stateFor("made-up"), null, "an unknown state is null");
assert.ok(Object.isFrozen(TABLE) && Object.values(TABLE).every(Object.isFrozen), "the table is frozen");
});
// Every card's answer for every picker selection, as cardAvailability() gave
// them before the card rules moved onto skills.js: generated once from that
// code and written out here, so the move is proven to change nothing. "none"
// is "start from scratch" (no spec picked). The scan is a set-up git project
// with nothing to commit; SCAN_CASES covers the three cards that read it.
const SCAN = { hasAgents: true, isGit: true, pending: 0 };
const CARDS = {
"plan2code-init": {
"none": { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
diagnosed: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
fixed: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
exploring: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
mapped: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
planned: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
documented: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
building: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
built: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
unrecognized: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
},
"plan2code-init-update": {
"none": { on: true },
diagnosed: { on: true },
fixed: { on: true },
exploring: { on: true },
mapped: { on: true },
planned: { on: true },
documented: { on: true },
building: { on: true },
built: { on: true },
unrecognized: { on: true },
},
"plan2code-0-pathfinder": {
"none": { on: true, next: true },
diagnosed: { on: false, reason: "The cause is found. Fix it in a quick task, or plan it." },
fixed: { on: false, reason: "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/." },
exploring: { on: true, next: true },
mapped: { on: false, reason: "This spec is already past the questions" },
planned: { on: false, reason: "This spec is already past the questions" },
documented: { on: false, reason: "This spec is already past the questions" },
building: { on: false, reason: "This spec is already past the questions" },
built: { on: false, reason: "This spec is already past the questions" },
unrecognized: { on: true, next: false },
},
"plan2code-1-plan": {
"none": { on: true, next: false },
diagnosed: { on: true, next: false },
fixed: { on: false, reason: "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/." },
exploring: { on: false, reason: "Pathfinder is not finished with this spec yet" },
mapped: { on: true, next: true },
planned: { on: true, next: false },
documented: { on: false, reason: "The plan is written. Revise it instead if it moved." },
building: { on: false, reason: "The plan is written. Revise it instead if it moved." },
built: { on: false, reason: "The plan is written. Revise it instead if it moved." },
unrecognized: { on: true, next: false },
},
"plan2code-1b-revise-plan": {
"none": { on: false, reason: "Needs a spec that is already written up" },
diagnosed: { on: false, reason: "Needs a spec that is already written up" },
fixed: { on: false, reason: "Needs a spec that is already written up" },
exploring: { on: false, reason: "Needs a spec that is already written up" },
mapped: { on: false, reason: "Needs a spec that is already written up" },
planned: { on: false, reason: "Needs a spec that is already written up" },
documented: { on: true },
building: { on: true },
built: { on: false, reason: "The spec is fully built" },
unrecognized: { on: false, reason: "Needs a spec that is already written up" },
},
"plan2code-2-document": {
"none": { on: false, reason: "Needs a drafted plan first" },
diagnosed: { on: false, reason: "Needs a drafted plan first" },
fixed: { on: false, reason: "Needs a drafted plan first" },
exploring: { on: false, reason: "Needs a drafted plan first" },
mapped: { on: false, reason: "Needs a drafted plan first" },
planned: { on: true, next: true },
documented: { on: false, reason: "The phases are already written up" },
building: { on: false, reason: "The phases are already written up" },
built: { on: false, reason: "The phases are already written up" },
unrecognized: { on: false, reason: "Needs a drafted plan first" },
},
"plan2code-3-implement": {
"none": { on: false, reason: "Needs the phase checklists written up first" },
diagnosed: { on: false, reason: "Needs the phase checklists written up first" },
fixed: { on: false, reason: "Needs the phase checklists written up first" },
exploring: { on: false, reason: "Needs the phase checklists written up first" },
mapped: { on: false, reason: "Needs the phase checklists written up first" },
planned: { on: false, reason: "Needs the phase checklists written up first" },
documented: { on: true, next: true },
building: { on: true, next: true },
built: { on: false, reason: "All tasks are already done" },
unrecognized: { on: false, reason: "Needs the phase checklists written up first" },
},
"plan2code-3-implement-review": {
"none": { on: false, reason: "Needs the phase checklists written up first" },
diagnosed: { on: false, reason: "Needs the phase checklists written up first" },
fixed: { on: false, reason: "Needs the phase checklists written up first" },
exploring: { on: false, reason: "Needs the phase checklists written up first" },
mapped: { on: false, reason: "Needs the phase checklists written up first" },
planned: { on: false, reason: "Needs the phase checklists written up first" },
documented: { on: true, next: false },
building: { on: true, next: false },
built: { on: false, reason: "All tasks are already done" },
unrecognized: { on: false, reason: "Needs the phase checklists written up first" },
},
"plan2code-4-finalize": {
"none": { on: false, reason: "Needs a spec that is fully built" },
diagnosed: { on: false, reason: "Needs a spec that is fully built" },
fixed: { on: false, reason: "Needs a spec that is fully built" },
exploring: { on: false, reason: "Needs a spec that is fully built" },
mapped: { on: false, reason: "Needs a spec that is fully built" },
planned: { on: false, reason: "Needs a spec that is fully built" },
documented: { on: false, reason: "Needs a spec that is fully built" },
building: { on: false, reason: "Needs a spec that is fully built" },
built: { on: true, next: true },
unrecognized: { on: false, reason: "Needs a spec that is fully built" },
},
"plan2code-quick-task": {
"none": { on: true },
diagnosed: { on: true, next: true },
fixed: { on: true },
exploring: { on: true },
mapped: { on: true },
planned: { on: true },
documented: { on: true },
building: { on: true },
built: { on: true },
unrecognized: { on: true },
},
"plan2code-review": {
"none": { on: true },
diagnosed: { on: true },
fixed: { on: true },
exploring: { on: true },
mapped: { on: true },
planned: { on: true },
documented: { on: true },
building: { on: true },
built: { on: true },
unrecognized: { on: true },
},
"plan2code-xray": {
"none": { on: true },
diagnosed: { on: true },
fixed: { on: true },
exploring: { on: true },
mapped: { on: true },
planned: { on: true },
documented: { on: true },
building: { on: true },
built: { on: true },
unrecognized: { on: true },
},
"plan2code-diagnose": {
"none": { on: true },
diagnosed: { on: true },
fixed: { on: true },
exploring: { on: true },
mapped: { on: true },
planned: { on: true },
documented: { on: true },
building: { on: true },
built: { on: true },
unrecognized: { on: true },
},
"plan2code-changelog": {
"none": { on: true },
diagnosed: { on: true },
fixed: { on: true },
exploring: { on: true },
mapped: { on: true },
planned: { on: true },
documented: { on: true },
building: { on: true },
built: { on: true },
unrecognized: { on: true },
},
"plan2code-git": {
"none": { on: true },
diagnosed: { on: true },
fixed: { on: true },
exploring: { on: true },
mapped: { on: true },
planned: { on: true },
documented: { on: true },
building: { on: true },
built: { on: true },
unrecognized: { on: true },
},
"plan2code-handoff": {
"none": { on: true },
diagnosed: { on: true },
fixed: { on: true },
exploring: { on: true },
mapped: { on: true },
planned: { on: true },
documented: { on: true },
building: { on: true },
built: { on: true },
unrecognized: { on: true },
},
};
const SCAN_CASES = [
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-init", { on: true }],
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-init-update", { on: false, reason: "Needs an AGENTS.md. Set the project up first." }],
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-git", { on: true, note: "Not a git repository yet: it offers to start one" }],
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-init", { on: false, reason: "AGENTS.md is already written. Refresh it instead." }],
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-init-update", { on: true }],
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-git", { on: true, note: "3 files to commit" }],
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-init", { on: false, reason: "AGENTS.md is already written. Refresh it instead." }],
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-init-update", { on: true }],
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-git", { on: true, note: "1 file to commit" }],
];
test("card rules: every card gives the same answer for every spec state as before", () => {
assert.deepEqual(SKILL_CATALOG.map((e) => e.skill), Object.keys(CARDS), "one row per card, in card order");
for (const entry of SKILL_CATALOG) {
for (const [sel, want] of Object.entries(CARDS[entry.skill])) {
const spec = sel === "none" ? null : { dir: "specs/x", name: "x", state: sel };
assert.deepEqual(cardAvailability(entry, SCAN, spec), want, `${entry.skill} with ${sel}`);
}
}
});
test("card rules: a state the table does not know is treated like files on disk", () => {
for (const entry of SKILL_CATALOG) {
const weird = cardAvailability(entry, SCAN, { dir: "specs/x", name: "x", state: "made-up" });
assert.deepEqual(weird, CARDS[entry.skill].unrecognized, `${entry.skill} with an unknown state`);
}
});
test("card rules: Init, Init update and Git read the scan, not the spec", () => {
for (const [scan, skill, want] of SCAN_CASES) {
const entry = SKILL_CATALOG.find((e) => e.skill === skill);
assert.deepEqual(cardAvailability(entry, scan, null), want, `${skill} with ${JSON.stringify(scan)}`);
}
});
test("finished: any finished state is never the picker's default, not only fixed", () => {
// The test's own copy of the table, with a made-up second finished state.
const table = { ...TABLE, archived: { label: "Archived", next: null, finished: true } };
const lookup = (name) => (Object.hasOwn(table, name) ? table[name] : null);
const specs = [
{ dir: "specs/a", name: "a", state: "archived" },
{ dir: "specs/b", name: "b", state: "fixed" },
{ dir: "specs/c", name: "c", state: "planned" },
];
assert.equal(defaultSpec(specs, lookup)?.dir, "specs/c", "the newest spec still in play");
assert.equal(defaultSpec(specs.slice(0, 2), lookup), null, "only finished specs: start from scratch");
assert.equal(defaultSpec(specs)?.dir, "specs/a", "the real table does not know archived, so it is in play");
// The cards greyed for a fixed bug give a made-up finished state the same reason.
const archived = { dir: "specs/a", name: "a", state: "archived" };
for (const entry of SKILL_CATALOG) {
const fixed = cardAvailability(entry, SCAN, { dir: "specs/b", name: "b", state: "fixed" });
assert.deepEqual(cardAvailability(entry, SCAN, archived, lookup), fixed, `${entry.skill} treats archived as it treats fixed`);
}
});
// One spec folder per state, in the shapes classifySpec() reads.
const PHASE = (ticks) => "# Phase 1\n\n" + ticks.map((x, i) => `- [${x ? "x" : " "}] **Task 1.${i + 1}:** Step ${i + 1}\n`).join("");
const FIXTURES = {
diagnosed: { "DIAGNOSIS-20261017.md": "# Diagnosis\n\n**Status:** Diagnosed\n" },
fixed: { "DIAGNOSIS-20261017.md": "# Diagnosis\n\n**Status:** Fixed\n" },
exploring: { "pathfinder/map.md": "# Map\n\nStatus: Working\n" },
mapped: { "PLAN-DRAFT-20261017.md": "# Plan draft\n\n**Status:** Phase 3 Complete - Resume at Phase 4\n" },
planned: { "PLAN-DRAFT-20261017.md": "# Plan draft\n\n**Status:** Draft\n" },
documented: { "overview.md": "# Overview\n", "phase-1.md": PHASE([false, false]) },
building: { "overview.md": "# Overview\n", "phase-1.md": PHASE([true, false]) },
built: { "overview.md": "# Overview\n", "phase-1.md": PHASE([true, true]) },
unrecognized: { "notes.md": "Some loose notes.\n" },
};
// The states a scan of these fixtures reports, against the table's: the
// lines that name what does not match, empty when they agree.
function scanProblems(fixtures, table) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-states-"));
try {
for (const [name, files] of Object.entries(fixtures))
for (const [rel, text] of Object.entries(files)) {
const file = path.join(root, "specs", name, rel);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, text);
}
const scan = scanProject(root);
const problems = scan.specs.filter((sp) => sp.state !== sp.name).map((sp) => `the ${sp.name} fixture scans as ${sp.state}`);
const seen = new Set(scan.specs.map((sp) => sp.state));
for (const state of seen) if (!Object.hasOwn(table, state)) problems.push(`the scan returns ${state}, which spec-states.js lacks`);
for (const state of Object.keys(table)) if (!seen.has(state)) problems.push(`no fixture reaches ${state}: add one, or drop it from spec-states.js`);
return problems;
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
}
test("the scan: every state it can return is in the table, and a fixture reaches every state in it", () => {
assert.deepEqual(scanProblems(FIXTURES, TABLE), []);
// The check names what is missing.
const { built, ...short } = FIXTURES;
assert.deepEqual(scanProblems(short, TABLE), ["no fixture reaches built: add one, or drop it from spec-states.js"]);
const { unrecognized, ...known } = TABLE;
assert.deepEqual(scanProblems(FIXTURES, known), ["the scan returns unrecognized, which spec-states.js lacks"]);
});
// The states no card names in its `states` list: a card that is on for "any"
// spec does not count, since it would take a state nobody thought about. A
// finished state is taken by no card on purpose.
function untakenStates(skills, table) {
const taken = new Set(skills.flatMap((sk) => (Array.isArray(sk.states) ? sk.states : [])));
return Object.entries(table)
.filter(([name, s]) => !s.finished && !taken.has(name))
.map(([name]) => `no card's states take ${name}: add it to the skills.js entries whose card it lights`);
}
test("card rules: every state still in play is taken by at least one card", () => {
assert.deepEqual(untakenStates(SKILLS, TABLE), []);
// The check names the state: Document and Plan are the cards that take planned.
const without = SKILLS.map((sk) =>
Array.isArray(sk.states) && (sk.skill === "plan2code-2-document" || sk.skill === "plan2code-1-plan")
? { ...sk, states: sk.states.filter((st) => st !== "planned") }
: sk
);
assert.deepEqual(untakenStates(without, TABLE), ["no card's states take planned: add it to the skills.js entries whose card it lights"]);
});
test("card rules: a card's states and greyed reasons name only real states", () => {
const known = new Set([...Object.keys(TABLE), "none"]);
for (const sk of SKILLS) {
if (Array.isArray(sk.states)) for (const st of sk.states) assert.ok(known.has(st), `${sk.skill} takes ${st}, which is no state`);
for (const key of Object.keys(sk.greyed || {})) assert.ok(key === "default" || key === "finished" || known.has(key), `${sk.skill}'s greyed names ${key}, which is no state`);
if (Array.isArray(sk.states) && sk.card) assert.ok(sk.greyed && sk.greyed.default, `${sk.skill} has a default greyed reason`);
}
});
// The states the dashboard skill's prose (src/plan2code.md) never mentions,
// by name in backticks (`planned`) or by label in quotes ("Ready to
// document"). The agent reads that prose to choose its recommendation, so
// every state needs a word there; a bare word ("reading or exploring", a file
// named building-habits.md) is not one.
function unmentionedStates(prose, table) {
const lower = prose.toLowerCase();
return Object.entries(table)
.filter(([name, s]) => !prose.includes("`" + name + "`") && !lower.includes(`"${s.label.toLowerCase()}"`))
.map(([name, s]) => `src/plan2code.md mentions neither \`${name}\` nor "${s.label}"`);
}
test("the dashboard skill: its prose names every spec state", () => {
const prose = fs.readFileSync(path.join(import.meta.dirname, "..", "src", "plan2code.md"), "utf8");
assert.deepEqual(unmentionedStates(prose, TABLE), []);
const sample = 'Only `planned` and "Ready to build", while building and exploring are bare words.';
const some = { planned: TABLE.planned, documented: TABLE.documented, building: TABLE.building, exploring: TABLE.exploring };
assert.deepEqual(unmentionedStates(sample, some), [
'src/plan2code.md mentions neither `building` nor "Building"',
'src/plan2code.md mentions neither `exploring` nor "Exploring"',
]);
});
+83 -17
View File
@@ -15,7 +15,9 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { applyPatch, scanProject } from "../src/web-console/lib.mjs";
import { scanProject } from "../src/web-console/scan.mjs";
import { applyPatch } from "../src/web-console/patches.mjs";
import { joinedCss } from "./css-helpers.mjs";
import {
ROOT,
CONSOLE_CLI,
@@ -31,6 +33,7 @@ import {
WEB_CONSOLE_DIR,
consoleDoc,
consoleDocFiles,
HANDOFFS_DIR,
} from "./web-console-test-helpers.mjs";
const choice = (id, extra = {}) => ({
@@ -321,6 +324,62 @@ test("settle and a defaulted reply id go through post end to end", async () => {
/* ------------------------------------------------------------ session hops */
// A pick-up hops into the stored workflow and spec; the page sends only the
// id. A missing spec folder, a workflow that is not a workflow name, or the
// Handoff skill's own handoff falls back to Quick Task, flagged. (No skills sit beside the source tree, so the
// stored skill name stands there.)
test("a pick-up comes with the stored skill's resume command, handoffFile, and falls back to Quick Task", async () => {
process.env.PLAN2CODE_HANDOFFS_DIR = HANDOFFS_DIR;
const store = await import("../src/web-console/handoffs.mjs");
const worktree = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pickup-"));
fs.mkdirSync(path.join(worktree, "specs", "lunch-vote"), { recursive: true });
const make = (rec) => {
const h = store.newHandoff({ worktree, project: worktree, workflow: "implement", skill: "plan2code-3-implement", title: "T", ...rec }, new Date(2026, 9, 17, 10, 0 + make.n++));
fs.writeFileSync(h.path, "# Handoff: T\n");
return h;
};
make.n = 0;
const s = consoleSession(["--workflow", "dashboard"]);
const resumeOf = (workflow, spec = "") =>
`node "${path.join(ROOT, "src", "web-console", "console.mjs")}" open --resume ${s.sid} --no-open --workflow ${workflow}${spec}`;
try {
const good = make({ spec: "specs/lunch-vote" });
const goneSpec = make({ spec: "specs/deleted" });
const badMeta = make({ spec: null });
const metaFile = path.join(HANDOFFS_DIR, badMeta.id + ".json");
fs.writeFileSync(metaFile, fs.readFileSync(metaFile, "utf8").replace('"workflow": "implement"', '"workflow": "Not A Workflow"'));
const cases = [
[good, resumeOf("implement", " --spec specs/lunch-vote"), undefined],
[goneSpec, resumeOf("quick-task"), true],
[badMeta, resumeOf("quick-task"), true],
// The Handoff skill's own handoff carries on in Quick Task, never in another handoff.
[make({ workflow: "handoff", skill: "plan2code-handoff" }), resumeOf("quick-task"), true],
];
for (const [h, resume, fallback] of cases) {
assert.equal((await s.send("/submit", { actions: [{ i: "__pickup", type: "pickup", handoff: h.id }], reply: "pick up" })).status, 200);
const res = waitFor(s);
assert.equal(res.status, 0);
assert.equal(res.json.resume, resume);
assert.equal(res.json.handoffFile, h.path);
assert.equal(res.json.fallback, fallback);
}
// A stored spec with shell characters never reaches `resume`: Quick Task, flagged.
const hostile = make({ spec: "specs/x;touch pwned" });
assert.equal((await s.send("/submit", { actions: [{ i: "__pickup", type: "pickup", handoff: hostile.id }], reply: "pick up" })).status, 200);
const hot = waitFor(s).json;
assert.equal(hot.resume, resumeOf("quick-task"));
assert.equal(hot.fallback, true);
// An id that is not a handoff id gets the fallback and no handoffFile.
assert.equal((await s.send("/submit", { actions: [{ i: "__pickup", type: "pickup", handoff: "../x" }], reply: "pick up" })).status, 200);
const bad = waitFor(s).json;
assert.equal(bad.handoffFile, undefined);
assert.equal(bad.fallback, true);
} finally {
cli(["stop", "--session", s.sid]);
fs.rmSync(worktree, { recursive: true, force: true });
}
});
test("a launch, a dashboard press and Commit it now each come with their resume command", async () => {
const s = consoleSession(["--workflow", "dashboard"]);
try {
@@ -366,6 +425,15 @@ test("the built skills name the skill file to follow after a hop", async () => {
assert.equal(res.status, 200);
const got = run(["wait", "--session", opened.sid, "--seconds", "10"]).json;
assert.equal(got.skillFile, path.join(ROOT, "skills", "plan2code-review", "SKILL.md"));
assert.equal(got.handoffSkill, undefined, "a launch is not a handoff stop");
const stopRes = await fetch(`${m[1]}/submit`, {
method: "POST",
headers: { "content-type": "application/json", cookie, connection: "close" },
body: JSON.stringify({ actions: [{ i: "__stop", type: "stop", handoff: true }], reply: "stop with a handoff" }),
});
assert.equal(stopRes.status, 200);
const stopped = run(["wait", "--session", opened.sid, "--seconds", "10"]).json;
assert.equal(stopped.handoffSkill, path.join(ROOT, "skills", "plan2code-handoff", "SKILL.md"), "a handoff stop in a built skill names the Handoff skill file");
} finally {
run(["stop", "--session", opened.sid]);
}
@@ -406,7 +474,8 @@ test("every console workflow has its notes, and its skill's Interface reads them
const notesFor = {
init: "init", "init-update": "init", pathfinder: "pathfinder", plan: "plan", "revise-plan": "revise-plan",
document: "document", implement: "implement", "implement-review": "implement", "quick-task": "quick-task",
review: "review", finalize: "finalize", handoff: "handoff", changelog: "changelog", git: "git",
review: "review", finalize: "finalize", handoff: "handoff", changelog: "changelog", git: "git", xray: "xray",
diagnose: "diagnose",
};
const skills = fs.readdirSync(path.join(ROOT, "src")).filter((f) => /^plan2code(-.*)?\.md$/.test(f));
for (const f of skills) {
@@ -548,13 +617,6 @@ test("a wait with nothing open leaves a working agent working", () => {
}
});
test("the git board lets go of a working agent that went adrift", () => {
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
const at = js.indexOf("const gitMode = ");
const line = js.slice(at, js.indexOf(";", at));
assert.ok(line.includes("(agentWorking() && !agentAdrift())"), line);
});
test("post --file - reads the patch from stdin, UTF-8 and a BOM included", () => {
const s = openSession();
try {
@@ -648,16 +710,22 @@ test("a finish ends the working stretch, and resuming a pause starts a fresh one
});
test("a card with a note box over the git board flows at its own height, never shrunk under the board", () => {
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
const css = joinedCss();
const rule = css.slice(css.indexOf(".git-cards > .card,"), css.indexOf("{", css.indexOf(".git-cards > .card,")));
assert.ok(rule.includes(".git-cards > .card.is-primary.has-grow"), "the board's natural-height rule outranks .has-grow");
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
const fn = js.slice(js.indexOf("function markGrowBox("), js.indexOf("function naturalHeight("));
assert.ok(fn.includes("isGitBoard()"), "no box grows over the board");
});
test("a card and its pager in the git board's card slot fill the board's width, never shrink to their content", () => {
const css = joinedCss();
// .card and .pager centre with auto inline margins; in the slot's grid those
// would shrink a short confirm, and the pager under it, to fit their content.
assert.match(css, /\.card\s*\{[^}]*margin:\s*0 auto/, "the base card still centres outside the board");
assert.match(css, /\.pager\s*\{[^}]*margin:\s*0 auto/, "the base pager still centres outside the board");
assert.match(css, /\.git-cards > \.card,\s*\.git-cards > \.pager\s*\{\s*margin:\s*0;\s*\}/, "the card slot drops the auto margins for both");
});
test("long task lines, long words, a narrow board and a narrow Ask pane never widen the page", () => {
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
const css = joinedCss();
const rule = (sel) => {
const at = css.indexOf("\n" + sel + " {");
assert.ok(at > -1, `${sel} has a rule`);
@@ -674,12 +742,10 @@ test("long task lines, long words, a narrow board and a narrow Ask pane never wi
});
test("over the git board a note box grows with its text, and the no-repo note only points above when a card is there", () => {
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
const css = joinedCss();
assert.match(css, /\.git-cards > \.card textarea \{ field-sizing: content; max-height: 50vh; \}/);
const view = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board-view.js"), "utf8");
const fn = view.slice(view.indexOf("export function drawGitBoard("), view.indexOf("function header("));
assert.ok(fn.includes("ctx.hasCard"), "the note checks for a card first");
assert.ok(fn.includes("will ask what to do here in a moment"));
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
assert.match(js, /hasCard: Boolean\(card\)/, "the host says whether a card is in the slot");
});
+114
View File
@@ -0,0 +1,114 @@
// Web console tests, the page's shared state: public/state.js holds what
// every screen reads (`page`) and the hooks a screen calls instead of the
// render loop and the draft's save. It only defines, so it imports here under
// plain Node, page or no page.
// Run with: node --test scripts/test-web-console-state.mjs
import test from "node:test";
import assert from "node:assert/strict";
import { page, redraw, onRedraw, saveNow, onSave, fresh, freshChat, hooks, useHooks, stage, setDraft, bootData } from "../src/web-console/public/state.js";
test("state: page starts as app.js always started it", () => {
assert.equal(page.S, null, "no server state before the first frame");
assert.equal(page.selected, null, "no question picked");
assert.equal(page.view, "questions", "the questions tab");
assert.deepEqual(page.local, {
staged: {},
drafts: {},
images: {},
sent: {},
stopping: null,
afterBuild: null,
homeward: null,
launching: null,
deleting: null,
retract: {},
chat: { draft: "", history: [], about: null, pending: [], lastSeenReplyId: null, images: [], conversation: null },
});
});
test("state: the rest of the shared state starts as app.js always started it", () => {
const { S, local, selected, view, ...rest } = page;
assert.deepEqual(rest, {
agentLastSeen: null,
pendingResult: false,
pendingStop: false,
pendingBannerUp: false,
gone: false,
chatFrame: null,
chatDot: false,
chatError: "",
askRowCount: 0,
docInView: null,
wsFrame: null,
meterFrame: null,
updateFrame: null,
subagentsFrame: null,
overview: { key: null, text: null },
wake: null,
dashPick: null,
mentionPop: null,
heldPose: null,
scopeMine: null,
launchScoping: false,
});
});
test("state: fresh() and freshChat() hand out a new empty draft each time", () => {
assert.deepEqual(fresh(), page.local);
assert.notEqual(fresh(), fresh(), "two calls share one object");
assert.notEqual(fresh().chat, fresh().chat, "two drafts share one chat");
assert.deepEqual(freshChat(), page.local.chat);
});
for (const [name, call, on] of [
["redraw", redraw, onRedraw],
["saveNow", saveNow, onSave],
]) {
test(`state: ${name}() does nothing until a hook is set, then calls the latest one once per call`, () => {
assert.doesNotThrow(() => call(), `${name}() throws with no hook`);
let first = 0;
let second = 0;
on(() => first++);
call();
call();
assert.equal(first, 2, "each call runs the hook once");
on(() => second++);
call();
assert.deepEqual([first, second], [2, 1], "a second hook replaces the first");
});
}
test("state: a hook a screen calls throws by name until start-up sets it, then runs the one set", () => {
assert.throws(() => hooks.banner("x"), /hooks\.banner was called before start-up set it/);
const seen = [];
useHooks({ banner: (text) => seen.push(text) });
hooks.banner("hello");
assert.deepEqual(seen, ["hello"]);
useHooks({ banner: (text) => seen.push(text + "!") });
hooks.banner("again");
assert.deepEqual(seen, ["hello", "again!"], "a second set replaces the first");
assert.throws(() => hooks.unknown(), /hooks\.unknown was called/);
});
test("state: stage() stages or takes back an answer, then saves and redraws; setDraft() only saves", () => {
let saved = 0;
let drawn = 0;
onSave(() => saved++);
onRedraw(() => drawn++);
stage("q1", { k: "A" });
assert.deepEqual(page.local.staged, { q1: { k: "A" } });
assert.deepEqual([saved, drawn], [1, 1]);
stage("q1", null);
assert.deepEqual(page.local.staged, {}, "null takes the answer back");
assert.deepEqual([saved, drawn], [2, 2]);
setDraft("note-q1", "typed");
assert.equal(page.local.drafts["note-q1"], "typed");
assert.deepEqual([saved, drawn], [3, 2], "a draft is kept without a redraw");
delete page.local.drafts["note-q1"];
});
test("state: bootData() is null without a page, and asked again it says the same", () => {
assert.equal(bootData(), null);
assert.equal(bootData(), null);
});
+1 -1
View File
@@ -9,7 +9,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { defaultInstruction, offered } from "../src/web-console/public/subagents.js";
import { readSubagentCursor } from "../src/web-console/lib.mjs";
import { readSubagentCursor } from "../src/web-console/settings.mjs";
import {
ROOT,
HOME,
+2 -1
View File
@@ -12,7 +12,8 @@ import path from "node:path";
import { spawn } from "node:child_process";
import { defaultName } from "../src/web-console/public/workspace.js";
import { meterView } from "../src/web-console/public/meter.js";
import { readLedger, readWorkspaceCursor, WORKSPACE_FILE } from "../src/web-console/lib.mjs";
import { readLedger } from "../src/web-console/sessions.mjs";
import { readWorkspaceCursor, WORKSPACE_FILE } from "../src/web-console/workspace.mjs";
import {
ROOT,
CONSOLE_CLI,
+13 -2
View File
@@ -21,13 +21,16 @@ import path from "node:path";
import { execFileSync, spawnSync } from "node:child_process";
import http from "node:http";
import { fileURLToPath } from "node:url";
import { readChat } from "../src/web-console/lib.mjs";
import { readChat } from "../src/web-console/inbox.mjs";
export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
export const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
export const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-test-"));
export const MODELS_DIR = path.join(HOME, "plan2code");
// Handoffs are written outside every repo, under ~/.plan2code/handoffs, so
// each test file gets its own throwaway folder for them too.
export const HANDOFFS_DIR = path.join(HOME, "handoffs");
// A spawned console server or CLI must not inherit relocation vars (an
// exported GIT_DIR would redirect the board's reads), SSH markers (they set
// `remote` in open output) or leftover PLAN2CODE_* knobs.
@@ -51,7 +54,7 @@ for (const k of AMBIENT_ENV_KEYS) delete scrubbed[k];
// cannot open. An empty file is the portable "no global config".
const EMPTY_GITCONFIG = path.join(HOME, "empty-gitconfig");
fs.writeFileSync(EMPTY_GITCONFIG, "");
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_NO_BROWSER: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG };
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_HANDOFFS_DIR: HANDOFFS_DIR, PLAN2CODE_NO_BROWSER: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG };
// Every server these tests start runs the release check at boot. A fresh
// cached failure keeps the whole suite off the network and bannerless.
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
@@ -176,6 +179,14 @@ export const helpTemplate = () => {
return tpl[1];
};
// The Planny poses each skill's starting screen clones, from index.html.
export const poseTemplate = () => {
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
const tpl = html.match(/<template id="start-poses">([\s\S]*?)<\/template>/);
assert.ok(tpl, "index.html has the start-poses template");
return tpl[1];
};
// The server checks magic bytes only, so a JPEG header and some padding will do.
export const JPEG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.alloc(400, 7), Buffer.from([0xff, 0xd9])]);
+93 -9
View File
@@ -22,6 +22,11 @@
* `--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.
*
* `plan2code update` starts no agent: it re-runs the npx install with `--update`, which
* reinstalls whatever ~/.plan2code/install.json lists. Before an agent starts, one line says
* when a newer release is out (releaseNotice), read from the web console's cached release check
* and never waiting on the network.
*
* On a terminal it opens with a Planny banner (renderBanner) and colors its headings, numbers,
* defaults and errors (paint). Color is on only on a TTY (stdout and stderr each checked on
* its own) with NO_COLOR unset; piped runs print plain text and no banner.
@@ -41,6 +46,15 @@ const STATE_FILE = path.join(os.homedir(), '.plan2code', 'launcher.json');
// Menus longer than this print compactly (id-only, two columns).
const MODELS_MENU_COMPACT_AT = 30;
const PICKER_PROMPT = 'Choose the project folder to open Plan2Code in';
const UPDATE_COMMAND = 'update';
// The same URL src/web-console/update-check.mjs exports as REPO_URL. This file may require
// nothing but Node built-ins (and update-check.mjs is ESM), so it keeps its own copy.
const REPO_URL = 'https://github.com/jparkerweb/plan2code.git';
// The web console's cached release check, and how long it counts as fresh (update-check.mjs
// CACHE_MS). PLAN2CODE_CONSOLE_HOME moves the console's files, as in files.mjs.
const CONSOLE_HOME = process.env.PLAN2CODE_CONSOLE_HOME || path.join(os.homedir(), '.plan2code', 'console');
const UPDATE_CACHE_FILE = path.join(CONSOLE_HOME, 'update-check.json');
const UPDATE_CACHE_MS = 60 * 60 * 1000;
// The escape values install.js's COLORS uses, copied: this file is installed alone and may
// require nothing but Node built-ins.
@@ -608,12 +622,89 @@ async function exitWith(code, fromShortcut) {
process.exit(code);
}
/**
* Spawn a resolved command with `args`. A .cmd/.bat wrapper on Windows goes through cmd.exe,
* since Node refuses to spawn one without a shell.
*/
function spawnCommand(file, args, options) {
return IS_WINDOWS && /\.(cmd|bat)$/i.test(file)
? spawn(
process.env.ComSpec || 'cmd.exe',
['/d', '/s', '/c', `"${[file, ...args].map(quoteForCmd).join(' ')}"`],
{ ...options, windowsVerbatimArguments: true }
)
: spawn(file, args, options);
}
/** `plan2code update`: the npx install with --update, passing npx's exit code through. No agent starts. */
function runUpdate() {
console.log('Updating Plan2Code...');
const npx = findOnPath('npx');
if (!npx) {
console.error(`${ce.red('plan2code:')} npx was not found on your PATH. It comes with Node.js 18+ (https://nodejs.org).`);
return process.exit(127);
}
const child = spawnCommand(npx, ['--yes', '--allow-git=all', `git+${REPO_URL}`, '--update'], { stdio: 'inherit' });
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
process.on(signal, () => {});
}
child.on('error', (error) => {
console.error(`${ce.red('plan2code:')} failed to start npx: ${error.message}`);
process.exit(1);
});
child.on('exit', (code) => process.exit(code ?? 1));
}
/** -1, 0 or 1 comparing two plain X.Y.Z versions; null unless both are X.Y.Z (as update-check.mjs). */
function compareVersions(a, b) {
const semver = /^\d+\.\d+\.\d+$/;
if (typeof a !== 'string' || typeof b !== 'string' || !semver.test(a) || !semver.test(b)) return null;
const x = a.split('.').map(Number);
const y = b.split('.').map(Number);
for (let i = 0; i < 3; i++) {
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
}
return 0;
}
/**
* One line when a newer release is out, from the console's cached check only. A missing or
* stale cache prints nothing and starts a detached refresh (the copied update-check.mjs) so
* the next start knows; the start never waits on it. Any error is swallowed: the notice must
* never stand between the person and their agent.
*/
async function releaseNotice() {
try {
const installed = (readJsonFile(path.join(__dirname, 'version.json')) || {}).version;
if (typeof installed !== 'string') return;
const cache = readJsonFile(UPDATE_CACHE_FILE);
if (cache && typeof cache.checkedAt === 'number' && Date.now() - cache.checkedAt < UPDATE_CACHE_MS) {
if (compareVersions(installed, cache.latest) === -1) {
console.log(c.yellow(`Plan2Code v${cache.latest} is out (you have v${installed}). Run: plan2code update`));
}
return;
}
const checker = path.join(__dirname, 'update-check.mjs');
if (!fs.existsSync(checker)) return;
const refresh =
'import(process.argv[1]).then((m) => m.checkForUpdate({ installed: process.argv[2], cacheFile: process.argv[3] })).catch(() => {});';
const href = require('url').pathToFileURL(checker).href;
spawn(process.execPath, ['-e', refresh, href, installed, UPDATE_CACHE_FILE], {
detached: true,
stdio: 'ignore',
windowsHide: true,
}).unref();
} catch {}
}
async function launch() {
const argv = process.argv.slice(2);
if (argv[0] === UPDATE_COMMAND) return runUpdate();
const fromShortcut = argv.includes(PICK_FOLDER_FLAG);
const { cli: requestedCli, rest: extraArgs } = takeCliFlag(argv.filter((arg) => arg !== PICK_FOLDER_FLAG));
printIntro();
await releaseNotice();
const { cli, code } = await chooseCli(requestedCli);
if (!cli) return exitWith(code, fromShortcut);
saveState({ lastCli: cli.id });
@@ -636,14 +727,7 @@ async function launch() {
const args = cli.args(extraArgs);
const options = { cwd, stdio: 'inherit' };
const child =
IS_WINDOWS && /\.(cmd|bat)$/i.test(cli.path)
? spawn(
process.env.ComSpec || 'cmd.exe',
['/d', '/s', '/c', `"${[cli.path, ...args].map(quoteForCmd).join(' ')}"`],
{ ...options, windowsVerbatimArguments: true }
)
: spawn(cli.path, args, options);
const child = spawnCommand(cli.path, args, options);
// Ctrl+C reaches the CLI directly through the shared console; keep this wrapper alive so it
// can hand back the CLI's exit status instead of dying first.
@@ -669,4 +753,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 = { mergeModels, modelEntries, renderBanner, paint, hasModelFlag };
module.exports = { mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions };
@@ -14,7 +14,7 @@
import fs from "node:fs";
import path from "node:path";
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, isoDate, stamp, now } from "./common.mjs";
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, isoDate, stamp, now, LOOP_TOKENS, scrapeHits } from "./common.mjs";
const USAGE = `
pathfinder.mjs: Pathfinder map bookkeeping. JSON on stdout (trail: --text prints the footer itself).
@@ -84,16 +84,6 @@ const SCHEMA_KEYS = ["Type", "State", "Blocked by", "Claimed", "Resolved", "Lock
const TYPES = ["grill · HITL", "research · AFK", "sketch · HITL", "legwork · HITL", "legwork · AFK"];
const STATES = ["open", "claimed", "resolved", "out-of-scope"];
const GLYPH = { x: "●", "/": "◉", " ": "○", "!": "⊘", "-": "⊝" };
const LOOP_TOKENS = /\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
// The metrics collector's own scrape patterns (plan2code-metrics/src/collector.ts).
const SCRAPE = [
{ name: "overall confidence with %", re: /(?:Overall|Final|Total)?\s*\**[Cc]onfidence\**[:\s*]+(\d{1,3})%/ },
{ name: "confidence table cell", re: /[|]\s*[Cc]onfidence\s*[|]\s*(\d{1,3})/ },
{ name: "bare Requirements + number", re: /[Rr]equirements?[:\s|]+(\d{1,2})/ },
{ name: "bare Feasibility + number", re: /[Ff]easibility[:\s|]+(\d{1,2})/ },
{ name: "bare Integration + number", re: /[Ii]ntegration[:\s|]+(\d{1,2})/ },
{ name: "bare Risk + number", re: /[Rr]isk[:\s|]+(\d{1,2})/ },
];
const DIMENSIONS = [
{ key: "Requirements-clarity", word: "Requirements" },
{ key: "Feasibility-technical", word: "Feasibility" },
@@ -1058,15 +1048,6 @@ function walk(dir) {
return outList;
}
function scrapeHits(text) {
const hits = [];
for (const s of SCRAPE) {
const m = text.match(s.re);
if (m) hits.push(`${s.name}: "${m[0].trim()}"`);
}
return hits;
}
async function cmdLint(loc) {
const problems = [];
const add = (level, file, message) => problems.push({ level, file: rel(loc.root, file), message });
+10 -10
View File
@@ -39,7 +39,7 @@ Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it
- **Plan, don't do.** Every question resolves a DECISION. The pull to just build it is the edge of the map — hand off.
- **Confirm before creating anything.** No files, no issues, until the Intent Gate (Step 0) and backend pick (Step 1) return.
- **One question at a time** (`research` excepted — parallel); fork-menu between decisions, fresh session after ~3.
- **One question at a time** (`research` runs in parallel); fork-menu between decisions, fresh session after ~3.
- **Refer by name.** "[Export format](<link>)", never "02" or "#42" in prose. Bare ids belong on `Blocked by:` lines and in commands.
- **HITL questions are never self-answered.** Ask and wait; an agent that answers its own grill has broken the skill.
- **Questions are ground truth; the map is a rebuildable index.** A filled `## Answer` beats any state marker; detail lives in one place.
@@ -51,7 +51,7 @@ Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it
## Auto-Discovery and Mode Selection
⚠️ `specs/` is gitignored — NEVER use Glob. Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
⚠️ `specs/` is gitignored: NEVER use Glob; list it with `ls specs/` or `Get-ChildItem specs/`.
**Brief/recap/minutes asked?** → read references/brief.md: `reconcile`, then `brief-data --range <range>` (`github`: its brief section), write plain-English `briefs/brief-<YYYYMMDD>.md` from the output, STOP. Never resolves.
@@ -83,7 +83,7 @@ Read references/chart.md
0. `[Chart - Step 0: Intent Gate]` **Before creating anything**, use AskUserQuestion for the outcome and WAIT: **chart a map** (foggy — Step 1), **`/plan2code-1-plan`** (clear — STOP), **`/plan2code-quick-task`** (tiny — STOP). HITL, never self-select "chart".
1. `[Chart - Step 1: Name and backend]` Only after the gate says "chart." Confirm the kebab-case idea name, then ask — HITL, never self-picked — **local files or GitHub Issues?** Recommend `local` for solo work; offer `github` only if preflight passes, naming the repo's visibility. THEN the first write.
2. `[Chart - Step 2: Destination]` Grill until it is one or two lines. It fixes scope — settle it first.
3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter.
3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter. Unfamiliar code? `/plan2code-xray` explains an area first.
4. `[Chart - Step 4: Map the frontier]` Grill again **breadth-first**: fan out, never deep on one thread. Surface the open decisions and what is takeable now.
5. `[Chart - Step 5: Create the map]` `**Status:** Charting`, Destination, Ground rules (backend first), an empty index, the fog in `## Not yet specified`. Say once where it lives and who sees it.
6. `[Chart - Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass — on `github`, create all first, wire edges second. The rest stays fog. Include a `grill · HITL` testing-posture question; `/plan2code-1-plan` Phase 1 needs it.
@@ -102,7 +102,7 @@ Assume NO memory of any prior session.
1. `[Work - Step 1: Load]` Read the map whole. No question yet.
2. `[Work - Step 2: Reconcile]` **Always.** `local`: run `reconcile`. The answer wins: a question whose `## Answer` its state contradicts is resolved, a missing `Resolved:` is backfilled from the claim (today if none), a claim with no `## Answer` (a crash) is released, and every marker is rebuilt from the questions. Tell the human each `repairs` entry in one line. Re-fire every question in `refire` (research cut off before its `Research complete:` line; resolve.md → Interrupted research). `--dry-run` first if the map looks badly off. `github`: the reconcile checks in the backend playbook.
3. `[Work - Step 3: Frontier]` Every question open, unclaimed, and unblocked, first in order. `local`: run `frontier` (`frontier`, `blocked` with each blocker, `stranded`, `nextNN`, `counts`).
3. `[Work - Step 3: Frontier]` Every question open, unclaimed, and unblocked, first in order. `local`: run `frontier` (`blocked` with each blocker, `stranded`, `nextNN`, `counts`).
4. `[Work - Step 4: Choose and claim]` The one the user named, else first on the frontier. Mark it claimed on the question and the map, **saved before any work** (`local`: `claim <NN>`, which refuses a blocked or non-open question and a second open claim). A `research` pick fires unclaimed instead (resolve.md); then claim the next one.
- Stranded on an `out-of-scope` blocker? Check this first: re-frame or rule out, re-run Step 3.
- Frontier empty but questions remain (`allBlocked`)? Report the chain, STOP.
@@ -126,7 +126,7 @@ The map clears only when ALL hold:
3. The destination is reachable with nothing left to decide
4. All four confidence dimensions score ≥ 18/25
Score the four dimensions (handoff.md rubric) and write them to the map's `**Confidence:**` line. `local`: run `gate`; it checks 1, 2 and 4 against the files, plus the handoff preflight and the Requirements, Feasibility and Risk caps; condition 3, the Integration cap and the scores stay yours (its `judgment` list). Any failing: name it, keep working. All passing: follow the handoff playbook, set `**Status:** Cleared`, run `lint`, stop. The PLAN-DRAFT is always local — `/plan2code-1-plan` cannot read a tracker.
Score the four dimensions (handoff.md rubric) and write them to the map's `**Confidence:**` line. `local`: run `gate`; it checks 1, 2 and 4 against the files, plus the handoff preflight and the Requirements, Feasibility and Risk caps; condition 3, the Integration cap and the scores stay yours (its `judgment` list). Any failing: name it, keep working. All passing: follow the handoff playbook, set `**Status:** Cleared`, run `lint`, stop. The PLAN-DRAFT is always local: Plan cannot read a tracker.
## Trail Footer
@@ -134,11 +134,11 @@ Read references/trail.md
> Fallback: once the map exists, end every response with a marker path (`●` done · `◉` here · `○` open · `⊘` blocked · `⊝` out of scope) `START`→`⚑`, a named legend, a plain-English confidence note, then ONE closer: asking → Form B, `WAITING ON YOU`, no command; menu → Form C, `NEXT UP` + `OR START FRESH`; session end → Form A, `NEXT STEP` + resume command with `--web` (map issue URL on `github`).
Close EVERY response with the trail once the map exists. You pick the form by what the turn does. `local`: `trail` draws it from the files, so paste its output verbatim. Asking → Form B, `trail --form B --item "<probe>" ... --text` (one `--item` per open probe, up to three). Menu after a decision → Form C, `trail --form C` WITHOUT `--text`: paste its `text`, then build the question tool from its `menu`. Session end → Form A, `trail --form A --text`. `github`: draw it by hand per the backend playbook.
Close EVERY response with the trail once the map exists; the turn picks the form. `local`: `trail` draws it from the files; paste its output verbatim. Asking → `trail --form B --item "<probe>" ... --text` (one `--item` per open probe, up to three). Menu → `trail --form C` WITHOUT `--text`: paste its `text`, then build the question tool from its `menu`. Session end → `trail --form A --text`. `github`: by hand per the backend playbook.
## Session End
Report each question resolved (name + gist), what graduated, what's still open; offer a brief for today. Nothing to commit — `local` is gitignored, `github` already on the tracker. Then the mascot, then the Trail Footer.
Report each question resolved (name + gist), what graduated, what's still open; offer a brief for today. Nothing to commit (`local` is gitignored). Then the mascot, then the Trail Footer.
**Web console:** at session end or on a `__stop`, post `finish` (Form A's command) BEFORE `stop` (notes/pathfinder.md).
@@ -156,9 +156,9 @@ Report each question resolved (name + gist), what graduated, what's still open;
| Issue | Action |
|---|---|
| Session stops mid-question, or map drift | Release the claim, note why (or leave it: the next reconcile releases a claim with no answer). Work Step 2 repairs both; questions win. Never reconcile mid-question: it would release your own live claim. |
| A script cannot run (no `node`) | Say so once; do the step by hand from questions.md (markers, blocking, schema) and the reference that names the step. Footer by hand: the trail's glyph path, then Form A `NEXT STEP · start a new conversation and run:` + the command, Form B `WAITING ON YOU · answer here, in this conversation:` + the items, or Form C `OR START FRESH · new conversation, paste:` + the command. |
| Frontier empty, fog remains | Not sharp yet. Grill it into a question, or clear the map |
| Session stops mid-question, or map drift | Release the claim (or leave it: the next reconcile releases a claim with no answer). Work Step 2 repairs both; questions win. Never reconcile mid-question: it releases your own live claim. |
| A script cannot run (no `node`) | Say so once; do the step by hand from questions.md and the step's reference, and draw the footer by hand from trail.md (or its fallback above). |
| Frontier empty, fog remains | Grill it into a question, or clear the map |
| Reference file missing | Use the fallback blockquote under its `Read` line |
| `gh` fails mid-session on a `github` map | Report and STOP. Falling back to local forks the map |
| User skips to planning | Their call. Name what is undecided, route to `/plan2code-1-plan` |
+9 -9
View File
@@ -40,8 +40,7 @@ Check if `./AGENTS.md` exists:
- Resolve ambiguities through questions - do NOT assume
- Document unavoidable assumptions clearly
- Present/confirm technology decisions with user
- NEVER write implementation code
- Keep responses conceptual - detailed specs belong in final PLAN-DRAFT only
- NEVER write implementation code; keep responses conceptual, detailed specs belong in the final PLAN-DRAFT only
- If no file access, output content in code blocks with file path headers
---
@@ -52,8 +51,11 @@ Before Phase 1, run `node "<S>/specs.mjs" list` from the project root (`<S>`: `s
- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4
- Status "Escalated from Quick Task - Resume at Phase 2": Acknowledge, verify requirements, skip to Phase 2
- Status "Draft" or "Complete": Ask user how to proceed
- A spec folder holding a `DIAGNOSIS-*.md` (Diagnose's write-up of a bug): read it first, as the Phase 1 brief (the bug, its cause, the suggested fix); that folder's name is the feature name (do not ask for one), so the PLAN-DRAFT lands beside the diagnosis
- No PLAN-DRAFT: Begin at Phase 1. Console: its idea card carries `"templates": "idea"` (console.md → The kinds)
`node "<S>/specs.mjs" check-draft specs/<feature-name>` checks a written PLAN-DRAFT (Phase 7).
---
### Clarification Protocol
@@ -101,6 +103,7 @@ After confirmation, proceed with analysis:
> 1. **Types**: Unit, Integration, E2E, or None
> 2. **Phase testing**: Run after each phase?
> 3. **Coverage**: Critical paths / Moderate (~60-80%) / Comprehensive (>80%)
> 4. **Approach**: Code first (default) or Test first (each task's test is written and seen failing before its code)
>
> Say 'skip testing' to omit."
@@ -124,7 +127,7 @@ After confirmation, proceed with analysis:
### PHASE 2: System Context Examination
**Existing projects:**
**Existing projects:** (unfamiliar code? `/plan2code-xray` explains an area first)
1. Examine directory structure
2. Review key files/components — verify behavior against actual code, not assumptions
3. Identify patterns, conventions, code style
@@ -233,6 +236,8 @@ State assessment and ask user to confirm.
Replace values with actuals. Optionally add plain `key: value` lines below for readability (no bold/markdown).
5. Run `node "<S>/specs.mjs" check-draft specs/<feature-name>` and fix every error before the closing message.
## Templates
### PLAN-DRAFT Format
@@ -243,7 +248,7 @@ Header: Title, Created date, Status (Draft | Phase 3 Complete - Resume at Phase
Sections:
1. **Executive Summary** — 2-3 sentences
2. **Requirements** — 2.1 Functional (FR-N checklist), 2.2 Non-Functional (NFR-N checklist), 2.3 Out of Scope, 2.4 Testing Strategy table (Types, Phase Testing, Coverage)
2. **Requirements** — 2.1 Functional (FR-N checklist), 2.2 Non-Functional (NFR-N checklist), 2.3 Out of Scope, 2.4 Testing Strategy table (Types, Phase Testing, Coverage, plus a `| Approach | Test first |` row only when picked; absent means code first)
3. **Tech Stack** — table: Category / Technology / Version / Justification
4. **Architecture** — 4.1 Pattern (name + rationale), 4.2 System Context Diagram, 4.3 Components table, 4.4 Data Model, 4.5 API Design
5. **Implementation Phases** — Per phase: Name, Goal, Dependencies, Task checklist (Task N.N)
@@ -292,8 +297,3 @@ When complete (PLAN-DRAFT created), tell user:
- **Abort:** Confirm with user, list files needing cleanup, stop workflow
- **Lost context:** Attach PLAN-DRAFT, state phase
- **Confidence stuck <90%:** List blockers, ask targeted questions
## Reminders
- Final phase: PLANNING PHASE 7: Transition Decision
- Do NOT implement - design and present plan only
+6 -12
View File
@@ -16,6 +16,7 @@ The FIRST thing you do, before anything else — before Auto-Discovery: ask **we
- `node "<S>/specs.mjs" list`: every active spec with its `planDrafts` (file and **Status:** line).
- `node "<S>/specs.mjs" status <spec>`: once written, the phases, task counts, goals, parallel groups and `checks` the files produce.
- `node "<S>/specs.mjs" check <spec>`: the written overview.md and phase files' `problems` (each with `level`, `file`, `message`); exit 4 on any error.
- `node "<S>/specs.mjs" metrics <spec> --step document --set verification_items_added=<N>`: the METRICS_JSON line.
## Rules
@@ -74,11 +75,7 @@ If no plan exists and user wants to skip:
| Action-oriented | Imperative: "Create...", "Implement..." |
| Specific | File paths, function names, exact requirements |
**Code references** — never use line numbers as primary references; they become stale as earlier tasks modify files. Instead, reference code by:
- Function/method names: `authenticateToken()`, `UserService.createUser()`
- Class/interface names: `UserRepository`, `AuthConfig`
- Semantic descriptions: "the JWT verification logic", "the error handler for duplicate emails"
- Code patterns: "the switch statement handling request types", "the validation block for email format"
**Code references:** never use line numbers as primary references; they go stale as earlier tasks modify files. Name the function or class (`UserService.createUser()`, `AuthConfig`), or describe the code ("the JWT verification logic", "the switch statement handling request types").
Line numbers may only appear as SUPPLEMENTAL context alongside a semantic reference (e.g., "Update `validateEmail()` (currently ~L45) to...").
@@ -110,12 +107,8 @@ Line numbers may only appear as SUPPLEMENTAL context alongside a semantic refere
- Quick Reference (Key Files, Environment Variables, External Dependencies)
7. **Write** each `phase-X.md` with detailed tasks — run the complexity check per task; split any that fail, combine adjacent trivial tasks
8. **Analyze** parallel execution eligibility
8a. **Check the structure:** `specs.mjs status specs/<feature-name>`. Fix every `error` and `warn` in `checks` (task numbering, a checkbox under Prerequisites or criteria, a checklist row with no phase file), and confirm `phases` and `parallelGroups` read back as you wrote them
9. **Verify** all PLAN-DRAFT requirements covered:
- 9A: Re-read PLAN-DRAFT as source of truth
- 9B: Cross-reference each section against docs
- 9C: Fix gaps, update documentation
- 9D: Output verification summary
8a. **Check the structure:** `specs.mjs check specs/<feature-name>`. Fix every error before step 9 and the sign-off; fix each warning or explain it in the summary. `status` should read `phases` and `parallelGroups` back as written
9. **Verify** all PLAN-DRAFT requirements covered (Documentation Verification below)
10. **Present** summary to user
### Parallel Eligibility Analysis
@@ -171,6 +164,7 @@ Use kebab-case for feature name (e.g., `user-authentication`).
- "Run after each phase": Add testing task block at end of EVERY phase
- "Dedicated phase only": Create final Phase N: Testing
- "None" or empty: Omit testing tasks
- `| Approach | Test first |` in 2.4: in every phase, order each task's test before its code and put a plain sub-bullet ` - Test: <where the test drives the behaviour>` directly under the task line (no checkbox, so the loop's task count is unchanged), for example `` - Test: through `POST /votes` ``
**Small Projects (1-2 phases):** Combine sections, still create separate overview.md and phase-1.md. Note: "Small project - phases combined"
@@ -188,7 +182,7 @@ Sections, in this order: Summary (from Executive Summary), Phase Checklist, Para
Header: Phase name, Status on its own line as `**Status:** <value>` (Not Started | In Progress | Complete; `specs.mjs mark` updates it), Estimated Tasks count.
Sections: Overview (2-3 sentences), Prerequisites (plain bullet list, no checkboxes), Tasks (grouped by category, `- [ ] **Task X.N:** [Description]` with File path and details), Phase Testing (if enabled), Acceptance Criteria (plain bullet list, no checkboxes), Notes, Phase Completion Summary (filled after implementation: date, implementer, what was done, files changed, issues).
Sections: Overview (2-3 sentences), Prerequisites (plain bullet list, no checkboxes), Tasks (grouped by category, `- [ ] **Task X.N:** [Description]` with File path and details, plus a ` - Test:` sub-bullet under each task when the approach is Test first), Phase Testing (if enabled), Acceptance Criteria (plain bullet list, no checkboxes), Notes, Phase Completion Summary (filled after implementation: date, implementer, what was done, files changed, issues).
## Session End
+5 -2
View File
@@ -27,6 +27,8 @@ This file controls the two referenced workflows. Follow each referenced workflow
Read references/implement.md
The habits in `references/building-habits.md` apply exactly as Implementation Mode reads them.
Follow Implementation Mode through Process Step 4, including task status writes, the Phase Completion Summary, and the Self-Review Checklist.
Override Implementation Mode at the sign-off boundary:
@@ -52,6 +54,7 @@ Run Review Mode with this explicit scope:
- Use overview.md and the active phase file for spec-compliance context; they do not broaden scope to other phases.
- Read related callers, dependencies, and project files when needed to verify a finding, but do not turn them into unrelated review targets.
- Review all changed files completely and apply the full focused-review depth required by Review Mode.
- Review Mode's helper rule applies: a fresh helper runs the analysis when available, this session verifies every finding, and the Stage 4 report carries the Reviewed by line. The helper's brief carries the phase's `phase-X.md` and its change set only, never Stage 1's work notes.
Override Review Mode's completion and session-end behavior:
@@ -80,13 +83,13 @@ Return to Implementation Mode and render its Completion Report Format with heade
Include the normal implementation completion sections plus:
- **Review Results:** scope, files reviewed, finding totals by severity, and fixes applied.
- **Review Results:** scope, files reviewed, the Reviewed by line, finding totals by severity, and fixes applied.
- **Unresolved Review Findings:** concise numbered list, or `None`.
- **Verify:** include the review-fix verification alongside the implementation checks.
Then ask:
> Reply `approved` to mark this reviewed phase complete, or describe any issues.
> Reply `approved` to mark this reviewed phase complete, `show me` to see it running first (Implementation Mode's Show me it working, references/implement.md), or describe any issues.
Only this prompt can obtain phase approval.
+21 -37
View File
@@ -4,7 +4,7 @@ Start all IMPLEMENTATION MODE responses with '⚡ [PHASE X: Phase Name]'
## Role
Senior software engineer implementing solutions exactly as specified. Follow specs precisely, update progress, flag issues.
Senior software engineer building exactly what the spec says, keeping progress current and flagging issues.
## Interface
@@ -22,18 +22,16 @@ The FIRST thing you do, before anything else in this file — before reading a s
- Follow `./AGENTS.md` if it exists
- Implement specs EXACTLY - no creative additions
- Update checkboxes immediately after each task
- ONE phase per conversation (default)
- Run tests ONLY if explicitly listed as a phase task
- Run tests ONLY if a phase task or a task's `Test:` line lists them
- Do NOT run git commands - provide commit instructions for user
- Flag blockers clearly - never skip silently
- BUILD to spec, not redesign
- If file operations unavailable, output contents in code blocks with file path header
- If filesystem inaccessible, ask user to paste file contents
- Read `references/building-habits.md` when a bug or unexpected failing test turns up, before any task in a Test first phase (its tasks carry `Test:` lines), and before any task that changes no behaviour; follow it.
- No file tools: output contents in code blocks with a file path header; no filesystem: ask the user to paste file contents
## Required Context
Need implementation spec files to proceed. `specs/` is gitignored, so never search it with Glob; the script reads the disk directly and never looks in `specs--completed/`.
Needs the spec files. `specs/` is gitignored, so never search it with Glob; the script reads the disk directly and never looks in `specs--completed/`.
**Option 1: User provides an overview.md path** → `specs.mjs status <that path>`.
@@ -59,7 +57,7 @@ These checkbox states apply to Task items and the Phase Checklist in overview.md
- `[/]` -> `[x]`: User APPROVES completed phase
- `[/]` stays `[/]`: On abort (preserves resume capability)
Never reset `[/]` to `[ ]`. Started work stays marked for conscious resume decisions.
Never reset `[/]` to `[ ]`: started work stays marked so resuming is a conscious choice.
**Disk Write Rule:** Write task completion status (`[x]`) to `phase-X.md` on disk immediately after each task — never batch status updates. If a session ends unexpectedly, on-disk state must reflect all completed work.
@@ -75,7 +73,7 @@ Never reset `[/]` to `[ ]`. Started work stays marked for conscious resume decis
| `checkoff` | Every phase is approved but tasks in them are still open (manual steps, blockers). Never say "nothing left to do": run Manual Check-Off below. |
| `none` | Nothing to implement: say why (`reason`). Every phase complete → `/plan2code-4-finalize --web` |
After selection, `mark --to in-progress`, read `phase-X.md`, begin.
After selection, claim it (Process 1), read `phase-X.md`, begin.
### Manual Check-Off
@@ -93,7 +91,7 @@ After the last one: `tick`'s `remaining` empty (`next` is `none`) → "NEXT STEP
| Rule | Description |
|------|-------------|
| Match existing patterns | Follow codebase conventions |
| Follow spec exactly | Use specified file/function names and structures |
| Follow spec exactly | Use specified file/function names and structures (create exactly `src/services/UserService.ts`, never rename or relocate) |
| No unsolicited improvements | Don't refactor outside current tasks |
| No extra files | Only create files mentioned in tasks |
| Minimal dependencies | No packages outside approved tech stack |
@@ -102,41 +100,29 @@ After the last one: `tick`'s `remaining` empty (`next` is `none`) → "NEXT STEP
## Examples
**Following Specs:** Create exactly `src/services/UserService.ts` as specified — never rename or relocate.
**Blocker format:** `- [!] **Task 2.3:** ... > BLOCKED: [reason]. > User action: [action].` Then proceed to next non-dependent task.
## Process
### 1. Identify and Claim Phase
Act on `status`'s `next` (Parallel Phase Selection above).
**Once selected:** `specs.mjs mark <spec> --phase <N> --to in-progress` (a no-op when it is already `[/]`).
Act on `next` (Parallel Phase Selection above), then `specs.mjs mark <spec> --phase <N> --to in-progress` (a no-op when already `[/]`).
State: `⚡ [PHASE X: Phase Name] - Marking in-progress and starting`
### 2. Verify Prerequisites
Process Prerequisites section in order. Prerequisites use plain bullets (no checkboxes).
For each prerequisite:
Process the Prerequisites section in order. For each:
- **Verifiable:** Check condition, note "VERIFIED" inline
- **Actionable:** Complete action, note "VERIFIED" inline
- **Cannot verify:** Note "ASSUMED: [reason]" inline
- **Blocked:** Note "BLOCKED: [reason]" inline, STOP phase
Proceed only when all prerequisites are verified or assumed.
If any blocked, STOP and inform user.
Proceed only when all are verified or assumed; if any is blocked, STOP and tell the user.
### 3. Implement Tasks Sequentially
For each task:
1. Read task specification completely
2. Implement exactly as specified
3. Mark `[ ]` to `[x]`
4. Move to next task
For each task: read its spec completely, implement exactly that, mark `[ ]` to `[x]`, move on. When a task carries a `Test:` line, follow the test-first habit for it.
### 4. Complete Phase
@@ -159,21 +145,21 @@ After all tasks:
3. Use Completion Report Format
4. Do NOT mark phase `[x]` until user says "approved"
5. Address issues before re-requesting sign-off
6. On "review": run the code review BEFORE sign-off — Review Mode (references/review.md in the installed skill, src/plan2code-review.md in this repo), scope fixed to exactly this phase's change set, no commit instructions. Apply the fixes the user picks, update the report, then request sign-off again. The phase stays `[/]` throughout.
### 6. After User Approval
See "After Approval / Session End" section below.
6. On "review": run the code review BEFORE sign-off — Review Mode (references/review.md in the installed skill, src/plan2code-review.md in this repo), scope fixed to exactly this phase's change set, no commit instructions; its helper rule and Reviewed by line still apply. Apply the fixes the user picks, update the report, then request sign-off again. The phase stays `[/]` throughout.
7. **Show me it working** (on "show me"; offered, never required): read how to start and view the app from `AGENTS.md` (Commands). Missing: work it out from the project (`package.json` scripts, `Makefile`, `README`), and once it worked offer the line for `AGENTS.md`; cannot work it out: ask the person. Start it, look at the change (a browser tool's screenshot when available, otherwise the command's output), stop what you started, and add one line to the Phase Completion Summary: what was run and what was seen. Screenshots go on the web console page only, never under `specs/`. Then request sign-off again.
## Issue Handling
| Type | Action | Format |
|------|--------|--------|
| Blocker | Mark `[!]`, continue non-dependent tasks, report at phase end | `> BLOCKED: [reason]. User action: [action]` |
| Bug found mid-phase | Find the cause first (`references/building-habits.md`): reproduce, then fix, then keep the regression test | `> BUG: [cause]. Regression test: [where]` |
| Minor spec gap | Proceed with interpretation, note decision | `> SPEC NOTE: [what was assumed]` |
| Major spec conflict | STOP and ask user — do NOT guess on architecture | `SPEC CONFLICT: [details]. Please clarify.` |
Default: ONE phase per conversation. Small phase (<5 tasks in `status`): ask if should continue with next. Large (>40): warn at start.
Cause unclear or the fix big? Stop and suggest `/plan2code-diagnose`.
Small phase (<5 tasks in `status`): ask whether to continue with the next. Large (>40): warn at start.
## Templates
@@ -181,12 +167,11 @@ Default: ONE phase per conversation. Small phase (<5 tasks in `status`): ask if
Before sign-off, verify:
- [ ] All tasks `[x]` or blocked `[!]`
- [ ] All mentioned files exist and properly formatted
- [ ] All mentioned files exist and are well formed
- [ ] No unaddressed TODO/FIXME in new code
- [ ] Code compiles without syntax errors
- [ ] Implementation matches spec exactly
- [ ] Tests executed (if testing tasks present)
- [ ] Test results documented
- [ ] Tests run and results documented (if testing tasks present)
- [ ] Blocked tasks documented
- [ ] "Phase Completion Summary" filled
- [ ] READY FOR SIGN-OFF (do NOT update overview.md yet)
@@ -205,7 +190,7 @@ Sections: Summary (2-3 sentences), Tasks Completed (Y/Z + blocked list), Test Re
╰┬─┬╯
```
> Reply "approved" to mark this phase complete, "review" to run a focused code review of this phase's changes first, or describe any issues.
> Reply "approved" to mark this phase complete, "review" to run a focused code review of this phase's changes first, "show me" to see it running first, or describe any issues.
### After Approval / Session End
@@ -260,7 +245,6 @@ If user says "abort", "cancel", or similar:
| Issue | Solution |
|-------|----------|
| Lost context mid-phase | Attach specs, say "resume from Task X.Y" |
| Spec unclear/conflicting | Mark task blocked, ask user |
| Need to change plan | Pause, use `/plan2code-1b-revise-plan` |
## Learning Capture
+4 -3
View File
@@ -47,7 +47,7 @@ If multiple active spec folders exist or nothing provided, ask user for:
## Process
Complete steps in order. Report progress after each.
Report progress after each step.
---
@@ -245,8 +245,9 @@ Ask: "Submit this feedback + run metrics to the maintainer via GitHub? (optional
**Confirm with user before moving files.**
1. Remove temporary scratch files not part of the final spec record (ask first; never `pathfinder/`). Everything left is the record: `overview.md` (with completion summary), every `phase-X.md`, `PLAN-DRAFT-*.md`, `PLAN-CONVERSATION-*.md`, `pathfinder/` (if present).
2. `specs.mjs archive <spec> --dry-run` and show the user its `files`; on their yes, `specs.mjs archive <spec>`. It moves the whole folder to `specs--completed/<feature-name>/` (name preserved exactly) and verifies the original is gone (`sourceRemoved`, `filesAtTarget`). Exit 5 `target-exists`: an archive of that name already exists; nothing moved, ask the user how to proceed.
3. In the same confirm, say the spec's remembered web console workspace folders will be forgotten too. After a successful move, on that yes: `node "<D>/console.mjs" forget --spec specs/<feature-name>` (<D>: references/web-console/ beside this SKILL.md). `forgot: false` just means none were saved; any failure is one line, never a blocker.
2. `specs.mjs archive <spec> --dry-run` and show the user its `files`; ask "Archive it? (yes / no / show me)"; on their yes, `specs.mjs archive <spec>`. It moves the whole folder to `specs--completed/<feature-name>/` (name preserved exactly) and verifies the original is gone (`sourceRemoved`, `filesAtTarget`). Exit 5 `target-exists`: an archive of that name already exists; nothing moved, ask the user how to proceed.
3. On "show me" (offered, never required), one last look at the whole feature: start the app as `AGENTS.md` Commands says (missing: work it out from `package.json` scripts, `Makefile` or `README` and, once it worked, offer the line for `AGENTS.md`; else ask), look at it (a browser tool's screenshot, else the command's output), stop what you started, add one line to `overview.md`'s Completion Summary (what was run, what was seen; screenshots on the web console page only), then ask again.
4. In the same confirm, say the spec's remembered web console workspace folders will be forgotten too. After a successful move, on that yes: `node "<D>/console.mjs" forget --spec specs/<feature-name>` (<D>: references/web-console/ beside this SKILL.md). `forgot: false` just means none were saved; any failure is one line, never a blocker.
---
+142
View File
@@ -0,0 +1,142 @@
# 🔎 DIAGNOSE MODE
Start all DIAGNOSE MODE responses with '🔎 [DIAGNOSE]'
## Role
Bug detective. Find a bug's cause and write it up, **without fixing it**: reproduce it, narrow it down, name the cause with the file and function, size the fix, and hand the write-up to Quick Task (small fix) or Plan (big fix). Reads, runs and judges; never repairs.
## Interface
The FIRST thing you do, before anything else in this file, before asking about the bug: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow diagnose` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-diagnose/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/diagnose.md. The bug questions, the growing cause, the bug name and the hand-off all go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context. On the console, a `__stop` action is the person ending the session (console-stop.md); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console-finish.md).
## Project Context (BLOCKING)
Check if `./AGENTS.md` exists:
1. **Exists:** Read and use for project context/conventions
2. **Missing:** STOP and respond:
> ```
> ⋅
> ╭───╮ ?
> │ ★ │╱
> ╱│ ~ │ Hmm, I don't see an AGENTS.md...
> ╰┬─┬╯
> ```
>
> "No `AGENTS.md` found. This file provides project context (conventions, architecture, tech stack).
>
> **To create it:** `plan2code-init`
>
> Let me know when ready to continue."
## Scripts
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-diagnose/scripts/` globally). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
- `node "<S>/specs.mjs" list`: the spec folders already under `specs/`, with their state, so a bug name never lands on an existing folder.
## Rules
- Follow `./AGENTS.md`.
- **Never change code.** The only writes allowed: the diagnosis file; a throwaway reproduction script outside the project's source (the OS temp folder, or `specs/<bug-name>/`); and a new failing test in the project's existing runner, only when the person agrees to keep it. Temporary logging goes outside the source tree, or is reverted before you finish. Say what you wrote and where.
- **Read `references/building-habits.md` and follow Find the cause first to the letter**, steps 1 and 2: proof before a fix. Build a command that fails on this bug and see it fail the way the report says. If none can be built (timing, one customer's data, production only), say so, rank your best guesses with the evidence for each, and say what would confirm each one. Its steps 3 and 4 (fix, keep the reproduction) belong to whoever fixes it: carry them into the hand-off.
- **Cite everything.** The cause names its `file` and function (`path:line` where it helps); every claim rests on something you ran or read. No evidence, no claim: call it a guess.
- **No git writes.** Read-only git (`log`, `show`, `diff`, and `bisect` as Step 3 says) is fine; never commit, stash, reset or switch the person's branch.
- Plain words. Name the files and functions; skip jargon the person did not use.
## Process
### Step 1: The Bug
A typed argument is the report; ask only for what it leaves out. Otherwise ask in one batch (console: three `text` cards, the first with a placeholder example of a real report, no `"templates"`):
> "1. **What is wrong?** The bug, in a sentence or two.
> 2. **Expected vs actual:** what should happen, and what happens instead.
> 3. **How to see it:** the steps, command, page or input that shows it (and since when, if known)."
Follow up until you could show someone else the bug. Never guess a missing step.
### Step 2: Reproduce
Build the smallest command that fails on the bug: a test in the project's runner, a script, a `curl`, a CLI run. Run it and confirm it fails **the way the report says**, not for some other reason.
- **It fails as reported:** that command is the proof. Keep it for the write-up.
- **It cannot be built:** say why in one line, and move on to ranked guesses in Step 3.
- **It passes (no bug seen):** say so, show what you ran, and ask what differs on their side (data, version, environment) before going further.
A reproduction written as a new test inside the project is offered, never assumed: "Keep this failing test in `<path>` as the regression test for the fix? (yes/no)". No → move it outside the source tree or delete it.
### Step 3: Narrow
- **A known-good version exists** (it worked before): `git bisect` with the reproduction as the check, in a throwaway worktree (`git worktree add <tmp> HEAD`, removed at the end) so the person's checkout never moves; in place only on a clean tree, with `git bisect reset` before you finish. Then read the commit it lands on.
- **Otherwise:** read the code path from the entry point the reproduction hits to where the wrong value or behaviour first appears.
- Temporary logging only outside the source tree, or reverted at once.
Stop when you can name the line where right turns into wrong.
### Step 4: Name the Cause and Size the Fix
1. **The cause**, in one line, with `file`, function and how sure: **Proven** (the reproduction shows it) or **Unproven** (ranked guesses, each with its evidence and what would confirm it).
2. **The suggested fix**, in a few lines: what changes, where. Do not write it.
3. **Its size:**
| Size | When | Hand to |
|------|------|---------|
| Small | A few files, no design choice | `/plan2code-quick-task` |
| Big | A design choice, many files, or risk (data, security, public API) | `/plan2code-1-plan` |
Console: the cause is a doc that grows as evidence lands (notes/diagnose.md).
### Step 5: Write the Diagnosis
Ask for a kebab-case bug name (console: a `text` card with `pattern` `^[a-z0-9]+(-[a-z0-9]+)*$`), offering one from the bug (e.g. `csv-export-drops-rows`). Check it against `specs.mjs list`. Then write `specs/<bug-name>/DIAGNOSIS-<YYYYMMDD>.md`:
```markdown
# Diagnosis: <Bug title>
**Date:** <YYYY-MM-DD>
**Status:** Diagnosed
## The Report
What is wrong · expected vs actual · how to see it
## Reproduction
`<command>`, and what it shows (or why none could be built)
## The Cause
<one line> · `<file>` `<function>` · **Proven** / **Unproven**
<the evidence: the run, the lines, the bisected commit>
## Ranked Guesses
(only when unproven: each guess, its evidence, what would confirm it)
## Suggested Fix
<what changes, where> · **Size:** Small (Quick Task) / Big (Plan)
Once fixed, turn the reproduction into a regression test (references/building-habits.md, Find the cause first).
```
Nothing was found worth writing (the bug did not reproduce and no guess holds up)? Say so, write nothing, and end.
## Session End
Work summary: the bug, the cause and how sure, the fix's size, the file written (or that nothing was kept), and anything else you wrote (a kept failing test, a throwaway script and where).
**Next step**, as the closing line:
- **Small fix:** "Next (NEW conversation): `/plan2code-quick-task specs/<bug-name>`. It reads the diagnosis first, as the starting point."
- **Big fix:** "Next (NEW conversation): `/plan2code-1-plan specs/<bug-name>`. It reads the diagnosis first, as its brief, and plans in the same folder."
- **Nothing kept:** "Diagnose complete." Mention `/plan2code-diagnose` again with more detail.
On the console, `finish.command` is the same command with the real folder filled in (`/plan2code-quick-task specs/csv-export-drops-rows`), never a placeholder; the dashboard shows the folder as "Bug diagnosed" with that card lit.
```
⋅
╭───╮
╲│ ★ │╱
│ ◡ │ Found it!
╰┬─┬╯
```
Adapted from Matt Pocock's `diagnose` skill and pstack's debugging playbook (both MIT).
+2 -2
View File
@@ -15,7 +15,7 @@ import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { EXIT, consoleLib, fail, gitRepo, out, parseArgs, readText, run } from "./common.mjs";
import { EXIT, consoleModule, fail, gitRepo, out, parseArgs, readText, run } from "./common.mjs";
const USAGE = `
git.mjs: read-only facts and exact commands for the Git skill. JSON on stdout.
@@ -182,7 +182,7 @@ const remoteNames = (root) => g(["remote"], root).out.split(/\r?\n/).filter(Bool
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
async function prHosts() {
return (await consoleLib()).readPrHosts();
return (await consoleModule("settings.mjs")).readPrHosts();
}
function readStatus(root) {
@@ -1,107 +0,0 @@
#!/usr/bin/env node
// handoff-path.mjs: where the handoff document goes, and whether git would pick it up.
//
// The handoff skill names its file <dir>/<YYYY-MM-DD-HHmm>-handoff.md, takes the
// timestamp from the clock rather than a guess, creates the folder, and checks
// whether the file would be tracked by git (is this a repo, is the path
// ignored). That is a fixed sequence with one right answer per machine, so it
// lives here. Whether to add an ignore line is the user's call.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { EXIT, fail, out, parseArgs, run, isoDate, now } from "./common.mjs";
const USAGE = `
handoff-path.mjs: pick the handoff file path and check it against git. JSON on stdout.
node handoff-path.mjs [--dir temp|<path>] [--root <dir>] [--dry-run]
--dir temp (the default): the OS temporary directory. Anything else is a
folder, relative to --root (default: the current directory), e.g.
handoffs (a project folder literally named temp: ./temp).
Created if missing (not with --dry-run).
Prints { path, dir, created, timestamp, git: { repo, inRepo, ignored,
ignoreLine }, warning? }. The file name is <YYYY-MM-DD-HHmm>-handoff.md; if one
already exists for this minute, -2, -3... is appended so earlier handoffs are
never overwritten. git.ignored is null when the file is outside a repo (nothing
to ignore); false means it would show up in git status, and then git.ignoreLine
is the .gitignore line to offer and the top-level warning says so.
Exit: 0 ok · 2 bad arguments · 5 the folder cannot be created, or --dir names
an existing file (not-a-folder).
`;
function git(cwd, args) {
try {
return { ok: true, out: execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim() };
} catch (err) {
return { ok: false, status: err.status };
}
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["dir", "root"] });
const root = path.resolve(args.root || ".");
const choice = args.dir || "temp";
const dir = choice === "temp" ? os.tmpdir() : path.resolve(root, choice);
let created = false;
if (fs.existsSync(dir) && !fs.statSync(dir).isDirectory()) {
fail(EXIT.REFUSED, "not-a-folder", `${dir} exists and is a file, not a folder.`, "Pass a folder for --dir (a new one is created), or use --dir temp.");
}
if (!fs.existsSync(dir)) {
if (!args["dry-run"]) {
try {
fs.mkdirSync(dir, { recursive: true });
created = true;
} catch (err) {
fail(EXIT.REFUSED, "mkdir-failed", `Could not create ${dir}: ${err.message}`, "Pick another folder, or use --dir temp.");
}
}
}
const d = now();
const pad = (n) => String(n).padStart(2, "0");
const timestamp = `${isoDate(d)}-${pad(d.getHours())}${pad(d.getMinutes())}`;
let file = path.join(dir, `${timestamp}-handoff.md`);
for (let n = 2; fs.existsSync(file); n++) file = path.join(dir, `${timestamp}-${n}-handoff.md`);
// Compare real paths: git prints the repo's real top level, while the folder
// may arrive as an 8.3 short name (C:\Users\JOHN~1\...) or through a symlink
// (macOS /tmp -> /private/tmp). A folder not created yet (--dry-run) resolves
// through its nearest existing ancestor. Git runs from that ancestor too, so
// the file is checked against the repo it would actually land in.
const existing = (() => {
let p = dir;
while (!fs.existsSync(p) && path.dirname(p) !== p) p = path.dirname(p);
return p;
})();
const realDir = path.join(fs.realpathSync.native(existing), path.relative(existing, dir));
const realFile = path.join(realDir, path.basename(file));
const top = git(existing, ["rev-parse", "--show-toplevel"]);
const gitInfo = { repo: top.ok || git(root, ["rev-parse", "--show-toplevel"]).ok, inRepo: false, ignored: null };
if (top.ok) {
const repoRoot = fs.realpathSync.native(path.resolve(top.out));
const relToRepo = path.relative(repoRoot, realFile);
gitInfo.inRepo = !!relToRepo && !relToRepo.startsWith("..") && !path.isAbsolute(relToRepo);
if (gitInfo.inRepo) {
// check-ignore exits 0 when ignored, 1 when not; it honours global and nested ignore files.
const ci = git(repoRoot, ["check-ignore", "-q", relToRepo.split(path.sep).join("/")]);
gitInfo.ignored = ci.ok;
const relDir = path.relative(repoRoot, realDir).split(path.sep).join("/");
// The repo root itself is never the line to ignore: offer the handoff files instead.
gitInfo.ignoreLine = relDir ? `${relDir}/` : "*-handoff.md";
}
}
out({
ok: true,
path: file,
dir,
created,
dryRun: !!args["dry-run"],
timestamp,
git: gitInfo,
...(gitInfo.inRepo && gitInfo.ignored === false ? { warning: `This file would be tracked by git. Offer to add "${gitInfo.ignoreLine}" to .gitignore; do not add it without asking.` } : {}),
});
});
+4 -24
View File
@@ -38,28 +38,15 @@ the next task (and shape the whole document around it), but still confirm.
## Where to write it
Ask the user if they would like to save the file to the temporary directory of the user's OS (this should be the default) or to some other location like `./handoffs/` at the repo root. Then let the script pick the exact path, from the project root:
No question to ask: every handoff lives in `~/.plan2code/handoffs/`, outside every repo. From the project root, let the console name the file:
```
node "<S>/handoff-path.mjs" --dir temp # or: --dir handoffs
node "<D>/console.mjs" handoff new --workflow handoff --skill plan2code-handoff --spec specs/<feature> --title "<short title>"
```
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-handoff/scripts/` globally). It prints one JSON object: `path` is `<dir>/<YYYY-MM-DD-HHmm>-handoff.md` from the clock (suffixed `-2`, `-3`... rather than overwrite an earlier handoff), and the folder is created if missing. Write the document to exactly that `path`. Exit 5 means the folder could not be created (or `--dir` names a file): ask for another location.
`<D>` is `references/web-console/` beside this SKILL.md, as in Interface. Pass `--spec` only when the work was inside a spec; the title is a few words naming the work. It prints one JSON object: write the document to exactly its `path`, and tell the person that path. Exit 3 means it could not write there: say so and stop.
### Make sure you aren't leaking the file into version control
The handoff is working state for the next session, not a project artifact, so it
should stay out of commits and PRs. Don't assume it will — this skill may run in
any repo. The same output's `git` block says:
- `repo: false`, or `inRepo: false` (the OS temp dir): nothing to ignore; just tell the user where the file is.
- `ignored: true`: git already ignores it (via any `.gitignore`, global or nested; `git check-ignore` is the check).
- `ignored: false`: it would be tracked; `git.ignoreLine` is the line to offer, and the top-level `warning` says so.
If it is **not** ignored, do not silently modify the user's `.gitignore`. Tell
them the file would be tracked by git and offer to add the `ignoreLine` (e.g.
`handoffs/`) to `.gitignore` — let them decide. Some users may want handoffs committed so
teammates get them; that's a legitimate choice, so present it, don't force it.
The dashboard lists the handoff for this checkout until it is picked up, and old ones go after 30 days.
## If this touched a plan2code spec
@@ -142,10 +129,3 @@ lives (env var name, secret manager entry) rather than its value.
Tell the user the path you wrote to and give a one-line summary of the confirmed
next task, so they know what the incoming agent will start on. Mention that a
fresh session can be pointed at the file to resume the work.
If your ignore check above found the file is in a repo and **not** gitignored
(`git.ignored: false`, which includes a repo with no `.gitignore`), say so plainly
here, e.g. "note: `handoffs/` isn't gitignored in this repo, so this file will
show up in `git status` and could be committed", and offer to add the
`ignoreLine`. Outside a repo there is nothing to ignore. Never leave
the user unaware that the handoff might ride along into a commit.
+10 -3
View File
@@ -75,6 +75,9 @@ When you make a mistake, get corrected, or discover something about this codebas
2. Keep it specific to this repo. General advice belongs nowhere.
3. If this fix is a workflow rather than a rule, put it in `.claude/skills/` and link it from here.
4. Include the change in the same commit and mention it in your summary.
5. A rule broken twice becomes an automated check (a test, a lint rule or a script), not more prose.
6. Before adding a line, look for one on the same topic: sharpen or extend that one rather than adding a near-duplicate.
7. Keep the log to 17 entries at most. Over the cap, first merge entries that share a cause, then drop the lowest-value ones: one-offs unlikely to recur, rules a test or script now enforces, and entries about code that no longer exists.
## Failure log
@@ -85,8 +88,12 @@ When you make a mistake, get corrected, or discover something about this codebas
If the section is missing, flag it:
> "Your Keeping this file current section is missing. Want me to add it?"
If it exists but lacks any of rules 5 to 7, offer to add them (keep the repo's own wording of rules it already has).
If user confirms, add/update the section before proceeding. If user declines, continue.
**Tidy the log** on every run, per rules 6 and 7: find entries that share a topic or cause, and, over 17 entries, the lowest-value ones. Propose merges (each merged line, and the lines it replaces) and removals (each with its reason) as one preview; apply only on yes. Nothing to merge and at or under 17: say so in one line.
Proceed to Step 2.
---
@@ -121,7 +128,7 @@ Present the user with update options:
> "What would you like to add or update in AGENTS.md?"
>
> **Options:**
> - **1. Commands** - Build, test, run, lint, or other CLI commands
> - **1. Commands** - Build, test, run, lint, how to run and view the app, or other CLI commands
> - **2. Architecture** - How components interact, data flow, key patterns
> - **3. Gotchas/Pitfalls** - Traps to avoid, non-obvious behaviors
> - **4. Testing** - Test patterns, how to run specific tests, fixtures
@@ -143,13 +150,13 @@ Present the user with update options:
| Category | Questions |
|----------|-----------|
| Commands | Purpose? Flags? Prerequisites? |
| Commands | Purpose? Flags? Prerequisites? How to run and view the app? |
| Architecture | Components? Interactions? Pattern? |
| Gotchas | What was unexpected? Workaround? |
| Testing | Commands? Fixtures? Mocking? |
| Environment | Local/CI/deploy? Env vars/files? |
| Rules | Project-wide or specific? Why? |
| Failure Log | What went wrong? Correct behaviour (imperative, one line)? |
| Failure Log | What went wrong? Correct behaviour (imperative, one line)? Merge into an entry on the same topic if one exists; over 17 entries, propose what to prune (rule 7). |
| Other | "Tell me what to add." |
| Sync & Maintain | Scope: all surfaces or specific? Then follow the Sync & Maintain section. |
| Review | Per section: "Still accurate?" |
+4 -1
View File
@@ -26,7 +26,7 @@ The FIRST thing you do, before anything else in this file — before exploring t
## Content
1. **Commands**: Build, lint, test, run single test, and other common development tasks
1. **Commands**: Build, lint, test, run single test, other common development tasks, and how to start the app and where to view it (URL or command), when it has one
2. **Architecture**: High-level "big picture" structure requiring multi-file context to understand
3. **How to Use This File**: A short paragraph explaining that sections below contain brief summaries and agents should follow the markdown links to `.agents-docs/` for full details — only read what's relevant to the current task.
4. **Failure Log**: running list of mistakes and/or corrections that went wrong via the AI Agent at least once.
@@ -78,6 +78,9 @@ When you make a mistake, get corrected, or discover something about this codebas
2. Keep it specific to this repo. General advice belongs nowhere.
3. If this fix is a workflow rather than a rule, put it in `.claude/skills/` and link it from here.
4. Include the change in the same commit and mention it in your summary.
5. A rule broken twice becomes an automated check (a test, a lint rule or a script), not more prose.
6. Before adding a line, look for one on the same topic: sharpen or extend that one rather than adding a near-duplicate.
7. Keep the log to 17 entries at most. Over the cap, first merge entries that share a cause, then drop the lowest-value ones: one-offs unlikely to recur, rules a test or script now enforces, and entries about code that no longer exists.
## Failure log
+9 -5
View File
@@ -36,10 +36,11 @@ Check for `./AGENTS.md` first:
## Rules
- Complete clarification before presenting plan
- Keep plans concise and actionable
- Focus on immediate implementation only
- Complete clarification before presenting the plan; keep it concise, actionable and about this change only
- Standalone workflow - does NOT create spec files or feed into steps 2-4
- Launched with a spec folder holding a `DIAGNOSIS-*.md`: read it first, as the bug's context (its cause and suggested fix are already found; re-run its reproduction before and after the fix). Once it passes, set the diagnosis `**Status:**` to `Fixed`; escalating, use that folder rather than asking for a name. Fixed, with nothing in the folder past the diagnosis (no `PLAN-CONVERSATION`, `PLAN-DRAFT`, `pathfinder/map.md` or `overview.md`)? It is done: run `node "<S>/specs.mjs" archive <spec> --dry-run` from the project root (`<S>` is `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-quick-task/scripts/` globally), show its `files`, ask "Archive it to `specs--completed/`? (yes / no)", and on yes run it without `--dry-run`. On no it stays on the dashboard as "Bug fixed".
- Cause unclear or the fix big? Stop and suggest `/plan2code-diagnose`.
- Read `references/building-habits.md` when the ask is a bug fix or a test fails unexpectedly, after a yes to "Write the test first?", and before a change meant to alter no behaviour; follow it.
```
⋅
@@ -51,6 +52,8 @@ Check for `./AGENTS.md` first:
Ask what feature the user wants, then ask follow-up questions until 100% clear. Console: that first card carries `"templates": "idea"` (console.md → The kinds).
**Write the test first?** Ask it with the follow-ups (or on its own if there are none) only when the change alters behaviour AND the project already has a test runner you can see (a `test` script in `package.json`, pytest config in `pytest.ini` or `pyproject.toml`, `go.mod` with `_test.go` files, or similar). Never for a pure refactor, a docs change, or a project with no runner. Console: one `confirm` card in the same batch as the other plan questions; terminal: one line in the same prompt. On yes, name the test spot in the plan's Verify section and follow the test-first habit.
## Scope Validation
After achieving clarity, assess scope:
@@ -136,12 +139,13 @@ Then tell user: "Created `specs/<feature-name>/PLAN-DRAFT-<date>.md`. Start new
- `path/to/new-file.ts` - [create: purpose]
### Steps
1. [Step]
1. [Step] (fixing a bug: this step is the reproduction; find the cause first)
2. [Step]
3. [Continue...]
### Verify
- [ ] [How to test/confirm]
- [ ] [Test first: the test spot, e.g. "test through `POST /votes`"]
---
```
@@ -156,6 +160,6 @@ Ready to implement? (yes / modify / escalate / abort)
## Session End
Work summary — tell user: task name, plan delivered (or PLAN-DRAFT created if escalated).
Work summary — tell user: task name, plan delivered (or PLAN-DRAFT created if escalated). After a build, offer: "Reply `show me` to see it running." **Show me it working** (offered, never required): start the app as `AGENTS.md` Commands says (missing: work it out from `package.json` scripts, `Makefile` or `README` and, once it worked, offer the line for `AGENTS.md`; else ask), look at the change (a browser tool's screenshot, else the command's output), stop what you started, and add one line to the work summary: what was run and what was seen. Screenshots go on the web console page only.
**On the web console:** a `__stop` action in a send is the person ending the session: see console-stop.md. At every session end (built, escalated, aborted) post `finish` BEFORE `stop`, as notes/quick-task.md describes. After a build, keep waiting for the review button's answer before you stop.
@@ -0,0 +1,51 @@
# Reviewer Brief
> Part of plan2code-review: filled in by the main session at Step 3 (Analyze) and handed, whole, to ONE fresh helper.
Fill every `{{...}}` field, drop the lines that do not apply, and send the filled text as the helper's entire instructions. Never add the builder's conversation, reasoning, work notes or self-review: the helper's value is that it did not see them.
---
You are an independent code reviewer. You did not write this change and have not seen the conversation that produced it. Judge it only on the spec and the code.
## What you are reviewing
- **Project root:** `{{absolute project path}}`
- **Spec:** `{{specs/<feature>/overview.md}}` and `{{specs/<feature>/phase-X.md}}`, or "no spec: review against best practice and the project's conventions".
- **Scope:** `{{Focused | Branch | Full}}`. Review type: `{{type from Step 1}}`. Focus first on: `{{prioritized dimensions}}`.
- **Change set:** `{{base branch from review-scope.mjs, or "explicit file list"}}`
{{one line per file: path (status, ~lines)}}
## What you may read
- Every file in the change set, completely, before flagging anything in it.
- Their direct callers and callees, only to confirm or drop a finding.
- The spec files above, and `AGENTS.md` at the project root for conventions.
- The review-depth references, in `{{absolute references/ path}}`: `verification-protocol.md` (always), `dimensions.md` (Branch and Full), `false-positives.md` (Full).
## What you must not do
- Edit, create or delete any file, or run anything that writes (no installs, builds that write output, git commands that change state).
- Ask the person questions. When something is unclear, say so in your return.
- Guess intent from anything but the spec and the code.
- Widen the scope: other files are context, never targets.
## How to review
Cover all 11 dimensions (Correctness, Completeness, Security, Performance, Standards, Tech Debt, Test Quality, Maintainability, Spec Compliance, UX/DX, Improvements), as `dimensions.md` lays out for this scope. Apply `verification-protocol.md` to every finding: High confidence only, verified at the cited line, fix checked against its callers. Investigate until certain or drop it. Run each finding through the adversarial self-check before returning it.
## What you return
Findings only, grouped by severity (Critical, Warning, Suggestion), each exactly:
```
**[Severity] [Title]** -- `file:line` (Confidence: High)
[What's wrong -- 1-2 sentences]
**Fix:** [code or recommendation]
```
Then one line per dimension with no finding: `Dimension: clean -- [what you checked]` or `Dimension: N/A -- [why]`. Then, when a spec was given, one line per `[x]` task it lists: met, or which finding it fails. No preamble, no summary table: the main session verifies every finding and writes the report.
---
Credit: the rule that only an agent who did not write the code gives the verdict is adapted from pstack's independent reviewer.
+7 -2
View File
@@ -63,7 +63,7 @@ Three levels -- auto-detected, always respect explicit user override:
1. **User prompt** — use it.
2. **Conversation context** — recent work? Those artifacts. Scope: `focused`.
3. **Standalone, nothing named** — do not assume a target. Do a quick scan (no file reading): `review-scope.mjs`, `specs.mjs list`, recent commits. Then ask what to review (`ask_user_question`; a `choice` on the console, scope questions up front), offering only options the scan supports, each with its size: the branch's changes vs base (files, ~lines, `commits`), uncommitted changes only (when any), a spec/plan under `specs/` (when any), a named subsystem or full codebase, or specific files/folders (free text via Other). Recommend the likeliest first. Nothing found (`empty: true`, no specs)? Ask for files or a subsystem. Use the answer as the scope, then continue.
4. **Scan details** — `review-scope.mjs` compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
4. **Scan details** — `review-scope.mjs` diffs the branch against its base (`main`, else `master`, or `--base`) plus staged, unstaged and untracked changes: `files`, `counts`, `commits`, `mix`, `batchByRisk`. `empty: true` or exit 3 `not-a-repo`? Ask user what to review. Exit 3 `no-base`? Rerun with `--base <trunk>`, asking which branch is the trunk if unclear.
**Classify review type** from context (auto-detect; use `ask_user_question` only if ambiguous):
@@ -93,6 +93,8 @@ Three levels -- auto-detected, always respect explicit user override:
### Step 3: Analyze
**Who reviews:** when your tool can start a helper (subagent) and helpers are not switched off for this skill run, fill references/reviewer-brief.md and hand the analysis to ONE fresh helper; do not analyze in parallel. The brief carries the review-depth references, the dimensions and the finding format: send only the filled brief. With no helper, or one that fails or returns nothing usable, run this step in this session.
**Load review depth (conditional on scope):**
| Scope | Load |
@@ -103,7 +105,7 @@ Three levels -- auto-detected, always respect explicit user override:
Read references/verification-protocol.md
> Fallback: re-read source at cited line, verify issue is real, verify fix doesn't break callers. For architectural findings, trace a use case end-to-end.
> Fallback: re-read the cited line, confirm the issue is real and the fix keeps callers working; trace a use case for architectural findings.
Read references/dimensions.md (Branch and Full scopes)
@@ -133,6 +135,8 @@ Read references/false-positives.md (Full scope only; fallback rules below apply
Run every finding through the false-positive detection shortcuts before presenting. Drop findings that fail.
**Helper's findings:** when a helper ran the analysis, open every finding's cited `file:line` yourself and confirm it with verification-protocol.md and the false-positive shortcuts (fallback above). Drop any you cannot confirm; adjust severity if needed, never add unverified findings. Note how many you dropped for the report.
### Step 4: Spec & Test Assessment
**Specs** (skip if none): Each `[x]` task correct? Criteria met? Paths match?
@@ -147,6 +151,7 @@ Run every finding through the false-positive detection shortcuts before presenti
🔬 [Review Mode Complete]
**Overview:** [2-3 sentences] **Scope:** [X files, ~Y lines]
**Reviewed by:** a fresh helper (N findings checked, M dropped) · or this session (helpers off) · or this session (this tool cannot start helpers) · or this session (helper failed). In-session, add once: this review was not independent of the work it reviewed.
**Dimension Coverage:** Report all 11. Clean dimensions grouped on one summary line.
+336
View File
@@ -0,0 +1,336 @@
#!/usr/bin/env node
// xray.mjs: what git history says about the code, for the X-ray skill.
//
// Two reads, both fixed sequences over git with one right answer per repo:
// hotspots (which files change most, which change together, which hot source
// files have no test) and history (one file's commits, who wrote its lines,
// and the pull requests behind it). The script only reads. What the numbers
// mean for the code is the agent's call.
import fs from "node:fs";
import path from "node:path";
import { execFileSync, spawnSync } from "node:child_process";
import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
const USAGE = `
xray.mjs: churn, co-change and one file's history from git. JSON on stdout.
It never changes the repository.
node xray.mjs hotspots [--root <dir>] [--path <area>] [--max-commits 500] [--top 20]
node xray.mjs history <path> [--root <dir>] [--max-commits 50]
hotspots Reads the last --max-commits commits (merges skipped), scoped to
--path when given. Only files tracked at HEAD count (renamed,
deleted and untracked generated files drop out); lockfiles, dist/,
build/ and node_modules/ are left out too. Prints { ok, root,
window: { commits, capped }, churn, pairs, untested }.
churn [{ file, commits }], most changed first.
pairs [{ a, b, together, support }]: files changed together in
at least 3 commits; support is together divided by the
smaller of the two files' commit counts. Highest support
first. Commits touching more than 50 files are left out
of pairs (bulk renames and formatting sweeps).
untested [{ file, commits }]: source files changed in at
least 2 commits, with no test file
anywhere in the repo whose name contains the file's base
name.
capped is true when older commits fell outside the window. Each list
holds at most --top entries.
history One file's story. Prints { ok, path, commits, blame, prs, sources }.
commits [{ hash, date, author, subject }] from git log --follow,
newest first, at most --max-commits.
blame { lines, authors: [{ author, lines, share }], oldest,
newest } at HEAD; null when the file is gone at HEAD.
prs [{ number, subject, title, summary }] parsed from commit
and merge subjects (#123, Merge pull request #123).
title and summary (the body's first paragraph) come from
gh pr view, for at most 10, when gh is installed and
signed in; otherwise they are null.
sources { git: true, blame: true|false,
gh: "used"|"missing"|"unauthenticated"|"timed-out" }.
Exit: 0 ok · 2 bad arguments · 3 not a git repository (not-a-repo), or the
path has no history (no-history).
`;
const GH_TIMEOUT_MS = 5000;
const GH_MAX_PRS = 10;
const PAIR_MIN = 3;
const PAIR_MAX_FILES = 50;
const UNTESTED_MIN = 2;
/** Run git with an args array (never a shell). { ok, out }. */
function git(cwd, args) {
try {
const stdout = execFileSync("git", args, {
cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
maxBuffer: 64 * 1024 * 1024,
windowsHide: true,
// Without this, some reads refresh the index on disk: a write.
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
});
return { ok: true, out: stdout };
} catch {
return { ok: false, out: "" };
}
}
function count(value, flag, fallback) {
if (value === undefined) return fallback;
const n = Number(value);
if (!Number.isInteger(n) || n < 1) fail(EXIT.USAGE, "bad-number", `--${flag} needs a whole number above 0, got "${value}".`, "Run with --help for usage.");
return n;
}
/** The repository's top level for --root, or the not-a-repo failure. */
function repoTop(root) {
const top = fs.existsSync(root) ? git(root, ["rev-parse", "--show-toplevel"]) : { ok: false };
if (!top.ok) {
fail(EXIT.NOT_FOUND, "not-a-repo", `${root} is not inside a git repository.`, "X-ray needs git history; explain mode can still read the code.");
}
return path.resolve(top.out.trim());
}
/** A path from the person (relative to --root) as a forward-slash path relative to the repo top. */
function repoPath(root, top, p) {
const abs = path.resolve(root, p);
// Compare real paths: git prints the real top level, while --root may be an
// 8.3 short name or arrive through a symlink. A path that does not exist
// any more (a deleted file) resolves through its nearest existing ancestor.
let existing = abs;
while (!fs.existsSync(existing) && path.dirname(existing) !== existing) existing = path.dirname(existing);
const real = path.join(fs.realpathSync.native(existing), path.relative(existing, abs));
return path.relative(fs.realpathSync.native(top), real).split(path.sep).join("/");
}
const hasCommits = (top) => git(top, ["rev-parse", "--verify", "-q", "HEAD"]).ok;
/* -------------------------------------------------------------- hotspots */
const LOCKFILES = new Set([
"package-lock.json",
"npm-shrinkwrap.json",
"yarn.lock",
"pnpm-lock.yaml",
"bun.lockb",
"bun.lock",
"Cargo.lock",
"Gemfile.lock",
"poetry.lock",
"Pipfile.lock",
"composer.lock",
"go.sum",
"uv.lock",
"flake.lock",
"packages.lock.json",
]);
function skipped(file) {
const base = file.slice(file.lastIndexOf("/") + 1);
if (LOCKFILES.has(base) || base.endsWith(".lock")) return true;
return /(^|\/)(dist|build|node_modules)\//.test(file);
}
const SOURCE_EXT = /\.(m?[jt]sx?|cjs|cts|mts|py|rb|go|rs|java|kt|kts|scala|cs|fs|php|swift|m|mm|c|cc|cpp|cxx|h|hpp|ex|exs|erl|clj|dart|lua|pl|r|jl|hs|ml|vue|svelte|sh|ps1)$/i;
const TEST_DIR = /(^|\/)(tests?|__tests__|specs?|e2e)\//i;
const TEST_NAME = /([._-](test|spec)s?\.[^/]+$)|(^tests?_)|(_tests?\.[^/]+$)/i;
const baseName = (file) => file.slice(file.lastIndexOf("/") + 1);
const stem = (file) => baseName(file).replace(/\.[^.]+$/, "");
const isTest = (file) => TEST_DIR.test(file) || TEST_NAME.test(baseName(file)) || /^test-/i.test(baseName(file));
/** [hash, [file...]] per commit, newest first, merges skipped. */
function commitFiles(top, limit, scope) {
if (!hasCommits(top)) return [];
const args = ["-c", "core.quotepath=off", "log", "--no-merges", "--no-renames", `-n${limit}`, "--name-only", "--format=%x01%H"];
if (scope) args.push("--", scope);
const log = git(top, args);
if (!log.ok) return [];
return log.out
.split("\x01")
.slice(1)
.map((block) => {
const [hash, ...files] = block.split("\n").map((l) => l.trim());
return [hash, files.filter(Boolean)];
});
}
function hotspots(argv) {
const args = parseArgs(argv, { values: ["root", "path", "max-commits", "top"] });
const root = path.resolve(args.root || ".");
const max = count(args["max-commits"], "max-commits", 500);
const topN = count(args.top, "top", 20);
const top = repoTop(root);
const scope = args.path ? repoPath(root, top, args.path) || "." : null;
// One commit past the window says whether anything older was cut off.
let commits = commitFiles(top, max + 1, scope);
const capped = commits.length > max;
if (capped) commits = commits.slice(0, max);
// Only files tracked at HEAD count: a renamed or deleted file's history
// would otherwise crowd live files out of the top lists, and untracked
// build output (a gitignored skills/) drops out on its own.
const tracked = git(top, ["-c", "core.quotepath=off", "ls-files"]);
const files = tracked.ok ? tracked.out.split("\n").map((l) => l.trim()).filter(Boolean) : [];
const present = new Set(files);
const churn = new Map();
const together = new Map();
for (const [, all] of commits) {
const files = [...new Set(all.filter((f) => present.has(f) && !skipped(f)))].sort();
for (const f of files) churn.set(f, (churn.get(f) || 0) + 1);
if (files.length > PAIR_MAX_FILES) continue;
for (let i = 0; i < files.length; i++) {
for (let j = i + 1; j < files.length; j++) {
const key = `${files[i]}\n${files[j]}`;
together.set(key, (together.get(key) || 0) + 1);
}
}
}
const byChurn = [...churn].map(([file, n]) => ({ file, commits: n })).sort((x, y) => y.commits - x.commits || x.file.localeCompare(y.file));
const pairs = [];
for (const [key, n] of together) {
if (n < PAIR_MIN) continue;
const [a, b] = key.split("\n");
const support = Math.round((n / Math.min(churn.get(a), churn.get(b))) * 100) / 100;
pairs.push({ a, b, together: n, support });
}
pairs.sort((x, y) => y.support - x.support || y.together - x.together || x.a.localeCompare(y.a) || x.b.localeCompare(y.b));
// Tests are looked for across the whole repo, not only inside --path: a
// file under src/ is usually tested from a sibling tests/ folder.
const testNames = files.filter(isTest).map((f) => baseName(f).toLowerCase());
const untested = byChurn.filter(({ file, commits: n }) => {
if (n < UNTESTED_MIN || !SOURCE_EXT.test(file) || isTest(file)) return false;
const name = stem(file).toLowerCase();
return !testNames.some((t) => t.includes(name));
});
out({
ok: true,
root: top,
...(scope ? { path: scope } : {}),
window: { commits: commits.length, capped },
churn: byChurn.slice(0, topN),
pairs: pairs.slice(0, topN),
untested: untested.slice(0, topN),
});
}
/* --------------------------------------------------------------- history */
function blameSummary(top, file) {
const r = git(top, ["blame", "--line-porcelain", "HEAD", "--", file]);
if (!r.ok) return null;
const authors = new Map();
let lines = 0;
let oldest = Infinity;
let newest = -Infinity;
let author = null;
for (const line of r.out.split("\n")) {
if (line.startsWith("author ")) author = line.slice(7);
else if (line.startsWith("author-time ")) {
const t = Number(line.slice(12));
if (t < oldest) oldest = t;
if (t > newest) newest = t;
} else if (line.startsWith("\t")) {
lines++;
authors.set(author, (authors.get(author) || 0) + 1);
}
}
const day = (t) => (Number.isFinite(t) ? new Date(t * 1000).toISOString().slice(0, 10) : null);
return {
lines,
authors: [...authors]
.map(([name, n]) => ({ author: name, lines: n, share: Math.round((n / lines) * 100) / 100 }))
.sort((x, y) => y.lines - x.lines || x.author.localeCompare(y.author)),
oldest: day(oldest),
newest: day(newest),
};
}
const PR_PATTERNS = [/Merge pull request #(\d+)/gi, /#(\d+)\b/g];
function prNumbers(subjects) {
const seen = new Map();
for (const subject of subjects) {
for (const pattern of PR_PATTERNS) {
for (const m of subject.matchAll(pattern)) {
const n = Number(m[1]);
if (!seen.has(n)) seen.set(n, subject);
}
}
}
return [...seen].map(([number, subject]) => ({ number, subject, title: null, summary: null }));
}
/** "used", "missing", "unauthenticated" or "timed-out", filling in prs as it goes. */
function ghDetails(top, prs) {
const gh = (args) => spawnSync("gh", args, { cwd: top, encoding: "utf8", timeout: GH_TIMEOUT_MS, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
const timedOut = (r) => r.error?.code === "ETIMEDOUT" || (r.signal && r.status === null);
const auth = gh(["auth", "status"]);
if (auth.error?.code === "ENOENT") return "missing";
if (timedOut(auth)) return "timed-out";
if (auth.error || auth.status !== 0) return "unauthenticated";
let status = "used";
for (const pr of prs.slice(0, GH_MAX_PRS)) {
const r = gh(["pr", "view", String(pr.number), "--json", "title,body"]);
if (timedOut(r)) {
status = "timed-out";
break;
}
if (r.status !== 0) continue; // an issue number, or a PR this remote does not know
try {
const { title, body } = JSON.parse(r.stdout);
pr.title = title || null;
// The first paragraph that says something, minus any heading lines on
// top of it: GitHub's template puts "## Summary" right above the text.
const paragraphs = (body || "").replace(/\r\n/g, "\n").split(/\n\s*\n/).map((p) => p.replace(/^(#{1,6}\s[^\n]*(\n|$))+/, "").trim());
pr.summary = paragraphs.find(Boolean) || null;
} catch {}
}
return status;
}
function history(argv) {
const args = parseArgs(argv, { values: ["root", "max-commits"] });
const target = args._[0];
if (!target) fail(EXIT.USAGE, "missing-path", "history needs the file to read.", "Run: node xray.mjs history <path>");
const root = path.resolve(args.root || ".");
const max = count(args["max-commits"], "max-commits", 50);
const top = repoTop(root);
const file = repoPath(root, top, target);
const log = hasCommits(top) ? git(top, ["log", "--follow", `-n${max}`, "--format=%H%x1f%aI%x1f%an%x1f%s", "--", file]) : { ok: false };
const commits = (log.ok ? log.out.split("\n") : [])
.filter(Boolean)
.map((line) => {
const [hash, date, author, subject] = line.split("\x1f");
return { hash, date, author, subject };
});
if (!commits.length) {
fail(EXIT.NOT_FOUND, "no-history", `${file} has no commits in this repository.`, "Check the path (relative to --root), or run hotspots to see which files have history.");
}
// Merges hide from a file's own log; the first-parent merges that touched
// it carry the "Merge pull request #N" subjects.
const merges = git(top, ["log", "--first-parent", "--merges", `-n${max}`, "--format=%s", "--", file]);
const subjects = [...commits.map((c) => c.subject), ...(merges.ok ? merges.out.split("\n").filter(Boolean) : [])];
const prs = prNumbers(subjects);
const blame = blameSummary(top, file);
const gh = ghDetails(top, prs);
out({ ok: true, path: file, commits, blame, prs, sources: { git: true, blame: blame !== null, gh } });
}
run(USAGE, async (argv) => {
const [command, ...rest] = argv;
if (command === "hotspots") return hotspots(rest);
if (command === "history") return history(rest);
fail(EXIT.USAGE, "unknown-command", command ? `Unknown command "${command}".` : "No command given.", "Run with --help: the commands are hotspots and history.");
});
+154
View File
@@ -0,0 +1,154 @@
# 🩻 X-RAY MODE
Start all X-RAY MODE responses with '🩻 [X-RAY]'
## Role
Codebase guide. Two jobs, one card: **explain** how and why an area of the code works, citing the files and the history behind it, or **find the rough spots** worth fixing and hand the ones the person picks to Pathfinder or Plan as a brief. Reads, counts and judges; never builds.
## Interface
The FIRST thing you do, before anything else in this file, before the mode question: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow xray` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-xray/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/xray.md. The mode question, the answer or the ranked list, and the save offer all go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context. On the console, a `__stop` action is the person ending the session (console-stop.md); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console-finish.md).
## Project Context (BLOCKING)
Check if `./AGENTS.md` exists:
1. **Exists:** Read and use for project context/conventions
2. **Missing:** STOP and respond:
> ```
> ⋅
> ╭───╮ ?
> │ ★ │╱
> ╱│ ~ │ Hmm, I don't see an AGENTS.md...
> ╰┬─┬╯
> ```
>
> "No `AGENTS.md` found. This file provides project context (conventions, architecture, tech stack).
>
> **To create it:** `plan2code-init`
>
> Let me know when ready to continue."
## Scripts
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-xray/scripts/` globally). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
- `node "<S>/xray.mjs" hotspots [--path <area>] [--max-commits 500] [--top 20]`: counts from `git` history. `churn` (files by commits), `pairs` (files changed together in 3+ commits, ranked by `support`), `untested` (often-changed source files with no test named after them), and `window` (`capped: true` when the history ran past `--max-commits`).
- `node "<S>/xray.mjs" history <path> [--max-commits 50]`: one file's story. `commits` (hash, date, author, subject, following renames), `blame` (authors by line share, oldest and newest lines), `prs` (titles and first paragraphs, when `gh` works), and `sources` (`gh`: `used`, `missing`, `unauthenticated` or `timed-out`).
- Exit 3 `not-a-repo`: no git history. Explain mode carries on from the code alone; rough-spots mode reads the code and judges without the counts, and says so.
## Rules
- Follow `./AGENTS.md`.
- **Never edit code.** The only files you write are the ones the person asks to keep, under `specs/<name>/`.
- **Cite everything.** Every claim names its file (`path:line` where it helps); every "why" names the commit (short hash) or PR it rests on. No citation, no claim: say it is a guess.
- **Say once which sources could not be used** (no `gh`, `gh` not signed in, no git history), near the top of the answer, so a thin "why" is never read as "there was no reason".
- **Never stop to ask for an install** or a sign-in. Use what is there.
- **The counts are leads, not verdicts.** A script ranks; you read the code and judge.
- Plain words. Name the files and functions; skip jargon the person did not use.
## Process
### Step 1: Mode and Area
A typed argument skips the question:
| Argument | Mode | Area |
|----------|------|------|
| `explain <area>` | Explain | `<area>` |
| `survey` or `survey <area>` | Rough spots | the whole repo, or `<area>` |
| plain text (`how does the exporter work`) | Explain | read from the text |
| none | ask | ask |
Otherwise ask both at once (console: a `choice` and a `text` card in one batch):
> "What do you want to know?
> 1. **Explain an area**: how it works and why it is that way
> 2. **Find the rough spots**: what makes this code hard to change, ranked
>
> Which area? (a folder, file or feature; required to explain, optional for rough spots)"
Explain with no area: ask for one. Never guess the mode from a vague request.
### Step 2a: Explain an Area
1. **Find the area's code.** Search for it, then read its entry points and the files they lean on. Read enough to trace one real use end to end.
2. **Its history.** Run `xray.mjs history` on the 1-5 key files. Read the commits and PRs that shaped them; follow a subject that matters into its diff (`git show <hash> --stat`, then the lines).
3. **Answer:**
```
🩻 [X-RAY] <area>
Sources: code, git history, PRs (or: no gh, git only · no git history, code only)
## In one paragraph
## How it works
Entry points · the flow, step by step · the data it holds and passes · its boundaries (what calls it, what it calls)
## Why it is this way
The decisions behind the shape, each with its commit or PR
## Worth knowing
Traps, odd corners, what a newcomer would get wrong
```
Cite `file` paths in every section and short commit hashes in the "why".
4. **Offer to keep it:** "Save this as `specs/<name>/XRAY-<area-slug>-<date>.md`, as input for Pathfinder or Plan? (yes/no)". `<name>` is the spec folder it belongs to (ask, offering the area's kebab-case slug), `<date>` is `YYYYMMDD`. Yes → write the answer there exactly as shown. Console: the answer is a doc, the offer a `confirm` card.
### Step 2b: Find the Rough Spots
1. **Count.** Run `xray.mjs hotspots` (with `--path` when an area was given).
2. **Read and judge.** Open the top candidates: the strongest `pairs`, the heaviest `churn`, every `untested` file near the top. Look for:
- **Files that always change together**: one idea split across places.
- **Shallow wrappers**: a layer that only passes calls through, adding a place to change.
- **Tangled boundaries**: modules reaching into each other's insides, circular imports, one change rippling outward.
- **Untested hot spots**: code that changes often with nothing to catch a break.
Drop false alarms: a pair that changes together for a good reason (a test beside its code, a schema and its migration), generated files, a churn spike from one big rename.
3. **Present a ranked list**, worst first, at most 10:
```
1. <short name> [files that change together]
Files: a.ts, b.ts, c.ts
Why it hurts: <one sentence, citing the evidence: "changed together in 14 of 16 commits">
Today: to change <X> you must touch a.ts, b.ts and c.ts.
```
Every spot carries a concrete "to change X today you must touch..." example. No spots worth raising: say so, with what you checked, and end.
4. **The pick.** "Which are worth fixing? Reply with numbers, each with an optional note (e.g. `1, 3: the exporter part only`)." Console: a `multi` card, one option per spot, notes in the free text.
5. **Write the brief** with the picked spots only: `specs/<name>/ARCHITECTURE-BRIEF-<YYYYMMDD>.md` (`<name>` asked as above, offering the area's slug or `codebase-health`):
```markdown
# Architecture Brief: <area or "whole codebase">
**Date:** <YYYY-MM-DD> · **Area:** <area> · **Sources:** <as above>
## 1. <short name>
**Files:** ... · **Evidence:** ...
**Today:** to change <X> you must touch ...
**Note:** <the person's note, or none>
```
Nothing picked: write nothing, and say so.
## Session End
Work summary: the mode, the area, the sources used, and the file written (or that nothing was kept).
**Next step:**
- A brief written, the fix big or unclear → "Next (NEW conversation): `/plan2code-0-pathfinder` with `specs/<name>/` as its notes."
- A brief written, the fix settled → "Next (NEW conversation): `/plan2code-1-plan` with `specs/<name>/` as its brief."
- An explain answer saved → whichever of the two fits the person's aim; unsure → ask.
- Nothing kept → "X-ray complete." Mention `/plan2code-xray` again for another area.
On the console, `finish.command` is `/plan2code-0-pathfinder` or `/plan2code-1-plan`, without placeholders.
```
⋅
╭───╮
╲│ ★ │╱
│ ◡ │ X-ray done!
╰┬─┬╯
```
The rough-spots mode adapts Matt Pocock's `improve-codebase-architecture` skill (MIT) and pstack's codebase survey; explain mode adapts pstack's `how` and `why`.
+33 -5
View File
@@ -32,9 +32,18 @@ The page draws the cards itself — you never send the list. It also knows the r
```
- No AGENTS.md → `recommend: "plan2code-init"`; the note says why.
- A spec mid-pipeline → recommend its next step; that card's `details` names where it stands ("Plan drafted", "Phase 2 of 4 is next"). The picker pre-selects the most recently touched spec — recommend for THAT one.
- A spec mid-pipeline → recommend its next step; that card's `details` names where it stands ("Plan drafted", "Phase 2 of 4 is next"). The picker pre-selects the most recently touched spec that is not `fixed` — recommend for THAT one.
- `exploring` ("Exploring"): Pathfinder is next.
- `mapped` ("Ready to plan"): Plan is next.
- `planned` ("Ready to document"): Document is next.
- `documented` ("Ready to build"): Implement is next.
- `building` ("Building"): Implement is next.
- `built` ("Ready to finalize"): Finalize is next.
- A spec that scans `unrecognized` ("files on disk") is input, not progress: its folder rides along on a Pathfinder or Plan launch as reference, and those are the only pipeline cards it lights. Read the files and recommend the fit — a settled design doc the person wrote is Plan's brief, loose notes are Pathfinder's. No skill generates such a doc; see the table below for what each one does write. Never flag Document or anything downstream of it for such a spec.
- Nothing on disk → `recommend: "plan2code-0-pathfinder"`; the note invites the first idea.
- A `diagnosed` spec ("Bug diagnosed") is a bug Diagnose wrote up: recommend Quick Task, or Plan when its `DIAGNOSIS-<date>.md` sizes the fix as big; its folder rides along on either launch.
- A `fixed` spec ("Bug fixed") is a diagnosed bug Quick Task fixed but did not archive: finished, so never recommend for it or name it in the note; the picker never pre-selects one and hides it while unavailable workflows are hidden. The person archives it (Quick Task offers that once the bug is fixed) or deletes it with the picker's ✕.
- Nothing on disk, or only `fixed` specs → `recommend: "plan2code-0-pathfinder"`; the note invites the first idea.
- A handoff in `state.scan.handoffs` newer than the most recently touched spec is usually the place to start: say so in `note` (the page has no card to `recommend` for it).
- Recommend only what you would tell a person who asked "where do I start?". When in doubt, no flag and a neutral note — the page falls back to flagging the selected spec's own next step.
- `recommend` must name a lit card for the initial selection. If the person switches specs or starts fresh, the page derives the suggestion and detail from its scan instead.
@@ -51,14 +60,16 @@ Ground truth for menu notes and Ask-tab answers. For anything beyond this table,
| 0-pathfinder | the idea, loose notes | `pathfinder/map.md`, `pathfinder/questions/NN-<slug>.md`; cleared → `PLAN-DRAFT-<date>.md` |
| 1-plan | idea or `PLAN-DRAFT` | `PLAN-DRAFT-<date>.md`, `PLAN-CONVERSATION-<date>.md` |
| 1b-revise-plan | `overview.md`, `phase-X.md` | the same, revised |
| quick-task | the ask | code; escalated → `PLAN-DRAFT-<date>.md` |
| quick-task | the ask; a `DIAGNOSIS-*.md` when launched on one | code; the diagnosis set to `Fixed`, then the folder moved to `specs--completed/` on a yes; escalated → `PLAN-DRAFT-<date>.md` |
| 2-document | `PLAN-DRAFT`, `PLAN-CONVERSATION` (optional) | `overview.md`, `phase-X.md` |
| 3-implement(-review) | `overview.md`, `phase-X.md` | code; `[x]` marks + completion summary in `phase-X.md` |
| review | spec, diff | the fixes picked; no spec writes |
| 4-finalize | spec + code | summary in `overview.md`; moves the spec to `specs--completed/` |
| handoff | conversation, spec, git | `<timestamp>-handoff.md` (OS temp or `handoffs/`) |
| handoff | conversation, spec, git | `~/.plan2code/handoffs/<id>.md`, listed on the dashboard |
| changelog | `CHANGELOG.md`, `package.json`, git history | `CHANGELOG.md` entries, `package.json` version; no commits |
| git | git status, branches, diffs, `AGENTS.md` | commits, branches; optional `.gitignore`, push, publish; no spec writes |
| xray | the codebase, `git` history, `gh` when present | an answer; `ARCHITECTURE-BRIEF-<date>.md` or `XRAY-<area>-<date>.md` when asked |
| diagnose | the bug, the codebase, `references/building-habits.md` | `DIAGNOSIS-<date>.md`; no code changes |
## A pick arrives
@@ -72,7 +83,7 @@ A card click is a send whose action carries the skill:
"reply": "Start Implement (/plan2code-3-implement) for specs/lunch-vote, right here in this session." }
```
`__launch` names no question; like `__stop` it is about the session. `spec` is the picker's selected spec dir — present only when the launched skill takes a spec and the person picked one; absent means "start from scratch".
`__launch` names no question; like `__stop` it is about the session. `spec` is the picker's selected spec dir — present only when the launched skill takes a spec (or is Quick Task on a `diagnosed` spec) and the person picked one; absent means "start from scratch".
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your own file-read tool instead.** Every Plan2Code skill below the dashboard ships `disable-model-invocation: true` on purpose — it exists to be read and followed inline, not launched as a sub-skill — and calling one through a skill-invocation tool errors out and strands the hand-off mid-launch.
@@ -101,6 +112,23 @@ If `skill` is not in the table below, say so on the page and stay the dashboard.
| plan2code-1b-revise-plan | revise-plan | | plan2code-4-finalize | finalize |
| plan2code-quick-task | quick-task | | plan2code-handoff | handoff |
| plan2code-git | git | | plan2code-changelog | changelog |
| plan2code-xray | xray | | plan2code-diagnose | diagnose |
## A pick-up arrives
A handoff chip's **Pick it up here** sends `__pickup` with `resume`, `skillFile` and `handoffFile` (and `fallback` when the named skill or spec is gone, or the Handoff skill wrote it). Read `console-launches.md` → A pick-up, then do as a pick does: `resume` first, then the skill's file, then the handoff.
## A delete arrives
The ✕ on a picker chip asks for that spec to go, after a two-step confirm on the page: `{ "i": "__delete", "type": "delete", "spec": "specs/<name>" }`. The page never deletes; you do, through the console's checked command, never your own `rm`:
1. `node "<D>/console.mjs" delete-spec --spec <action.spec>` from the project root. Exit 0 → `{ ok, removed }`. Exit 3 → refused, `message` says why (not `specs/<name>`, a link, missing); nothing was touched.
2. `node "<D>/console.mjs" open --resume <sid> --no-open --workflow dashboard`, which rescans `specs/`.
3. Post the menu again with `--wait`; the note says what was deleted, or why it was not. Stay the dashboard.
A `fixed` spec is deleted after one confirm on the page (its own Delete button, no name to type); your steps are the same.
A handoff's Delete is the same `__delete` with `handoff` (an id) instead of `spec`: run `node "<D>/console.mjs" delete-handoff --handoff <action.handoff>`, then steps 2 and 3.
## Coming back from another skill
+31
View File
@@ -0,0 +1,31 @@
# Building Habits
> Read by Quick Task, Implement, Implement + Review and Diagnose at the moments they name. Never invoked as a skill.
## Find the cause first
When a bug is reported or turns up, or a test fails unexpectedly:
1. Before changing any code, build a command that fails on this bug: a test, a script, a `curl`, a CLI run. Run it and see it fail the way the bug report says.
2. If no such command can be built (timing, one customer's data, production only), say so. List your best guesses, ranked, with the evidence for each, and let the person decide whether to fix on a guess.
3. Name the cause in one line, fix it, then run the reproduction again and see it pass.
4. Keep the reproduction: turn it into a regression test in the project's existing test runner. With no runner, describe it in the summary and discard it. Never add a test framework for it. When Test first also applies, the reproduction is that first failing test: write it once.
## Test first
Applies only when the phase's tasks carry `Test:` lines (the plan picked Test first), or the person said yes to "Write the test first?" in Quick Task. For each task:
1. Write the test at the task's named test spot (its `Test:` line, or the plan's Verify section).
2. Run it and see it fail for the right reason: the behaviour is missing, not a typo or an import error.
3. Write the code until the test passes. Keep the change to what the test asks for.
4. Never weaken, skip or delete a test to make it pass. If the test itself is wrong, say so and fix the test on its own.
## Pin behaviour first
For a task meant to change no behaviour (a restructure, a rename, a move):
1. Before touching the code, add or confirm tests that cover what the task touches.
2. Run them and see them pass.
3. Make the change.
4. Run the same tests, unchanged. They must pass. A test that needs editing means behaviour changed: stop and say so.
Adapted from Matt Pocock's `diagnose` and `tdd` skills and pstack's debugging playbook (both MIT).
+53 -19
View File
@@ -210,34 +210,68 @@ export function rel(root, p) {
return path.relative(root, p).split(path.sep).join("/") || ".";
}
/* ------------------------------------------------- planning-file patterns */
// The loop completion markers. The loop scans specs/ for them, so no planning
// file may contain one. The one copy every skill script checks against.
export const LOOP_TOKENS = /\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
// The metrics collector's own scrape patterns (plan2code-metrics/src/collector.ts).
export const SCRAPE = [
{ name: "overall confidence with %", re: /(?:Overall|Final|Total)?\s*\**[Cc]onfidence\**[:\s*]+(\d{1,3})%/ },
{ name: "confidence table cell", re: /[|]\s*[Cc]onfidence\s*[|]\s*(\d{1,3})/ },
{ name: "bare Requirements + number", re: /[Rr]equirements?[:\s|]+(\d{1,2})/ },
{ name: "bare Feasibility + number", re: /[Ff]easibility[:\s|]+(\d{1,2})/ },
{ name: "bare Integration + number", re: /[Ii]ntegration[:\s|]+(\d{1,2})/ },
{ name: "bare Risk + number", re: /[Rr]isk[:\s|]+(\d{1,2})/ },
];
/** Every SCRAPE pattern that matches `text`, as `<name>: "<match>"`. */
export function scrapeHits(text) {
const hits = [];
for (const s of SCRAPE) {
const m = text.match(s.re);
if (m) hits.push(`${s.name}: "${m[0].trim()}"`);
}
return hits;
}
/* --------------------------------------------------------- the web console */
// The web console ships beside these scripts in every installed skill
// (references/web-console/), and in this repo it sits at src/web-console/. Its
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
// metrics-bait scan, so the scripts import it rather than keep a second copy.
const CONSOLE_LIB_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
// scan.mjs is the one home of the spec-state classifier, and its settings.mjs
// of the pull-request host store, so the scripts import them rather than keep
// a second copy.
const CONSOLE_DIR_CANDIDATES = [
path.join(HERE, "..", "references", "web-console"), // installed skill
path.join(HERE, "..", "web-console"), // src/skill-scripts in the repo
];
let consoleLibPromise;
export function consoleLib() {
consoleLibPromise ||= (async () => {
for (const candidate of CONSOLE_LIB_CANDIDATES) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-lib-missing",
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
const consoleModules = new Map();
/** One of the web console's modules by file name ("scan.mjs"), imported once. */
export function consoleModule(file) {
if (!consoleModules.has(file)) {
consoleModules.set(
file,
(async () => {
const candidates = CONSOLE_DIR_CANDIDATES.map((dir) => path.join(dir, file));
for (const candidate of candidates) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-module-missing",
`The web console's ${file} is not beside this script (looked in ${candidates.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
);
})()
);
})();
return consoleLibPromise;
}
return consoleModules.get(file);
}
// The one read-only git reader (git-repo.mjs) ships beside lib.mjs, so the git
// The one read-only git reader (git-repo.mjs) ships beside scan.mjs, so the git
// skill's scripts read the repository with exactly the code the console uses.
const GIT_REPO_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "git-repo.mjs"), // installed skill
+154 -4
View File
@@ -14,7 +14,7 @@
import fs from "node:fs";
import path from "node:path";
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleLib, isoDate, phaseFiles } from "./common.mjs";
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleModule, isoDate, phaseFiles, LOOP_TOKENS, scrapeHits } from "./common.mjs";
const USAGE = `
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
@@ -32,6 +32,22 @@ specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
phases, and consistency checks. <spec> is specs/<name>, <name>, or a path
to its overview.md.
node specs.mjs check <spec> [--root <dir>]
Fail on a malformed spec: status's error and warn checks, plus every
checkbox under ## Tasks being a "- [ ] **Task N.M:**" line, no loop
completion token and no bare metric word (outside a METRICS_JSON
comment) in overview.md or a phase file. An indented " - Test:"
sub-bullet is fine. Exit 4 with the problems when any is an error.
node specs.mjs check-draft <file|spec> [--root <dir>]
Fail on a malformed PLAN-DRAFT (a path, or a spec's newest non-archived
draft): its **Status:** line; for a Complete draft, the sections
Document reads, a ### Phase heading in section 5 and a parseable
METRICS_JSON comment (warns when no phase names an FR- item); always no
loop completion token and no bare metric word (Plan's own Confidence
header line is allowed; a pathfinder-written draft has none). Exit 4 on
any error.
node specs.mjs metrics <spec> --step document|finalize [--set key=value ...]
The METRICS_JSON comment for that step, countable fields computed from
the files; judgment fields come from --set (numbers only).
@@ -484,7 +500,7 @@ function nextPhase(phases, groups, haveChecklist, leftovers = []) {
async function cmdList(args) {
const root = path.resolve(args.root || ".");
const { scanProject } = await consoleLib();
const { scanProject } = await consoleModule("scan.mjs");
const scan = scanProject(root);
const specs = scan.specs.map((s) => {
const dir = path.join(root, s.dir);
@@ -752,10 +768,144 @@ async function cmdArchive(args) {
});
}
/* ---------------------------------------------------------------- checks */
// METRICS_JSON comments are the one place a metric word may sit beside a number.
const METRICS_COMMENT_RE = /<!--\s*METRICS_JSON[\s\S]*?-->/g;
// The collector's confidence patterns. Plan's draft header carries a
// "**Confidence:** NN%" line on purpose (the collector's fallback when
// METRICS_JSON is missing), so a Plan-written draft is exempt from these two.
const CONFIDENCE_HITS = ["overall confidence with %", "confidence table cell"];
function proseChecks(text, file, add, { allowConfidence = false } = {}) {
const m = text.match(LOOP_TOKENS);
if (m) add("error", file, "loop-token", `contains the loop completion token ${m[0]} (the loop scans specs/ for these)`);
for (const h of scrapeHits(text.replace(METRICS_COMMENT_RE, ""))) {
if (allowConfidence && CONFIDENCE_HITS.some((name) => h.startsWith(`${name}:`))) continue;
add("error", file, "metric-word", `metrics-scraper bait (${h}); hyphenate the label or reword`);
}
}
// The lint-style report: ok with the problems when nothing is an error, else
// the failure shape (error, message, next, the same lines on stderr), written
// here rather than through fail(), which would drop the problems list.
function checkReport(command, base, problems) {
const errors = problems.filter((p) => p.level === "error").length;
const report = { ...base, errors, warnings: problems.length - errors, problems };
if (!errors) {
out({ ok: true, ...report });
return;
}
const message = `${command} found ${errors} error${errors === 1 ? "" : "s"}.`;
const next = `Fix each error in problems, then rerun ${command}.`;
out({ ok: false, error: `${command}-failed`, message, next, ...report });
process.stderr.write(`error: ${message}\nnext: ${next}\n`);
process.exitCode = EXIT.INVALID;
}
async function cmdCheck(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1], { allowArchived: true });
const problems = [];
const add = (level, file, code, message) => problems.push({ level, file, code, message });
const at = (name) => `${spec.rel}/${name}`;
const files = phaseFiles(spec.dir);
// status's own checks, each pinned to the phase file it opens with (by its
// real name: status says phase-N.md even for a phase-1-setup.md), else
// overview.md (a missing file or checklist row is fixed in the overview).
for (const c of specStatus(spec).checks) {
if (c.level !== "error" && c.level !== "warn") continue;
const named = c.code !== "missing-checklist-row" && c.message.match(/^phase-(\d+)/i);
add(c.level, at(named && files.has(Number(named[1])) ? files.get(Number(named[1])) : "overview.md"), c.code, c.message);
}
const names = [...(fs.existsSync(path.join(spec.dir, "overview.md")) ? ["overview.md"] : []), ...[...files.keys()].sort((a, b) => a - b).map((n) => files.get(n))];
for (const name of names) {
const text = readText(path.join(spec.dir, name)) || "";
if (name !== "overview.md") {
const tasks = section(text, /^#{1,6}\s+Tasks\b/i);
for (const [i, line] of (tasks ? tasks.lines : []).entries()) {
if (CHECKBOX_RE.test(line) && !TASK_RE.test(line)) {
add("error", at(name), "bad-task-line", `${name}:${tasks.start + 2 + i} is a checkbox under Tasks that is not a task line ("- [ ] **Task N.M:**"): ${line.trim().slice(0, 120)}`);
}
}
}
proseChecks(text, at(name), add);
}
checkReport("check", { spec: spec.rel, checked: names.map(at) }, problems);
}
const DRAFT_STATUSES = ["Draft", "Phase 3 Complete - Resume at Phase 4", "Escalated from Quick Task - Resume at Phase 2", "Complete"];
// The headings Document reads out of a Complete draft.
const DRAFT_SECTIONS = [
{ name: "## 1. Executive Summary", re: /^##\s+1\.\s+Executive Summary\b/im },
{ name: "## 2. Requirements", re: /^##\s+2\.\s+Requirements\b/im },
{ name: "### 2.1", re: /^###\s+2\.1\b/m },
{ name: "### 2.4", re: /^###\s+2\.4\b/m },
{ name: "## 3. Tech Stack", re: /^##\s+3\.\s+Tech Stack\b/im },
{ name: "## 4. Architecture", re: /^##\s+4\.\s+Architecture\b/im },
{ name: "## 5. Implementation Phases", re: /^##\s+5\.\s+Implementation Phases\b/im },
{ name: "## 6. Risks and Mitigations", re: /^##\s+6\.\s+Risks and Mitigations\b/im },
{ name: "## 7. Success Criteria", re: /^##\s+7\.\s+Success Criteria\b/im },
{ name: "## 9. Assumptions", re: /^##\s+9\.\s+Assumptions\b/im },
];
/** A PLAN-DRAFT path, or a spec whose newest non-archived draft is used. */
function resolveDraft(root, arg) {
if (arg && /\.md$/i.test(arg) && !/\/overview\.md$/i.test(arg.replace(/\\/g, "/"))) {
const file = path.resolve(root, arg);
if (!fs.existsSync(file)) fail(EXIT.NOT_FOUND, "draft-not-found", `No file at ${rel(root, file)}.`, "Pass a PLAN-DRAFT-*.md path, or the spec folder to check its newest draft.");
return file;
}
const spec = resolveSpec(root, arg, { allowArchived: true });
const live = planDrafts(spec.dir).filter((d) => !d.archived);
if (!live.length) fail(EXIT.NOT_FOUND, "no-draft", `${spec.rel} has no PLAN-DRAFT-*.md.`, "Write the PLAN-DRAFT first (Plan's Phase 7), or pass its path.");
return path.join(spec.dir, live.at(-1).file);
}
async function cmdCheckDraft(args) {
const root = path.resolve(args.root || ".");
const file = resolveDraft(root, args._[1]);
const shown = rel(root, file);
const text = readText(file) || "";
const problems = [];
const add = (level, f, code, message) => problems.push({ level, file: f, code, message });
const status = statusOf(text);
const value = status === null ? null : status.trim();
if (value === null) add("error", shown, "bad-status", "has no **Status:** line");
else if (!DRAFT_STATUSES.includes(value)) add("error", shown, "bad-status", `**Status:** "${value}" is not one of ${DRAFT_STATUSES.join(" | ")}`);
// Only a Complete draft is read by Document; the others (a pathfinder draft
// at Resume at Phase 4 has placeholder sections by design) get the light check.
if (value === "Complete") {
for (const s of DRAFT_SECTIONS) if (!s.re.test(text)) add("error", shown, "missing-section", `has no ${s.name} heading (Document reads it)`);
const phasesSec = section(text, /^##\s+5\.\s+Implementation Phases\b/i);
if (phasesSec && !phasesSec.lines.some((l) => /^###\s+Phase\b/i.test(l))) add("error", shown, "no-phases", "section 5 has no ### Phase heading");
// Whitespace after METRICS_JSON, as the collector's own pattern requires.
const metrics = text.match(/<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/);
let parsed = false;
if (metrics) {
try {
JSON.parse(metrics[1]);
parsed = true;
} catch {}
}
if (!parsed) add("error", shown, "no-metrics", metrics ? "the METRICS_JSON comment does not parse as JSON" : "has no <!-- METRICS_JSON {...} --> comment (Plan's Phase 7 writes it)");
const frSec = section(text, /^###\s+2\.1\b/);
if (frSec && phasesSec && /\bFR-\d+/.test(frSec.lines.join("\n")) && !/\bFR-\d+/.test(phasesSec.lines.join("\n"))) {
add("warn", shown, "untraced-requirements", "section 2.1 lists FR- items but no phase in section 5 names one");
}
}
// A pathfinder-written draft (no METRICS_JSON yet) carries no confidence
// line, as pathfinder.mjs lint already holds it to.
const byPathfinder = /plan2code-0-pathfinder/.test(text) && !/METRICS_JSON/.test(text);
proseChecks(text, shown, add, { allowConfidence: !byPathfinder });
checkReport("check-draft", { checked: [shown], status: value }, problems);
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "step", "phase", "to", "task"], lists: ["set"] });
const cmd = args._[0];
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, tick: cmdTick, archive: cmdArchive };
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, metrics, mark, tick, archive. Run with --help.");
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, tick: cmdTick, archive: cmdArchive, check: cmdCheck, "check-draft": cmdCheckDraft };
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, check, check-draft, metrics, mark, tick, archive. Run with --help.");
await commands[cmd](args);
});
+7 -1
View File
@@ -51,6 +51,9 @@ for whichever comes first:
session (files created or modified by the phase or the quick task, plus the
tests and docs changed for it). Do not ask about scope. Use overview.md and
the phase file for spec compliance; they do not widen the scope.
- **The helper rule still applies:** a fresh helper runs the analysis when
available, you verify every finding, and the report carries its Reviewed by
line.
- **No commit instructions and no next-conversation routing** mid-review. The
way back out carries both.
- The page takes the whole report, so the "top 10 of 15+" rule does not apply,
@@ -117,14 +120,17 @@ review set it to its own stage):
"body": "Reviewed and ready for sign-off. The review found 3 issues: 2 fixed, 1 still open in the Review findings tab. The report is updated.",
"verdicts": [
{ "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" },
"thread": [{ "who": "agent", "text": "Review done: 2 of 3 findings fixed; the rest is written up in the findings tab." }]
}]
}
```
Review Mode's own closing gate ("Reply approved to commit") is this card:
`show` runs as `notes/implement.md` → Show me it working says, then reopens
this card without it. Review Mode's own closing gate ("Reply approved to commit") is this card:
approving the phase now covers the fixes too, so there is no separate "Check
the fixes" step. On approval, continue at `notes/implement.md` → After
approval: the finish.
+46
View File
@@ -0,0 +1,46 @@
// Plan2Code Web Console - the `chat` command: hand over Quick questions now, never waiting.
import path from "node:path";
import { readJson } from "./files.mjs";
import { healthOk, listHandles, pidAlive, terminalLine } from "./sessions.mjs";
import { chatReplyLines, collectChat, deliverableChat } from "./inbox.mjs";
import { pendingWorkspaceChanges } from "./workspace.mjs";
import { changeLine } from "./public/workspace.js";
import { withSubagents, advanceSubagents, serverGone, advanceCursor, advanceWorkspace } from "./cmd-post-wait.mjs";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
let print, mustSession, sessionProject;
export function useCli(cli) {
({ print, mustSession, sessionProject } = cli);
}
/* ----------------------------------------------------------------- chat */
// The instant check a build makes between tasks. Never sleeps, and never
// touches result.json: card sends stay with `wait`.
export async function cmdChat() {
const dir = mustSession();
const sid = path.basename(dir);
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === sid);
if (!handle || !pidAlive(handle.pid) || !(await healthOk(handle))) {
print(serverGone(sid));
process.exitCode = 20;
return;
}
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
const changes = pendingWorkspaceChanges(dir);
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
if (!entries.length && !changes.length && !subCursor) {
print({ chat: [] });
process.exitCode = 10;
return;
}
print({ ...out, terminalLine: terminalLine(handle.url) });
advanceCursor(dir, entries);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
+153
View File
@@ -0,0 +1,153 @@
// Plan2Code Web Console - the `help` command: the CLI's usage and the contract's topic files.
import fs from "node:fs";
import path from "node:path";
import { HERE } from "./files.mjs";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
let args, print, die;
export function useCli(cli) {
({ args, print, die } = cli);
}
/* ----------------------------------------------------------------- help */
export function cmdHelp() {
const topic = args._[0];
if (topic !== undefined) return helpTopic(String(topic));
process.stdout.write(`console.mjs — the Plan2Code web console. A detached server, a loopback
port, and the filesystem as transport; this CLI is the whole agent surface.
open [--file <payload.json>] [--workflow <w>] [--title "<t>"] [--spec <dir>]
[--session|--resume <sid>] [--no-open] [--idle-ms <ms>]
Start or resume a session and its server. Prints { ok, sid, session,
url, terminalLine }, plus swept { sessions, scratch, handoffs } when
old sessions, scratch files or handoffs were removed. Run it FIRST, before
reading anything: the page shows a starting screen until your
first post. --file is optional, and --title defaults to the
project's folder name. Also prints workspace: { folders: [{ name,
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
May also print subagents: { state, revision, max, instruction } and
a reply holding only its "Subagents: ..." lines, when a standing
instruction (the page's Subagents switch) is owed to you.
post --session <sid> --file <patch.json | -> [--wait <N>]
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. --wait <N>
then waits up to N seconds in the same command (two JSON lines;
the exit code is the wait's). The patch may carry settle: true
(or a list of item ids) to mark the latest send's cards answered
with what was sent; doc blocks may carry file: "<path>" (and
select: "tasks"), read from the project, and a doc refresh: true
re-reads them. A doc's version moves up by itself. A patch may
carry run: { event, id, tasks? } (session meter points) and folderIssue:
{ name, reason, hint? } (a workspace folder you could not read);
both go to the ledger, never into the state. A patch may also
carry helpers: [{ id, title, ask, state, result? }] or one
{ id: "alone", alone: true }, merged by id, for the Subagents tab
(help subagents).
wait --session <sid> [--seconds <N>]
A bounded wait slice, sized below your shell timeout. Exit 0 = the
result is on stdout, 10 = still waiting ("Waiting on your answer
in the web console"; call again), 20 = server gone (open --resume
<sid>), 30 = cancelled. Exits 0 and 10 carry terminalLine.
Exit 0 may carry "chat" (Quick questions); with no card send it
is type: "chat" and actions is empty. Exit 0 may also carry
"workspace" (changes since you last heard, each once, with a
"Workspace: ..." line in reply); exit 10 counts them as
pendingWorkspace, and a change alone never ends a slice.
Exit 0 may also carry "subagents" (a console setting, not typed
by the person, with its "Subagents: ..." lines last in reply); a
setting change alone never ends a slice either. A hop
(__launch, __dashboard, __commit) carries resume, the exact
open --resume command, and skillFile when installed. Collecting
a send sets the page to working; a wait with a question open
hands the turn back.
chat --session <sid>
Collect Quick questions, workspace changes and a Subagents
setting change now, never waiting, never touching card sends.
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
10 = none, 20 = server gone.
terminalLine is "→ Look at the web console: <url>": end your terminal
messages with it during a console session.
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
Copy a cited note attachment into specs/<idea>/attachments/. Prints
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
missing. Paste link as it is.
forget --spec specs/<idea>
Drop the workspace folders remembered for that spec, in this
folder (Finalize, after archiving it). Prints { ok, spec, forgot };
forgot is false when nothing was saved. Exit 2 = bad usage.
delete-spec --spec specs/<name>
Delete that spec folder for good (the dashboard's Delete button, a
__delete action). Only an existing specs/<name> folder inside this
worktree: never a link, never deeper, never specs--completed/.
Prints { ok, removed }; exit 2 = bad usage, 3 = refused, with
{ ok: false, message } saying why. Nothing is touched on a refusal.
handoff new --workflow <w> --skill <s> [--spec specs/<name>] [--title "<t>"] [--from-stop]
Claim a handoff for this checkout in ~/.plan2code/handoffs/ (Stop
with a handoff, the Handoff skill). Writes only <id>.json; you write
the document at path. Prints { ok, id, path, meta }; exit 2 = bad
usage, 3 = a bad value, with { ok: false, message } saying why.
delete-handoff --handoff <id>
Delete that handoff for good (a Handoff chip's Delete, a __delete
action): <id>.md and <id>.json, only in ~/.plan2code/handoffs/,
never a link. Prints { ok, removed }; exit 2 = bad usage, 3 =
refused, with { ok: false, message } saying why. Nothing is touched
on a refusal.
status [--session <sid>] [--all]
One session, or (--all) every session on this machine, every project.
stop --session <sid> | --all
Shut a session's server down. Always post finish first.
workflows: dashboard · init · init-update · pathfinder · quick-task · plan ·
revise-plan · document · implement · implement-review · review ·
finalize · handoff · git · changelog · xray · diagnose
A session handed to you by the dashboard (a --session id): resume it with
"open --resume <sid> --no-open --workflow <yours>" (the resume it carries) -- never a
fresh "open", which would strand the page the person is watching.
The contract is console.md beside this file, read once; the rest is
read when its moment comes. help <topic> prints one; help topics lists
them. Build sessions (implement, implement-review, quick-task) also read
building.md.
`);
}
// The contract's topic files, by the name console.md's index gives them.
// Printing one saves an agent the path hunt: it already runs this CLI.
export const HELP_TOPICS = {
console: "console.md",
building: "building.md",
"building-review": "building-review.md",
finish: "console-finish.md",
stop: "console-stop.md",
attachments: "console-attachments.md",
chat: "console-chat.md",
workspace: "console-workspace.md",
subagents: "console-subagents.md",
launches: "console-launches.md",
dashboard: "console-launches.md",
meter: "console-meter.md",
trouble: "console-trouble.md",
};
for (const f of fs.existsSync(path.join(HERE, "notes")) ? fs.readdirSync(path.join(HERE, "notes")) : []) {
if (f.endsWith(".md")) HELP_TOPICS[f.slice(0, -3)] ??= `notes/${f}`;
}
HELP_TOPICS["init-update"] ??= HELP_TOPICS.init;
HELP_TOPICS["implement-review"] ??= HELP_TOPICS.implement;
function helpTopic(topic) {
const names = Object.keys(HELP_TOPICS).sort();
if (topic === "topics") {
print({ topics: Object.fromEntries(names.map((n) => [n, HELP_TOPICS[n]])) });
return;
}
const file = Object.hasOwn(HELP_TOPICS, topic) ? HELP_TOPICS[topic] : null;
if (!file) die(`no help topic "${topic}". Topics: ${names.join(", ")}`, 2);
process.stdout.write(fs.readFileSync(path.join(HERE, file), "utf8"));
}
+650
View File
@@ -0,0 +1,650 @@
// Plan2Code Web Console - the `open` command: start or resume a session, its server and the browser.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { HERE, HOME_DIR, SESSIONS_DIR, appendEvent, ensureDir, nowIso, readJson, updateState } from "./files.mjs";
import {
appendLedger,
bindLoopback,
handOff,
handleFile,
healthOk,
listHandles,
newSessionId,
newToken,
nextLaunchId,
pidAlive,
readLedger,
reapHandles,
remoteWarning,
removeScratch,
removeSessions,
repoRoots,
SESSION_MAX_AGE_MS,
sessionDir,
staleScratch,
staleSessions,
sweepUploads,
terminalLine,
UPLOAD_MAX_AGE_MS,
} from "./sessions.mjs";
import { scanProject } from "./scan.mjs";
import {
applyPatch,
blankState,
isOpen,
switchWorkflow,
resolveDocFiles,
resolveDocImages,
validate,
} from "./patches.mjs";
import {
initialWorkspace,
readWorkspace,
rememberedWorkspace,
workspaceForAgent,
writeWorkspaceCursor,
} from "./workspace.mjs";
import { readPrHosts, resetSubagentCursor } from "./settings.mjs";
import { snapshot } from "./git-repo.mjs";
import { handoffsDir, listHandoffs, removeHandoffs, staleHandoffs } from "./handoffs.mjs";
import {
readPatch,
failValidation,
liftReread,
gitBlock,
ledgerFromPost,
awaitSubagentSync,
withSubagents,
advanceSubagents,
} from "./cmd-post-wait.mjs";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
let args, print, die;
export function useCli(cli) {
({ args, print, die } = cli);
}
// PLAN2CODE_CONSOLE_TRACE=1 prints where the time goes, to stderr: the
// start path is what stands between someone and their first look at the page,
// and it is only worth optimising with numbers in hand.
const TRACE = Boolean(process.env.PLAN2CODE_CONSOLE_TRACE);
function trace(what) {
if (TRACE) process.stderr.write(`trace ${Math.round(performance.now())}ms ${what}\n`);
}
/* ----------------------------------------------------------------- open */
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written by `open` alone, which starts every session: a
// `wait` or a `post` every few seconds need not rewrite it each time.
function leavePointer() {
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
}
export async function cmdOpen() {
trace("open: start");
leavePointer();
const { project, worktree, branch } = repoRoots();
reapHandles(project);
trace("open: project found");
let sid = args.resume || args.session;
let dir;
let state;
// A new skill run for the meter: a fresh open, or a resume into another workflow.
let launched = true;
// Everything `open` does to a stored state, as a step it can take twice:
// once now, on the read below, so a bad payload is refused before anything
// starts, and again on a fresh read under the state lock when it writes, so
// a send the person made in between is kept rather than written over.
let reshape = (s) => s;
if (sid) {
sid = path.basename(sid);
dir = sessionDir(sid);
if (!fs.existsSync(dir)) die(`no session "${sid}" to resume`, 1);
state = readJson(path.join(dir, "state.json"));
if (!state) die(`session "${sid}" has no state`, 1);
// A resume can also be a hand-off: the dashboard launches another skill
// into its own session, and the first thing that skill needs is for the
// page to stop being a dashboard. Letting the flags restate these fields
// on resume means one command both reuses the server and turns the page,
// rather than a resume plus a whole extra post.
const switching = args.workflow && args.workflow !== state.workflow;
launched = Boolean(switching);
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. Git counts as a launch from anywhere:
// Commit it now on a finished screen and Changelog's "Commit this now?"
// both stand in for its dashboard card, and a finish left
// behind would keep the page on the old ending above the new questions
// (or the new board). A hop also drops the last run's state.git, since
// switchWorkflow() starts from a blank state.
// A skill run inline from another (a quick task's review) never switches
// through here, so it keeps the page.
const hop =
switching &&
(args.workflow === "dashboard" ||
state.workflow === "dashboard" ||
args.workflow === "git");
if (hop) fs.rmSync(path.join(dir, "draft.json"), { force: true });
reshape = (s) => {
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (s.finish && /^\s*paused\b/i.test(String(s.finish.headline || ""))) {
delete s.finish;
// A new agent picking the session up: its own working turn, timed
// from now, not the paused run's last status.
s.agent = { status: "working", since: nowIso() };
// The old run's warning about what a stop would lose is about its
// unsaved work; the new run posts its own when it has some.
delete s.stopWarning;
// So is its count: the open questions it counted are dropped below,
// and the page falls back to its own tally until the new run posts.
s.headline = { stage: "", cleared: 0, total: 0, confidence: "", note: "" };
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
s.items = (s.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(s.items.map((i) => i.topic));
s.topics = (s.topics || []).filter((t) => liveTopics.has(t.id));
}
if (hop) {
s = switchWorkflow(s, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
} else if (switching) s.workflow = args.workflow;
if (args.title) s.title = args.title;
if (args.spec) s.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete s.wake;
return s;
};
} else {
sid = newSessionId();
// Named, not made: the folder is created once --file has passed, so a
// rejected first payload leaves no empty session behind for nothing to sweep.
dir = sessionDir(sid);
state = blankState({
sid,
project,
workflow: args.workflow,
// Until the agent knows what the session is about, the folder it runs
// in is the honest name, and it lets `open` go before any thinking.
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
// Only a freshly opened dashboard plays Planny's wake-up.
if (args.workflow === "dashboard") state.wake = true;
}
// A first payload's meter and folder reports, as `post` takes them: checked
// now, before anything is written, and appended once the launch is.
let openRun;
let openIssue;
let openReread;
let patch = null;
if (args.file) {
patch = readPatch(args.file);
if (!patch) die(`could not read --file ${args.file} as one JSON object`, 2);
({ run: openRun, folderIssue: openIssue } = patch);
delete patch.run;
delete patch.folderIssue;
openReread = liftReread(patch, args.workflow || state.workflow);
}
const base = reshape;
if (patch) {
// Against the page as this open leaves it (a hop starts blank), so a
// refresh never re-reads the last skill's files into the new page.
try {
patch = resolveDocFiles(patch, base(structuredClone(state)), worktree);
patch = resolveDocImages(patch, base(structuredClone(state)), dir);
} catch (e) {
die(e.message, 3);
}
}
const settle = (s) => {
s = base(s);
// On every open, so a resume from another worktree refreshes both.
s.worktree = worktree;
s.branch = branch;
return s;
};
reshape = (s) => (patch ? applyPatch(settle(s), patch) : settle(s));
state = settle(state);
if (patch) {
ledgerFromPost(dir, openRun, openIssue, state.workflow);
try {
state = applyPatch(state, patch);
} catch (e) {
die(e.message, 3);
}
const problems = validate(state);
if (problems.length) return failValidation(problems);
}
ensureDir(dir);
// A fresh session needs a fresh server, and a server is a whole Node boot:
// the slowest thing `open` does, bar the browser. Start both now, before
// the scan and the state write, so their start-up runs alongside them
// instead of after. The server does look at the state as it boots, and on
// a fresh session finds none yet: it takes the worktree from its command
// line, not from the state, and picks the state up on its first request or
// poll tick. No page can reach it before it is listening, and the state is
// on disk long before a browser gets there.
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null;
// A live pid gets a second, longer look before it is given up on, as `stop`
// gives one: a server busy right after a post can miss the first, and a
// second server for the same session strands the page on the first.
const reusable =
existing && pidAlive(existing.pid)
? healthOk(existing).then((ok) => ok || healthOk(existing, 5000))
: Promise.resolve(false);
let boot = null;
if (!existing) boot = await startServer(project, worktree, sid, dir);
// The dashboard's spec picker reads its inventory straight off the session
// state, so the scan belongs to `open` rather than to the agent: filesystem
// facts, recomputed every time the session becomes (or stays) a dashboard,
// never something a model has to remember to fetch. Rooted at the worktree's
// own top level: `project` is the common-dir key so linked worktrees share
// sessions, but each shows the specs on its own disk.
const scan = state.workflow === "dashboard" ? scanProject(worktree) : null;
// This checkout's unused handoffs live outside every repo (handoffs.mjs), so
// they join the scan here and not in scanProject(), which also serves
// `specs.mjs list`. handoffsDir rides along so the page never guesses it.
if (scan) {
scan.handoffs = listHandoffs(worktree);
scan.handoffsDir = handoffsDir();
}
// The git board's data, the same way: the console's own read-only snapshot
// (git-repo.mjs), taken before the lock so no git process runs under it.
const gitSnap = state.workflow === "git" ? snapshot(worktree, { prHosts: readPrHosts() }) : null;
// Under the state lock, which a send on the page takes too: the result and
// the state are read fresh here and the state is rebuilt from that read, so
// nothing the person sent since the read above is lost or stamped over.
let carried = false;
let written;
try {
written = updateState(dir, (fresh) => {
const next = fresh ? reshape(fresh) : state;
if (scan) next.scan = scan;
// A launch or hop starts the board fresh; a plain resume (a server
// restart) keeps the last word on whether a Refresh failed.
if (gitSnap) next.git = launched ? gitBlock(gitSnap, openReread ?? { refreshFailed: false }) : gitBlock(gitSnap, openReread, fresh?.git);
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
carried = Boolean(waiting && !waiting.consumedAt);
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) next.phase = "collecting";
return next;
});
} catch (e) {
written = { error: e.message };
}
if (!written || written.error) {
// A server just started for this state would only serve a page that never starts.
if (boot) boot.kill();
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
// A new agent conversation has been told nothing yet (FR-6).
try {
resetSubagentCursor(dir);
} catch {}
trace("open: state written");
// Dashboard launches are recorded too (they score nothing), so the folder
// issues the page shows reset with every skill run. Never fatal: the meter
// is advice, and the page must not wait on it.
try {
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
} catch {}
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
// Month-old sessions and scratch files: listed before the print so the
// agent can see what went, removed after it so the page waits for nothing.
// Nothing about this reaches the page.
const sweptSessions = staleSessions(SESSIONS_DIR, Date.now(), SESSION_MAX_AGE_MS, sid);
const sweptScratch = staleScratch(HOME_DIR, Date.now(), SESSION_MAX_AGE_MS);
const sweptHandoffs = staleHandoffs(Date.now(), SESSION_MAX_AGE_MS);
const swept =
sweptSessions.length || sweptScratch.length || sweptHandoffs.length
? { swept: { sessions: sweptSessions, scratch: sweptScratch, handoffs: sweptHandoffs } }
: {};
const sweep = () => {
sweepUploads(SESSIONS_DIR, Date.now(), UPLOAD_MAX_AGE_MS, sid).catch(() => {});
removeSessions(SESSIONS_DIR, sweptSessions).catch(() => {});
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
removeHandoffs(sweptHandoffs).catch(() => {});
};
// A standing instruction the new agent is owed, as `subagents` and a
// `reply` holding only its lines; neither key when nothing is owed.
const subagentsOwed = () => {
awaitSubagentSync(dir, state.workflow);
const [out, cursor] = withSubagents(dir, { reply: "" });
return [out.subagents ? out : {}, cursor];
};
// Reuse a live server if one is already serving this session.
if (existing && (await reusable)) {
if (!args["no-open"]) openBrowser(existing.url);
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
session: dir,
url: existing.url,
reused: true,
pendingResult: carried,
terminalLine: terminalLine(existing.url),
workspace,
...owed,
...swept,
...remoteWarning(),
});
advanceSubagents(dir, subCursor);
sweep();
return;
}
// A handle whose pid is alive but is not ours (the pid was reused) leaves
// this for last: nothing could be started until that was known.
let started = boot || (await startServer(project, worktree, sid, dir));
let handle = await awaitHandle(started);
if (!handle && started.handoff) {
// The handover went wrong somewhere (a platform that will not pass the
// socket, a server that died taking it). Once more the old way, where
// the server binds its own port: slower, and certain.
started.kill();
started = await startServer(project, worktree, sid, dir, { handoff: false });
handle = await awaitHandle(started);
}
if (!handle) {
const log = tail(path.join(dir, "server.log"), 12);
die(`the console server did not start within 8s.\n${log}`, 1);
}
trace("open: server listening");
// Unref'd, or the cap itself would hold the process open for its full span.
await Promise.race([started.released, new Promise((r) => setTimeout(r, 2000).unref())]);
trace("open: socket handed over");
// The early tab went to the port `open` bound. If the server ended up
// anywhere else, that tab is a dead end, so send the browser to the real one.
if (!args["no-open"] && handle.url !== started.opened) openBrowser(handle.url);
const remote = remoteWarning();
const notes = [];
if (remote.note) notes.push(remote.note);
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
session: dir,
url: handle.url,
port: handle.port,
pid: handle.pid,
pendingResult: carried,
terminalLine: terminalLine(handle.url),
workspace,
...owed,
...swept,
...(remote.remote ? { remote: remote.remote } : {}),
...(notes.length ? { note: notes.join(" ") } : {}),
});
advanceSubagents(dir, subCursor);
// After the print, never before it: the page and the link wait for nothing.
sweep();
}
/**
* The workspace as `open` hands it to the agent, and the cursor seeded to
* match: the agent now has the whole list, so no change up to here is owed.
* Read-only on workspace.json, which only the server writes; on a fresh
* session the server has not made it yet, so what was remembered for this
* folder and spec stands in, the same list the server is about to make.
*/
function workspaceOnOpen(dir, worktree, specDir) {
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
try {
writeWorkspaceCursor(dir, ws.version || 0);
} catch {}
return workspaceForAgent({ ...ws, missing });
}
function isFolder(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
/**
* Start a detached server for the session, and the browser with it.
*
* The browser is the slowest thing in the whole start: from `start <url>` to
* its first request is most of a second on Windows, far longer than the
* server takes to boot. So the port is bound HERE, the link exists while the
* server is still booting, and the browser is sent at once. The bound socket
* is then handed to the server over an IPC channel; a request that arrives
* before the handover waits in the socket's queue, and one this process
* happened to accept is passed across as a socket of its own. Nothing the
* browser sends is refused or lost on the way.
*
* The order is timed. The server is spawned first, because its boot is the
* longest step the agent waits on. The bind comes next and overlaps that
* boot: a process's first listen() blocks for ~50ms on Windows while the
* socket stack loads, which is time the server spends booting anyway.
*/
async function startServer(project, worktree, sid, dir, { handoff = true } = {}) {
const token = newToken();
const handlePath = handleFile(project, sid);
ensureDir(path.dirname(handlePath));
fs.rmSync(handlePath, { force: true });
const logFd = fs.openSync(path.join(dir, "server.log"), "a");
const child = spawn(
process.execPath,
[
path.join(HERE, "server.mjs"),
// Always `--flag=value`, never two words: a base64url token can start
// with "--", and parseArgs would read it as the next flag and leave the
// server with `token: true`. The paths get the same form for the same reason.
`--session=${dir}`,
`--token=${token}`,
`--project=${project}`,
// The checkout the session runs in, which the state does not hold yet
// on a fresh open. See WORKTREE in server.mjs.
`--worktree=${worktree}`,
...(handoff ? ["--handoff"] : []),
...(args["idle-ms"] ? [`--idle-ms=${args["idle-ms"]}`] : []),
],
{
// Detached, because harness-managed background tasks get killed at
// assorted timeouts and on compaction, which would take the human's
// half-finished answers with them. Detached processes are immune.
detached: true,
// Redirecting stdio to a file is what lets the child outlive us. The
// IPC channel is only for the handover, and is closed straight after.
stdio: ["ignore", logFd, logFd, ...(handoff ? ["ipc"] : [])],
// windowsHide defaults to FALSE, and `detached` on Windows gives the
// child its own console window which "once enabled, cannot be disabled".
// Omit this and every handoff flashes a black box at the user.
windowsHide: true,
}
);
fs.closeSync(logFd);
let exited = false;
child.on("exit", () => (exited = true));
child.on("error", () => (exited = true));
trace("open: server spawned");
let opened = null;
let released = Promise.resolve();
if (handoff) {
const pre = await bindLoopback();
trace("open: port bound");
// No socket to give (the bind failed): the server binds its own, and the
// channel is let go once it has.
released = handOff(child, pre);
if (pre && !args["no-open"]) opened = `http://127.0.0.1:${pre.address().port}/s/${token}/`;
} else child.unref();
// Each spawn blocks for a moment (tens of ms for cmd.exe on Windows), so
// the browser's comes after the server's: the server's boot is what the
// agent waits on, and the browser's lead is most of a second regardless.
if (opened) {
openBrowser(opened);
trace("open: browser sent");
}
return {
handlePath,
handoff,
opened,
released,
dead: () => exited,
kill: () => {
try {
child.kill();
} catch {}
},
};
}
// Learn the port by waiting for the handle file, not by parsing stdout:
// stdout went to the log file, and the file handshake is race-free and is
// the same code path the reap sweep uses. Checked every 10ms: the file is
// tiny, and a coarse tick here is dead time added to every first paint.
// Null when the server died first, or never showed up.
async function awaitHandle(started) {
const deadline = Date.now() + 8000;
while (Date.now() < deadline) {
const handle = readJson(started.handlePath);
if (handle && handle.url) return handle;
if (started.dead()) return null;
await new Promise((r) => setTimeout(r, 10));
}
return null;
}
function tail(file, lines) {
try {
return fs.readFileSync(file, "utf8").split("\n").slice(-lines).join("\n");
} catch {
return "(no server log)";
}
}
/**
* Best-effort, never fatal. If we cannot open a browser we still printed the URL,
* and the URL is the primary channel.
*/
function openBrowser(url) {
try {
if (process.env.NO_BROWSER || process.env.PLAN2CODE_NO_BROWSER) return;
// Do not try from a place where there is no browser to open.
if (process.env.SSH_CONNECTION || process.env.REMOTE_CONTAINERS) return;
// A browser of their choosing: a command line, run through the shell,
// with the link appended. The token is base64url, so the quoted link
// carries nothing a shell would read.
const custom = process.env.PLAN2CODE_BROWSER;
if (custom) {
spawn(`${custom} "${url}"`, { shell: true, detached: true, stdio: "ignore", windowsHide: true }).unref();
return;
}
const plat = process.platform;
if (plat === "win32") {
// The empty "" is the mandatory window-title argument: omit it and
// `start` treats a quoted URL as the title and opens nothing.
spawn(process.env.COMSPEC || "cmd.exe", ["/d", "/s", "/c", "start", '""', `"${url}"`], {
windowsVerbatimArguments: true,
detached: true,
stdio: "ignore",
windowsHide: true,
}).unref();
return;
}
if (plat === "darwin") {
spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
return;
}
// Linux and friends. WSL first: xdg-open there either is absent or opens a
// Linux browser that cannot reach the Windows host.
if (isWsl()) {
const exe = which("wslview") ? "wslview" : "powershell.exe";
const argsFor = exe === "wslview" ? [url] : ["-NoProfile", "-Command", "Start-Process", `"${url}"`];
spawn(exe, argsFor, { detached: true, stdio: "ignore" }).unref();
return;
}
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return; // headless
spawn(process.env.BROWSER || "xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
} catch {
/* never fatal */
}
}
function isWsl() {
if (process.platform !== "linux") return false;
try {
return /microsoft/i.test(fs.readFileSync("/proc/version", "utf8"));
} catch {
return false;
}
}
function which(bin) {
const dirs = (process.env.PATH || "").split(path.delimiter);
return dirs.some((d) => {
try {
fs.accessSync(path.join(d, bin), fs.constants.X_OK);
return true;
} catch {
return false;
}
});
}
+676
View File
@@ -0,0 +1,676 @@
// Plan2Code Web Console - `post` and `wait`: publish a patch, then collect what the person sent.
import fs from "node:fs";
import path from "node:path";
import { HERE, appendEvent, fileStamp, nowIso, readJson, sleepSync, updateState, writeJsonAtomic } from "./files.mjs";
import {
appendLedger,
healthOk,
lastLaunchId,
listHandles,
pidAlive,
readLedger,
repoRoots,
terminalLine,
} from "./sessions.mjs";
import { applyPatch, isOpen, proseProblems, resolveDocFiles, resolveDocImages, validate } from "./patches.mjs";
import {
CHAT_FILE,
chatReplyLines,
collectChat,
deliverableChat,
unansweredChat,
readChat,
validateChat,
writeCursor,
} from "./inbox.mjs";
import { pendingWorkspaceChanges, writeWorkspaceCursor } from "./workspace.mjs";
import { readPrHosts, readSubagentCursor, readSubagentSetting, writeSubagentCursor } from "./settings.mjs";
import { snapshot } from "./git-repo.mjs";
import { handoffsDir, isHandoffId, markHandoffUsed, readHandoffMeta } from "./handoffs.mjs";
import { RUN_EVENTS, TASK_EVENTS, MAX_COMMITS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
import { blockFor, offered } from "./public/subagents.js";
import { changeLine } from "./public/workspace.js";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
let args, print, die, mustSession, sessionProject;
export function useCli(cli) {
({ args, print, die, mustSession, sessionProject } = cli);
}
/* ----------------------------------------------------------------- post */
// A patch from a file, or from stdin with `--file -`: a heredoc piped into
// the command saves the agent writing a file first, one tool call a turn.
// A file PowerShell wrote comes with a BOM (Out-File / Set-Content in 5.1) or
// in UTF-16 (its `>`), and both are the documented Windows route, so both read.
export function readPatch(file) {
try {
const buf = fs.readFileSync(file === "-" ? 0 : path.resolve(file));
let text;
if (buf[0] === 0xff && buf[1] === 0xfe) text = buf.subarray(2).toString("utf16le");
else if (buf[0] === 0xfe && buf[1] === 0xff) text = Buffer.from(buf.subarray(2)).swap16().toString("utf16le");
else text = buf.toString("utf8");
// A patch is one JSON object: an array, string or number would merge
// into the state as junk keys ("0", "1"...) and still report ok.
const patch = JSON.parse(text.replace(/^\uFEFF/, ""));
return patch && typeof patch === "object" && !Array.isArray(patch) ? patch : null;
} catch {
return null;
}
}
export function failValidation(problems) {
process.stderr.write("console: the payload was rejected, nothing was written.\n");
for (const p of problems) process.stderr.write(" - " + p + "\n");
// exitCode, not exit(): the agent has to read these lines to fix the patch,
// and process.exit() can truncate a pipe Node has not flushed.
process.exitCode = 3;
}
export async function cmdPost() {
// `post --wait <seconds>` is a post and then a wait in one command: one tool
// call per turn instead of two. A rejected post never waits (exit 3).
if (args.wait !== undefined && args.wait !== true && !Number.isFinite(Number.parseFloat(args.wait))) {
die("post --wait takes the slice in seconds, as wait --seconds does", 2);
}
if (!postOnce()) return;
if (args.wait === undefined) return;
// A bare --wait takes the slice from --seconds, as wait does.
args.seconds = args.wait === true ? args.seconds : args.wait;
return cmdWait();
}
function postOnce() {
const dir = mustSession();
const file = args.file;
if (!file) die("post needs --file <path to a JSON patch>", 2);
let patch = readPatch(file);
if (!patch) die(`could not read --file ${file} as one JSON object`, 2);
const statePath = path.join(dir, "state.json");
const before = readJson(statePath);
if (!before) die("that session has no state", 1);
try {
patch = resolveDocFiles(patch, before, before.worktree || repoRoots().worktree);
patch = resolveDocImages(patch, before, dir);
} catch (e) {
die(e.message, 3);
}
// Meter and folder reports go to the ledger, never into state.json. Checked
// here, before anything is written: a rejected post appends nothing.
const { run, folderIssue } = patch;
delete patch.run;
delete patch.folderIssue;
const reread = liftReread(patch, before.workflow);
const ledgerLines = ledgerFromPost(dir, run, folderIssue, before.workflow);
// Taken before the lock: git processes must not run while it is held.
const snap = reread === undefined ? null : snapshot(before.worktree || repoRoots().worktree, { prHosts: readPrHosts() });
// The patch is applied to a fresh read under the state lock, never to the
// read above: a send the person made in between is in the file, and a write
// built on the older read would take it away. Nothing in here may exit, so
// the lock is always let go; a refusal is carried out and reported after.
let refused = null;
let problems = [];
let written;
try {
written = updateState(dir, (fresh) => {
if (!fresh) {
refused = ["that session has no state", 1];
return null;
}
let next;
try {
next = applyPatch(fresh, patch);
} catch (e) {
refused = [e.message, 3];
return null;
}
// The result card and the fresh board land in this one write.
if (snap) {
next.git = gitBlock(snap, reread, fresh.git);
// The footer names the branch too: after a switch or a create it is
// the new one, and mid-rebase the one being rebased.
const onBranch = snap.head && (snap.head.branch || snap.head.rebasing);
if (onBranch) next.branch = onBranch;
}
problems = validate(next);
if (!problems.length && patch.chat) problems = validateChat(next, readChat(dir));
return problems.length ? null : next;
});
} catch (e) {
die(e.message, 1);
}
if (refused) die(...refused);
if (problems.length) return failValidation(problems);
const next = written.state;
for (const line of ledgerLines) appendLedger(dir, line);
// A build scores its tasks as it clears them (meter.js, PROGRESS_WORKFLOWS),
// after any `run` in the same post, so a phase finished here ends its count.
if (patch.headline && typeof patch.headline === "object") {
const ledger = readLedger(dir);
const progress = progressEntry(ledger, lastLaunchId(ledger), next.workflow, patch.headline.cleared);
if (progress) appendLedger(dir, progress);
}
appendEvent(dir, { type: "post", items: (patch.items || []).length });
const open = next.items.filter((i) => isOpen(i) && i.required !== false && i.kind !== "notice").length;
// Only a live server's link: no handle, no line, never a dead link.
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir));
print({
ok: true,
items: next.items.length,
open,
phase: next.phase,
...unansweredNote(dir, next),
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
});
return true;
}
/**
* A patch's `reread`, the agent's "re-read the repo" signal on the git board
* (FR-10), lifted out of the patch, or exit 3 when it is malformed or not on a
* git session. state.git itself is the console's own: a patch never carries it.
*/
export function liftReread(patch, workflow) {
if (Object.hasOwn(patch, "git")) die("state.git is the console's own: post reread instead", 3);
const { reread } = patch;
delete patch.reread;
if (reread === undefined) return undefined;
const flagOnly =
reread && typeof reread === "object" && !Array.isArray(reread) && Object.keys(reread).length === 1 && typeof reread.refreshFailed === "boolean";
if (reread !== true && !flagOnly) die("reread must be true or { refreshFailed: true|false }", 3);
if (workflow !== "git") die("reread only goes with the git workflow", 3);
return reread;
}
/**
* The new state.git from a snapshot. The agent's refreshFailed wins; without
* one, a newer FETCH_HEAD means a refresh worked, and anything else keeps the
* last word on it.
*/
export function gitBlock(snap, reread, previous) {
let refreshFailed;
if (reread && typeof reread === "object") refreshFailed = reread.refreshFailed;
else if (snap.lastFetch && (!previous?.lastFetch || Date.parse(snap.lastFetch) > Date.parse(previous.lastFetch))) refreshFailed = false;
else refreshFailed = Boolean(previous?.refreshFailed);
// A failed fetch still touches FETCH_HEAD, so its time is not a refresh:
// the board keeps saying when the last one that worked was.
if (refreshFailed === true && reread && typeof reread === "object") return { ...snap, lastFetch: previous?.lastFetch ?? null, refreshFailed };
return { ...snap, refreshFailed };
}
/**
* The ledger lines a post's `run` and `folderIssue` stand for, or exit 3 on
* the first bad one. Ids are scoped by the skill run in progress, so the same
* `run` posted twice counts once, and `phase-2` in one Implement run never
* collides with `phase-2` in the next.
*/
export function ledgerFromPost(dir, run, issue, workflow) {
if (run === undefined && issue === undefined) return [];
const launch = lastLaunchId(readLedger(dir));
const lines = [];
if (run !== undefined) {
const event = run && typeof run === "object" ? run.event : undefined;
if (!RUN_EVENTS.has(event)) die(`run: unknown event "${event}"`, 3);
if (typeof run.id !== "string" || !run.id.trim()) die("run: id required", 3);
if (run.tasks !== undefined) {
if (!TASK_EVENTS.has(event)) die(`run: tasks only goes with ${[...TASK_EVENTS].join(" or ")}`, 3);
if (!isTaskCount(run.tasks)) die(`run: tasks must be a whole number from 1 to ${MAX_TASKS}`, 3);
}
if (run.commits !== undefined) {
if (event !== "git-commits") die("run: commits only goes with git-commits", 3);
const ok = Number.isInteger(run.commits) && run.commits >= 1 && run.commits <= MAX_COMMITS;
if (!ok) die(`run: commits must be a whole number from 1 to ${MAX_COMMITS}`, 3);
}
lines.push({
kind: "run",
id: `${launch}:${run.id}`,
event,
workflow,
...(run.tasks !== undefined ? { tasks: run.tasks } : {}),
...(run.commits !== undefined ? { commits: run.commits } : {}),
});
}
if (issue !== undefined) {
const text = (v) => typeof v === "string" && v.trim() !== "";
const ok =
issue && typeof issue === "object" && text(issue.name) && text(issue.reason) && (issue.hint === undefined || text(issue.hint));
if (!ok) die("folderIssue must be { name, reason, hint? }, each a non-empty string", 3);
const problems = proseProblems(JSON.stringify([issue.reason, issue.hint || ""]), "folderIssue");
if (problems.length) die(problems.join("\n "), 3);
lines.push({
kind: "folder-issue",
id: `${launch}:${issue.name}`,
name: issue.name,
reason: issue.reason,
...(issue.hint ? { hint: issue.hint } : {}),
});
}
return lines;
}
/* ----------------------------------------------------------------- wait */
export async function cmdWait() {
const dir = mustSession();
// "240s" reads as 240. A --seconds with no number in it at all would make
// the deadline NaN, and the slice would end at once with exit 10: a busy
// loop, not a wait. So that is refused rather than guessed at.
const given = args.seconds;
const asked = typeof given === "string" ? Number.parseFloat(given) : NaN;
if (given !== undefined && !Number.isFinite(asked)) {
die(`--seconds must be a number, got "${args.seconds}"`, 2);
}
const seconds = Math.max(5, given === undefined ? 240 : asked);
const sid = path.basename(dir);
const project = sessionProject(dir);
const resultPath = path.join(dir, "result.json");
const chatPath = path.join(dir, CHAT_FILE);
const deadline = Date.now() + seconds * 1000;
const pendingChat = () => deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
// A result may already be sitting there: the person can finish the form even
// when the agent's session died, and a fresh agent picks it up here.
const liveUrl = () => listHandles(project).find((h) => h.sid === sid)?.url || "";
const existing = readJson(resultPath);
if (existing && !existing.consumedAt) return consume(dir, resultPath, existing, liveUrl(), pendingChat());
const earlyChat = pendingChat();
if (earlyChat.length) return deliverChat(dir, sid, earlyChat, liveUrl());
markWaiting(dir);
// A stat every 50ms, and a read only when the file has moved. The old tick
// was a full read and parse every 400ms, which put up to 0.4s between the
// person pressing Send and the agent starting on it, on every single send.
let healthAt = 0;
// A busy server (right after a post, say) can miss one health check without
// being gone. Only a missing handle or dead pid is proof at once; a server
// that merely does not answer must fail three checks in a row, each with a
// longer look, before the slice ends with exit 20.
let healthMisses = 0;
// The check in flight, if any. Aborted on every way out, so a fetch left
// running never holds the process (and the agent) past the print.
let health = null;
const healthStop = new AbortController();
try {
return await pollSlice();
} finally {
healthStop.abort();
}
async function pollSlice() {
// Null, not the current stamp: a result written between the check above and
// this line would otherwise read as already seen and wait out the slice.
let seen = null;
let chatSeen = null;
while (Date.now() < deadline) {
const stamp = fileStamp(resultPath);
if (stamp && stamp !== seen) {
const result = readJson(resultPath);
if (result && !result.consumedAt) return consume(dir, resultPath, result, liveUrl(), pendingChat());
// Unreadable for a moment (a lock, a scanner): look again next tick.
seen = result ? stamp : null;
}
// The chat inbox beside it, on the same tick: a Quick question ends the
// slice as surely as a card send does.
const chatStamp = fileStamp(chatPath);
if (chatStamp !== chatSeen) {
chatSeen = chatStamp;
const entries = pendingChat();
if (entries.length) return deliverChat(dir, sid, entries, liveUrl());
}
// The health check runs beside the polling, never in its way: awaited
// inline, a slow /health (a busy server, just after a send) held a
// finished send back for up to the whole fetch timeout.
if (!health && Date.now() - healthAt > 5000) {
healthAt = Date.now();
const handle = listHandles(project).find((h) => h.sid === sid);
if (!handle || !pidAlive(handle.pid)) {
print(serverGone(sid));
process.exitCode = 20;
return;
}
const check = { done: false, ok: false };
health = check;
healthOk(handle, 4000, healthStop.signal).then((ok) => Object.assign(check, { done: true, ok }));
}
if (health && health.done) {
const { ok } = health;
health = null;
if (ok) healthMisses = 0;
else if (++healthMisses >= 3) {
print(serverGone(sid));
process.exitCode = 20;
return;
} else healthAt = Date.now() - 3000; // look again in about 2s, not 5s
}
await new Promise((r) => setTimeout(r, 50));
}
const state = readJson(path.join(dir, "state.json")) || {};
const items = (state.items || []).filter((i) => i.required !== false && i.kind !== "notice");
const answered = items.filter((i) => !isOpen(i)).length;
const draft = readJson(path.join(dir, "draft.json"), {});
const staged = Object.keys(draft.staged || {}).length;
const handle = listHandles(project).find((h) => h.sid === sid);
print({
status: "waiting",
sid,
elapsed: fmtMs(Date.now() - Date.parse(state.created || nowIso())),
answered,
total: items.length,
staged,
url: handle ? handle.url : "",
message: "Waiting on your answer in the web console",
next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.",
...unansweredNote(dir, state),
// A workspace change alone never ends a slice: it rides on the next send.
pendingWorkspace: pendingWorkspaceChanges(dir).length,
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
});
process.exitCode = 10;
}
}
// Quick questions already handed over with no reply yet. Always empty when all are answered.
function unansweredNote(dir, state) {
const seqs = unansweredChat(dir, state);
return seqs.length
? { unansweredChat: seqs, warning: "Quick questions " + seqs.join(", ") + " have no reply yet and the page still shows them as pending. Reply to each now (chat.replies, re = seq): do what was asked when you can, or say why you will not." }
: {};
}
export function serverGone(sid) {
return {
status: "server-gone",
sid,
message: "The console server is not running. Start it again with `open --resume <sid> --workflow <yours>` (it gets a new link: give it to the person; without --no-open the browser opens it), then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
};
}
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
function deliverChat(dir, sid, entries, url) {
const [withWs, changes] = withWorkspace(dir, {
type: "chat",
at: nowIso(),
sid,
actions: [],
chat: entries,
reply: chatReplyLines(entries),
});
const [out, subCursor] = withSubagents(dir, withWs);
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
advanceCursor(dir, entries);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
// The workspace changes the agent is owed, added to what it is about to read:
// the list as `workspace`, and one line each at the end of `reply`.
function withWorkspace(dir, out) {
const changes = pendingWorkspaceChanges(dir);
if (!changes.length) return [out, changes];
const reply = [out.reply, ...changes.map(changeLine)].filter(Boolean).join("\n");
return [{ ...out, workspace: changes, reply }, changes];
}
// Print first, then this, as with the chat cursor: a kill in between can only
// hand the same change over again, never skip one.
export function advanceWorkspace(dir, changes) {
if (!changes.length) return;
try {
writeWorkspaceCursor(dir, Math.max(...changes.map((c) => c.version)));
} catch {}
}
// The server rewrites the session's setting for a new workflow only once its
// watcher sees the state `open` just wrote, so a launch or hop that read the
// file at once would find the old workflow's and owe the agent nothing until
// its next pickup. Give the server a moment to catch up instead, never
// writing the file ourselves (FR-7). A session with no setting file at all is
// an older server, which never writes one: a short look, not the full wait.
const SUBAGENT_SYNC_WAIT_MS = 1500;
const SUBAGENT_SYNC_MISSING_MS = 250;
export function awaitSubagentSync(dir, workflow) {
if (!offered(workflow)) return;
const start = Date.now();
for (;;) {
const setting = readSubagentSetting(dir);
if (setting && setting.workflow === workflow) return;
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
if (Date.now() - start >= budget) return;
sleepSync(25);
}
}
// The Subagents switch the agent is owed, added to what it is about to read:
// the setting as `subagents`, and its lines last in `reply`, after card lines,
// Quick questions and Workspace lines (FR-9). Read from the session's own
// setting file only, which only the server writes (FR-7). A setting for
// another workflow is the server not having caught up with a hop yet: it
// rides on the next pickup instead.
export function withSubagents(dir, out) {
const setting = readSubagentSetting(dir);
if (!setting) return [out, null];
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
if (setting.workflow !== workflow) return [out, null];
const block = blockFor(setting, readSubagentCursor(dir));
if (!block) return [out, null];
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
return [{ ...out, subagents: block.field, reply }, block.cursor];
}
// After the print, like advanceWorkspace(): a kill in between repeats the
// block at the next pickup, never loses it.
export function advanceSubagents(dir, cursor) {
if (!cursor) return;
try {
writeSubagentCursor(dir, cursor);
} catch {}
}
// Print first, then this, exactly as consume() stamps a result: a kill in
// between can only hand the same chat over again, and collectChat() drops
// anything that already has a reply.
export function advanceCursor(dir, entries) {
if (!entries.length) return;
try {
writeCursor(dir, Math.max(...entries.map((e) => e.seq)));
} catch {}
appendEvent(dir, { type: "chat-collect", count: entries.length });
}
/**
* Hand a result to the agent, then mark it collected. In that order.
*
* Both halves of this guard the same thing, and it matters most in agents other
* than the one this was built against: plenty of harnesses cap a single shell
* call well below a wait slice and kill it at their own timeout.
*
* Printing before stamping means such a kill can only ever cause the NEXT wait
* to hand the same result over twice, which the agent can absorb. The other
* order loses answers someone pressed Send on, silently and permanently.
*
* And exiting by setting `exitCode` rather than calling process.exit(): stdout
* to a pipe is asynchronous, and process.exit() truncates whatever Node has not
* flushed. That would throw the result away just as thoroughly.
*/
function consume(dir, resultPath, result, url, chat = []) {
const collected = { ...result, consumedAt: nowIso() };
// The link, any chat and any workspace change ride on what the agent reads,
// never on result.json itself.
const withChat = { ...collected, chat };
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
const [withWs, changes] = withWorkspace(dir, withChat);
const [out, subCursor] = withSubagents(dir, withWs);
const hop = hopFor(path.basename(dir), result);
markPickedUp(result);
print({ ...out, ...hop, ...handoffFor(result), ...(url ? { terminalLine: terminalLine(url) } : {}) });
try {
writeJsonAtomic(resultPath, collected);
} catch {}
markWorking(dir, result);
appendEvent(dir, { type: "consume", kind: result.type });
ledgerAnswers(dir, result);
advanceCursor(dir, chat);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = result.type === "cancel" ? 30 : 0;
}
// A collected send is the agent's turn: the page says so at once, without the
// agent spending a whole post on "working" before it starts. The activity
// line belonged to the last stretch of work, so it goes; quietMinutes stays,
// since the page only counts it while working. Never fatal.
// The send is no longer waiting to be picked up either, so the phase the
// server set on it goes back to collecting (status and post report it).
function markWorking(dir, result) {
if (!result) return;
try {
updateState(dir, (s) => {
if (!s) return null;
if (result.type !== "submit") return s.phase === "submitted" ? { ...s, phase: "collecting" } : null;
// The cards this send carried, so `settle: true` settles what the agent
// was handed and never a later send still waiting to be collected.
const ids = [...new Set((result.actions || []).filter((a) => a && (a.type === "answer" || a.type === "skip") && typeof a.i === "string" && !a.i.startsWith("__")).map((a) => a.i))];
return applyPatch({ ...s, phase: "collecting", collected: { at: result.consumedAt || nowIso(), ids } }, { agent: { status: "working", activity: null } });
});
} catch {}
}
// Waiting on an open question (or a finished screen's buttons) is the
// person's turn, whatever the last post said: an agent that replied to a note
// and went back to `wait` without restating its status left the page on
// "working" with nobody working. With nothing open it stays as it is: an
// agent waiting out its research subagents is still working. Only a change
// is written.
function markWaiting(dir) {
try {
updateState(dir, (s) => {
if (!s || !s.agent || s.agent.status !== "working") return null;
// The dashboard's menu and the git board are the page's own, and theirs
// to click whenever the agent is waiting.
const theirTurn =
s.finish || s.workflow === "dashboard" || s.workflow === "git" || (s.items || []).some((i) => isOpen(i) && i.kind !== "notice");
return theirTurn ? applyPatch(s, { agent: { status: "waiting" } }) : null;
});
} catch {}
}
// The session hops a send can ask for, each with the one command that makes
// it and the skill file to follow after, so the agent copies instead of
// assembling `open --resume …` from the action's fields.
const HOP_ACTIONS = {
launch: (a) => ({ workflow: a.workflow, spec: a.spec, skill: a.skill }),
dashboard: () => ({ workflow: "dashboard", skill: "plan2code" }),
commit: () => ({ workflow: "git", skill: "plan2code-git" }),
pickup: pickupHop,
};
// A pick-up hops into the skill and spec the handoff's `.json` names (the page
// sends only the id). When the skill is no longer installed, the spec folder
// is gone, or the Handoff skill wrote it, Quick Task picks it up instead,
// flagged so the agent says so. In a
// source tree no skill sits beside the console, so nothing can be told to be
// missing and the stored skill stands.
function skillPath(skill) {
return path.resolve(HERE, "..", "..", "..", skill, "SKILL.md");
}
function pickupHop(action) {
const id = action.handoff;
const meta = isHandoffId(id) ? readHandoffMeta(id) : null;
const handoffFile = isHandoffId(id) ? path.join(handoffsDir(), id + ".md") : undefined;
const quick = { workflow: "quick-task", spec: undefined, skill: "plan2code-quick-task", handoffFile, fallback: true };
if (!meta) return quick;
if (typeof meta.workflow !== "string" || !/^[a-z-]+$/.test(meta.workflow)) return quick;
// The Handoff skill's own handoff: resuming it would only write another one.
if (meta.workflow === "handoff") return quick;
if (typeof meta.skill !== "string" || !/^[a-z0-9-]+$/.test(meta.skill)) return quick;
const specGone =
typeof meta.spec === "string" && meta.spec && (!SAFE_SPEC.test(meta.spec) || !fs.existsSync(path.join(meta.worktree || "", meta.spec)));
const skillGone = !fs.existsSync(skillPath(meta.skill)) && fs.existsSync(skillPath("plan2code-quick-task"));
if (specGone || skillGone) return quick;
return { workflow: meta.workflow, spec: meta.spec || undefined, skill: meta.skill, handoffFile };
}
// A stop that asked for a handoff gets the Handoff skill's file beside it, so
// the agent opens it instead of locating it. Only a built skill has one.
function handoffFor(result) {
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
if (!actions.some((a) => a && a.type === "stop" && a.i === "__stop" && a.handoff === true)) return {};
const file = path.resolve(HERE, "..", "..", "..", "plan2code-handoff", "SKILL.md");
return fs.existsSync(file) ? { handoffSkill: file } : {};
}
// A pick-up uses its handoff up as its hop is printed, so the next dashboard
// scan no longer lists it. Never fatal; a repeat delivery marks it again.
function markPickedUp(result) {
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
for (const a of actions) {
if (a && a.type === "pickup" && typeof a.i === "string" && a.i.startsWith("__") && isHandoffId(a.handoff)) {
try {
markHandoffUsed(a.handoff);
} catch {}
}
}
}
// A spec name that is safe to put in the `resume` command: `specs/<name>` with
// nothing a shell would act on. A handoff's `.json` and a page's send are both
// data off disk or the wire, so the name is checked here and not trusted.
const SAFE_SPEC = /^specs\/[^/\\"'`$;&|<>(){}*?!#~\r\n]+$/;
function hopFor(sid, result) {
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
const action = actions.find((a) => a && Object.hasOwn(HOP_ACTIONS, a.type) && typeof a.i === "string" && a.i.startsWith("__"));
if (!action) return {};
const { workflow, spec, skill, handoffFile, fallback } = HOP_ACTIONS[action.type](action);
if (typeof workflow !== "string" || !/^[a-z-]+$/.test(workflow)) return {};
const quote = (v) => (/[\s"]/.test(v) ? `"${v.replace(/"/g, '\\"')}"` : v);
const specArg = typeof spec === "string" && SAFE_SPEC.test(spec) ? ` --spec ${quote(spec)}` : "";
const out = { resume: `node "${path.join(HERE, "console.mjs")}" open --resume ${sid} --no-open --workflow ${workflow}${specArg}` };
if (typeof skill === "string" && /^[a-z0-9-]+$/.test(skill)) {
const file = skillPath(skill);
if (fs.existsSync(file)) out.skillFile = file;
}
if (typeof handoffFile === "string") out.handoffFile = handoffFile;
if (fallback) out.fallback = true;
return out;
}
// One `answer` ledger line per item the person answered in this send, for
// the session meter. The id carries the send's stamp, so a send collected
// twice (a kill before consumedAt was written) still counts once, while the
// same question answered again in a later round counts again: that round was
// real back-and-forth. Never fatal: the meter is advice.
function ledgerAnswers(dir, result) {
if (!result || result.type !== "submit" || !Array.isArray(result.actions)) return;
try {
const launch = lastLaunchId(readLedger(dir));
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
const items = new Set();
for (const a of result.actions) {
if (a && a.type === "answer" && typeof a.i === "string" && !a.i.startsWith("__")) items.add(a.i);
}
for (const i of items) appendLedger(dir, { kind: "answer", id: `${launch}:answer:${result.at}:${i}`, workflow });
} catch {}
}
function fmtMs(ms) {
if (!Number.isFinite(ms) || ms < 0) return "0s";
const s = Math.round(ms / 1000);
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
return `${m}m ${s % 60}s`;
}
+283
View File
@@ -0,0 +1,283 @@
// Plan2Code Web Console - the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop.
import fs from "node:fs";
import path from "node:path";
import { SESSIONS_DIR, appendEvent, readJson } from "./files.mjs";
import { attachmentName, healthOk, listHandles, pidAlive, projectRoot, repoRoots, sessionDir } from "./sessions.mjs";
import { removeSpec } from "./scan.mjs";
import { isOpen } from "./patches.mjs";
import { pendingChatCount } from "./inbox.mjs";
import { forgetWorkspace, specKey } from "./workspace.mjs";
import { newHandoff, removeHandoff } from "./handoffs.mjs";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
let args, print, die, mustSession, sessionProject;
export function useCli(cli) {
({ args, print, die, mustSession, sessionProject } = cli);
}
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
// still be one of our servers, so its pid gets no second look.
const MAX_SERVER_LIFE_MS = 4 * 60 * 60 * 1000;
/* ----------------------------------------------------------------- keep */
// Copy one of the session's note attachments into specs/<idea>/attachments/, so
// a spec file can cite it after the session is swept. Run by the agent, never
// the server: the server still never writes into a project.
export function cmdKeep() {
const usage = "keep needs --session <sid> --upload <path> --name <name> --spec specs/<idea>";
if ([args.upload, args.name, args.spec].some((v) => typeof v !== "string")) die(usage, 2);
const dir = mustSession();
const state = readJson(path.join(dir, "state.json"));
if (!state) die("that session has no state", 1);
const project = state.project;
const upload = path.resolve(args.upload);
// Compared as real paths: Windows hands the same folder out both long
// (C:\Users\Justin.Parker) and 8.3 (C:\Users\JUSTIN~1.PAR), and the reply's
// path need not be spelled the way this session's directory is.
// A path that does not exist (yet) resolves through its nearest real parent,
// so a missing upload still reads as missing, not as somewhere else.
const real = (p) => {
try {
return fs.realpathSync.native(p);
} catch {
const parent = path.dirname(path.resolve(p));
return parent === path.resolve(p) ? path.resolve(p) : path.join(real(parent), path.basename(p));
}
};
if (!inside(real(path.join(dir, "uploads")), real(upload))) die("upload is not in this session's uploads folder", 3);
const spec = path.resolve(project, args.spec);
const attachments = path.join(spec, "attachments");
if (!inside(project, spec) || !inside(fs.realpathSync(project), realNearest(attachments))) {
die("spec folder is outside the project", 3);
}
if (!fs.existsSync(upload) || !fs.statSync(upload).isFile()) die("no such upload", 3);
// The file the link is written for has to be in the project too, or the
// relative link would point out of it.
if (typeof args.from === "string" && !inside(project, path.resolve(project, args.from))) {
die("--from is outside the project", 3);
}
// One upload, one copy: kept again under another name, the copy it already
// has (named for the same upload id) is the one reused.
// Named from the real path: an 8.3 spelling (7CF881~1.JPG) would name the
// copy after the short form and miss the copy this upload already has.
const named = attachmentName({ upload: real(upload), name: args.name });
const suffix = named.slice(named.lastIndexOf("-"));
let existing = null;
try {
existing = fs.readdirSync(attachments).find((f) => f.endsWith(suffix));
} catch {}
const file = existing || named;
const target = path.join(attachments, file);
fs.mkdirSync(attachments, { recursive: true });
let reused = false;
try {
fs.copyFileSync(upload, target, fs.constants.COPYFILE_EXCL);
} catch (err) {
if (err.code !== "EEXIST") throw err;
reused = true;
}
const slashes = (p) => p.split(path.sep).join("/");
const linkBase = typeof args.from === "string" ? path.dirname(path.resolve(project, args.from)) : spec;
const kept = slashes(path.relative(project, target));
print({
ok: true,
path: kept,
link: slashes(path.relative(linkBase, target)),
image: path.extname(target) === ".jpg",
reused,
});
appendEvent(dir, { type: "keep", id: path.basename(upload, path.extname(upload)), path: kept });
}
// Whether child sits strictly under parent. path.relative handles drive
// letters and POSIX alike; Windows paths fold case, as the server's do.
function inside(parent, child) {
const fold = (s) => (process.platform === "win32" ? s.toLowerCase() : s);
const rel = path.relative(fold(path.resolve(parent)), fold(path.resolve(child)));
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
}
// p with its nearest existing ancestor's symlinks and junctions resolved, so a
// linked specs/, spec or attachments/ folder cannot carry a copy out of the project.
function realNearest(p) {
let existing = p;
while (!fs.existsSync(existing)) existing = path.dirname(existing);
return path.join(fs.realpathSync(existing), path.relative(existing, p));
}
/* --------------------------------------------------------------- forget */
// Drop the folder list remembered for one spec (Finalize, once the spec is
// archived). The project's own list and every other spec's are untouched.
export function cmdForget() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
let spec = specKey(args.spec);
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
const worktree = repoRoots().worktree;
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
}
/* ---------------------------------------------------------- delete-spec */
// The dashboard's Delete button, carried out by the agent: the page never
// writes into a project. removeSpec() does every check; a refusal is exit 3
// with the reason, and the remembered workspace for the spec goes with it.
export function cmdDeleteSpec() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("delete-spec needs --spec specs/<name>", 2);
const worktree = repoRoots().worktree;
try {
const done = removeSpec(worktree, args.spec);
forgetWorkspace(worktree, args.spec);
print(done);
} catch (err) {
print({ ok: false, message: err.message });
process.exit(3);
}
}
/* --------------------------------------------------------------- handoff */
// A handoff the agent is about to write, claimed in ~/.plan2code/handoffs/
// (handoffs.mjs) for this checkout: the Stop flow's "Stop with a handoff" and
// the Handoff skill both start here. Only the .json is written; the agent
// writes the document at the printed path.
export function cmdHandoff() {
const usage = "handoff needs: handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]";
if (args._[0] !== "new" || args._.length > 1) die(usage, 2);
if (typeof args.workflow !== "string" || typeof args.skill !== "string") die(usage, 2);
if ("from-stop" in args && args["from-stop"] !== true) die("--from-stop takes no value", 2);
const { worktree, project } = repoRoots();
try {
const { id, path: file, meta } = newHandoff({
worktree,
project,
spec: args.spec,
workflow: args.workflow,
skill: args.skill,
title: args.title,
fromStop: args["from-stop"] === true,
});
print({ ok: true, id, path: file, meta });
} catch (err) {
print({ ok: false, message: err.message });
process.exit(3);
}
}
// The dashboard's Delete on a Handoff chip, carried out by the agent, the
// same shape as delete-spec: removeHandoff() does every check.
export function cmdDeleteHandoff() {
if (typeof args.handoff !== "string" || !args.handoff.trim()) die("delete-handoff needs --handoff <id>", 2);
try {
print(removeHandoff(args.handoff));
} catch (err) {
print({ ok: false, message: err.message });
process.exit(3);
}
}
/* --------------------------------------------------------------- status */
export async function cmdStatus() {
const project = projectRoot();
if (args.session || args.sid) {
const dir = mustSession();
const state = readJson(path.join(dir, "state.json")) || {};
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir));
const result = readJson(path.join(dir, "result.json"));
return print({
sid: state.sid,
session: dir,
workflow: state.workflow,
title: state.title,
phase: state.phase,
items: (state.items || []).length,
open: (state.items || []).filter(isOpen).length,
url: handle ? handle.url : "",
live: handle ? pidAlive(handle.pid) : false,
pendingResult: Boolean(result && !result.consumedAt),
pendingChat: pendingChatCount(dir, state),
});
}
let sids = [];
try {
sids = fs.readdirSync(SESSIONS_DIR).sort().reverse();
} catch {
return print({ sessions: [] });
}
const handles = listHandles(project);
const rows = [];
for (const sid of sids.slice(0, Number(args.limit || 20))) {
const dir = sessionDir(sid);
const state = readJson(path.join(dir, "state.json"));
if (!state) continue;
if (!args.all && state.project !== project) continue;
const handle = handles.find((h) => h.sid === sid);
const result = readJson(path.join(dir, "result.json"));
rows.push({
sid,
workflow: state.workflow,
title: state.title,
phase: state.phase,
created: state.created,
live: handle ? pidAlive(handle.pid) : false,
url: handle ? handle.url : "",
pendingResult: Boolean(result && !result.consumedAt),
pendingChat: pendingChatCount(dir, state),
});
}
print({ sessions: rows });
}
/* ----------------------------------------------------------------- stop */
export async function cmdStop() {
// --all is this folder's sessions; one named session is found wherever
// the command runs from.
const named = !args.all && (args.session || args.sid) ? sessionDir(path.basename(args.session || args.sid)) : null;
const project = named && fs.existsSync(named) ? sessionProject(named) : projectRoot();
const handles = listHandles(project);
const targets = args.all
? handles
: handles.filter((h) => h.sid === path.basename(args.session || args.sid || ""));
if (!targets.length) return print({ ok: true, stopped: 0 });
let stopped = 0;
let skipped = 0;
for (const h of targets) {
// Identify the process before killing it. A handle file can outlive a
// reboot in the system temp directory, and PIDs get reused; without this
// check `stop --all` can kill an unrelated program that happens to have
// inherited the number. /health returning our own sid is the only proof:
// a live pid and a young handle are not, since a server that died a
// minute ago leaves exactly that behind for any process to inherit. A
// busy server gets a second, longer look, and still has to answer as
// ours; one that does not is left alone, and only its handle goes.
const young = Date.now() - Date.parse(h.startedAt || 0) < MAX_SERVER_LIFE_MS;
const ours = (await healthOk(h)) || (young && pidAlive(h.pid) && (await healthOk(h, 5000)));
if (!ours) {
skipped++;
try {
fs.rmSync(h.handlePath, { force: true });
} catch {}
continue;
}
try {
process.kill(h.pid);
stopped++;
} catch {}
try {
fs.rmSync(h.handlePath, { force: true });
} catch {}
}
print({ ok: true, stopped, ...(skipped ? { skippedStaleHandles: skipped } : {}) });
}
+3 -1
View File
@@ -22,7 +22,9 @@ free to close that terminal and kill them mid-write. While you wait, post
and update the count as each returns. Never write a `finish.body` that says
work "is running in the background" or "will finish on its own". Mark every
reported helper `done` or `failed` before the finish, so the Subagents tab
never ends on a row still running.
never ends on a row still running: post each one's `done` in the same turn its
notice arrives, and a `finish` is refused (exit `3`, naming the helper) while
any row is still `running`.
## 1. Post the finish
+50 -2
View File
@@ -17,7 +17,7 @@ menu judgment and the launch steps; this is what the page does around them.
```
`spec` is the picker's selected spec dir, present only when the launched skill
takes a spec and the person picked one. `resume` is the one command to run
takes a spec (or is Quick Task on a `diagnosed` spec) and the person picked one. `resume` is the one command to run
first, before reading anything: it reuses the live server and turns the page
from the menu into the skill's starting screen while you read. `skillFile` is
the skill to read next (absent outside an install: then
@@ -47,7 +47,7 @@ first, and post before anything slow.
## What the page already knows
`state.scan` is `{ hasAgents, isGit, pending, specs: [{ dir, name, state, detail, touched }] }`,
`state.scan` is `{ hasAgents, isGit, pending, specs: [{ dir, name, state, detail, touched }], handoffs, handoffsDir }`,
a snapshot of the last `open` (a spec created mid-session appears the next time
the session resumes as a dashboard). `pending` is how many files a commit would
take (`null` when git cannot say): the Git card never greys out, shows the count
@@ -63,3 +63,51 @@ person's turn by itself.
A `__stop` before a pick ends the session the usual way: `finish` (paused
headline, `"command": "/plan2code"`) then `stop` (`console-stop.md`).
`handoffs` is this checkout's unused handoffs, newest first (`[{ id, title,
next, written, spec, skill, workflow }]`, read from `~/.plan2code/handoffs/`
by `open`, a dashboard only), and `handoffsDir` is that folder. The picker shows
them as dashed **Handoff** chips after the specs.
## A pick-up
Selecting a handoff chip shows a preview and hides the skill cards. **Pick it up
here** sends a hop like a launch, naming only the id:
```jsonc
{ "type": "submit",
"actions": [{ "i": "__pickup", "type": "pickup", "handoff": "2026-10-17-1152-handoff" }],
"reply": "Pick up the handoff \"Lunch vote\" right here in this session.",
"resume": "node \"…/console.mjs\" open --resume <sid> --no-open --workflow quick-task --spec specs/lunch-vote",
"skillFile": "…/plan2code-quick-task/SKILL.md",
"handoffFile": "~/.plan2code/handoffs/2026-10-17-1152-handoff.md" }
```
`wait` has already read the handoff's stored skill and spec, marked the handoff
used (the next scan no longer lists it) and put the command in `resume`. Run
`resume`, read `skillFile` with your file-read tool, then read `handoffFile`,
follow the skill from where its real work starts, and carry on from the
handoff's **Next task**. When the send carries `"fallback": true` the named
skill or spec was gone, or the Handoff skill wrote it: say so in one line,
since Quick Task is picking it up.
The handoff's document stays on disk until the 30-day sweep.
## A delete
The ✕ on a picker chip, after the page's two-step confirm (what goes, then
the spec's name typed), sends `{ "i": "__delete", "type": "delete", "spec":
"specs/<name>" }` with a `reply` saying it is for good. It is no hop: it
carries no `resume`, and you stay the dashboard. The console never writes into
a project, so the page only asks; delete through
`node "<CONSOLE>" delete-spec --spec <spec>`, never your own `rm`. It takes
only an existing `specs/<name>` folder inside the worktree (never a link,
never deeper, never `specs--completed/`), exits 3 with `message` on a refusal
having touched nothing, and drops the workspace remembered for that spec.
Then `open --resume <sid> --no-open --workflow dashboard` to rescan, and post
the menu again with `--wait`, its note saying what went or why it did not.
The page shows the chip as "Deleting…" until that rescan lands.
A handoff's **Delete** sends the same `__delete`, with `handoff` (its id) where a
spec has `spec`. Delete it through
`node "<CONSOLE>" delete-handoff --handoff <id>` (exit 3 with `message` when it
refuses, nothing touched), then rescan and post the menu as for a spec.
+2 -2
View File
@@ -9,7 +9,7 @@ The page's top bar shows a meter of how much work this console session has
done (green, yellow, red), so the person knows when a fresh session would be
sharper. It is advice only and never blocks anything. The console counts
launches itself: Plan, Revise plan, Document, Review, Quick task, Init, Init
update, Finalize, Git and Changelog score when their session opens, and there is nothing to
update, Finalize, Git, Changelog, X-ray and Diagnose score when their session opens, and there is nothing to
post for them.
It counts answers itself too: every card the person answers in a send adds to
@@ -27,7 +27,7 @@ Per-unit work is yours to report, with `run` in any post:
nothing now: answers count instead), `pathfinder-research`, `plan`,
`revise-plan`, `document`, `implement-phase`, `implement-review-phase`,
`review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`,
`git`, `changelog`, `git-commits` and `git-conflict` (Git's own, see
`git`, `changelog`, `xray`, `diagnose`, `git-commits` and `git-conflict` (Git's own, see
`notes/git.md`).
An unknown event is exit `3`. Post only the events your notes name: a skill
that scores when its session opens (the list above this one) already has its
+35
View File
@@ -43,6 +43,41 @@ you are halfway through writing their last answers. The one exception is an
agent that has stopped checking in: then Stop comes back, and the request waits
on disk for whichever session collects it next.
## Stop with a handoff
Off the dashboard, the Stop dialog offers **Stop with a handoff** first and
**Just stop and save** second. The handoff choice sends the same `__stop`, with
`handoff: true`, and `wait` adds `handoffSkill` (the Handoff skill's `SKILL.md`,
present in a built skill):
```jsonc
{ "type": "submit",
"actions": [ /* staged answers and notes, as usual */,
{ "i": "__stop", "type": "stop", "handoff": true } ],
"reply": "...the answer lines...\nStop here, save my place and write a handoff, so the dashboard can pick this up later.",
"handoffSkill": "…/plan2code-handoff/SKILL.md" }
```
Act on it in this turn, in this order:
1. **Handle the answers** exactly as in "Stop requests" step 1.
2. **Save your place** exactly as step 2 there.
3. **Make the handoff file:**
`node "<CONSOLE>" handoff new --workflow <yours> --skill <your skill> [--spec <spec>] --title "<short title>" --from-stop`
It prints the `path` to write.
4. **Write the handoff.** Open `handoffSkill` with your file-read tool (never a
skill-invocation tool) and write the document it describes to that `path`.
Skip its questions and its "Where to write it" step: infer the Next task
from where the work stands, and say in the document that it was inferred.
5. **Post `finish`** (`console-finish.md`) with a headline starting "Paused", a
`body` that names the handoff path and says the dashboard will offer it, and
the resume command, without `--wait`.
6. **`stop`** the server.
With no `handoffSkill` (a source checkout), use the structure in
`~/.agents/skills/plan2code-handoff/SKILL.md`. Do not ask whether they are
sure: the page already asked.
## Back to the dashboard, mid-workflow
On every workflow but the dashboard, a triangle left of Stop session takes the
+8 -3
View File
@@ -39,7 +39,7 @@ several are due at once (a build's start), read them in one batch.
| --- | --- |
| `building.md` (`building`) | You run `implement`, `implement-review` or `quick-task`: right after `open`, then `notes/implement.md` or `notes/quick-task.md`. |
| `building-review.md` (`building-review`) | A build's review is asked for on the page (a `review` verdict, `__review`, Implement + Review's Stage 2). |
| `notes/<workflow>.md` (`<workflow>`) | Right after `open`: `init` (also init-update), `pathfinder`, `plan`, `revise-plan`, `document`, `implement` (also implement-review), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`. The dashboard's is `console-launches.md`. |
| `notes/<workflow>.md` (`<workflow>`) | Right after `open`: `init` (also init-update), `pathfinder`, `plan`, `revise-plan`, `document`, `implement` (also implement-review), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`. The dashboard's is `console-launches.md`. |
| `console-launches.md` (`launches`) | You are the dashboard. |
| `console-finish.md` (`finish`) | Before your first `finish` post, and when a send carries `__commit`, or `__dashboard` from a finished screen. |
| `console-stop.md` (`stop`) | A send carries `__stop`, or `__dashboard` with no finish up; or your notes say to post a `stopWarning`. |
@@ -65,7 +65,7 @@ terminal — that path loses nothing, and they can switch either way at any time
1. `node "<CONSOLE>" open --workflow <w>`, where `<w>` is one of `dashboard`,
`init`, `init-update`, `pathfinder`, `quick-task`, `plan`, `revise-plan`,
`document`, `implement`, `implement-review`, `review`, `finalize`,
`handoff`, `git`, `changelog`. Get it right: the page decides from it what
`handoff`, `git`, `changelog`, `xray`, `diagnose`. Get it right: the page decides from it what
to offer and what stopping costs. `--title` defaults to the folder name;
`--spec specs/<idea>` when you already know the spec. It prints
`{"ok":true,"sid":"...","session":"...","url":"...","terminalLine":"→ Look at the web console: ..."}`
@@ -161,9 +161,10 @@ An action whose `i` starts with `__` is about the session, not a question:
| Action | Read |
| --- | --- |
| `__stop`, `__dashboard` (no finish up) | `console-stop.md` |
| `__stop` (plain, or with `handoff: true`), `__dashboard` (no finish up) | `console-stop.md` |
| `__commit`, `__dashboard` (from a finished screen) | `console-finish.md` |
| `__launch` | `console-launches.md` |
| `__delete` | `console-launches.md` (the dashboard only) |
| `__brief` | `notes/pathfinder.md` |
| `__review`, `__done` | `building-review.md` |
| `__git` | `notes/git.md` |
@@ -352,6 +353,10 @@ with `"_delete": true` removes the whole tab).
(relative to the project, never outside it). 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 could name.
- **`image`** instead of `md`: `{ "id", "image": "shots/run.png", "alt": "..." }`
shows 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`.
- **`version`** moves by itself: a known doc whose content changed is the next
version. Send one only to jump; it never goes back. Write a one-line `note`
when you change a doc, and `"stale": true` while answers it does not reflect
File diff suppressed because it is too large. Load diff
+294
View File
@@ -0,0 +1,294 @@
// Plan2Code Web Console - where the console's files live, how they are written safely, and the argument parser both command lines share.
//
// Two directories with deliberately different durability:
//
// runtime handle os.tmpdir()/plan2code-console/<cwd-hash>/<sid>.json
// port, pid, token, url. Losing it on reboot is correct,
// because the server is gone too. (Jupyter's jpserver-<pid>.json pattern.)
//
// session state ~/.plan2code/console/sessions/<sid>/
// the request, the human's draft, the result, the event log.
// Deliberately NOT under specs/: that keeps the console clear of
// the metrics confidence scraper and the loop's completion-marker
// parser, and it survives a `git clean`.
//
// Node built-ins only. No build step.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { pidAlive } from "./sessions.mjs";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const PUBLIC_DIR = path.join(HERE, "public");
export const HOME_DIR =
process.env.PLAN2CODE_CONSOLE_HOME ||
path.join(os.homedir(), ".plan2code", "console");
export const SESSIONS_DIR = path.join(HOME_DIR, "sessions");
// The person's own settings (colors, theme), shared by every session. Lives in
// HOME_DIR rather than beside a session precisely because it is NOT session
// state: a browser ties localStorage to the origin, and the origin carries the
// ephemeral port, so the file under this dir is the only copy of a preference
// that survives the next session's new port.
// Model menus for the `plan2code` launcher. The shipped list (bin/models.json) is the
// authors' and is overwritten by every install; the user's additions (models.json) are
// theirs. The launcher reads both. PLAN2CODE_MODELS_DIR moves them, for tests.
export const PLAN2CODE_DIR = process.env.PLAN2CODE_MODELS_DIR || path.join(os.homedir(), ".plan2code");
export const SHIPPED_MODELS_FILE = path.join(PLAN2CODE_DIR, "bin", "models.json");
export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
// so every session within the hour reuses one lookup.
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
// test run (or a second sandboxed instance) shares one handle directory with
// the real thing, and `stop --all` reaches outside its own world and kills a
// session someone is actually using.
export const RUNTIME_DIR = process.env.PLAN2CODE_CONSOLE_HOME
? path.join(process.env.PLAN2CODE_CONSOLE_HOME, "runtime")
: path.join(os.tmpdir(), "plan2code-console");
export const SCHEMA = 1;
/* ------------------------------------------------------------------ args */
export function parseArgs(argv) {
const out = { _: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a.startsWith("--")) {
const eq = a.indexOf("=");
if (eq > -1) out[a.slice(2, eq)] = a.slice(eq + 1);
else if (argv[i + 1] && !argv[i + 1].startsWith("--")) out[a.slice(2)] = argv[++i];
else out[a.slice(2)] = true;
} else out._.push(a);
}
return out;
}
/* ------------------------------------------------------------------- fs */
export function ensureDir(dir) {
fs.mkdirSync(dir, { recursive: true });
return dir;
}
// Atomic replace. The waiter polls result.json and WILL land mid-write eventually.
//
// The retry loop is not paranoia: on Windows, antivirus and the search indexer
// hold transient locks that surface as EPERM/EBUSY from rename. It is intermittent,
// unreproducible on demand, and looks exactly like a logic bug. Retry from day one.
export function writeJsonAtomic(file, data) {
const tmp = file + "." + process.pid + ".tmp";
const body = JSON.stringify(data, null, 2);
let lastErr;
for (let attempt = 0; attempt < 4; attempt++) {
try {
const fd = fs.openSync(tmp, "w");
try {
fs.writeFileSync(fd, body);
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
fs.renameSync(tmp, file);
return body;
} catch (err) {
lastErr = err;
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
sleepSync(40 * (attempt + 1));
}
}
try {
fs.rmSync(tmp, { force: true });
} catch {}
throw lastErr;
}
// A cheap "has this file changed?" fingerprint: one stat instead of a read and
// a parse. An atomic write replaces the file, so a new write always moves at
// least one of these. "" for a file that is not there.
export function fileStamp(file) {
try {
const st = fs.statSync(file, { throwIfNoEntry: false });
return st ? `${st.mtimeMs}:${st.size}:${st.ino}` : "";
} catch {
return "";
}
}
export function readJson(file, fallback = null) {
try {
return JSON.parse(fs.readFileSync(file, "utf8"));
} catch {
return fallback;
}
}
export function readText(file) {
try {
return fs.readFileSync(file, "utf8");
} catch {
return "";
}
}
export function appendEvent(dir, event) {
const line = JSON.stringify({ at: nowIso(), ...event });
fs.appendFileSync(path.join(dir, "events.ndjson"), line + "\n");
return line;
}
/* ----------------------------------------------------- the state lock */
// state.json has two writers in two processes: console.mjs (`open` and `post`,
// the agent's side) and the server (`/submit` stamps the phase and records
// what was sent on each item). Each writer reads the file, changes it and
// writes it back, so two of them overlapping lose whichever wrote first. Every
// read-modify-write of state.json therefore runs under this lock, a file
// created with O_EXCL beside it. The sections it guards are a read, a merge
// and a write, milliseconds long, so a lock older than LOCK_STALE_MS, or one
// whose holder has died, is a crash left behind and is broken. The wait runs
// past the stale age, so a writer always gets in eventually.
export const STATE_LOCK_FILE = "state.json.lock";
const LOCK_STALE_MS = 5000;
const LOCK_WAIT_MS = 7000;
function lockStale(lock) {
try {
const st = fs.statSync(lock);
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) return true;
const pid = Number.parseInt(fs.readFileSync(lock, "utf8"), 10);
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && !pidAlive(pid);
} catch (err) {
// Gone between the failed create and this look: free, so try again.
return err.code === "ENOENT";
}
}
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
const lock = path.join(dir, lockName);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
try {
fd = fs.openSync(lock, "wx");
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
} catch {}
continue;
}
sleepSync(Math.min(5 * (attempt + 1), 50));
}
}
try {
try {
fs.writeSync(fd, String(process.pid));
} finally {
fs.closeSync(fd);
}
return fn();
} finally {
try {
fs.rmSync(lock, { force: true });
} catch {}
}
}
// The one way to change state.json: under the lock, read it fresh, hand it to
// fn (null when there is no state yet, with the raw text beside it), and write
// back whatever fn returns. A null return writes nothing. Returns the written
// state and its text, or null.
export function updateState(dir, fn) {
const file = path.join(dir, "state.json");
return withStateLock(dir, () => {
let text = null;
try {
text = fs.readFileSync(file, "utf8");
} catch {}
let state = null;
try {
state = text === null ? null : JSON.parse(text);
} catch {}
const next = fn(state, text);
if (!next) return null;
return { state: next, text: writeJsonAtomic(file, next) };
});
}
export function sleepSync(ms) {
// Node built-ins only, and this runs in short one-shot CLI commands.
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
export function nowIso() {
return new Date().toISOString();
}
// Every whole, parsable object line of an ndjson file, in order.
export function readJsonLines(file) {
let text;
try {
text = fs.readFileSync(file, "utf8");
} catch {
return [];
}
const lines = text.split("\n");
lines.pop(); // "" after a complete last line, or the half-written one
const out = [];
for (const line of lines) {
if (!line.trim()) continue;
try {
const entry = JSON.parse(line);
if (entry && typeof entry === "object") out.push(entry);
} catch {}
}
return out;
}
// Append one JSON line to an ndjson file, returning what was stored.
export function appendJsonLine(file, stored) {
let lead = "";
try {
const st = fs.statSync(file);
// A fragment left by a crash mid-append must not swallow this line too.
if (st.size > 0) {
const fd = fs.openSync(file, "r");
try {
const b = Buffer.alloc(1);
fs.readSync(fd, b, 0, 1, st.size - 1);
if (b[0] !== 0x0a) lead = "\n";
} finally {
fs.closeSync(fd);
}
}
} catch {}
const line = lead + JSON.stringify(stored) + "\n";
let lastErr;
for (let attempt = 0; attempt < 4; attempt++) {
try {
fs.appendFileSync(file, line);
return stored;
} catch (err) {
lastErr = err;
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
sleepSync(40 * (attempt + 1));
}
}
throw lastErr;
}
+296
View File
@@ -0,0 +1,296 @@
// Plan2Code Web Console - the handoff store.
//
// Every handoff lives in one folder, outside every repo:
//
// ~/.plan2code/handoffs/<id>.md the Handoff skill's document, written by
// the agent and never changed here
// ~/.plan2code/handoffs/<id>.json who wrote it, for which checkout, spec
// and skill, and whether it was picked up
//
// This module is the only code that names, lists, marks, deletes and sweeps
// them. The console ships inside every skill, so the Stop flow, the Handoff
// skill and the dashboard all reach it through console.mjs commands.
// PLAN2CODE_HANDOFFS_DIR moves the folder, for tests.
//
// Node built-ins only. No build step.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
export const HANDOFFS_DIR = process.env.PLAN2CODE_HANDOFFS_DIR || path.join(os.homedir(), ".plan2code", "handoffs");
// Read at call time, so a test that sets the variable after import sees it.
export function handoffsDir() {
return process.env.PLAN2CODE_HANDOFFS_DIR || path.join(os.homedir(), ".plan2code", "handoffs");
}
export const HANDOFF_ID = /^\d{4}-\d{2}-\d{2}-\d{4}-handoff(-\d+)?$/;
export function isHandoffId(id) {
return typeof id === "string" && HANDOFF_ID.test(id) && id === path.basename(id);
}
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
// clock, as the skill scripts' now() does. Copied, not imported: the console
// is copied into skills on its own and may not reach src/skill-scripts/.
function clock() {
const pinned = process.env.PLAN2CODE_NOW;
if (pinned) {
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
const d = new Date(pinned);
if (!Number.isNaN(d.getTime())) return d;
}
return new Date();
}
const pad = (n) => String(n).padStart(2, "0");
/* ----------------------------------------------------------------- write */
/**
* Claim a new handoff for the agent to write. The id is the local minute,
* `YYYY-MM-DD-HHmm-handoff`, with `-2`, `-3` and so on after a clash; the
* `.json` is created exclusively, so two sessions in the same minute never
* share one. Only the `.json` is written: the agent writes the `.md` at the
* returned path. A bad field throws, naming it, before anything is created.
*/
export function newHandoff({ worktree, project, spec, workflow, skill, title, fromStop } = {}, now = clock()) {
if (typeof workflow !== "string" || !/^[a-z-]+$/.test(workflow)) throw new Error(`workflow must be lowercase letters and dashes, got ${JSON.stringify(workflow)}`);
if (typeof skill !== "string" || !/^[a-z0-9-]+$/.test(skill)) throw new Error(`skill must be a skill name, got ${JSON.stringify(skill)}`);
if (spec !== undefined && spec !== null && spec !== "" && (typeof spec !== "string" || !/^specs\/[^/\\]+$/.test(spec))) {
throw new Error(`spec must be specs/<name>, got ${JSON.stringify(spec)}`);
}
const dir = handoffsDir();
fs.mkdirSync(dir, { recursive: true });
const base = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}-handoff`;
for (let n = 1; ; n++) {
const id = n === 1 ? base : `${base}-${n}`;
// A lone .md left by hand also holds its name.
if (fs.existsSync(path.join(dir, id + ".md"))) continue;
let fd;
try {
fd = fs.openSync(path.join(dir, id + ".json"), "wx");
} catch (err) {
if (err.code === "EEXIST") continue;
throw err;
}
const meta = {
v: 1,
id,
title: typeof title === "string" ? title : "",
worktree,
project,
spec: spec || null,
workflow,
skill,
written: now.toISOString(),
fromStop: Boolean(fromStop),
usedAt: null,
};
try {
fs.writeSync(fd, JSON.stringify(meta, null, 2) + "\n");
} finally {
fs.closeSync(fd);
}
return { id, path: path.join(dir, id + ".md"), meta };
}
}
/* ------------------------------------------------------------------ read */
// A regular file in the folder, never a link: lstat, not stat.
function regularFile(file) {
try {
return fs.lstatSync(file).isFile();
} catch {
return false;
}
}
/** The handoff's `.json`, or null: an invalid id, a missing or linked file, or not a v1 record. */
export function readHandoffMeta(id) {
if (!isHandoffId(id)) return null;
const file = path.join(handoffsDir(), id + ".json");
if (!regularFile(file)) return null;
try {
const meta = JSON.parse(fs.readFileSync(file, "utf8"));
return meta && typeof meta === "object" && meta.v === 1 ? meta : null;
} catch {
return null;
}
}
/** Stamp `usedAt` (a pick-up) and rewrite the `.json`; the `.md` is never touched. */
export function markHandoffUsed(id, now = clock()) {
const meta = readHandoffMeta(id);
if (!meta) return null;
const next = { ...meta, usedAt: now.toISOString() };
const file = path.join(handoffsDir(), id + ".json");
const tmp = `${file}.${process.pid}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + "\n");
fs.renameSync(tmp, file);
return next;
}
const NEXT_MAX = 280;
// The case-folded resolved path, as removeSpec() compares realpaths.
function samePath(a, b) {
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
return typeof a === "string" && typeof b === "string" && fold(path.resolve(a)) === fold(path.resolve(b));
}
// The document's first `# ` heading, without a leading "Handoff" and the
// punctuation after it.
function docTitle(md) {
const m = md.match(/^# (.+)$/m);
if (!m) return "";
return m[1].replace(/^Handoff\b/i, "").replace(/^[\s:\-\u2013\u2014]+/, "").trim();
}
// The first paragraph under `## Next task`, on one line and cut to NEXT_MAX.
function docNext(md) {
const lines = md.split(/\r?\n/);
const at = lines.findIndex((l) => /^##\s+Next task\b/i.test(l));
if (at < 0) return "";
const para = [];
for (const line of lines.slice(at + 1)) {
if (/^#{1,6}\s/.test(line)) break;
if (!line.trim()) {
if (para.length) break;
continue;
}
para.push(line.trim());
}
const text = para.join(" ").replace(/\s+/g, " ").trim();
return text.length > NEXT_MAX ? text.slice(0, NEXT_MAX - 1).trimEnd() + "…" : text;
}
/**
* This checkout's handoffs still waiting to be picked up: a readable `.json`
* with no `usedAt`, a `.md` beside it, and the same worktree. Newest first,
* as `[{ id, title, next, written, spec, skill, workflow }]`.
*/
export function listHandoffs(worktree) {
const dir = handoffsDir();
let names;
try {
names = fs.readdirSync(dir);
} catch {
return [];
}
const out = [];
for (const name of names) {
if (!name.endsWith(".json")) continue;
const id = name.slice(0, -".json".length);
const meta = readHandoffMeta(id);
if (!meta || meta.usedAt || !samePath(meta.worktree, worktree)) continue;
const md = path.join(dir, id + ".md");
if (!regularFile(md)) continue;
let text;
try {
text = fs.readFileSync(md, "utf8");
} catch {
continue;
}
out.push({
id,
title: docTitle(text) || meta.title || "",
next: docNext(text),
written: meta.written,
spec: meta.spec ?? null,
skill: meta.skill,
workflow: meta.workflow,
});
}
return out.sort((a, b) => String(b.written).localeCompare(String(a.written)));
}
/* ---------------------------------------------------------------- remove */
/**
* Delete one handoff, both files (or whichever one exists), for the
* dashboard's Delete (`delete-handoff`). Only a handoff id; each file must be
* a regular file, never a link, whose real folder is the handoffs folder.
* Every refusal throws with the reason, and nothing is touched.
*/
export function removeHandoff(id) {
if (!isHandoffId(id)) throw new Error(`not a handoff id: ${id}`);
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
const dir = handoffsDir();
const names = [id + ".md", id + ".json"];
const present = [];
for (const name of names) {
let st;
try {
st = fs.lstatSync(path.join(dir, name));
} catch {
continue;
}
if (st.isSymbolicLink()) throw new Error(`${name} is a link, so it is not deleted from here`);
if (!st.isFile()) throw new Error(`${name} is not a file`);
present.push(name);
}
if (!present.length) throw new Error(`there is no handoff ${id}`);
const realDir = fold(fs.realpathSync.native(dir));
for (const name of present) {
if (fold(path.dirname(fs.realpathSync.native(path.join(dir, name)))) !== realDir) {
throw new Error(`${name} resolves outside the handoffs folder, so it is not deleted`);
}
}
for (const name of present) fs.rmSync(path.join(dir, name));
return { ok: true, removed: present };
}
/* ----------------------------------------------------------------- sweep */
/**
* Handoffs untouched for `maxAgeMs`, picked up or not: the `.json`'s mtime,
* or the `.md`'s when there is no `.json`. Regular files with a handoff id
* only, as staleScratch() does for the console folder.
*/
export function staleHandoffs(now, maxAgeMs) {
const dir = handoffsDir();
let names;
try {
names = fs.readdirSync(dir);
} catch {
return [];
}
const ids = new Set();
for (const name of names) {
const m = name.match(/^(.+)\.(md|json)$/);
if (m && isHandoffId(m[1])) ids.add(m[1]);
}
const stale = [];
for (const id of ids) {
for (const ext of [".json", ".md"]) {
let st;
try {
st = fs.lstatSync(path.join(dir, id + ext));
} catch {
continue;
}
if (st.isFile() && now - st.mtimeMs > maxAgeMs) stale.push(id);
break;
}
}
return stale;
}
// Every id re-checked against the same rule before anything is removed.
export async function removeHandoffs(ids) {
const dir = handoffsDir();
const removed = [];
for (const id of ids) {
if (!isHandoffId(id)) continue;
try {
await fs.promises.rm(path.join(dir, id + ".md"), { force: true });
await fs.promises.rm(path.join(dir, id + ".json"), { force: true });
removed.push(id);
} catch {}
}
return removed;
}
+237
View File
@@ -0,0 +1,237 @@
// Plan2Code Web Console - the Quick question chat's inbox beside the card slot.
import path from "node:path";
import { CHAT_LIMIT } from "./public/chat.js";
import { appendJsonLine, nowIso, readJson, readJsonLines, writeJsonAtomic } from "./files.mjs";
import { isPlainObject, proseProblems } from "./patches.mjs";
/* ------------------------------------------------------- the chat inbox */
// The Quick question chat rides its own channel beside the card slot, so the
// two never contend: a chat message never waits on an uncollected card send,
// and a card send never waits on chat. Every file has exactly one writer:
//
// chat.ndjson the server. One JSON line per entry: message / decision / reset.
// chat-cursor.json console.mjs. The last seq the agent was handed.
// state.json console.mjs `post`. The agent's replies, under chat.replies.
// (state.json as a whole has a second writer, the server's
// /submit, so every change to it goes through updateState().)
//
// The Workspace and the session meter follow the same rule, in files that
// switchWorkflow() never touches, so they carry across dashboard hops:
//
// workspace.json the server. Folders, version, change log, missing, remote.
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
export const CHAT_FILE = "chat.ndjson";
export const CHAT_CURSOR_FILE = "chat-cursor.json";
/**
* The inbox's entries with `seq > afterSeq`. A final segment with no newline
* is a line still being written: it is left for the next read, never parsed
* half-way. A line that will not parse is skipped rather than thrown on.
*/
export function readChat(dir, afterSeq = 0) {
return readJsonLines(path.join(dir, CHAT_FILE)).filter((e) => Number.isInteger(e.seq) && e.seq > afterSeq);
}
// Single-writer rule: only the server may call this (server.mjs and its routes).
export function appendChat(dir, entry) {
const last = readChat(dir).reduce((max, e) => Math.max(max, e.seq), 0);
return appendJsonLine(path.join(dir, CHAT_FILE), { ...entry, seq: last + 1, at: nowIso() });
}
export function readCursor(dir) {
const saved = readJson(path.join(dir, CHAT_CURSOR_FILE), { seq: 0 });
const n = Number(saved && saved.seq);
return Number.isInteger(n) && n > 0 ? n : 0;
}
// Never backwards: a slow collector finishing after a faster one must not
// hand the faster one's entries over again.
export function writeCursor(dir, seq) {
writeJsonAtomic(path.join(dir, CHAT_CURSOR_FILE), { seq: Math.max(readCursor(dir), seq) });
}
// The conversation the inbox is on: the one its last reset opened.
export function currentConversation(entries) {
for (let i = entries.length - 1; i >= 0; i--) {
const e = entries[i];
if (e.kind === "reset") return { conversation: e.conversation, workflow: e.workflow || "", sinceSeq: e.seq };
}
return { conversation: 0, workflow: "", sinceSeq: 0 };
}
// Typed messages only: Approve / Decline and resets never count to the limit.
export function typedCount(entries, conversation) {
return entries.filter((e) => e.kind === "message" && e.conversation === conversation).length;
}
/**
* The chat block of a page frame: the current conversation's person entries
* from the inbox and the agent's replies from the state, as one list. A reply
* sits straight after the entry it answers; one naming nothing here goes last.
*/
export function chatForFrame(entries, state) {
const { conversation } = currentConversation(entries);
const person = entries
.filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation)
.sort((a, b) => a.seq - b.seq);
const replies = (state?.chat?.replies || []).filter((r) => r && r.conversation === conversation);
const messages = [];
const placed = new Set();
for (const p of person) {
messages.push({ from: "person", ...p });
replies.forEach((r, i) => {
if (r.re !== p.seq) return;
messages.push({ from: "agent", ...r });
placed.add(i);
});
}
replies.forEach((r, i) => placed.has(i) || messages.push({ from: "agent", ...r }));
return { conversation, messages, typed: typedCount(entries, conversation), limit: CHAT_LIMIT };
}
/**
* What the agent has not been handed yet: entries past the cursor, minus any
* message or decision that already has a reply. The second half is what keeps
* a lost cursor from ever causing a second answer. Resets always go through.
*/
export function collectChat(dir, state) {
const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re));
return readChat(dir, readCursor(dir)).filter((e) => e.kind === "reset" || !replied.has(e.seq));
}
// What is worth handing over: the collected entries once one of them is
// something the person said. A reset alone (every session opens with one)
// waits and rides along with the next message, or `wait` would return on the
// opening line of every session and every first card reply would carry it.
// A run of resets (the session's opening one, then one per skill switch)
// says one thing, so only the last of each run is handed over; it carries the
// highest seq of the run, so the cursor still moves past all of them.
export function deliverableChat(entries) {
if (!entries.some((e) => e.kind !== "reset")) return [];
return entries.filter((e, i) => !(e.kind === "reset" && entries[i + 1] && entries[i + 1].kind === "reset"));
}
// Things the person said that were handed over but never answered. The page keeps
// showing "working on the answer" for each until a reply lands, so the agent is
// told on every post and every wait slice until it has replied (a refusal is a reply).
export function unansweredChat(dir, state) {
const { conversation } = currentConversation(readChat(dir, 0));
const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re));
const cursor = readCursor(dir);
return readChat(dir, 0)
.filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation)
.filter((e) => e.seq <= cursor && !replied.has(e.seq))
.map((e) => e.seq);
}
// How many things the person said are still waiting to be collected.
export function pendingChatCount(dir, state) {
return collectChat(dir, state).filter((e) => e.kind !== "reset").length;
}
// The chat entries as the lines appended to `reply`, in the note's shape.
// Whatever the person typed is indented past its first line, so only a real
// entry ever starts a line: a typed "Approved: edit p1" must not read as one.
export function chatReplyLines(entries) {
const indent = (s, pad) => String(s).replace(/\r?\n/g, "\n" + pad);
const lines = [];
for (const e of entries) {
if (e.kind === "message") {
lines.push(`Quick question: ${indent(e.text, " ")}`);
if (e.about && e.about.label) lines.push(` About: ${indent(e.about.label, " ")}`);
for (const img of e.images || []) lines.push(` Image: ${img.path} (${img.name})`);
for (const f of e.files || []) lines.push(` File: ${f.path} (${f.name})`);
} else if (e.kind === "decision") {
lines.push(`${e.decision === "approve" ? "Approved" : "Declined"}: edit ${e.re}`);
if (e.text) lines.push(` Note: ${indent(e.text, " ")}`);
} else if (e.kind === "reset") {
lines.push("New conversation started. Treat earlier chat as closed.");
}
}
return lines.join("\n");
}
// A project-relative path: no root, no drive letter, no step outside.
function projectRelative(p) {
if (typeof p !== "string" || !p.trim()) return false;
if (/^[\\/]/.test(p) || /^[A-Za-z]:/.test(p)) return false;
return !p.split(/[\\/]/).includes("..");
}
function underSpec(file, specDir) {
const norm = (s) => {
const t = s.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
return process.platform === "win32" ? t.toLowerCase() : t;
};
const f = norm(file);
const spec = norm(specDir);
return Boolean(spec) && (f === spec || f.startsWith(spec + "/"));
}
/**
* The house rules for the agent's chat replies, checked against the inbox
* they answer. Same shape as validate(): problems as sentences, [] when fine.
*/
export function validateChat(state, entries) {
const replies = state?.chat?.replies;
if (replies == null) return [];
if (!Array.isArray(replies)) return ['"chat.replies" must be an array'];
const problems = [];
const targets = new Set(
entries.filter((e) => e.kind === "message" || e.kind === "decision").map((e) => e.seq)
);
const ids = new Set();
for (const r of replies) {
if (!isPlainObject(r)) {
problems.push("every chat reply must be an object");
continue;
}
const name = typeof r.id === "string" && r.id.trim() ? r.id : "(no id)";
if (name === "(no id)") problems.push('every chat reply needs a non-empty string "id"');
else if (ids.has(r.id)) problems.push(`duplicate chat reply id "${r.id}"`);
ids.add(r.id);
if (!Number.isInteger(r.re) || !targets.has(r.re)) {
problems.push(`chat reply "${name}" needs "re": the seq of the message or decision it answers`);
}
if (!Number.isInteger(r.conversation)) problems.push(`chat reply "${name}" needs an integer "conversation"`);
if (typeof r.md !== "string" || !r.md.trim()) problems.push(`chat reply "${name}" needs its answer in "md"`);
const p = r.proposal;
if (p != null) {
if (!isPlainObject(p)) problems.push(`chat reply "${name}" "proposal" must be an object`);
else {
if (typeof p.summary !== "string" || !p.summary.trim()) {
problems.push(`chat reply "${name}" proposal needs a plain-English "summary"`);
}
if (!Array.isArray(p.files) || !p.files.length) {
problems.push(`chat reply "${name}" proposal needs "files": the project files it would change`);
} else {
for (const f of p.files) {
if (!projectRelative(f)) {
problems.push(`chat reply "${name}" proposal file "${f}" must be a project-relative path`);
} else if (state.specDir && underSpec(f, state.specDir)) {
problems.push(`a chat edit cannot touch the running skill's own files under ${state.specDir}/`);
}
}
}
}
}
if (r.changed != null) {
const count = (n) => Number.isInteger(n) && n >= 0;
if (!Array.isArray(r.changed) || !r.changed.every((c) => isPlainObject(c) && typeof c.file === "string" && count(c.added) && count(c.removed))) {
problems.push(`chat reply "${name}" "changed" must be a list of { file, added, removed }`);
}
}
}
const prose = JSON.stringify(replies.map((r) => [r && r.md, r && r.proposal && r.proposal.summary]));
problems.push(...proseProblems(prose, "a chat reply"));
return problems;
}
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff. Show more