Add Diagnose and X-ray, shared building habits, fresh-helper reviews, and a Bug fixed spec state

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-16 19:28:11 -07:00
1 parent 80ae3decdd
commit 33a0dbd34a
58 files changed
+3270 -236

No files matched your search

+14 -8
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
@@ -102,9 +105,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 +129,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.
@@ -151,6 +156,7 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
| `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 |
@@ -190,7 +196,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `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 |
| `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. |
@@ -198,7 +204,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `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 |
| `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:
@@ -214,7 +220,7 @@ Key design points:
- **`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.
- **`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`) 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.
@@ -294,10 +300,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 +320,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.
+14 -4
View File
@@ -84,12 +84,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 +135,15 @@ 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, every one of these (the tests fail on a miss, but not all at once):
- `src/plan2code.md`: the skill/workflow table and "What each skill reads and writes" (checked by `scripts/check-skill-table.mjs`: every backticked token must appear in the skill's prompt).
- `src/web-console/public/answers.js`: `WORKFLOW_LABEL`, `CONSOLE_WORKFLOWS`, `resumeCommand()`, a `SKILL_CATALOG` card (utilities go in group `"extra"` before Changelog: tests pin Changelog then Git last), `START_POSES` and `cardAvailability()`.
- `src/web-console/public/meter.js`: `WEIGHTS`, `LAUNCH_COUNTED` (if its launch scores), `WORKFLOW_NAMES`, `LAUNCH_LABELS`, `RUN_LABELS`; and in `src/web-console/console-meter.md` the event list, plus the sentence near its top naming the skills that score on launch (when it joins `LAUNCH_COUNTED`).
- `src/web-console/public/index.html`: a start-pose `<svg class="pose pose-<workflow>" data-pose="<workflow>">` in `<template id="start-poses">` (pose CSS in `app.css`), and a line in Help's About list.
- `src/web-console/notes/<workflow>.md`, named in the skill's Interface line.
- `src/web-console/console.mjs` usage text, and `src/web-console/console.md` (the `open --workflow` list and the `notes/<workflow>.md` row).
- Tests: `notesFor` in `scripts/test-web-console-speed.mjs` and `CONSOLE_WORKFLOW_LIST` in `scripts/test-web-console-logic.mjs`.
- Optional: `STARTER_SET_FOR` in `public/starters.js` (unlisted gets "general") and `SUBAGENT_WORKFLOWS` in `public/subagents.js` (only for skills that offer helpers).
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`.
+26 -6
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,7 +199,15 @@ 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. **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. 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.
@@ -569,9 +578,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
@@ -691,7 +710,8 @@ 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) and `models.json`. 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
+2
View File
@@ -86,6 +86,7 @@ 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.
## Failure log
@@ -100,3 +101,4 @@ When you make a mistake, get corrected, or discover something about this codebas
- 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.
+30
View File
@@ -2,6 +2,36 @@
All notable changes to Plan2Code will be documented in this file.
## Unreleased
### ✨ 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.
### 🔧 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.
- **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).
### 🐛 Fixed
- **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 |
+8 -4
View File
@@ -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 |
| 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) |
@@ -361,6 +363,8 @@ console or the terminal; add `--web` to skip the question and go straight to the
| `/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-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 |
+2
View File
@@ -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 };
+1 -1
View File
@@ -8,7 +8,7 @@
"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-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-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs"
},
"devDependencies": {
"husky": "^9.0.0"
+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));
+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:/);
});
+207
View File
@@ -115,6 +115,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 +161,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 +513,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");
+2 -1
View File
@@ -303,7 +303,8 @@ 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");
assert.equal(SKILL_CATALOG.at(-2), entry, "the Git card comes right before Handoff");
assert.equal(SKILL_CATALOG.at(-1).skill, "plan2code-handoff", "the Handoff card is last");
for (const isGit of [true, false, undefined]) {
for (const pending of [0, 3, null]) {
const scan = { hasAgents: true, pending, ...(isGit === undefined ? {} : { isGit }) };
+44
View File
@@ -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]);
}
});
+222
View File
@@ -32,6 +32,7 @@ import {
sortAttachments,
cardAvailability,
cardPresentation,
defaultSpec,
CATALOG_GROUPS,
CONTINUE_IN_CONSOLE,
CONSOLE_WORKFLOWS,
@@ -46,6 +47,11 @@ import {
handoffShape,
handoffText,
launchReply,
launchTarget,
deleteAction,
deleteReply,
deleteSummary,
isDeletableSpecDir,
MAX_NOTE_IMAGES,
noteAction,
noteReplyLines,
@@ -148,6 +154,7 @@ import {
writeSubagentSetting,
repoRoots,
scanProject,
removeSpec,
SPEC_STATES,
validate,
WORKSPACE_FILE,
@@ -634,6 +641,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 +664,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 +687,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 +707,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 +731,118 @@ 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("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 +1018,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 +1100,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 +1291,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", () => {
+56
View File
@@ -716,3 +716,59 @@ 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]);
}
});
+17
View File
@@ -225,6 +225,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.
+2 -1
View File
@@ -406,7 +406,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) {
+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 lib.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
@@ -121,7 +121,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,7 +143,7 @@ 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? |
+1 -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.
+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`.
+17 -4
View File
@@ -32,9 +32,11 @@ 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.
- 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.
- 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,7 +53,7 @@ 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 |
@@ -59,6 +61,8 @@ Ground truth for menu notes and Ask-tab answers. For anything beyond this table,
| handoff | conversation, spec, git | `<timestamp>-handoff.md` (OS temp or `handoffs/`) |
| 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 +76,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 +105,15 @@ 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 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.
## 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).
+26
View File
@@ -210,6 +210,32 @@ 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
+153 -3
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, consoleLib, 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).
@@ -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,
@@ -116,15 +119,18 @@ review set it to its own stage):
"items": [{ "id": "signoff", "status": "reopened",
"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": "show", "label": "Show me it working" },
{ "id": "approve", "label": "Approve this phase" },
{ "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.
+16 -1
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
@@ -63,3 +63,18 @@ 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`).
## 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.
+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
+7 -2
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: ..."}`
@@ -164,6 +164,7 @@ An action whose `i` starts with `__` is about the session, not a question:
| `__stop`, `__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
+31 -2
View File
@@ -42,6 +42,7 @@ import {
ensureDir,
fileStamp,
forgetWorkspace,
removeSpec,
handOff,
handleFile,
healthOk,
@@ -88,6 +89,7 @@ import {
updateState,
UPLOAD_MAX_AGE_MS,
resolveDocFiles,
resolveDocImages,
validate,
validateChat,
workspaceForAgent,
@@ -267,6 +269,7 @@ async function cmdOpen() {
// 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);
}
@@ -656,6 +659,7 @@ function postOnce() {
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);
}
@@ -1301,6 +1305,24 @@ function cmdForget() {
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.
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);
}
}
/* ----------------------------------------------------------------- help */
function cmdHelp() {
@@ -1370,6 +1392,12 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
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.
status [--session <sid>] [--all]
One session, or (--all) every session on this machine, every project.
stop --session <sid> | --all
@@ -1377,7 +1405,7 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
workflows: dashboard · init · init-update · pathfinder · quick-task · plan ·
revise-plan · document · implement · implement-review · review ·
finalize · handoff · git · changelog
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
@@ -1636,6 +1664,7 @@ const COMMANDS = {
chat: cmdChat,
keep: cmdKeep,
forget: cmdForget,
"delete-spec": cmdDeleteSpec,
status: cmdStatus,
stop: cmdStop,
help: cmdHelp,
@@ -1655,7 +1684,7 @@ if (Number.isFinite(nodeMajor) && nodeMajor < 18) {
if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
process.stderr.write(
"console: usage: console.mjs <open|post|wait|chat|keep|forget|status|stop|help> [--session <id>] [--file <patch.json>] [--seconds N]\n"
"console: usage: console.mjs <open|post|wait|chat|keep|forget|delete-spec|status|stop|help> [--session <id>] [--file <patch.json>] [--seconds N]\n"
);
process.exit(2);
}
+167 -15
View File
@@ -24,7 +24,7 @@ import { fileURLToPath } from "node:url";
import { countPending } from "./git-repo.mjs";
import { CHAT_LIMIT } from "./public/chat.js";
import { DOC_TYPES } from "./public/answers.js";
import { DOC_TYPES, isDeletableSpecDir } from "./public/answers.js";
import { defaultName } from "./public/workspace.js";
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
@@ -579,9 +579,10 @@ export async function removeScratch(consoleDir, names) {
// What User Preferences -> Cleanup never removes. The console folder keeps its
// protected files, its sessions dir (old sessions go one by one, by age) and,
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
// console, the launcher (bin/, launcher.json) and the models the person added.
// console, the launcher (bin/, launcher.json), the install record that
// `plan2code update` reads (install.json) and the models the person added.
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
@@ -785,8 +786,13 @@ export function newToken() {
// Where a spec folder stands, named after the step its files are ready for.
// "unrecognized" is a folder with files but no pipeline shape: it launches
// Pathfinder or Plan (the files may be reference docs) but unlocks nothing
// else, exactly like picking no spec at all.
// else, exactly like picking no spec at all. "diagnosed" is a bug Diagnose
// wrote up and nobody has fixed or planned yet: it lights Quick Task and Plan.
// "fixed" is that bug once Quick Task marked it Fixed: finished, so the
// dashboard never picks or suggests it, and Quick Task offers to archive it.
export const SPEC_STATES = new Set([
"diagnosed",
"fixed",
"exploring",
"mapped",
"planned",
@@ -796,7 +802,9 @@ export const SPEC_STATES = new Set([
"unrecognized",
]);
function maxMtime(dir, depth = 4, budget = { n: 400 }) {
// The newest mtime under dir. `tally.files` counts the files the same walk
// sees (within its depth and budget), for the dashboard's delete dialog.
function maxMtime(dir, depth = 4, budget = { n: 400 }, tally = null) {
let best = 0;
if (depth < 0 || budget.n <= 0) return best;
let entries;
@@ -810,8 +818,11 @@ function maxMtime(dir, depth = 4, budget = { n: 400 }) {
if (e.name.startsWith(".")) continue;
const p = path.join(dir, e.name);
try {
if (e.isDirectory()) best = Math.max(best, maxMtime(p, depth - 1, budget));
else best = Math.max(best, fs.statSync(p).mtimeMs);
if (e.isDirectory()) best = Math.max(best, maxMtime(p, depth - 1, budget, tally));
else {
best = Math.max(best, fs.statSync(p).mtimeMs);
if (tally) tally.files++;
}
} catch {}
}
return best;
@@ -825,6 +836,16 @@ function readText(file) {
}
}
// A spec file's Status line value, in any of the forms the skill scripts
// accept (`**Status:**`, `**Status**:`, `Status:`). Same pattern as STATUS_RE
// in src/skill-scripts/specs.mjs; the console cannot import it, so keep the
// two copies in step. A CRLF file's trailing `\r` is dropped.
const STATUS_LINE_RE = /^[ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*(.+?)[ \t\r]*$/m;
function statusOf(text) {
const m = text.match(STATUS_LINE_RE);
return m ? m[1] : "";
}
// A spec folder's pipeline position, from its files alone. Furthest artifact
// wins: an overview beats a draft beats a map, so a spec mid-way through two
// stages reports the later one.
@@ -837,9 +858,7 @@ function classifySpec(dir, names) {
const planDraft = drafts.length > 0;
const planConv = has(/^PLAN-CONVERSATION.*\.md$/i);
const liveDraft = drafts.filter((n) => !/-prev\.md$/i.test(n)).sort().reverse()[0] || drafts[0];
const draftStatus = liveDraft
? (readText(path.join(dir, liveDraft)).match(/\*\*Status:\*\*\s*([^\n]+)/) || [])[1] || ""
: "";
const draftStatus = liveDraft ? statusOf(readText(path.join(dir, liveDraft))) : "";
const resumeAt = draftStatus.match(/Resume at Phase\s*(\d+)/i);
if (phases.length) {
@@ -870,10 +889,19 @@ function classifySpec(dir, names) {
// Status line: Plan still has phases to run before Document can start.
if (resumeAt) return { state: "mapped", detail: `plan draft, resume at Phase ${resumeAt[1]}` };
if (planDraft) return { state: "planned", detail: "plan drafted" };
// A bug Diagnose wrote up, with nothing after it yet. A pathfinder map or a
// plan conversation means planning has started, so the usual states win.
// Quick Task marks the write-up Fixed once the bug is gone: then the bug is
// done, and the folder waits only to be archived.
const diagnosis = names.filter((n) => /^DIAGNOSIS-.*\.md$/i.test(n)).sort().reverse()[0];
const diagnosisStatus = diagnosis ? statusOf(readText(path.join(dir, diagnosis))).replace(/\*+/g, "").trim() : "";
if (diagnosis && !planConv && !fs.existsSync(path.join(pfDir, "map.md")))
return /^fixed/i.test(diagnosisStatus)
? { state: "fixed", detail: "bug fixed" }
: { state: "diagnosed", detail: "bug diagnosed, not fixed" };
if (isDir(pfDir)) {
const mapText = readText(path.join(pfDir, "map.md"));
const m = mapText.match(/\*\*Status:\*\*\s*([^\n]+)/);
const status = m ? m[1].replace(/\*+/g, "").trim() : "";
const status = statusOf(mapText).replace(/\*+/g, "").trim();
if (/^cleared/i.test(status)) return { state: "mapped", detail: "all decisions made" };
let qTotal = 0;
let qDone = 0;
@@ -930,11 +958,13 @@ export function scanProject(root) {
} catch {
continue;
}
const tally = { files: 0 };
specs.push({
dir: `specs/${name}`,
name,
...classifySpec(dir, files),
touched: maxMtime(dir),
touched: maxMtime(dir, 4, { n: 400 }, tally),
files: tally.files,
});
}
specs.sort((a, b) => b.touched - a.touched || a.name.localeCompare(b.name));
@@ -948,6 +978,38 @@ export function scanProject(root) {
};
}
/**
* Delete one spec folder, for the dashboard's Delete button (`delete-spec`).
* Only an existing `specs/<name>` folder, as isDeletableSpecDir() spells it,
* whose real path sits directly in the worktree's own specs/: never a link to
* somewhere else, never specs--completed/, never anything deeper. specs/ is
* gitignored, so a mistake here cannot be undone; every refusal throws with
* the reason, and nothing is touched.
*/
export function removeSpec(worktree, dir) {
if (!isDeletableSpecDir(dir)) throw new Error(`"${dir}" is not a spec folder: only specs/<name> can be deleted`);
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
const root = path.resolve(worktree);
const target = path.join(root, dir);
let st;
try {
st = fs.lstatSync(target);
} catch {
throw new Error(`there is no ${dir} to delete`);
}
if (st.isSymbolicLink()) throw new Error(`${dir} is a link to another folder, so it is not deleted from here`);
if (!st.isDirectory()) throw new Error(`${dir} is not a folder`);
const real = fs.realpathSync.native(target);
const realSpecs = fs.realpathSync.native(path.join(root, "specs"));
const realRoot = fs.realpathSync.native(root);
const rel = path.relative(fold(realRoot), fold(realSpecs));
if (rel !== "specs" || fold(path.dirname(real)) !== fold(realSpecs)) {
throw new Error(`${dir} resolves outside the project's specs/ folder, so it is not deleted`);
}
fs.rmSync(real, { recursive: true });
return { ok: true, removed: dir };
}
/* -------------------------------------------------------------- liveness */
// PID reuse is real, so process.kill(pid, 0) is necessary but not sufficient.
@@ -1246,7 +1308,7 @@ function mergeDocs(current, patchList) {
// version: the agent no longer has to track what the page holds, and a
// repost of unchanged content is not a new version.
if (prev && typeof entry.version !== "number" && typeof prev.version === "number") {
const text = (blocks) => JSON.stringify((blocks || []).map((b) => [b.id, b.md, b.state]));
const text = (blocks) => JSON.stringify((blocks || []).map((b) => [b.id, b.md, b.state, b.image, b.alt]));
if (text(prev.blocks) !== text(doc.blocks)) doc.version = prev.version + 1;
}
}
@@ -1410,6 +1472,83 @@ export function resolveDocFiles(patch, state, worktree) {
return { ...patch, docs };
}
/**
* Image blocks: `{ "id", "image": "shots/run.png", "alt": "..." }` shows a
* screenshot the agent saved under the session's `shots/` folder (Show me it
* working). The path resolves against the session folder and must land, after
* `realpath`, directly inside `<session>/shots/` under a plain name, so the page
* can only ever be pointed at the agent's own pictures. The bytes decide the
* type, as checkDocument() does for documents: a text file renamed `.png` is
* refused. Stored session-relative; an image block never carries `md` or `file`.
* Runs in the CLI beside resolveDocFiles(), so applyPatch never touches the disk.
*/
export const SHOTS_DIR_NAME = "shots";
export const SHOT_MAX = 5 * 1024 * 1024;
export const SHOT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(png|jpe?g|webp)$/i;
// What an image's first bytes say it is ("png", "jpeg", "webp"), or null.
export function shotType(buf) {
if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return "png";
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "jpeg";
if (buf.length >= 12 && buf.toString("ascii", 0, 4) === "RIFF" && buf.toString("ascii", 8, 12) === "WEBP") return "webp";
return null;
}
export function resolveDocImages(patch, state, dir) {
if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch;
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
const shotsDir = path.join(path.resolve(dir), SHOTS_DIR_NAME);
const check = (image, docId) => {
if (typeof image !== "string" || !image.trim()) throw new Error(`doc "${docId}": an image block's "image" must be a path`);
const where = `doc "${docId}": image ${image}`;
let real;
try {
real = fs.realpathSync.native(path.resolve(dir, image));
} catch {
throw new Error(`${where} does not exist. Save it under the session's ${SHOTS_DIR_NAME}/ folder first.`);
}
let realShots;
try {
realShots = fs.realpathSync.native(shotsDir);
} catch {
realShots = shotsDir;
}
const name = path.basename(real);
if (fold(path.dirname(real)) !== fold(realShots)) {
throw new Error(`${where} is outside the session's ${SHOTS_DIR_NAME}/ folder (${shotsDir}); only pictures saved there can be shown.`);
}
if (!SHOT_NAME.test(name)) throw new Error(`${where}: name it with letters, digits, dots, dashes or underscores, ending .png, .jpg, .jpeg or .webp`);
const stat = fs.statSync(real);
if (!stat.isFile()) throw new Error(`${where} is not a file`);
if (stat.size > SHOT_MAX) throw new Error(`${where} is larger than ${SHOT_MAX / 1024 / 1024} MB`);
const ext = path.extname(name).slice(1).toLowerCase();
const want = ext === "jpg" ? "jpeg" : ext;
if (shotType(fs.readFileSync(real)) !== want) throw new Error(`${where} is not a ${want.toUpperCase()} image (its bytes say otherwise)`);
return `${SHOTS_DIR_NAME}/${name}`;
};
const docs = patch.docs.map((entry) => {
if (!isPlainObject(entry) || !Array.isArray(entry.blocks)) return entry;
const prevBlocks = (state.docs || []).find((d) => d && d.id === entry.id)?.blocks || [];
return {
...entry,
blocks: entry.blocks.map((b) => {
if (!isPlainObject(b)) return b;
const prevBlock = prevBlocks.find((x) => x && x.id === b.id);
if (b.image === undefined || b.image === null) {
// Text or a file over what was an image: it stops being one.
return ("md" in b || "file" in b) && prevBlock && typeof prevBlock.image === "string" ? { ...b, image: null, alt: null } : b;
}
if (("md" in b && b.md != null) || ("file" in b && b.file != null)) {
throw new Error(`doc "${entry.id}": block "${b.id}" is an image; it cannot also carry "md" or "file"`);
}
if (b.alt != null && typeof b.alt !== "string") throw new Error(`doc "${entry.id}": block "${b.id}" "alt" must be text`);
return { state: prevBlock?.state || "settled", ...b, image: check(b.image, entry.id), md: null, file: null };
}),
};
});
return { ...patch, docs };
}
/**
* Apply an agent patch to the session state.
*
@@ -1556,12 +1695,15 @@ const JARGON = [
];
// The loop parses these out of agent output; pathfinder forbids them under specs/.
// The other copy is LOOP_TOKENS in src/skill-scripts/common.mjs: the console is
// not a skill script and cannot import it, so keep the two in step.
const FORBIDDEN_TOKENS =
/\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
// plan2code-metrics scrapes confidence with patterns that do NOT require a
// percent sign, so a bare "Requirements 22" in a rendered doc can poison a run's
// metrics. Keep those four words away from bare numbers.
// metrics. Keep those four words away from bare numbers. The skill scripts'
// copy is SCRAPE in src/skill-scripts/common.mjs; keep the two in step.
const METRICS_BAIT = /\b(Requirements?|Feasibility|Integration|Risk)[:\s|]+\d{1,2}\b/;
// The marker and metrics-bait scan on its own, for agent text that never
@@ -1761,6 +1903,16 @@ export function validate(state) {
);
}
// An image block's alt text is its caption, read by the same newcomers a
// title is.
for (const d of state.docs || []) {
for (const b of (isPlainObject(d) && Array.isArray(d.blocks) ? d.blocks : [])) {
if (!isPlainObject(b) || typeof b.image !== "string" || typeof b.alt !== "string") continue;
const hit = JARGON.find((re) => re.test(b.alt));
if (hit) problems.push(`doc "${d.id}" image "${b.id}" alt text contains internal vocabulary (${hit.source})`);
}
}
// Scan what the AGENT wrote, never what the person typed. `submitted` is the
// server's record of an answer someone pressed Send on; if their own words
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
+83
View File
@@ -0,0 +1,83 @@
# Diagnose on the Web Console
Workflow notes for `diagnose`, part of the web console contract (`console.md`).
## The bug
A typed argument that already describes the bug skips the cards it answers.
Otherwise ask in one batch (at most three open), posted with `--wait`:
```jsonc
{
"title": "Diagnose a bug",
"headline": { "stage": "The bug", "cleared": 0, "total": 3 },
"items": [
{ "id": "bug", "kind": "text", "title": "What is wrong",
"body": "The bug, in a sentence or two.",
"placeholder": "The CSV export drops the last row when the report has more than 100 rows." },
{ "id": "expected", "kind": "text", "title": "Expected and actual",
"body": "What should happen, and what happens instead.",
"placeholder": "Expected 150 rows in the file; it has 149, and the last order is missing." },
{ "id": "see-it", "kind": "text", "title": "How to see it",
"body": "The steps, command, page or input that shows it, and since when if you know.",
"placeholder": "Run npm run export -- --month 2026-09 and count the rows. It worked last month." }
]
}
```
No `"templates"` on these cards: the starter templates are for a fresh idea,
and a bug report is not one. A follow-up the answers leave open is a new card
with a new id.
## The cause
Post the cause as a doc, `id` `"cause"`, as soon as there is something to show,
and grow it as evidence lands, with `"agent": { "status": "working",
"activity": "..." }` while you reproduce and narrow:
```jsonc
"docs": [{ "id": "cause", "title": "The cause", "note": "Reproduced; narrowing", "blocks": [
{ "id": "repro", "state": "settled", "md": "## Reproduction\n\n`node scripts/export-check.mjs` fails: 149 rows, expected 150." },
{ "id": "found", "state": "settled", "md": "## The cause\n\n`src/export.ts` `writeRows()`: the loop stops at `rows.length - 1`. **Proven** by the reproduction." },
{ "id": "fix", "state": "settled", "md": "## Suggested fix\n\nLoop to `rows.length`. **Size:** Small (Quick Task)." }
]}]
```
- **Unproven** guesses are `assumed` blocks, one per guess, ranked, each with
its evidence and what would confirm it. A guess the evidence proves becomes
`settled`; one it rules out is removed (`"_delete": true`).
- Keeping a failing test inside the project is a `confirm` card pointing at
the doc (`"doc": "cause"`), `yesLabel` "Keep it", `noLabel` "Throw it away".
## The bug name
With the cause written, ask the folder name, posted with `--wait`:
```jsonc
{ "id": "name", "kind": "text", "title": "Name for the write-up", "doc": "cause",
"body": "The diagnosis is saved as `specs/<name>/DIAGNOSIS-<date>.md`. Lowercase words joined by dashes.",
"placeholder": "csv-export-drops-rows",
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$",
"patternHint": "Lowercase letters, numbers and dashes, like csv-export-drops-rows." }
```
Once written, re-send the doc with
`"saved": "specs/<name>/DIAGNOSIS-<date>.md"` and its blocks replaced by one
`file` block for that path (delete the old ids).
## The finish
`command` is `/plan2code-quick-task specs/<name>` (small fix) or
`/plan2code-1-plan specs/<name>` (big fix) with the real folder filled in
(`/plan2code-quick-task specs/csv-export-drops-rows`), never a placeholder: a
copied command must reach the diagnosis. `body` names the cause, how sure, and that the
next step reads the diagnosis first. `doc` is `"cause"`. `"dashboard": true`,
then keep waiting for the press (`console-finish.md`): back on the dashboard
the folder shows as "Bug diagnosed", with that card lit.
Nothing kept (the bug did not reproduce and no guess held up): leave
`command` out and say so in `body`.
A stop before the file is written ends on a finish whose `body` says nothing
was kept (and names any throwaway script or kept test you wrote), with
`"command": "/plan2code-diagnose"` (`console-stop.md`).
+1 -1
View File
@@ -12,7 +12,7 @@ know:
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`, as a `file` block on `overview.md`) so the page reader sees it land. |
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
| 6, Spec Cleanup | A `review` item before moving anything (`doc`: Step 3's summary), verdicts `yes` ("Archive it"), `show` ("Show me it working", token `show me`) and `no`, the archive paths in `body`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). On `show`, run it as `notes/implement.md` → Show me it working says (the summary line goes into `overview.md`'s Completion Summary), then reopen the card without `show`. |
Post `activity` as each step starts, before its doc or question lands — reading
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
+17 -4
View File
@@ -64,13 +64,14 @@ only ever be offered once nothing could come of it:
]}],
"items": [{
"id": "signoff", "kind": "review", "title": "Approve this phase", "doc": "report",
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, or say what to change.",
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, see it running, or say what to change.",
"verdicts": [
{ "id": "review", "label": "Review the code first" },
{ "id": "show", "label": "Show me it working" },
{ "id": "approve", "label": "Approve this phase" },
{ "id": "changes", "label": "I want changes" }
],
"token": { "approve": "approved", "changes": "needs changes" },
"token": { "approve": "approved", "changes": "needs changes", "show": "show me" },
"nothingYet": "Nothing is marked complete until you approve.",
"gate": { "id": "signoff", "authoritative": true }
}]
@@ -83,7 +84,19 @@ change, treat it as "describe any issues": do the change first and ask again.
`changes` means exactly what it says: address it, update the report, and reopen
the item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
person asking for the code review before they approve anything — read
`building-review.md`.
`building-review.md`. `show` is the terminal's `show me`: see below.
### Show me it working
On `show`, run the workflow's **Show me it working** paragraph (start the app,
look at the change, stop it, one summary line in `phase-X.md`). Save each
screenshot under the session's `shots/` folder, never under `specs/`, and post
them as image blocks in a `shown` doc (`console.md` → Documents), with what was
run in a `md` block above them; no browser tool means that block alone says
what the command printed. Then reopen the same card (`"status": "reopened"`)
without the `show` verdict, a `thread` reply naming what was seen. The same
holds on Finalize's card and the one `building-review.md` reopens; Quick
Task's card is settled instead (`notes/quick-task.md`).
`gate` marks the one approval that counts. The server refuses a second open
authoritative gate, which is what keeps a composed workflow from asking for
@@ -172,7 +185,7 @@ Stage 3 fixes, with no "Check the fixes" item: Stage 4 is the only gate. The
post that starts Stage 2's review carries `"run": { "event": "review", "id":
"review" }`: in this workflow it scores the review stage's 1 point on the meter
as it begins, and the phase's final `run` leaves that point out. Stage 4 is the
sign-off above **without the review verdict** — the phase was already reviewed
sign-off above (`show` included) **without the review verdict** — the phase was already reviewed
— with the review results and unresolved findings in the report doc, header
"Reviewed and ready for sign-off" in the item's `body`. The finish never
carries `review`, and its post carries `"run": { "event":
+15
View File
@@ -70,6 +70,21 @@ Workflow notes for `quick-task`, part of the web console contract
Check for a Quick question between steps, and do not call `wait` until the
build is done. Tick the Verify block's boxes too as the checks pass, in the
post that reports them.
- **See it running, before the finish:** a finished screen freezes every open
card, so ask first. Once the build is done, post a `review` item "See it
running" (`"doc": "plan"`, verdicts `show` ("Show me it working") and `fine`
("No need, finish up"), token `show me` / `no`) with `--wait`. On `show`, run
it as `notes/implement.md` → Show me it working says, its one line going into
the work summary (the finish's `body`); then, or on `fine`, settle the card in
the same post as the finish.
- **Archive a fixed bug, before the finish:** launched on a diagnosed folder
and now Fixed with nothing past the diagnosis, post a `confirm` card
"Archive this bug?" in the same post as "See it running": the dry run's
`files` in `body`, `yesLabel` "Archive it", `noLabel` "Keep it in specs/",
and `consequences` naming `specs--completed/<bug>/`. On yes, run
`node "<S>/specs.mjs" archive <spec>` (the skill file says where `<S>` is),
and say where it went in the finish's `body`. On no, the
dashboard lists the folder as "Bug fixed", never pre-selected.
- **The finish after the build:** `command` is the commit command, filled in,
in the project's commit format (AGENTS.md), with
`"where": "When you are happy with it, commit it from your terminal:"`, and
+73
View File
@@ -0,0 +1,73 @@
# X-ray on the Web Console
Workflow notes for `xray`, part of the web console contract (`console.md`).
## The mode question
A typed argument that names the mode and area skips it. Otherwise ask both in
one batch, posted with `--wait`:
```jsonc
{
"title": "Codebase X-ray",
"headline": { "stage": "Choosing", "cleared": 0, "total": 2 },
"items": [
{ "id": "mode", "kind": "choice", "title": "What you want to know", "allowOther": false,
"body": "Explain one area, or rank what makes this code hard to change.",
"options": [
{ "k": "1", "text": "Explain an area", "detail": "How it works and why it is that way, citing files and the commits behind it." },
{ "k": "2", "text": "Find the rough spots", "detail": "Ranked spots that make change hard. You pick the ones worth fixing; they become a brief for Pathfinder or Plan." }
] },
{ "id": "area", "kind": "text", "title": "Which area", "required": false,
"body": "A folder, file or feature. Needed to explain; leave it empty to survey the whole repository.",
"placeholder": "src/exporter, the code that builds the CSV reports" }
]
}
```
Explain picked with the area left empty: ask for it again as a required `text`
card. No recommendation on the mode: only the person knows what they came for.
## Explain mode
The answer is a doc, `id` `"answer"`, one block per section (`In one paragraph`,
`How it works`, `Why it is this way`, `Worth knowing`), with the `Sources:` line
at the top of the first. Then the save offer as a `confirm` card pointing at it:
```jsonc
{ "id": "keep", "kind": "confirm", "title": "Keep this answer", "doc": "answer",
"body": "Save it as `specs/exporter/XRAY-exporter-20261016.md`, as input for Pathfinder or Plan?",
"yesLabel": "Save it", "noLabel": "No, just reading" }
```
Ask the folder name in the same batch as a `text` card with `pattern`
`^[a-z0-9]+(-[a-z0-9]+)*$` when it is not obvious. Once written, re-send the doc
with `"saved": "specs/<name>/XRAY-<area-slug>-<date>.md"`.
## Rough-spots mode
The ranked list is a doc, `id` `"spots"`, one block per spot (its files, why it
hurts, the "to change X today" example). The pick is one `multi` card pointing
at it, posted with `--wait`:
```jsonc
{ "id": "pick", "kind": "multi", "title": "Worth fixing", "doc": "spots", "required": false,
"body": "Tick the spots worth fixing. Add a note for any of them in the box (\"1: the exporter part only\"). Only ticked spots go into the brief.",
"options": [
{ "k": "1", "text": "Exporter and its formatter always change together", "detail": "src/export.ts, src/format.ts: together in 14 of 16 commits." }
] }
```
Nothing ticked: nothing is written. Otherwise write the brief, then add it as a
second doc with `"saved": "specs/<name>/ARCHITECTURE-BRIEF-<date>.md"` and a
`file` block.
## The finish
`command` is `/plan2code-0-pathfinder` (big or unclear) or `/plan2code-1-plan`
(settled), never with a placeholder; leave it out when nothing was kept. `doc`
is the brief or the saved answer when there is one. `"dashboard": true`, then
keep waiting for the press (`console-finish.md`).
A stop before anything was written ends on a finish whose `body` says nothing
was kept, with `"command": "/plan2code-xray"` (`console-stop.md`).
+103 -8
View File
@@ -270,6 +270,8 @@ export const WORKFLOW_LABEL = {
handoff: "Handoff",
git: "Git",
changelog: "Changelog",
xray: "X-ray",
diagnose: "Diagnosing",
};
export function workflowLabel(workflow) {
@@ -296,6 +298,8 @@ export const CONSOLE_WORKFLOWS = [
"/plan2code-handoff",
"/plan2code-git",
"/plan2code-changelog",
"/plan2code-xray",
"/plan2code-diagnose",
];
// Rides on the end of the command as part of the skill's argument. Every
@@ -465,6 +469,10 @@ export function resumeCommand({ workflow, specDir } = {}) {
return "/plan2code-git";
case "changelog":
return "/plan2code-changelog";
case "xray":
return "/plan2code-xray";
case "diagnose":
return "/plan2code-diagnose";
default:
return dir ? `/plan2code-0-pathfinder ${dir}/pathfinder` : "/plan2code-0-pathfinder";
}
@@ -680,15 +688,26 @@ export const SKILL_CATALOG = [
"A fresh-eyes pass over what changed: bugs, gaps, and the things the builder was too close to see. Problems come back ranked with a suggestion each, you pick which ones get fixed, and it fixes them.",
},
{
skill: "plan2code-handoff",
command: "/plan2code-handoff",
workflow: "handoff",
skill: "plan2code-xray",
command: "/plan2code-xray",
workflow: "xray",
group: "extra",
chip: "Utility",
title: "Handoff",
blurb: "Pack the current session into a document a fresh session can pick up cold.",
title: "Codebase X-ray",
blurb: "Explain how and why an area works, or find the rough spots worth fixing.",
about:
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
"Two ways into code you did not write. Explain an area: how it works, step by step, and why it is that way, citing the files and the commits and pull requests behind it. Or find the rough spots: files that always change together, thin layers, tangled boundaries and busy code with no tests, ranked with a concrete example each. You tick the ones worth fixing and they become a brief for Pathfinder or Plan. It never changes code.",
},
{
skill: "plan2code-diagnose",
command: "/plan2code-diagnose",
workflow: "diagnose",
group: "extra",
chip: "Utility",
title: "Diagnose a bug",
blurb: "Find a bug's cause and write it up, without fixing it.",
about:
"Something is broken and nobody knows why. Diagnose asks what goes wrong and how to see it, then builds a command that fails on the bug before it forms a theory. It narrows the cause down to a file and a function, says how sure it is, and sizes the fix. The write-up lands in a spec folder, and the dashboard then offers Quick Task to fix it, or Plan when the fix is big. It never changes code.",
},
{
skill: "plan2code-changelog",
@@ -712,6 +731,17 @@ export const SKILL_CATALOG = [
about:
"Shows your branch, what is ahead or behind, and every local and remote branch. Switch, create, delete or clean up branches, pull (rebasing when they have split, with help on conflicts), push or publish, and commit with a clear message. It asks before every push, publish and delete, and never force-pushes.",
},
{
skill: "plan2code-handoff",
command: "/plan2code-handoff",
workflow: "handoff",
group: "extra",
chip: "Utility",
title: "Handoff",
blurb: "Pack the current session into a document a fresh session can pick up cold.",
about:
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
},
];
// A workflow by the name its dashboard card gives it ("Implement"), for the
@@ -736,6 +766,8 @@ export const START_POSES = [
"handoff",
"git",
"changelog",
"xray",
"diagnose",
];
const POSE_ALIASES = { "init-update": "init", "revise-plan": "plan", "implement-review": "implement" };
@@ -754,6 +786,8 @@ export function catalogEntry(skill) {
// What the picker shows next to a spec's name — the pipeline position the
// server's scan worked out, in plain words.
export const SPEC_STATE_LABELS = {
diagnosed: "Bug diagnosed",
fixed: "Bug fixed",
exploring: "Exploring",
mapped: "Ready to plan",
planned: "Ready to document",
@@ -766,6 +800,7 @@ export const SPEC_STATE_LABELS = {
// The card each spec state exists to light up. Used as the fallback for the
// "Suggested" pill when the agent's menu payload names nothing.
const NEXT_FOR_STATE = {
diagnosed: "plan2code-quick-task",
exploring: "plan2code-0-pathfinder",
mapped: "plan2code-1-plan",
planned: "plan2code-2-document",
@@ -778,6 +813,16 @@ const ON = { on: true };
export const GIT_INIT_NOTE = "Not a git repository yet: it offers to start one";
export const pendingNote = (n) => `${n} file${n === 1 ? "" : "s"} to commit`;
const off = (reason) => ({ on: false, reason });
const FIXED_REASON = "This bug is fixed. Delete it with ✕, or move it to specs--completed/.";
/**
* The spec the picker opens on: the most recently touched one that is still
* in play. A fixed bug is finished, so it is never the default; with nothing
* else on disk the picker opens on "start from scratch" (null).
*/
export function defaultSpec(specs) {
return (Array.isArray(specs) ? specs : []).find((s) => s && s.state !== "fixed") || null;
}
/**
* Whether a catalog card is clickable for the current picker selection.
@@ -803,9 +848,13 @@ export function cardAvailability(entry, scan, sel) {
case "plan2code-init-update":
return hasAgents ? ON : off("Needs an AGENTS.md. Set the project up first.");
case "plan2code-quick-task":
// Always on; a diagnosed bug is the one spec it is the next step for.
return next ? { ...ON, next } : ON;
case "plan2code-review":
case "plan2code-handoff":
case "plan2code-changelog":
case "plan2code-xray":
case "plan2code-diagnose":
return ON;
case "plan2code-git":
// Never greyed: a clean tree still has branches to switch, pull and push.
@@ -814,9 +863,12 @@ export function cardAvailability(entry, scan, sel) {
return ON;
case "plan2code-0-pathfinder":
if (!state || state === "exploring") return { ...ON, next };
if (state === "diagnosed") return off("The cause is found. Fix it in a quick task, or plan it.");
if (state === "fixed") return off(FIXED_REASON);
return off("This spec is already past the questions");
case "plan2code-1-plan":
if (state === "exploring") return off("Pathfinder is not finished with this spec yet");
if (state === "fixed") return off(FIXED_REASON);
if (state === "documented" || state === "building" || state === "built")
return off("The plan is written. Revise it instead if it moved.");
return { ...ON, next };
@@ -840,10 +892,21 @@ export function cardAvailability(entry, scan, sel) {
}
}
/**
* The spec a card's launch carries: the picker's selection for the cards that
* take a spec, and for Quick Task only a diagnosed bug, whose write-up it reads
* first. Every other card launches untargeted.
*/
export function launchTarget(entry, sel) {
if (!entry || !sel) return null;
if (entry.spec) return sel;
return entry.skill === "plan2code-quick-task" && sel.state === "diagnosed" ? sel : null;
}
export function cardPresentation(entry, scan, sel, menu = {}) {
const availability = cardAvailability(entry, scan, sel);
const specs = scan && Array.isArray(scan.specs) ? scan.specs : [];
const initial = specs.length ? Boolean(sel && sel.dir === specs[0].dir) : !sel;
const first = defaultSpec(scan && scan.specs);
const initial = first ? Boolean(sel && sel.dir === first.dir) : !sel;
const requested = initial && typeof menu.recommend === "string" ? catalogEntry(menu.recommend) : null;
const recommendation = requested && cardAvailability(requested, scan, sel).on ? requested.skill : null;
const recommended = availability.on && (recommendation ? entry.skill === recommendation : availability.next);
@@ -871,6 +934,38 @@ export function launchReply(entry, spec) {
return `Start ${entry.title} (${entry.command})${target}, right here in this session.`;
}
/**
* Deleting a spec from the picker. The page only names the folder; the agent
* deletes it (`console.mjs delete-spec`, which runs lib.mjs's removeSpec() on
* this same rule), because the console never writes into a project. A
* deletable dir is exactly `specs/<one name>`: no deeper path, no `.` or `..`,
* no dotfolder, no backslash, never specs--completed/.
*/
export function isDeletableSpecDir(dir) {
return typeof dir === "string" && /^specs\/[^/\\]+$/.test(dir) && !/^specs\/\./.test(dir);
}
export function deleteAction(spec) {
return { i: "__delete", type: "delete", spec: spec.dir };
}
export function deleteReply(spec) {
return `Delete the spec folder ${spec.dir}/ for good, right here in this session.`;
}
// What the delete dialog says about the spec, from the scan alone. `touched`
// stays a number: the page formats it in the person's own locale.
export function deleteSummary(spec) {
const label = SPEC_STATE_LABELS[spec.state] || spec.state || "";
const n = spec.files;
return {
folder: `${spec.dir}/`,
stage: spec.detail ? `${label}: ${spec.detail}` : label,
files: Number.isInteger(n) ? `${n} file${n === 1 ? "" : "s"}` : "",
touched: Number.isFinite(spec.touched) && spec.touched > 0 ? spec.touched : null,
};
}
export function staleLaunchFeedback(title, adrift) {
if (!adrift) return null;
return {
+109
View File
@@ -2043,6 +2043,9 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.md-table th, .md-table td { border: 1px solid var(--rule); padding: 8px 11px; text-align: left; }
.md-table th { background: var(--panel-2); font-weight: 600; }
.md-img { max-width: 100%; border-radius: 8px; }
.doc-figure { margin: 0 0 13px; }
.doc-img { display: block; max-width: 100%; height: auto; border: 1px solid var(--rule); border-radius: 8px; }
.doc-figure figcaption { font-size: 13px; color: var(--ink-2); margin-top: 6px; }
.md a { color: var(--accent); }
/* ------------------------------------------------------------- footer */
@@ -3053,6 +3056,50 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
}
.spec-chip:not(.is-sel) .spec-chip-state { color: var(--ink-3); }
.spec-chip-detail { font-size: 11.5px; color: var(--ink-3); }
/* A spec's Delete button sits beside its chip, not inside it: a button cannot
hold a button. Quiet until the chip is hovered or focused. */
.spec-chip-wrap { position: relative; display: flex; }
.spec-chip-wrap.is-fixed .spec-chip:not(.is-sel) { opacity: 0.6; }
.spec-chip-wrap .spec-chip { padding-right: 36px; }
.spec-chip-del {
position: absolute;
top: 6px;
right: 6px;
width: 24px;
height: 24px;
display: grid;
place-items: center;
padding: 0;
border: 1px solid transparent;
border-radius: 6px;
background: transparent;
color: var(--ink-3);
font: inherit;
font-size: 15px;
line-height: 1;
cursor: pointer;
opacity: 0.55;
}
.spec-chip-wrap:hover .spec-chip-del,
.spec-chip-del:focus-visible { opacity: 1; }
.spec-chip-del:hover { color: var(--warn); border-color: var(--warn); opacity: 1; }
.spec-chip-del:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
.spec-chip-del:disabled { cursor: default; opacity: 0.3; }
.spec-chip-wrap.is-deleting .spec-chip { opacity: 0.5; }
.delete-facts { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 14px 0 0; font-size: 13.5px; }
.delete-facts dt { color: var(--ink-3); }
.delete-facts dd { margin: 0; overflow-wrap: anywhere; }
.delete-confirm { margin-top: 16px; display: flex; flex-direction: column; gap: 8px; font-size: 13.5px; }
.delete-confirm[hidden] { display: none; }
.delete-confirm input {
padding: 8px 10px;
border: 1px solid var(--rule-2);
border-radius: var(--radius);
background: var(--panel);
color: var(--ink);
font: inherit;
}
.delete-confirm input:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
/* ------------------------------------------------- dashboard confirm */
@@ -3524,6 +3571,68 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
/* Changelog -- the arm reaches the page and the newest line is written in step. */
.pose .cl-line { animation: gc-dot 2.4s ease-in-out infinite; }
/* Codebase X-ray -- the scan line sweeps down the file, the rough spot lights
up as it passes, and the lens and his star follow it down. */
.pose .xr-scan { animation: xr-scan 4s ease-in-out infinite; }
@keyframes xr-scan {
0%, 10% { opacity: 0; transform: translateY(0); }
16% { opacity: 1; }
74% { opacity: 1; }
80%, 100% { opacity: 0; transform: translateY(88px); }
}
.pose .xr-spot { animation: xr-spot 4s ease-out infinite; }
@keyframes xr-spot {
0%, 50% { opacity: 0; transform: scale(0.3); }
56% { opacity: 1; transform: scale(1.3); }
62%, 90% { opacity: 1; transform: scale(1); }
100% { opacity: 0; transform: scale(1); }
}
.pose .xr-lens { animation: xr-lens 4s ease-in-out infinite; }
@keyframes xr-lens {
0%, 10%, 100% { transform: translate(0, -3px); }
56%, 80% { transform: translate(0, 4px); }
}
.pose .xr-look { animation: xr-look 4s ease-in-out infinite; }
@keyframes xr-look {
0%, 10%, 100% { transform: translate(4px, -1px); }
56%, 80% { transform: translate(4px, 2px); }
}
/* Diagnose a bug -- the bug scuttles along its line, the magnifier and his
star follow it until it is caught, and the red mark under the line shows
once it holds still. Held still, the bug sits caught under the lens. */
.pose .dg-mark { fill: none; stroke: var(--warn); stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
.pose .dg-leg { fill: none; stroke: var(--ink); stroke-width: 2; stroke-linecap: round; }
.pose .dg-body { fill: var(--warn); }
.pose .dg-head { fill: var(--ink); }
.pose .dg-bug { animation: dg-bug 4s ease-in-out infinite; }
@keyframes dg-bug {
0%, 100% { transform: translate(-7px, 0) rotate(-12deg); }
14% { transform: translate(-2px, 0) rotate(10deg); }
26% { transform: translate(4px, 0) rotate(-10deg); }
36% { transform: translate(1px, 0) rotate(8deg); }
44%, 88% { transform: translate(0, 0) rotate(0deg); }
}
.pose .dg-lens { animation: dg-lens 4s ease-in-out infinite; }
@keyframes dg-lens {
0%, 100% { transform: translate(-9px, -2px); }
18% { transform: translate(-3px, -1px); }
30% { transform: translate(3px, 0); }
44%, 88% { transform: translate(0, 0); }
}
.pose .dg-mark { animation: dg-mark 4s ease-out infinite; }
@keyframes dg-mark {
0%, 44% { opacity: 0; }
52%, 88% { opacity: 1; }
96%, 100% { opacity: 0; }
}
.pose .dg-look { animation: dg-look 4s ease-in-out infinite; }
@keyframes dg-look {
0%, 100% { transform: translate(2px, 0); }
30% { transform: translate(5px, 0); }
44%, 88% { transform: translate(4px, 1px); }
}
@media (max-width: 720px) {
.dash { padding-top: 0; }
.launch-stage { height: 140px; }
+170 -18
View File
@@ -22,6 +22,7 @@ import {
briefPhrase,
cardAvailability,
cardPresentation,
defaultSpec,
CATALOG_GROUPS,
choiceAnswer,
DASHBOARD_COMMAND,
@@ -42,6 +43,11 @@ import {
IMAGE_QUALITY,
lastOpenCard,
launchReply,
launchTarget,
deleteAction,
deleteReply,
deleteSummary,
isDeletableSpecDir,
MAX_ATTACHMENTS,
nextOpenAfter,
MAX_DOC_BYTES,
@@ -597,6 +603,8 @@ function fresh() {
afterBuild: null,
homeward: null,
launching: null,
// A picker Delete sent and not yet answered by a rescan: { dir, scanAt }.
deleting: null,
retract: {},
chat: freshChat(),
};
@@ -812,13 +820,14 @@ const specList = () => {
};
// The spec the picker currently targets. Absent `specSel` means the picker
// has not been touched, so it defaults to the most recently touched spec —
// the first entry of the server's already-sorted list. An explicit "start
// from scratch" is stored as null, which is different.
// has not been touched, so it defaults to the most recently touched spec
// still in play (defaultSpec: the server's list is already sorted, and a
// fixed bug is skipped). An explicit "start from scratch" is stored as null,
// which is different.
const selSpec = () => {
const specs = specList();
if (!specs.length) return null;
if (local.specSel === undefined) return specs[0];
if (local.specSel === undefined) return defaultSpec(specs);
return specs.find((s) => s.dir === local.specSel) || null;
};
@@ -1054,8 +1063,8 @@ function adopt(body) {
const viaDashboard = prevWorkflow === "dashboard" || S.workflow === "dashboard";
if (prevWorkflow && prevWorkflow !== S.workflow && viaDashboard) {
// The pick rides into the skill it launched, never back home: arriving at
// the dashboard, the picker starts on the most recently touched spec, the
// one the agent's fresh menu recommends for.
// the dashboard, the picker starts on the most recently touched spec still
// in play, the one the agent's fresh menu recommends for.
const keepPick = S.workflow !== "dashboard" && "specSel" in local;
local = { ...fresh(), launching: local.launching, ...(keepPick ? { specSel: local.specSel } : {}) };
save();
@@ -3056,7 +3065,9 @@ function updateDismissed() {
}
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
const UPDATE_COMMAND = "plan2code update";
// For a machine without the plan2code command: the full installer, menu and all.
const UPDATE_FALLBACK_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
function releasesLink(text) {
const a = el("a", null, text);
@@ -3079,6 +3090,9 @@ function openUpdateModal() {
const row = $("update-command");
const code = el("code", null, UPDATE_COMMAND);
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
const fallbackRow = $("update-fallback");
const fallback = el("code", null, UPDATE_FALLBACK_COMMAND);
fallbackRow.replaceChildren(fallback, copyButton(UPDATE_FALLBACK_COMMAND, "btn small ghost handoff-copy", fallback));
$("update-modal").showModal();
}
@@ -3117,9 +3131,9 @@ function renderDashboard(main) {
// The agent's note reads the spec the picker opened on (the same "initial"
// test cardPresentation uses): another pick, or Start from scratch, gets
// the neutral line rather than context about a spec no longer shown.
const specsNow = (scan() && scan().specs) || [];
const first = defaultSpec(scan() && scan().specs);
const picked = selSpec();
const onInitial = specsNow.length ? Boolean(picked && picked.dir === specsNow[0].dir) : !picked;
const onInitial = first ? Boolean(picked && picked.dir === first.dir) : !picked;
if (typeof menu.note === "string" && menu.note.trim() && onInitial) {
wrap.appendChild(el("p", "dash-note", menu.note));
} else if (!S.menu && agentWorking()) {
@@ -3681,13 +3695,26 @@ function renderSpecPicker(specs) {
});
row.appendChild(scratch);
// A delete in flight ends when the agent's rescan lands (a new scan), gone
// or refused: either way the picker below is the truth again.
const sc = scan();
if (local.deleting && sc && sc.at !== local.deleting.scanAt) {
local.deleting = null;
save();
}
for (const spec of specs) {
const on = sel && sel.dir === spec.dir;
// A fixed bug is finished: hidden while unavailable workflows are, dimmed
// otherwise. A pick already on it stays visible, so it is never lost.
const fixed = spec.state === "fixed";
if (fixed && looks.hideUnavailable && !on) continue;
const deleting = Boolean(local.deleting && local.deleting.dir === spec.dir);
const wrap = el("div", "spec-chip-wrap" + (deleting ? " is-deleting" : "") + (fixed ? " is-fixed" : ""));
const b = el("button", "spec-chip" + (on ? " is-sel" : ""));
b.type = "button";
b.setAttribute("aria-current", String(Boolean(on)));
b.appendChild(el("span", "spec-chip-name", spec.name));
b.appendChild(el("span", "spec-chip-state", SPEC_STATE_LABELS[spec.state] || spec.state));
b.appendChild(el("span", "spec-chip-state", deleting ? "Deleting…" : SPEC_STATE_LABELS[spec.state] || spec.state));
if (spec.detail) b.appendChild(el("span", "spec-chip-detail", spec.detail));
b.addEventListener("click", () => {
local.specSel = spec.dir;
@@ -3695,7 +3722,17 @@ function renderSpecPicker(specs) {
render();
loadOverview();
});
row.appendChild(b);
wrap.appendChild(b);
if (isDeletableSpecDir(spec.dir)) {
const del = el("button", "spec-chip-del", "✕");
del.type = "button";
del.title = `Delete ${spec.dir}/`;
del.setAttribute("aria-label", `Delete the spec ${spec.name}`);
del.disabled = deleting || Boolean(local.deleting) || gone || pendingResult || Boolean(local.launching);
del.addEventListener("click", () => openDeleteConfirm(spec));
wrap.appendChild(del);
}
row.appendChild(wrap);
}
box.appendChild(row);
return box;
@@ -3781,7 +3818,7 @@ function renderConfirm(main, entry) {
// A card that takes a spec names the one the picker is holding, so START
// reads as "build THIS spec", not the skill in the abstract.
const target = entry.spec ? selSpec() : null;
const target = launchTarget(entry, selSpec());
if (target) {
const specLine = el("p", "confirm-spec");
specLine.appendChild(el("span", null, "for "));
@@ -3821,7 +3858,7 @@ function renderConfirm(main, entry) {
// through the same wait loop. The dashboard reads `skill` off it.
async function launchSkill(entry) {
if (gone || pendingResult || local.launching || finish()) return;
const target = entry.spec ? selSpec() : null;
const target = launchTarget(entry, selSpec());
// The card was clickable, so this should never fire — but a spec picked in
// one tab could have shifted the ground under a stale render in another.
if (!cardAvailability(entry, scan(), selSpec()).on) {
@@ -3839,7 +3876,7 @@ async function launchSkill(entry) {
};
// The picker's spec goes to the skill being launched, not to the card:
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected.
// a spec is selected, save Quick Task on a diagnosed bug.
if (target) action.spec = target.dir;
// The skill opens on the folders remembered for what it was launched for.
// Held until the launch is in flight: the swap's own frame re-renders the
@@ -5614,11 +5651,27 @@ function renderDoc(main, id) {
box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
}
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
box.appendChild(md(b.md, "md"));
box.appendChild(blockBody(b));
main.appendChild(box);
});
}
// A block's content: its markdown, or for an image block (a screenshot the
// agent saved under the session's shots/ folder) a captioned picture.
function blockBody(b) {
if (typeof b.image !== "string") return md(b.md, "md");
const fig = el("figure", "doc-figure");
const img = el("img", "doc-img");
img.src = "/shots/" + b.image.split("/").pop();
// The caption already says it: an alt repeating it is read twice, and shows
// twice in an export whose picture would not load.
img.alt = "";
img.loading = "lazy";
fig.appendChild(img);
if (b.alt) fig.appendChild(el("figcaption", null, b.alt));
return fig;
}
function printButton() {
const print = el("button", "btn small", "Print");
print.type = "button";
@@ -7495,6 +7548,88 @@ function openHomeConfirm() {
$("home-modal").showModal();
}
// The picker's Delete: a dialog in two steps. The first says what goes and
// that it is for good; "Delete this spec…" then reveals the second, which
// enables the final button only once the spec's name is typed exactly.
// Cancel, Escape or a click on Keep it at either step changes nothing.
let deleteTarget = null;
function openDeleteConfirm(spec) {
if (!isDeletableSpecDir(spec.dir) || gone || pendingResult || local.launching || local.deleting) return;
deleteTarget = spec;
const sum = deleteSummary(spec);
$("delete-blurb").textContent = `Everything in ${sum.folder} will be deleted from this project.`;
const facts = $("delete-facts");
facts.replaceChildren();
const fact = (term, value) => {
if (!value) return;
facts.appendChild(el("dt", "", term));
facts.appendChild(el("dd", "", value));
};
fact("Spec", spec.name);
fact("Folder", sum.folder);
fact("Stage", sum.stage);
fact("Files", sum.files);
fact("Last changed", sum.touched ? new Date(sum.touched).toLocaleString() : "");
$("delete-name-hint").textContent = spec.name;
$("delete-name").value = "";
$("delete-confirm").hidden = true;
const go = $("delete-go");
go.textContent = "Delete this spec…";
go.classList.remove("is-on");
go.disabled = false;
$("delete-modal").showModal();
}
function deleteStep() {
const go = $("delete-go");
if (!deleteTarget) return;
if ($("delete-confirm").hidden) {
$("delete-confirm").hidden = false;
go.textContent = "Delete for good";
go.classList.add("is-on");
go.disabled = true;
$("delete-name").focus();
return;
}
if ($("delete-name").value.trim() !== deleteTarget.name) return;
sendDelete(deleteTarget);
}
async function sendDelete(spec) {
const go = $("delete-go");
go.disabled = true;
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [deleteAction(spec)], reply: deleteReply(spec) }),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
const sc = scan();
local.deleting = { dir: spec.dir, scanAt: sc ? sc.at : null };
// The selection must not outlive the folder: back to the default pick,
// which the agent's fresh menu recommends for.
if (local.specSel === spec.dir) delete local.specSel;
pendingResult = true;
save();
$("delete-modal").close();
} catch (err) {
$("delete-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
: "That did not go through. Nothing was deleted; try again.",
"warn"
);
} finally {
deleteTarget = null;
render();
}
}
async function goHome() {
const go = $("home-go");
go.disabled = true;
@@ -7847,7 +7982,7 @@ function downloadDoc(doc) {
// assumptions or drafts. Without the marks a half-finished document reads,
// once it leaves the page, as a set of decisions.
const mark = { assumed: "> **Assumed for now, still open.**\n\n", draft: "> **Draft.**\n\n" };
const blocks = (doc.blocks || []).map((b) => (mark[b.state] || "") + (b.md || ""));
const blocks = (doc.blocks || []).map((b) => (mark[b.state] || "") + (typeof b.image === "string" ? b.alt || "" : b.md || ""));
const first = (doc.blocks || [])[0];
const titled = first && /^\s*#\s/.test(first.md || "");
const body = [titled || !doc.title ? null : `# ${doc.title}`, ...blocks].filter((x) => x != null).join("\n\n");
@@ -7910,6 +8045,9 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.md-table th, .md-table td { border: 1px solid #e4ddd1; padding: 8px 11px; text-align: left; }
.md-table th { background: #fbf9f6; font-weight: 600; }
.md-img { max-width: 100%; border-radius: 8px; }
.doc-figure { margin: 0 0 13px; }
.doc-img { display: block; max-width: 100%; border: 1px solid #e4ddd1; border-radius: 8px; }
.doc-figure figcaption { font-size: 13px; color: #5d564d; margin-top: 6px; }
.md a { color: #206cc3; }
@media print {
body { background: #fff; }
@@ -7922,7 +8060,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
// address on this origin (/state, say) would copy session data into something
// meant to be shared. A remote image keeps its own address; anything else on
// this origin becomes its alt text.
const INLINE_UPLOAD = /^\/uploads\/[0-9a-f-]{36}\.jpg$/;
const INLINE_UPLOAD = /^\/(?:uploads\/[0-9a-f-]{36}\.jpg|shots\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(?:png|jpe?g|webp))$/i;
function imageToAlt(img) {
const alt = img.getAttribute("alt") || "";
@@ -7977,7 +8115,7 @@ async function downloadDocHtml(doc) {
const box = el("div", "block " + (b.state || "settled"));
if (b.state === "assumed") box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
box.appendChild(md(b.md, "md"));
box.appendChild(blockBody(b));
body.appendChild(box);
}
// Copy buttons only work inside the console.
@@ -8160,6 +8298,20 @@ function openHelpOn(id) {
$("btn-home").addEventListener("click", openHomeConfirm);
$("update-done").addEventListener("click", () => $("update-modal").close());
$("delete-cancel").addEventListener("click", () => $("delete-modal").close());
$("delete-go").addEventListener("click", deleteStep);
$("delete-name").addEventListener("input", () => {
$("delete-go").disabled = !deleteTarget || $("delete-name").value.trim() !== deleteTarget.name;
});
$("delete-name").addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
deleteStep();
}
});
$("delete-modal").addEventListener("close", () => {
deleteTarget = null;
});
$("home-cancel").addEventListener("click", () => $("home-modal").close());
$("home-go").addEventListener("click", goHome);
$("btn-stop").addEventListener("click", openStopConfirm);
+96 -3
View File
@@ -595,6 +595,75 @@
</g>
</g>
</svg>
<!-- Codebase X-ray: seeing how it works. He holds a lens up to a file,
a scan line sweeps down it to show the structure inside, and a rough
spot lights up as the scan passes over it. -->
<svg class="pose pose-xray" data-pose="xray" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
<ellipse class="shadow" cx="126" cy="198" rx="44" ry="5" />
<g class="prop">
<rect class="sh" x="182" y="60" width="44" height="112" rx="6" />
<line class="lt" x1="196" y1="76" x2="196" y2="152" />
<path class="lt" d="M196 96 L212 96 M196 124 L212 124" />
<circle class="ac" cx="196" cy="76" r="4" />
<circle class="ac" cx="212" cy="96" r="3.5" />
<circle class="ac" cx="212" cy="124" r="3.5" />
<circle class="ac" cx="196" cy="152" r="4" />
<g class="xr-spot"><circle class="as" cx="212" cy="124" r="8" /></g>
<line class="as xr-scan" x1="188" y1="70" x2="220" y2="70" />
</g>
<g class="bob">
<g transform="translate(-14 0)">
<rect class="fl foot f1" x="94" y="179" width="20" height="10" rx="5" />
<rect class="fl foot f2" x="126" y="179" width="20" height="10" rx="5" />
<rect class="sh" x="80" y="72" width="80" height="108" rx="16" />
<path class="ln" d="M80 126 L66 150" /><circle class="fl" cx="66" cy="150" r="5.5" />
<g class="xr-look"><path class="ey blink" d="M126 86 L129.64 94.98 L139.31 95.67 L131.9 101.92 L134.23 111.33 L126 106.2 L117.77 111.33 L120.1 101.92 L112.69 95.67 L122.36 94.98 Z" /></g>
<path class="es" d="M110 120 Q122 129 134 120" />
<line class="ln" x1="160" y1="126" x2="192" y2="132" />
<g class="xr-lens">
<line class="ln" x1="192" y1="132" x2="204" y2="120" />
<circle class="lt" cx="214" cy="110" r="14" />
</g>
<circle class="fl" cx="192" cy="132" r="5.5" />
</g>
</g>
</svg>
<!-- Diagnose a bug: finding the cause. A small bug scuttles along one
line of a file, his magnifier follows it until it is caught, and the
line it sits on is marked in red. He looks, he does not fix. -->
<svg class="pose pose-diagnose" data-pose="diagnose" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
<ellipse class="shadow" cx="126" cy="198" rx="44" ry="5" />
<g class="prop">
<rect class="sh" x="176" y="60" width="46" height="112" rx="6" />
<line class="lt" x1="184" y1="78" x2="208" y2="78" />
<line class="lt" x1="188" y1="96" x2="214" y2="96" />
<path class="dg-mark" d="M184 124 Q187 120 190 124 T196 124 T202 124 T208 124 T214 124" />
<line class="lt" x1="188" y1="142" x2="208" y2="142" />
<line class="lt" x1="184" y1="158" x2="202" y2="158" />
<g class="dg-bug">
<path class="dg-leg" d="M195 111 L189 108 M195 115 L189 115 M195 119 L189 122 M205 111 L211 108 M205 115 L211 115 M205 119 L211 122 M198 104 L195 99 M202 104 L205 99" />
<ellipse class="dg-body" cx="200" cy="115" rx="5.5" ry="7" />
<circle class="dg-head" cx="200" cy="106" r="3.2" />
</g>
</g>
<g class="bob">
<g transform="translate(-14 0)">
<rect class="fl foot f1" x="94" y="179" width="20" height="10" rx="5" />
<rect class="fl foot f2" x="126" y="179" width="20" height="10" rx="5" />
<rect class="sh" x="80" y="72" width="80" height="108" rx="16" />
<path class="ln" d="M80 126 L66 150" /><circle class="fl" cx="66" cy="150" r="5.5" />
<g class="dg-look"><path class="ey blink" d="M126 86 L129.64 94.98 L139.31 95.67 L131.9 101.92 L134.23 111.33 L126 106.2 L117.77 111.33 L120.1 101.92 L112.69 95.67 L122.36 94.98 Z" /></g>
<path class="ln" d="M113 82 Q126 77 139 83" />
<line class="es" x1="114" y1="124" x2="128" y2="124" />
<line class="ln" x1="160" y1="126" x2="174" y2="140" />
<g class="dg-lens">
<line class="ln" x1="174" y1="140" x2="180" y2="127" />
<circle class="lt" cx="186" cy="114" r="14" />
</g>
<circle class="fl" cx="174" cy="140" r="5.5" />
</g>
</g>
</svg>
</template>
<!-- The Help dialog's content, cloned into #help-modal the first time ? is
@@ -1546,7 +1615,7 @@
<p>
When a newer Plan2Code release is out, the dashboard shows
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
to run in your terminal; × hides it until the next
to run in your terminal, <code>plan2code update</code>; × hides it until the next
<code>/plan2code</code>. The version at the bottom of Help links to
the Releases page.
</p>
@@ -1574,6 +1643,8 @@
<li><strong>Handoff.</strong> Pack the current session into a document a fresh session can pick up cold.</li>
<li><strong>Changelog.</strong> Checks the CHANGELOG version against the main branch and suggests entries for what is new.</li>
<li><strong>Git.</strong> Branches, pull, push and commits on one board, asking before anything leaves your machine. See "The git board".</li>
<li><strong>Codebase X-ray.</strong> Explains how and why an area of the code works, or finds the rough spots worth fixing.</li>
<li><strong>Diagnose a bug.</strong> Finds a bug's cause and writes it up without fixing it, ready to hand to Quick Task or Plan.</li>
</ul>
<h4>Picking a spec</h4>
<p>
@@ -2520,6 +2591,24 @@
</div>
</dialog>
<!-- Deleting a spec from the dashboard's picker. Two deliberate steps: the
first says what goes and that it is for good, the second wants the
spec's name typed. The page only asks; the agent deletes. -->
<dialog class="modal" id="delete-modal" aria-labelledby="delete-title">
<h2 id="delete-title">Delete this spec?</h2>
<p class="modal-blurb" id="delete-blurb"></p>
<dl class="delete-facts" id="delete-facts"></dl>
<p class="modal-why" id="delete-warn">This is permanent. <code>specs/</code> is not tracked by git, so nothing can bring these files back.</p>
<div class="delete-confirm" id="delete-confirm" hidden>
<label for="delete-name">To delete it for good, type <strong id="delete-name-hint"></strong></label>
<input type="text" id="delete-name" autocomplete="off" spellcheck="false" />
</div>
<div class="modal-actions">
<button type="button" class="btn ghost" id="delete-cancel">Keep it</button>
<button type="button" class="btn danger" id="delete-go">Delete this spec…</button>
</div>
</dialog>
<dialog class="modal" id="home-modal" aria-labelledby="home-title">
<h2 id="home-title">Leave this workflow?</h2>
<p class="modal-blurb" id="home-blurb"></p>
@@ -2570,7 +2659,7 @@
</dialog>
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
the copy row are filled by app.js; the update itself runs in a
the two copy rows are filled by app.js; the update itself runs in a
terminal, never from this page. -->
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
<h2 id="update-title">A new Plan2Code is available</h2>
@@ -2579,7 +2668,11 @@
<li>
Run this in your terminal (not in this page or your agent):
<div class="update-command" id="update-command"></div>
It opens the installer's menu. Back at your prompt with no output at all? npm
It updates everything that was installed (the skills, the <code>plan2code</code>
command and any extras you added), with no menu. If the <code>plan2code</code>
command is not installed, run this instead:
<div class="update-command" id="update-fallback"></div>
Back at your prompt with no output at all? npm
could not reach the repository and hid the reason: run
<code>git ls-remote https://github.com/jparkerweb/plan2code.git</code> to see it.
</li>
+10 -2
View File
@@ -30,14 +30,16 @@ export const WEIGHTS = Object.freeze({
"git-commits": 0,
"git-conflict": 1,
changelog: 1,
xray: 1,
diagnose: 1,
});
// Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder,
// implement and implement-review score only through the agent's `run`
// reports; dashboard and handoff never score; git and changelog score 1 on
// reports; dashboard and handoff never score; git, changelog, xray and diagnose score 1 on
// launch (Git then adds its commit tally and conflict help).
export const LAUNCH_COUNTED = Object.freeze(
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git", "changelog"])
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git", "changelog", "xray", "diagnose"])
);
// Git's commits weigh what they add up to: each `git-commits` run carries
@@ -140,6 +142,8 @@ const WORKFLOW_NAMES = Object.freeze({
handoff: "Handoff",
git: "Git",
changelog: "Changelog",
xray: "X-ray",
diagnose: "Diagnose",
});
// The skill run an entry belongs to, from its ledger id ("L3:..." -> "L3").
@@ -157,6 +161,8 @@ const LAUNCH_LABELS = Object.freeze({
finalize: "Finalize started",
git: "Git started",
changelog: "Changelog started",
xray: "X-ray started",
diagnose: "Diagnose started",
});
const RUN_LABELS = Object.freeze({
"pathfinder-chart": "Pathfinder map written",
@@ -177,6 +183,8 @@ const RUN_LABELS = Object.freeze({
"git-commits": "Commits in Git",
"git-conflict": "Git conflict help",
changelog: "Changelog run",
xray: "X-ray run",
diagnose: "Diagnose run",
});
// The unit a run names, from its ledger id ("L3:phase-2" -> "phase-2").
+1 -1
View File
@@ -24,7 +24,7 @@ export const SUBAGENT_WORKFLOWS = Object.freeze({
}),
review: Object.freeze({
instruction:
"Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.",
"Run the review's analysis in one fresh helper briefed only with the spec and the change set (references/reviewer-brief.md); verify every finding yourself before you report.",
}),
pathfinder: Object.freeze({
instruction:
+41
View File
@@ -54,6 +54,9 @@ import {
rememberedWorkspace,
removeCleanup,
remoteWarning,
SHOTS_DIR_NAME,
SHOT_NAME,
shotType,
saveSubagentStoreEntry,
PR_HOST_KINDS,
savePrHost,
@@ -131,6 +134,25 @@ const EXT_ALT = UPLOAD_EXTS.join("|");
const UPLOAD_ANY_ROUTE = new RegExp(`^/uploads/([0-9a-f-]{36})\\.(${EXT_ALT})$`);
const UPLOAD_NAME = new RegExp(`^[0-9a-f-]{36}\\.(${EXT_ALT})$`);
// Screenshots the agent saved for a doc's image block (Show me it working),
// only ever directly inside <session>/shots/ under SHOT_NAME's plain shape.
const SHOTS_DIR = path.join(DIR, SHOTS_DIR_NAME);
const SHOT_TYPES = { png: "image/png", jpeg: "image/jpeg", webp: "image/webp" };
function shotPath(name) {
if (!SHOT_NAME.test(name)) return null;
const file = path.resolve(SHOTS_DIR, name);
if (!file.startsWith(path.resolve(SHOTS_DIR) + path.sep)) return null;
try {
const real = fs.realpathSync.native(file);
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
if (fold(path.dirname(real)) !== fold(fs.realpathSync.native(SHOTS_DIR))) return null;
return fs.statSync(real).isFile() ? real : null;
} catch {
return null;
}
}
// A kept attachment's name, as attachmentName() in lib.mjs writes it:
// <slug>-<first 8 of the upload id>.<the upload's extension>.
const KEPT_ROUTE = new RegExp(`^/attachments/([a-z0-9-]{1,40}-[0-9a-f-]{8}\\.(${EXT_ALT}))$`);
@@ -1468,6 +1490,25 @@ const server = http.createServer((req, res) => {
});
}
// A screenshot for a doc's image block. Matched on the raw request line too,
// like uploads: anything URL parsing had to fold (`..`) is not a shot.
if (pathname.startsWith("/shots/") || req.url.startsWith("/shots/")) {
if (req.method !== "GET") return json(res, 405, { error: "method" });
const name = pathname.slice("/shots/".length);
const file = req.url === pathname ? shotPath(name) : null;
if (!file) return json(res, 404, { error: "not found" });
let buf;
try {
buf = fs.readFileSync(file);
} catch {
return json(res, 404, { error: "not found" });
}
// The bytes, not the name, pick the type: the file may have changed since it was posted.
const type = SHOT_TYPES[shotType(buf)];
if (!type) return json(res, 404, { error: "not found" });
return send(res, 200, buf, type, { "cache-control": "no-store" });
}
// Matched on the raw request line as well as the parsed path: URL parsing
// folds `..` segments away, and nothing that needed folding is an upload.
// GET and DELETE take images and documents alike.