Sync upstream v2.4.0 (web console, dashboard skill, implement-review, global launcher) with 24 review fixes and a look-around wake-up for Planny

AI Assisted
This commit is contained in:
jparkerweb committed 2026-09-28 19:37:41 -07:00
1 parent eefa7082ed
commit 0d7c2e140b
523 files changed
+339764 -363

No files matched your search

+110 -4
View File
@@ -5,8 +5,9 @@
```
plan2code/
├── src/ # Source workflow prompts (11 markdown files)
├── src/ # Source workflow prompts (13 markdown files)
│ ├── plan2code-0-pathfinder-references/ # Reference files for pathfinder skill
│ │ ├── brief.md # Dated plain-English decision briefs
│ │ ├── chart.md # MODE A: destination + frontier grills, templates
│ │ ├── grilling.md # Folded-in grilling + domain-modeling
│ │ ├── questions.md # On-disk question-file format + markers
@@ -32,6 +33,11 @@ plan2code/
├── src/statusline-claude/ # Claude CLI status line (Node.js, zero deps, single file)
│ ├── statusline.js # Self-contained: config, git, formatters, render
│ └── statusline-config.json # Default config template
├── src/launcher/ # Global `plan2code` command (Node.js, zero deps, single file)
│ └── plan2code.js # Opens /plan2code in Claude Code or Devin in the cwd (or a picked folder)
├── src/web-console/ # Local browser UI bundled into every skill (Node.js, zero deps, no build)
│ ├── console.mjs # CLI the agent drives: open, post, wait, stop
│ └── public/ # Page assets served to the browser
├── scripts/ # Development scripts
│ └── validate-char-count.js # Pre-commit character count validator
├── skills/ # Committed build artifact — one Agent Skill per src/ prompt
@@ -56,15 +62,17 @@ plan2code/
| `install.js` | Interactive installer — builds `skills/` from `src/`, then delegates installation to the skills CLI |
| `src/plan2code-*.md` | Source workflow prompts (the "source of truth") |
| `skills/` | Generated Agent Skills committed for installation and drift verification |
| `scripts/validate-char-count.js` | Pre-commit validator ensuring all source prompts ≤ 11,000 chars |
| `scripts/validate-char-count.js` | Pre-commit validator ensuring all source prompts ≤ 11,500 chars |
| `version.json` | Version metadata (name, version, description) |
| `QUICK-REFERENCE.md` | User quick-reference card |
| `src/statusline-claude/` | Claude CLI status bar (included in `A` Install All + dev tools; also via Custom → S) |
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code or Devin (installed by `I` and `A`; also via Custom → D) |
## Workflow Prompts (in `src/`)
| File | Step | Purpose |
|------|------|---------|
| `plan2code.md` | — | The dashboard: opens the web console's skill menu and launches the picked skill into its own session |
| `plan2code-init.md` | Init | Generate AGENTS.md as index + `.agents-docs/` section files (progressive discovery) |
| `plan2code-init-update.md` | Update | Update AGENTS.md with learnings; detects and routes edits to `.agents-docs/` files |
| `plan2code-0-pathfinder.md` | 0 | Chart a foggy idea as a local map of decision questions under `specs/<idea>/pathfinder/`, resolve them one at a time, hand a seeded PLAN-DRAFT to Step 1 |
@@ -73,6 +81,7 @@ plan2code/
| `plan2code-1b-revise-plan.md` | 1b | Mid-implementation revisions |
| `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-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 |
@@ -80,6 +89,7 @@ plan2code/
## Naming Convention
Workflow files follow a strict naming pattern:
- **The hub:** `plan2code.md` (bare name — `bare: true` in `SOURCE_PROMPTS`, no suffix; it is the dashboard the rest hang off, not a step)
- **Utilities:** `plan2code-<name>.md` (single dash)
- **Numbered steps:** `plan2code-<N>-<name>.md` (single dash, number, single dash)
@@ -90,13 +100,13 @@ Examples:
## Reference Files
Some workflows use companion reference files for depth that exceeds the 11k char limit. The orchestrator (main workflow file) loads them via `Read` directives during execution.
Some workflows use companion reference files for depth that exceeds the 11.5k char limit. The orchestrator (main workflow file) loads them via `Read` directives during execution.
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`)
**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.
Reference files are NOT subject to the 11,000 character limit. The review workflow pioneered this pattern (`verification-protocol`, `dimensions`, `false-positives`, `session-end`); the init-update workflow also uses it (`ai-agent-file-sync` for its Step 7), `plan2code-4-finalize.md` uses it for STEP 6.5 (`community-feedback-submission`), and `plan2code-0-pathfinder.md` leans on it hardest (`chart`, `grilling`, `questions`, `resolve`, `handoff`, `trail`, `github-issues`, `brief` — the orchestrator is a dispatcher, the depth lives in the references). Other workflows can adopt it when a source file's detail exceeds the 11k limit.
Reference files are NOT subject to the 11,500 character limit. The review workflow pioneered this pattern (`verification-protocol`, `dimensions`, `false-positives`, `session-end`); the init-update workflow also uses it (`ai-agent-file-sync` for its Step 7), `plan2code-4-finalize.md` uses it for STEP 6.5 (`community-feedback-submission`), and `plan2code-0-pathfinder.md` leans on it hardest (`brief`, `chart`, `grilling`, `questions`, `resolve`, `handoff`, `trail` — the orchestrator is a dispatcher, the depth lives in the references). Other workflows can adopt it when a source file's detail exceeds the 11.5k limit. The implement-review skill is a generated composition: `additionalReferences` in `SOURCE_PROMPTS` packages the canonical implement prompt, review prompt, and review reference directory into its own `references/` directory so those workflows are reused without source duplication.
## Repo-Local Skills (`.claude/skills/`)
@@ -108,6 +118,71 @@ Maintainer-only skills committed to the repo but deliberately excluded from the
Do not run `skills add` against the repository root: recursive discovery also finds these maintainer skills. `install.js` targets `skills/` and passes explicit workflow names instead. Global install/uninstall cleanup removes `plan2code-*` workflow skills from user skill directories; it never operates on this repository's `.claude/skills/` directory, and `sync-repo` intentionally has no `plan2code-` prefix.
## Web Console
Optional local browser UI shipped with **every** skill. Source lives in `src/web-console/` and is fanned into each skill by an `additionalReferences: [{ source: 'web-console', target: 'web-console' }]` entry in `SOURCE_PROMPTS`, landing at `skills/<skill>/references/web-console/`. The bare `plan2code` skill is the hub: it opens the console as `--workflow dashboard`, the page draws the skill menu itself (from `SKILL_CATALOG` in `public/answers.js`, kept in sync with the install set by a test), and a card click reaches the agent as a `{ "i": "__launch", "skill": ..., "workflow": ... }` send — the dashboard then **resumes its own session** under the launched skill's workflow (`open --resume <sid> --workflow <w>` restates `workflow`/`title`/`specDir` on the live server) and runs that skill's file. `plan2code-review` now has a console of its own AND still runs inside builds on the page (a `review` verdict on Implementation's sign-off card, or the **Review it now** button on a finished quick task), so `plan2code-3-implement` and `plan2code-quick-task` also carry `review.md` and the review references, the same way `implement-review` does. The list of skills with a console is duplicated as `CONSOLE_WORKFLOWS` in `public/answers.js` (it decides whether a copied hand-off asks the next session for the console); a test fails if the two disagree.
| File | Role |
|---|---|
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`) |
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()` |
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `mentions.js`, `favicon.js`, `app.css`, `render.js`, `palette.js`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server and the tests import `answers.js`, `palette.js`, `labels.js`, `boot.js`, `chat.js`, `help.js` and `starters.js`) parses them as ES modules without a reparse warning |
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (16 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `console.mjs`, `lib.mjs` and the page |
| `public/meter.js` | PURE, no imports: the session meter. `WEIGHTS` (the one place per-event points live; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), `pointsFrom()` (the count, folded from `ledger.ndjson` and deduplicated by id — never stored), `levelFor()` with `YELLOW_AT` 4 / `RED_AT` 6, `ringFraction()` (full at `RING_FULL` 8), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
| `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 |
| `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 13 starter templates 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. `scripts/test-web-console.mjs` imports this directly. |
| `public/labels.js` | `taskLabel()` / `activityLabel()`: rewrites a build's `Task 4.2 of 6` activity line to `Task 2 of 6` (only for `implement` / `implement-review`; a plan's `Task 2.1` is a real section number). A separate module for the same reason as `answers.js`: pure, so `node --test` can import it |
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `app.js` fills with one snore) 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 agent-facing contract, which is what every console prompt points at. Its **Workflow notes** section holds the per-workflow detail (Dashboard, Init and Init Update, Document, Review, Handoff, Pathfinder, Planning, Revision, Finalize), which keeps the prompts themselves to a one-line pointer |
| `building.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`), the sign-off (with the review offer as a verdict), the finish, and running the review on the page mid-session |
Key design points:
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (cancelled). The agent loops. Nothing blocks for the whole time a person takes.
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `console.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch }` when it found anything to clean.
- **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `<gitdir>/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it.
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `server.mjs`, which paints `data-width` on first load; `app.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
- **`GET /overview` is the one read-only file route.** 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.
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md plus 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` invocation writes `HERE` to `~/.plan2code/console/console-dir` 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 start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
- **No git process.** `repoRoots()` in `lib.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `lib.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
- **The first paint needs no fetch.** `server.mjs` renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to `app.css`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
- **Reads are stat-gated.** `fileStamp()` (mtime:size:ino) decides whether `state.json`, `result.json` and `looks.json` changed before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (`readState()` returns it; `/submit` clones before editing). `wait` stats `result.json` every 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
- **The Workspace and the session meter live beside `state.json`, one writer each, and outlive every hop.** Three session files, none of which `switchWorkflow()` ever touches, so both survive dashboard → skill → dashboard (a new console session starts with the original folder alone and a count of 0):
| File | Writer | Holds |
|---|---|---|
| `workspace.json` | `server.mjs` | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()`, now in `lib.mjs`, computed by the server at boot) |
| `ledger.ndjson` | `console.mjs` | append-only meter events — `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch) — and `folder-issue` reports |
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. The contract is in `console.md` (Workspace; Posting an update → Session meter) and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or the loop's marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `server.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `lib.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.jpg` serves images only, so a document is never handed back to a browser; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
- **Answers carry their terminal token.** Each item ships `fallbackText` and `token`, so a click resolves to the literal word the prompt already expects (`approved`, `a`, `skip`). No workflow needs a second code path, and declining the console degrades to prose with nothing lost.
- **A build tells the page how long silence is normal.** The page calls a working agent stuck after two minutes without a post, which is right for a conversation and wrong for a twenty-minute build task. `agent.quietMinutes` (1 to 60, counted only while `working`) stretches the stuck, adrift and Send-grace thresholds; `quietLimitMs()` in `answers.js` is the one rule.
- **A finished quick task's review button is a request through the wait loop**, like the brief: `{ "i": "__review" }` or `{ "i": "__done" }`. The agent keeps waiting after posting a finish that carries `review`, and takes the review up by posting `"finish": null`, which puts the session back to work. Implementation's review needs no such machinery: it is a verdict on the sign-off card, asked before approval, so the session never left work to take it up.
- **Back to the dashboard is the same kind of post-finish request.** A finish with `finish.dashboard: true` shows the button; a press arrives as `{ "i": "__dashboard", "type": "dashboard" }`, and the agent runs `open --resume <sid> --no-open --workflow dashboard` then posts `"finish": null` with a fresh `menu`. The agent waits ~10 minutes after the finish for it (alongside `__review` / `__done` on a quick task); after that the page swaps the button for the `/plan2code` command. `finish.command` is optional — without one the page shows the "All done" line — and `validate()` rejects a `<placeholder>` command and a non-boolean `dashboard`. The session-level actions are therefore `__brief`, `__stop`, `__launch`, `__review`, `__done` and `__dashboard`; a new post-finish button should copy this precedent.
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console.md → Stop requests → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `lib.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` does an unlocked read-modify-write of it — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
- **`validate()` in `lib.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 16 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `app.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
Tests: `node --test scripts/test-web-console.mjs` and `node scripts/parse-check.mjs` (both run by `npm test`). The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
**Adding a file under `public/` needs three edits, not one:** the file itself, the `SERVABLE` allow-list in `server.mjs`, and (for a module the page imports) a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a new module missing from it 404s and the page dies at import with no useful error (a test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint.
## Status Line
Optional Claude Code status bar living in `src/statusline-claude/`. Three-line bar (icon + content per line) showing model, project, branch, uncommitted diff stats, session duration + cost, context window usage, and plan/quota usage.
@@ -131,3 +206,34 @@ src/statusline-claude/
**Adaptive plan-usage display:** the formatter auto-selects between `5h/7d` rate-limit percentages (Pro/Max/Teams — when `rate_limits` present in stdin) and `Nk in · Nk out` session-token counts (Bedrock/Vertex/PAYG — when `rate_limits` absent). Segment is hidden when neither shape is available.
**Installer integration** lives in `install.js` under the `STATUS LINE INSTALLATION` section (`installStatusLine`, `uninstallStatusLine`). Included in `A` (Install All + dev tools); also available individually via Custom → `S`.
## Global `plan2code` Command
Typing `plan2code` in any directory opens the dashboard skill against the current project, **in that directory**, in one of two CLIs (the `CLIS` table in the launcher):
| CLI | Runs |
| --- | --- |
| Claude Code | `claude /plan2code --permission-mode bypassPermissions [args]` |
| Devin | `devin --permission-mode bypass [args] -- /plan2code` |
With both on `PATH` it asks `Which CLI should open Plan2Code?` as a numbered menu, the last pick pre-selected (Enter keeps it; a number, `claude` or `devin` also work); with one installed it uses that without asking; with neither it exits 127 naming both. `--cli claude` / `--cli devin` (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=`, 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>`) and waits for `Press Enter to continue, or Ctrl+C to cancel.` — 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 wait. 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` 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.)
- **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`.
- **No bin-name overlap** — the installer's own bin in `package.json` is `plan2code-install` (→ `install.js`), so `plan2code` belongs to the launcher alone. npx runs a package's only bin whatever it's named, so the README's `npx … plan2code.git` command is unaffected; keep it the only bin, or npx will need `-c plan2code-install`.
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model notice. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person cancelled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
**Desktop shortcut** — after the shims are written, `installLauncher()` (now async) calls `offerDesktopShortcut()`. It asks `Also add a Plan2Code shortcut to your desktop? (y/N)`, skips the question when stdin isn't a TTY, and refreshes an existing marked shortcut without asking. `installDesktopShortcut()` writes it to the real desktop (`[Environment]::GetFolderPath('Desktop')` on Windows, which covers OneDrive redirection; `xdg-user-dir DESKTOP` on Linux; `~/Desktop` otherwise):
| OS | File | Runs |
| --- | --- | --- |
| Windows | `Plan2Code.lnk` (written by `WScript.Shell`) | `pwsh.exe` (else Windows PowerShell) `-NoLogo -ExecutionPolicy Bypass -File "<bin>\plan2code.ps1" --pick-folder`, icon `src/launcher/plan2code.ico` (the web console's Peek-a-boo favicon, 16–256 px) copied to `~/.plan2code/bin/plan2code.ico` |
| macOS | `Plan2Code.command` (0755) | `exec "<bin>/plan2code" --pick-folder` in Terminal |
| Linux | `plan2code.desktop` (0755, `Terminal=true`, `gio … metadata::trusted`) | `"<bin>/plan2code" --pick-folder`, `Icon=` the web console's `favicon.png` copied to `~/.plan2code/bin/plan2code.png` |
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`) and `launcher.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 both `I` and `A` get it), `U` removes it, and Custom → `D` installs it alone.
+10 -4
View File
@@ -8,6 +8,7 @@
- External deps: `@inquirer/prompts`, `chalk`, `execa`, `ora`
- Interactive CLI via `@inquirer/prompts` (select, input, confirm)
- **File operations:** Synchronous fs in all packages
- **src/web-console:** ESM, Node built-ins only, no build step. It is bundled into every skill, so it must stay dependency-free and runnable as a plain `node console.mjs`. Anything added under `src/web-console/` ships to users — put tests in `scripts/` instead.
## Gotchas / Pitfalls
@@ -17,10 +18,15 @@
- **PowerShell mangles the CHANGELOG emoji:** `Get-Content` / `Select-String` render the `###` heading emoji as `?` under the default Windows console encoding, so a heading audit done that way reports garbage. Read `CHANGELOG.md` with a file-read or grep tool instead.
- **`.claude/skills/` is tracked, not ignored:** repo-local skills (`plan2code-changelog`, `plan2code-publish`, `sync-repo`) live there and are committed. Nothing in `.gitignore` touches `.claude/`, so a new skill only needs `git add`. Per the Failure Log convention in `AGENTS.md`, a correction that is a *workflow* rather than a rule belongs here as a skill, linked from AGENTS.md — not as a Failure log line.
- **Loop `.gitignore` setup:** `ensureGitignore()` runs at startup in `Controller.run()` as a pre-flight step, not just inside `createTaskCommit()`. This is critical for phase mode where the Node controller doesn't handle commits — without it, `git add -A` would stage spec files.
- **Workflow file character limit:** All `src/plan2code-*.md` files must be ≤ 11,000 characters. A husky pre-commit hook enforces this. The limit predates v2.2.0's single-format skill build and is retained as prompt-size discipline; generated `SKILL.md` files add a small YAML header.
- **Workflow file character limit:** All `src/plan2code-*.md` files must be ≤ 11,500 characters. A husky pre-commit hook enforces this, and `plan2code-metrics` (`improver.ts`, `applier.ts`) applies the same number to proposed prompt edits, so change them together. The limit predates v2.2.0's single-format build (it left buffer for the largest platform-specific YAML header to stay under Windsurf's 12,000 char limit) and is retained as a prompt-size discipline — the generated `SKILL.md` header is ~180 chars, so 11,500 still clears 12,000. It was raised from 11,000 in v2.4.0 so the web console's Interface lines could be added to Pathfinder and Planning without cutting any of their rules; when a prompt runs short of room, move detail into a reference file rather than compressing rules.
- **`skills/` is a committed build artifact:** edit `src/`, run `npm run build:skills`, and commit the regenerated skills in the same change. `npm test` runs `install.js --verify-skills` and fails on missing, unexpected, or stale files. Never edit `skills/` by hand.
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 11,000 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 11,500 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
- **User Feedback table format:** The `## User Feedback` markdown table in `overview.md` has a strict format the collector regex depends on. Field names must be exactly `Rating`, `Reason`, `Went Well`, `Went Poorly`. Pipe characters in values must be escaped as `\|`.
- **PLAN-DRAFT confidence numbers are scraped by regex:** when a `specs/<feature>/PLAN-DRAFT-*.md` contains no `<!-- METRICS_JSON ... -->` comment, `collector.ts` falls back to prose scraping (`collector.ts:186-241`). The overall-confidence pattern requires a literal `%`, but the four *breakdown* patterns (`collector.ts:201-204`) do **not** — `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep both the `%` sign **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class.
- **Reference file sizing guideline:** Files in `src/plan2code-*-references/` directories target ~100-200 lines each (soft guideline; evaluate splitting above 300). They are NOT subject to the 11,000 character limit. The pre-commit hook (`validate-char-count.js`) only checks `src/plan2code-*.md` flat files — subdirectory contents are automatically excluded.
- **The splitting guideline has a hard ceiling — reference files cannot always be split:** each new reference costs the orchestrator a `Read references/<file>.md` line plus its fallback blockquote (~150-200 chars), and orchestrators near the 11,000 limit have no room to spend. References now stay nested under every generated skill, so the old flat-file path-rewrite constraint no longer applies. When a reference legitimately exceeds 300 lines (e.g. `plan2code-0-pathfinder-references/chart.md`), that is an accepted trade-off, not an oversight.
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console.mjs` guards it. Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `lib.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
- **Web console oversized bodies:** `readBody()` in `server.mjs` calls `req.destroy()` past `MAX_BODY`, so an oversized JSON body gets no response at all: the client sees a connection reset, never a status code. A route that must answer 413 has to stop buffering and drain the rest of the body instead, as `readRaw()` (the `POST /upload` reader) does; memory still stays capped.
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(cwdHash(project))` in `lib.mjs`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalises its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
- **Web console assets require build and serving coverage:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are supported and the bundled MP3 chimes exercise that path. Any browser-served asset under `src/web-console/public/` must also be added to the hardcoded `SERVABLE` allow-list in `server.mjs` and covered by a test; otherwise the generated skill contains it but the server returns 404. The vendored `marked.esm.js` sha256 is recorded in `.readme/web-console.md`.
- **Reference file sizing guideline:** Files in `src/plan2code-*-references/` directories target ~100-200 lines each (soft guideline; evaluate splitting above 300). They are NOT subject to the 11,500 character limit. The pre-commit hook (`validate-char-count.js`) only checks `src/plan2code-*.md` flat files — subdirectory contents are automatically excluded.
- **The splitting guideline has a hard ceiling — reference files cannot always be split:** each new reference costs the orchestrator a `Read references/<file>.md` line plus its fallback blockquote (~150-200 chars), and orchestrators near the 11,500 limit have no room to spend. When a reference legitimately exceeds 300 lines (e.g. `plan2code-0-pathfinder-references/chart.md`), that is an accepted trade-off, not an oversight. (The second constraint here — that the flat-file `Read` path rewrite was non-recursive — went away in 2.1.0 along with the rewrite itself; `references/` is now the real path on every agent, nested references included.)
+5 -4
View File
@@ -31,9 +31,9 @@ cd plan2code-metrics && npm run build # Build the CLI
| Option | Action |
|--------|--------|
| `I` | Install the Plan2Code skills globally through the skills CLI — **skills only**, no dev tools |
| `A` | Everything in `I` plus `plan2code-loop`, `plan2code-bot`, `plan2code-metrics`, and the Claude Code status line |
| `U` | Uninstall Plan2Code skills and all dev tools (confirmation required) |
| `I` | Install the Plan2Code skills globally via the `skills` CLI, plus the global `plan2code` command (opens the dashboard in Claude Code or Devin) — no dev tools |
| `A` | Everything in `I` plus every dev tool: `plan2code-loop`, `plan2code-bot`, `plan2code-metrics`, and the Claude Code status line |
| `U` | Uninstall Plan2Code: skills + `plan2code` command + `plan2code-loop` + `plan2code-metrics` + `plan2code-bot` + Claude Code status line (confirmation required) |
| `C` | Open CUSTOM sub-menu |
| `Q` | Quit |
@@ -46,6 +46,7 @@ cd plan2code-metrics && npm run build # Build the CLI
| `M` | Install plan2code-metrics CLI only |
| `S` | Install Claude Code status line only |
| `B` | Install plan2code-bot CLI only |
| `D` | Install the global `plan2code` command only |
| `Q` | Return to main menu |
## Non-Interactive Flags
@@ -97,7 +98,7 @@ The skills CLI owns distribution from step 4 onward. It stores canonical skills
## Adding a New Workflow Prompt / Skill
1. Create `src/plan2code-<name>.md` with body content only and keep it under 11,000 characters.
1. Create `src/plan2code-<name>.md` with body content only and keep it under 11,500 characters.
2. Register it in `SOURCE_PROMPTS` in `install.js`; add a matching `generateStepLabel()` case when needed.
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`.
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env node
// set-synced.mjs: rewrite the "Last synced" line inside sync-repo.enc, in memory only.
// Decrypts, replaces exactly one anchored line, re-encrypts, then decrypts again to verify.
// Plaintext never touches disk and never passes through a shell pipe (PowerShell pipes
// re-encode UTF-8 through the console code page, which is how the body got mojibake).
// Usage: SKILL_PASSWORD=... node set-synced.mjs <file.enc> "<new value>"
// e.g. node set-synced.mjs sync-repo.enc "v2.4.0 (main @ 1a2b3c4)"
import { readFileSync, writeFileSync } from 'node:fs';
import { scryptSync, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
const MAGIC = Buffer.from('SENC', 'ascii');
const VERSION = 0x01;
const SCRYPT = { N: 1 << 17, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
const KEYLEN = 32, SALTLEN = 16, IVLEN = 12, TAGLEN = 16;
// Anchored to a whole line that starts with "**Last synced upstream:". Command text elsewhere in
// the body can mention the phrase without ever matching, because it never starts a line this way.
const LINE = /^\*\*Last synced upstream: .*\*\*$/gm;
const password = process.env.SKILL_PASSWORD;
const [encPath, value] = process.argv.slice(2);
if (!password) { console.error('ERROR: set SKILL_PASSWORD env var.'); process.exit(2); }
if (!encPath || !value) { console.error('Usage: node set-synced.mjs <file.enc> "<new value>"'); process.exit(2); }
if (value.includes('*') || value.includes('\n')) { console.error('ERROR: value may not contain * or a newline.'); process.exit(2); }
function decrypt(b64) {
const blob = Buffer.from(b64.trim(), 'base64');
if (!blob.subarray(0, MAGIC.length).equals(MAGIC) || blob[MAGIC.length] !== VERSION) throw new Error('bad header');
let off = MAGIC.length + 1;
const salt = blob.subarray(off, off += SALTLEN);
const iv = blob.subarray(off, off += IVLEN);
const tag = blob.subarray(off, off += TAGLEN);
const d = createDecipheriv('aes-256-gcm', scryptSync(password, salt, KEYLEN, SCRYPT), iv);
d.setAuthTag(tag);
return Buffer.concat([d.update(blob.subarray(off)), d.final()]).toString('utf8');
}
function encrypt(text) {
const salt = randomBytes(SALTLEN), iv = randomBytes(IVLEN);
const c = createCipheriv('aes-256-gcm', scryptSync(password, salt, KEYLEN, SCRYPT), iv);
const ct = Buffer.concat([c.update(Buffer.from(text, 'utf8')), c.final()]);
return Buffer.concat([MAGIC, Buffer.from([VERSION]), salt, iv, c.getAuthTag(), ct]).toString('base64') + '\n';
}
let body;
try { body = decrypt(readFileSync(encPath, 'utf8')); }
catch { console.error('Decryption failed: wrong password or corrupted data.'); process.exit(1); }
const hits = body.match(LINE) || [];
if (hits.length !== 1) { console.error(`ERROR: expected exactly one "Last synced" line, found ${hits.length}. Nothing written.`); process.exit(1); }
if (body.includes('�')) { console.error('ERROR: body contains U+FFFD (encoding damage). Nothing written.'); process.exit(1); }
const next = body.replace(LINE, `**Last synced upstream: ${value}**`);
const out = encrypt(next);
if (decrypt(out) !== next) { console.error('ERROR: round-trip verification failed. Nothing written.'); process.exit(1); }
writeFileSync(encPath, out);
console.error(`Updated: ${hits[0]} -> **Last synced upstream: ${value}**`);
+1 -1
View File
@@ -1 +1 @@
U0VOQwFWsr3rRb8R2aeM56NhDpk9tX1qvu7R2QrOHyjiQ7eFSJR192aTT9cBnZwYblAS6YKP5w5ye4J2FpdZRF1EYkN6tY6XBsmKjlaAXmyqENRs+4W7qgxydg+fiE97WYv50Z3kMMp17iRHzQXoRrjZnbPW6UjDjOOySmbcWmeqOj3m4gB1FbT/l3ViJ/dDAQiZHBTDjjYr6hz2zAiETG8HqpKSNNSYCTnIJn5q9F09P7O15AfSV4zfxMuSNj7G+joEVLzm2z3Q46AawJLFboUEg9yikggor7ccv0J1uk/MeHtnit4ieA21YekaHUCKeSRObRt6KCfAdaoz+FCFHxWXRBgYJk68d0fTzuyg8vCAaof1E9B4296svfiNtSe/EGP3pk2l+rcGFZCoddMnalCkg1KzLUG/R4bb3k3nTHLPuk3A3u3c35bt5+zpLqiC4aH8Ab3HWn3iTEVex68MCD6Whv1IL4AKcyKLEjo9uhhVKTViZxdq+O78oh/AvvWMwWd96sS6BIHawwwXSoMI3Oy5X/R/LQY/z82Y1dpYJuU+b4x+n/niZMKJQkeVApHBUp8oaGU3gUIWQEn2eZvrF7jDfsaks8fdzN+xHYmKhXPnLAOaoSOyxiBIzKiOJWBBske5GbCVTYkGeN58D4JVWyzks0PyMioeWXvRSfVFDSVP5p9qMfjF9Lf0QVdWFbV8FoNTfDWoUlXwObrwoUT/oTs3ELU5HPftq78kBVsJte7Xz+5tb1V/S6NG6WMqc7IjNZz2p/4vAPvXBLjZRloe0yjmLRaAOtKBrTy+OWG6rFeHSQLc+PsIGTb0eZiQeRX9GofJFLqazEuv55lX4LeToBbt0T/grFNQsa7y8IMAvSL9NbrxmccEx9/ZAwKzTVFcXT6xjK2/FQrohASKqFinTcbiY+lq8j12AjXv2Erh1Gpp8GyhVrbfHd/P1ykQ95V2NjfVvCzmMdTxD+J+PNGmpGSYWyjp9rNR4B5rO9BHXsYrMNBA80JIMc7OyUwwzf6iojnxYb2338yUesPK+LyiozCANcbOlZLQv2q0tz4puevVGWeMT+ecO2B/45zAcDbIosgKEMY9T0QcYc92IvJ0OhPLlOVgvx10iWY3QNalkDaIMiUQ706vHk+ULdZW/iRwJwph9BhaV5/NQUGZCdXBSGlOojLMr0VURRKc4z2FMVgz0V3jQ25OxQLFCCgXcgeHbJmUkzMPNNoG10ZIkfdUcOt7qLJ4vS9Ndqv0HotzcWWOCgz/JxDN3wKdD2HWZKpKK/ePE7uxzWTyS5wFyeKX4pOk6MUkcr5jUkO7FZ6CYSyxAq5n0ZU/mnfBFFpt6zD+r0Z8P/IagpVSjmVsd7dtpszIewePNW490dc2XpAPm4URpFatKoDJKkqSI0kZHYg6ogPC/m6BFJuhXWtyaeZyNluQTQFAMs1LSb7MU+9xUK4He/yKrsMDkmchKJYdDdEYZN8CD2NYGJAnyRwjjGPtffr5NQCBj4kUKXWr3e8LvPZuj432nG3K/TdZEtSdmZEKAMxejca5gdbkxN6qLet0hKhSaKVd29I2QRF33VMZ3FA5VnPduR1E/TeFhPJLoVik+/nvC1S8OsWOgGaiTRuKHbapBXYo3OLNDrd6CbaDzFAxMIlxtMpbESTKsgeo+5pqGgcZ0U48Mb9DxWfEDOsSX3Hp1U472OrL+Sk69+I8ytSkjt8E9dOhZFaYEKPwPrirIODMvmveGodgRWIOFQe9PJarkGbmSE5zj/95lawfd3JA3B5WmIs2f3ghbWWZKEpuzhIL0GdxlTQNkmuKEQDMhFn9a/Mnl9VkypQuh4BQlCvNcvdEjDs7GyIotyiHsAXefCjwMlpVkb1ZHFzOxPDzZfEVS8/J7asIb+AtLzM5fLhDbimE7Idpbo+1tG+tYwkxivxUwmR7n9Hc83poUT8qybSTDdlSKdq+/L1EH9cj8gTA9CBjqN2cYJsc8F2N2P4VoLHE2JUSjIZ+kpnFZ4YmUZZ8TuqmgkXZAyP+fUzFpUKlcoYFuSicSmza+5zoysbNyLWsvOdQrrsB44MEWykUJo/qZa4sHGNbJQCltTChrqlmnouNfjv+WNGM8zHzX9e0elu4ZP/e4e3ATKZs8H7Pjv7NBq4OZ+ZnEt5rxK3P6Du7C2mkL941L+m3DGa3leKOfRmZSWMZJccv1GUdSzQzi90tSeg65Or7M7or2L5JMYoIbRxP0PcsjfadndzOKIYIYoz67LK5NvQBJRvxf32WfAfTtJ+EU4LZvV3Grij1zQb95Ad4EBAwLWXJ1ZbPhk3ItYJv2yJqXKvujhXsHpuxQDAj2dJVhZwJkV3zLy8xUF4Ja2unF0jL3YOvjxiPK53BjIERh7l9OAY6mqQSVQDro/2bk9PdDczW+wYhfG/00mDiW26vlL6V6PH7RY0JKvoCcFOrMEbYQZYuPs/rDIJKoYX0L4nv6USQss9kSqXNCdfseX+8dDof6aDDimTwZM1UGzrflcEEim0VeG8MIUdWWFYPnLe6bVSDhiJp0yweKHQLFI22LwLKlyaJVFsJqjEGv2e5MCrztKLOB1K3834VmGjxDcg/3sFRDf0gYd/KEchDORZBnCTs/pffxApwGuGcCQY9VxZ9588//UI5Cm2e7yCADVywCkUViyf/98xAvCAcKYlTiTgkxLWE0O/PjMCT2qdVgo+BB7oZ1CQ4ov0Ked9EPmpkzIM5NuSNGSerCoIEPJrg0jawX1gRb8KDaM/xc5aQLoChd+rKBwwqRH550z7IyjbmerY8bH3greW0jaHZXIi0SgpIz9KVfPnpVLjtxOfxREGrkhUy3HBhap/Qw/yal4kiFTzkYKT2sm/yJy0k7NFGnN6u0Yf56pIIQi78jOoQtHAFiZkT/WdJYjhLrrR1ddJ4xqNxsfcmPZspiZvBDMaP5sh/vjLTVJh/riAMRLXIvWulebp2Lyh1CR/fwUx0taly+CCCqA55wfE9HbcuS7VfweuPm9Bg8xwC0kVapQfZ+AN1qXlNJxyPDew4hN3KV9Q2/MrDDgCxKKZNROGzBQpNYIkLvTlOv7tVQiBUiU2eFvXsYBMoGgfbVEKeBEGnyH1ESr2pJQVP2xQGnuhuJOEB1d6wruldwce3eKdaj+EENCGGfz/qM6QBtGYnzaqmT/L0gq35+W+TI0IkiB/Bt5dX4twISsKYBoC2ybAHZFAFKmAanFntJnH+hjF/8xz0VzphFkNuotPQNjYdQKonf3ehkdOrtQUFR5K1pWsjHAXRHoqbkRgh7CAUN5tTfhijesB6AePqHBCa/SKTzFNYMU3iduHRkS0/3fSw0qsZhAScluoccLXUUxg9osr1P4ttcTPQtcCKiPhvfISF8hD7jcZqVnd0unuKu8o0XYmUdLBd8mSclkT3eq8mI4XmFLE7zYkVvTe7kttlS7RRAZGWFFgFyF+eLkBJeP0Mqip6ihpybxKNmJ09z/hkLc9y9Mjn5N1oJZHgOlQAiP3cz6nvIXjQdGo1tZBPWM8oUxjxiOaZ0q5K3Rt3z1AZ+6FR//E5blOPtwzgYhhJGAg2BLSrnRJcrUzU5zf6DnnfR8nziPZbundhip7DelYotM3mwwuMJiI2dEWTt26vwyF/KRHznatm8LWukx5XUvxITZi27sJeKhCS4dcnwoqVSxhZ9tLjlpaM6FL3N0klssKMXUwU+dBm7r+e64RXgTPT6f97SpMsvOhF7NA5XZnJhMIU4X/3ONR2QhLoFQoOokuj7ZccFE8kH0Xtes6pgRAVw5fEBPKdxjoeY4Fl4ONb+94JyNW2brxx4lZURkIQJ6ssAooLC/OtSccchKmLV9t87j6RLXmGLUqrkEgIFa9nXgI3zvPSnjs3aLwh6stg3cSb4/r4c9Yj4ge8A0oK43m6JpdSGTEsOzwcSpO5E3zNZQLBcDp+hxDtBTIw0ADCbeOyRC79dvkKAz+sIH3eEYm5KqveRxGa/ouNZCMsobJnd8cjLEXGOgEiEg8vv47S3nDTWz3fA2oTzB66ORB3UP0XWY7Gwf+1x4yonLA/KldT8L/2AMnKJrQX7TwvSzvfqZWuqc2FCh6+OA/vZtfrYh3FtpH9ZwPsTMYGwxKNv4+pDJS3GVtjPRSYdo+V0Tu8zdRBUhpBsyGqeOpd6VuOGAw9HLTn8cuN4e3hUowz+jUXaN4hYqGOo7K96M9Mog3Jxf58ZhQd7dsA3JYojUco0Kcg5P0bhNFiI/JtKI3Z3Ysvl96uo9hKb8bLu8WW+E0FRwJ44rjB9BRetRnEaM/HQAZGsThtwUgIic9ZwmWkkLfjtH3ECjkHApJEzx5HwqvvZ/KD5rNUfjCZcyg8vo8vtafJTtIjT6iwXubvZ9kGlZtN5thHfrO0Bj2QkPikL92cCI+puWE1mpxX6W/2NyuORq8YCdC/IUsx7CgIOch5sZ8VR8ND/6H6E0n/RHB2/0g7RY155DfbGe9mos9rmKFoOrgiPAkUBXuxnfbIp7Nv6ezGu2G3HsLEf5VgEMvwjjBTRra71Laeu4LZPlsrYOOESQvwSzBAmg2OSFiClfL+Y7XtycOUZsMWvOXnThw7smwkj6Rf354vJbMEs3HKuwMdA170U0zOEGYaV1ccjpT23Ik/3REozJJmg6p/XAyQd+cRc2xGyjg1tOMzTB5CAInIAtM+uQqtXGx1qjJdFdBIJ315jXF5wxTidgtr5+zWNGWTP8eitfwjsgAdsM40xkyElg+rN5CuSbDSVS7cjdWQa71+h1UpXgtAqQac0mdm/cr1IP2JvrNR4R2dRjxwtFGIMUnFSRGnYFfSu+kZ4mgZzUFgKnDLB5/pV8ZxtyKT+i4PAMVah7xMO9CT2risZT8Ik1i53ZbyhUKFDcwRDjw/6iibSV8ksla/SXwK4V8bC4kL4+H1XOZlMYRJTJZmsENwkSAhBghW6TEqGo18ODzAELio8WKvrQNsJYDQCRHZSg2NY4GzbL1rKC73k3K0fWtD3qgyiP1Hyy41tf3Line truncated
U0VOQwFPzQDaoQ4CYmOCkXpHaowo5AUQDIe8GexmfBQyam+1kyWM8jdtIsQhvurM+YSqdSw5vQRKsM+i67u5IdqxLfAlM2dPIWaZko0A+sA9RYL9LuDa8RqocYVUfG/ZzwS5C7gzuTD8mPExVyGJYFXX29W6FwmVSoYKmUGYsi7zbiU2Bd4pWcvvdGZHEjSl320B9H2wuZHvX7tWUFfiueIvZM2LoKW/FY7IvhzlqQ6X0rtWgE1NqTr5254XwZ+Xl3dsy05i9N4rhq9hbJClJUFbJwXi2kasl5CEWLjpUfW8VbVJtUts/8lw0bp9MjGaWSkqn5bjBQZy79RRa959eg6f7Q6KIyUIna2iYRsoDYJmwz92d2qiL5lzmzISNe1m/30sYV3+HEoHtob2YX4JmKGJ2VvAe9dp9PFz0iU+JIxA+yECte5RPiCV5kPJnpPR+tgVvAE3SOB1e9qK4Kz/TKKnfE8LbfysgCJdBWvYdhkREwwTij2ywbTOxqw/vRPZ/UDrDTa7jLmML9jKCIO3cJgeFzC0zshbSqvk56qUvBWSPQEaPNmlou7exI0QW7oybpa3Z2JT/ecyxWp0Z//k6elN2sSgYDsiZnpUBJwDUyIEoU8mthj4rkXgKxLzEOx+G+vIeeOI+pHQtq7jLTj1DOj4o6J+SEfU4H8bss4H2EtGjY2RtJV0tYAyIAN2FVsJij4Z53mzyU+GohN9qV7s7vrGVLfHRIonVuffrqBvcR5ffa80LA+o6xH2R12dUbeX0VxPu5/J5mdFdhtA2Cg2cxEurRWt4BblHH+l/ijVskl5RUn5g5S/5c7bGym7uiKcUDvEHG2ql0ZbdNxjaLpnPeUG4k5gH/Lj5Dcf8+fP2kL9g1erBqecz9Hc+mY31mF+2gIw2kODtT8MkWWLDSWIaC2d0hm9vPpujT158WVVCATITUgsx6k8gilcdd0uUXEAWcYBCWjILD3p6zK/m6/rUwil8f8vKJGX7ZKVYrqE+nKfPMefzaL0nYmPH+IoEADESpcpWgbHzNeCCl1A8Jv//2Vy6SvQtGxIjEe2cGfGsQZwhdvbXNwHl72tHSp38B4+ViI3lff9SsMbJyqCeOU60isXbCg4byrf19kGbq3Ld/poLkDRg6O2mwp/J4IMv86+PBHf7mHkeTbHfpuxnRK74D9epntkhnArBeHMILbyFNgzCvWuQkiMdtzabBr9wYwUY4pwHFzjDiVuCrBtBN0RRty4WsJsbqbeTdM1R0AK46OJ4F7K5yYvvmfUMrM9U64+m+Q2iv+6j9XpB89iSmNlr3YCJTdFGErPj9hcVGbqEOdV/g1PrCpAZ1+dakrP4YBgTRBEO8+agMHMvIIMWL0UBmWb2IBc/uQ39aZbejBzbHmsOMkS+4zO3DH9+5Wty06KNKeyc0SnKBPYsoi6sZVJPdsw7F/AaqSAq2e/AYiA4JV2zlPDDZOlal7fNS4+F3Ydxjc/d8RJrWElqIPPW8aPJL0BHE4jWGzDvLMe+bcwfZrVjDJ8FOle/c39TZAEfZ15qDx2eLQxhiCeMc7gAAEHIA6UYBkZyZazcY4cKzDVHZGvqR/nKrx+BUxAEFD4b59dgCLjSdIK70YqurWnR+k8SuzUCLw8VfefqjQnjETiNOf8zfOfFDdmG7vDAdaM6X6bUoQFaIftPJQEY4j8ZOTHm0XJVDJp6mh6ali/ntcxgZDn+IAiMPauHzcfo+joHbkdqhD6JmQ5BQRiEjRfBy9n0URDfBbADgP/fXyGNLj3S2DzExOWPy2NO2ls1KAxPbyxgjOlAflW246a8NmR/nroaoXD3mF5/rOv23XKcDYmHFIF2bDyqKrA3uU3q14FzmY+Jb+kLCq9vsbTLVyjemoXh8j5/SyQ1AetbAbImQUFoM10pHBxPx6hbJghqYpqsv8MQ4Bn7yGDZq/c9AyrGCNtqDkiIlhFGrMXU1VJac4C/51je7M6ZqbHP9uKLR8T+ERXo3z26Gb6SNMf8J7/61QhlzvOIFEgovA5kCJR/uT/SVuP/cnN8epVJ6G9+jOpYoTlSzupOAcG4f845tEjMXSRh7pig45S+Nn0C/ScXnq/+50DkrtiEppdEKSVcJGEHdX/rHL/+LbndtYdOavJUeTnuSN78FbhVl/aL6nT9anu0jtLdARg1vzwiypp8btboZJ4x4BI86di62PTbIQ5pNi6coM35hqWVfBZ9h2HLh9CMM8zNsgQK77BNaip6/aA2as/CJQPNX3QvBqceG5Q5gfcqefTWw4QfdiWFvTyQmJztJFVBd4Ezur7BNDMV9kqcWMsyD13TBHDam2swtN+7f7Y36ti7ab2uPqIvSbeI4JE4eFR0fMgwmlhGBU6HBDM6JJ7OTWlqJVNn/rpZ3ulQ4C6v2z5P9sClPjmR23ONypnletATjIhM1Isl5tX4Zct5bBUGOsmYXzxBh5Dz1+fXPJgTpqUz/h1ZJQWbUIneRGo0fYvNUfk4rJd1QA2dKLr0DwHw3k+chvh2eJP32t0WBVE9x/QJLUrtaLisAaNh9hvqc3LU7KNn7tpOyp89/gSVHeYy0DqbUXcUWgAn1vwTE9H0MXfxKoqBPMC7sMfslMTgH47R8vGN0wwzuVYWI4I3yUDwXOnlFXLw7NUpa6eOGXrEAe62vOps/xt2DbhqGQHbuY+28nvYtb0iudN45pN3yl1MFDLbcYc1TVkxOAQRwBpzLuDPu9ZkIiewynTwGWChjuq8ysI1TtLkN78fdL7j4UUCbdOWv1c+v6n0ytGzb8L4j4XIV1gzuMzpdCt0bzxaxPL1lIZAdxDswd0OK7VlxjkHuZtCZwdEqndvem7VI6TzRuOsWCZQoz3WonLFyf/jOTSUxn9YnXfgkJKah1yIdrmUtfhwwEIqzthkQ0DWdXnwXmlx5C8hw4GhoH8LlWYNYjzKqFWfS1I92t2PDum7v7JY39KgYgHtOCZm+neCgGFqsv6BbJvVjk8RO+4HTfF8W75r/8v7Csm7V+pb9d4DQ2yF4nvicV11NdQORnXHnUzdMaW5fGDb79cZHKbPHK8UnU7p6ERxsWNDqXS+RJBy+Xs5t+JBxttTcXpmQGjpQnPwi1qKzvZm2RwybjL7CsSEs0zchb9Q01KJD4gA4tF1Tx4f6A8i/Kmj4AIO42YPiJCIijkBfUEU2nu3G6kimAeVmqbSpbxqgrFGdxx6yulw8m2blZTdyYgaGoDaJkXNos3jCsvKCaWaIQ0IfEHBJwV1l70Fy9eGvL0C9BIM6pCTRN4vt/7hlwbGY++ViA6QKchdzcIR3sY+sTJlI4bOWd05HYPH24FOoLXB8nWfb/L2HHPareZBn0NUMkvt+2Fc5SnjE1/C4XwDDq3Ugt/tMeZ10OIFxtxFenNZgnvslt54FvcPUaXLE6fB5Rr9mYmT9EKvHsb9S0U0DcBAtDP8n1eAme68KjuXvvl/0D+UtrXsueAyOjbh0U4OOzjHRqP+8zLFSfDoKgFdoflM3uQSuuYtCFwZfs58EaRq6GI2HY/90LrXwe5IsDyP0O5zt+1tP1FNV6hke9CJtEnuz6CsEt9Wz/D2cdyWgGML7kpLMV1ZMbhoO5OqbQ4AVrkXkP7kuS2aDfEzpIHSdz31LpRiEhGoMuXiWzqp1VcCdGz6hO4XL7YaAXy6bFOLOfb5+n7r63afX0KVmioF848qsId16PhkQI4E0RxLlgJiD728a2eMKoc28IDLoha6GdZoQiS/wtN2dc3G8NueU9RBO59jKd9S9hR3GNgwHNUNtsIYJiVzfDjJzwAw41hs3t2UuSyAqSDPPIGQ5cy8Ng+A5YiLQYcOCgjWqXpqJVLEOMWqUOTSWJ+OSaTcGfQFWYNKQ46tNfZcPvI1aW526yShDGPEQWQ4aWd2DunvkvwJL57nM/DHQfXg4QTtM+tmQ9UJLT3I3l6qgR5G3YtOWu6MAmLQUW0qnc/w4Dri7qVZ311e2x87nlU3w2IxMnYc8kpC4zMoSwYGmbIRpgQUZ5uUqbc7xvRsT+Zu+z26U/ezMskEAHIyfKJyoFb1DZBtx2J8psGvFNKWjIS+p2/tkZctBOARrRYpk/JzBSU5cGTLOkzfm13QMbnDR93lfJGizBCe4NUZayxozj/jULXPSaRjN7XpKd2Zp1KZOBZM74xklCfZW+pnDl/yXY2NqOgPjozNK8JzNhcQHfia2BUG+gss+/8ZN6PWfEXQ5CCNB649fgsujwHfSPdQ/Ss9WdW5ksgPLSenAlh1hHlzCfk70k0iAHSIl23g5NFFnNpudseWjSGslL+OfFpb7oJPybE84XiwSS2deNy2vLhbdvLlBQ/9e1eOnc3mb0+HZvQksYPuDf8lAJ8E+TQ+sJO82NCgwv9rM/KwtyacNagy0+VJjOwNMfYnH2WJxiMU3if4cew6Z/dB68bMd2BHbpFlHNsH51Vq3US1Z4+FLP6sbHMjFGaJiu78x04/S3DexCCOc7UgewJEVaH7teq2MQexilq25X20j2r2L41BO/n9DnenXuYOdoVL7etUu41hJSFJDzP0+LUA1Mt7jS2a69olcNNV1WorrCJJjwl/G+XxawurT/jVVGvu6wvDOioZo2vK5kYOYF73uIK67bznhJcKPavI6UBun554XJZlYzmpezKdlCTtlATH8u1r9hJGaV9e4WponWIlJ/ZK4QEZ0mitzjPXUuWUj7t94r/m7CTz4rp2yvHlFivDzhMATlVW1VTcH1C9EedGAmbN7Jvid6ZRRYULw+VyEfde19t+TtCkEiQtvZrlvWbIUlq6GbEwLkYmRfT/+3vVw8X4O69l9ehd2IBkkJ/GIEtRjNo0rMV6kBqjlmR/SSPGBBrz1mh+JNNjinnxQXyb6FkAx8CsSr2bhKttWz4xGjBOidl1K4RGFoptaVveS9U6oVEsGFBG8pHBRuw9HF896ab33KdKza3mSCCGMVgfxmtaMBsXfuTDIDfGUUyMJmmPYCmrixJLXprlhbsvYNGRPwZY43zCguRm9oLine truncated
+6
View File
@@ -0,0 +1,6 @@
root = true
[*]
end_of_line = lf
charset = utf-8
insert_final_newline = true
+2 -1
View File
@@ -4,7 +4,7 @@
# Git stores LF, and every text file is checked out as LF on all platforms.
# This is not cosmetic: scripts/validate-char-count.js measures the characters
# actually on disk, so a CRLF checkout adds ~1 character per line. The workflow
# prompts in src/plan2code-*.md run close to their 11,000 character budget
# prompts in src/plan2code-*.md run close to their 11,500 character budget
# (several sit above 10,800), and a CRLF working tree pushes them over — turning
# `npm test` into a check that passes or fails depending on how the repo was
# cloned. Pinning eol=lf makes the count reproducible everywhere.
@@ -16,6 +16,7 @@
# ─────────────────────────────────────────────────────────────────────────────
*.png binary
*.jpg binary
*.mp3 binary
*.jpeg binary
*.gif binary
*.ico binary
+4
View File
@@ -15,3 +15,7 @@ handoffs/
node_modules/
package-lock.json
SYNC.md
# Throwaway design prototypes (ai-assist-prototype). The decision they
# recorded lives in the code and the CHANGELOG; the files stay local.
prototypes/
+1
View File
@@ -13,6 +13,7 @@ produces are unchanged.
| Approach | Best for |
|----------|----------|
| `/plan2code-3-implement` | Interactive control, reviewing each phase, logic that needs your judgment |
| `/plan2code-3-implement-review` | The same interactive control, with a focused review and its fixes applied before you approve the phase |
| `plan2code-loop` | Straightforward implementations, batch work, overnight runs |
The loop reads the same `overview.md` and phase files. You can start with the loop and finish by
+6 -6
View File
@@ -15,18 +15,18 @@ background processes.** Optional, and unrelated to the workflow itself.
On Pro / Max / Teams accounts, where rate limits are available:
```
◦ ◦ Opus 5 / high │ plan2code │ feature/pathfinder-github-iss │ +12 -3
╭●╮ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
├■┤ 3h 5m ($4.62) │ ▰▰▰▰▰▱▱▱▱▱▱▱ 42% (84K) │ 5h: 28% · 7d: 61%
╭───╮ Opus 5 / high │ plan2code │ feature/pathfinder-github-iss │ +12 -3
│ ★ │ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
╰┬─┬╯ 3h 5m ($4.62) │ ▰▰▰▰▰▱▱▱▱▱▱▱ 42% (84K) │ 5h: 28% · 7d: 61%
```
On Enterprise / Bedrock / Vertex / pay-as-you-go, where they aren't, the last segment becomes session
token counts instead:
```
◦ ◦ Sonnet 5 │ plan2code │ main │ +12 -3
╭●╮ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
├■┤ 2m ($0.18) │ ▰▰▱▱▱▱▱▱▱▱▱▱ 18% │ 88k in · 3k out
╭───╮ Sonnet 5 │ plan2code │ main │ +12 -3
│ ★ │ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
╰┬─┬╯ 2m ($0.18) │ ▰▰▱▱▱▱▱▱▱▱▱▱ 18% │ 88k in · 3k out
```
The icons down the left are Planny, the project mascot.
+1 -1
View File
@@ -19,7 +19,7 @@ Built for **maintainers**. If you're using Plan2Code to ship features, you don't
## Install
```bash
node install.js # I (everything) — or C → B (bot only)
node install.js # A (everything + dev tools) — or C → B (bot only)
```
## Run
+6 -1
View File
@@ -5,6 +5,11 @@ conversation** — that's the whole trick.
← [Back to README](../README.md)
> **Prefer a page to a terminal?** Every skill can run in your browser — start at the
> `/plan2code` dashboard, add `--web` to a direct command (e.g. `/plan2code-1-plan --web`),
> or choose the console when offered. Questions, sign-offs and build progress stay on the page.
> See [web-console.md](web-console.md).
---
## Session 1 — Plan
@@ -73,7 +78,7 @@ Repeat. New conversation each time. It always finds the next open phase itself.
When you reach a parallel group, it offers you the choice — open a second agent, take the other
phase, and the `[/]` marks keep them from colliding.
**Optional, any time:** `/plan2code-review` for an independent second opinion on what just landed.
Use `/plan2code-3-implement-review` instead when review should run automatically before phase approval. `/plan2code-review` remains available for an independent second opinion at any other time.
---
+380
View File
@@ -0,0 +1,380 @@
# Plan2Code Web Console: design proposal
**Status:** implemented in v2.4.0. Kept as the design record, because it explains
*why* the thing is shaped the way it is. For how to use it, see
[web-console.md](./web-console.md); for where the code lives, see
[AGENTS-architecture.md](../.agents-docs/AGENTS-architecture.md).
**Date:** 2026-09-20
**Scope:** an optional local browser UI that `plan2code-0-pathfinder` and `plan2code-1-plan` can offer at startup, built as a shared component other workflow steps can adopt later.
---
## 1. Why this is smaller than it looks
Pathfinder is already written against a *delivery-channel abstraction*. Its rules say:
> AskUserQuestion when available; prose Q blocks only as fallback.
and `grilling.md` specifies the question object in full: a plain two-or-three-word header, the probe with its why-it-matters, two to four genuine options each described by its trade-off with exactly one named as the recommendation, plus an automatic `Other` escape hatch.
That is a form. The console is not a new workflow, it is a **third delivery channel** alongside the structured tool and prose. The methodology, the file formats, the gates and the rules are untouched.
Plan is the opposite: pure prose Q and A with seven phases and four named approval gates. But every one of its gates already resolves to a literal typed token (`approved`, `needs changes`, `approve / refine / abort`). That gives us the second half of the idea.
### The keystone: answers map back to the literal token
Every console request carries two extra fields:
| Field | Purpose |
| --- | --- |
| `fallbackText` | the exact terminal phrasing the prompt would have printed |
| `token` | what each button resolves to: `approved`, `H`, `A`, `S 1,3,5`, `yes`, `skip` |
Clicking **Approve** in the browser is then byte-identical to typing `approved` in the terminal. No prompt logic ever forks. If the console is absent, refused, or times out, the agent prints `fallbackText` and the session continues in the terminal with nothing lost. Mid-session switching in either direction is free, because the markdown files under `specs/` remain the only source of truth.
This one decision is what keeps the integration from metastasising across twelve prompt files.
---
## 2. Hard constraints found during research
These are verified, not assumed. They shape everything below.
### 2.1 The character limit is the binding constraint
`scripts/validate-char-count.js` caps every flat `src/plan2code-*.md` at 11,000 characters, enforced by a husky pre-commit hook. Measured today:
```
10995 5 plan2code-0-pathfinder.md <- 5 characters of headroom
10676 324 plan2code-1-plan.md
10835 165 plan2code-2-document.md
```
Neither target prompt can absorb the integration inline. **Trimming pathfinder by roughly 250 characters is a prerequisite task, not a nice-to-have.** Reference files are exempt from the limit, so all of the console contract lives in one.
### 2.2 Packaging needs zero installer code changes
`computeExpectedSkills()` in `install.js` copies `additionalReferences` directories verbatim through `listFilesRecursive()`, which has no extension filter. The initial implementation fanned one shared source directory into two skills; the current installer fans it into every skill.
Current packaging constraints:
- Reference files are copied as `Buffer`s, so binary assets are supported; the shipped MP3 chimes exercise this path. Browser-served assets must also be added to the server's `SERVABLE` allow-list and covered by a test.
- `skills/` is generated build output (committed, and checked for drift by `npm test`) and `buildSkills()` prunes files it doesn't expect. Assets must originate in `src/` and never be hand-placed.
### 2.3 `specs/` is gitignored, which is an argument *for* the server
Three prompts repeat the warning that Glob silently fails on `specs/` and only a shell listing works. A Node server enumerating candidate spec directories server-side and handing the page a list is strictly better than either a terminal listing or a browser file input.
### 2.4 Formats that must round-trip byte for byte
- `<!-- METRICS_JSON {...} -->` comments
- the `## User Feedback` table (exact field names `Rating`, `Reason`, `Went Well`, `Went Poorly`, pipes escaped as `\|`)
- the five-state checkbox alphabet `[ ]` `[/]` `[x]` `[?]` `[!]`, with the invariant "never reset `[/]` to `[ ]`"
- the handoff string `**Status:** Phase 3 Complete - Resume at Phase 4`, plain ASCII hyphen, single spaces
The console carries all of these as opaque strings and never reformats them.
### 2.5 Two regex landmines
- `plan2code-metrics` scrapes confidence with patterns like `/[Rr]equirements?[:\s|]+(\d{1,2})/` that **do not require a percent sign**. Nothing the console writes under `specs/` may contain bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number.
- The loop parses `TASK_COMPLETE`, `PHASE_COMPLETE` and friends. Pathfinder already forbids these tokens under `specs/`.
Both are cheap to enforce mechanically in the server's write path.
---
## 3. Architecture
### 3.1 Placement
```
src/web-console/
console.mjs CLI: open | post | wait | status | stop
server.mjs the HTTP server (spawned detached by `open`)
lib.mjs paths, atomic writes, patch merge, validate()
console.md the agent-facing contract
public/index.html markup shell only
public/app.js the client (no inline script, see CSP below)
public/app.css
public/render.js markdown tokens to DOM nodes
public/vendor/marked.esm.js pinned 15.0.7, MIT, lexer only
```
Wired in with one data entry per consumer:
```js
{
source: 'plan2code-0-pathfinder.md',
// ...
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
}
```
Lands at `~/.agents/skills/<skill>/references/web-console/` on all ~28 target agents. The server finds its own siblings via `path.dirname(fileURLToPath(import.meta.url))`.
The agent needs an absolute path to invoke it. `ai-assist-git-pr` already establishes the convention, proven on Windows, and we reuse its wording:
> `<SKILL_ROOT>` = the directory containing this `SKILL.md` (its install location). Use the absolute path you loaded it from.
### 3.2 The transport, which is the genuinely hard part
A turn-based agent must wait up to twenty minutes for a human. Claude Code's Bash tool caps at 600s and **harness-managed background tasks are not a safe place to wait**: there are open issues documenting them being killed at 5 to 20 minutes, killed on compaction, killed when a new prompt arrives, and leaked with no handle when spawned by subagents. Detached processes are explicitly immune.
So: **split into two processes with deliberately different lifetimes.**
```
# once, at handoff
node <SKILL_ROOT>/references/web-console/console.mjs open --file request.json
-> spawns server.mjs DETACHED, prints URL + session id, exits in under 300ms
# repeatedly, until done
node ... console.mjs wait --seconds 240
exit 0 -> stdout is the result JSON. Done.
exit 10 -> {"status":"waiting","elapsed":"6m12s","answered":3,"total":7,...}
Agent relays one line to the user and calls wait again.
exit 20 -> server is dead. Agent restarts it, re-reports the URL.
exit 30 -> human hit Cancel.
```
Why bounded rather than a single long block:
- The deadline lives in our code, not the harness's. `--seconds 240` covers a 20-minute session in five turns. Drop to `--seconds 90` for harnesses with a 120s default (Cursor auto-backgrounds and cannot be told not to).
- Every return is a free heartbeat: "still waiting, 3 of 7 answered, 6 minutes in" beats silence.
- Interruption is survivable. Ctrl-C the agent, compact the context, restart: the next `wait` re-attaches, because state is on disk.
The waiter uses `fs.watch` on the session **directory** (watching a file breaks on Windows when the file is replaced by rename) with a 500ms `stat` fallback as the authority, and pings `/health` every 5s for liveness. The result is delivered **through the filesystem**, not HTTP, which decouples the waiter from the server and is also the resumability story.
**Optional push accelerator, Claude Code only:** at `start`, also fire a backgrounded `until [ -f <dir>/result.json ]; do sleep 2; done`. If it survives, submit-to-agent latency drops to near zero. If it gets killed, nothing breaks, because the poll loop is the source of truth.
### 3.3 Port, lifecycle, security
| Concern | Decision |
| --- | --- |
| Port | `listen(0, '127.0.0.1')`, handle file in `os.tmpdir()/<tool>/<sha1(cwd).slice(0,8)>/`. This is Jupyter's `jpserver-<pid>.json` pattern and RFC 8252 §7.3. A fixed port is fatal here: you run git worktrees, so two agents in two checkouts of one repo is routine, and a fixed port makes that silently wrong. |
| Bind | the literal `127.0.0.1`, never `0.0.0.0`, never the string `localhost` (which may resolve to `::1` and produce the classic "server is up but the browser gets ECONNREFUSED" bug on Windows). |
| Auto-open | best-effort, never fatal. Skip when `DISPLAY` and `WAYLAND_DISPLAY` are both unset, or `SSH_CONNECTION` / `REMOTE_CONTAINERS` is set. Honour `BROWSER=` and `--no-open`. |
| Orphan prevention | a **server-side idle deadline** (30 min, bumped by any authenticated request) is the mechanism, not a nicety. Windows has no real SIGTERM, and a detached server with no console never sees `SIGINT`, so signal handlers cannot be relied on. Plus a 4h absolute cap, a `pagehide` beacon, an explicit `stop`, and a reap sweep on every `start`. |
| Liveness test | `process.kill(pid, 0)` **and** a `/health` check whose returned session id matches the handle. PID reuse is real; the sid match is what disambiguates. |
Security, six controls, about 60 lines:
1. Bind `127.0.0.1`.
2. **`Host` header allowlist.** This is the DNS-rebinding defence and the highest-value line in the server. Vite shipped GHSA-vg6x-rcgg-rjx6 for exactly this omission.
3. 128-bit token **in the URL path**, not the query string. Path placement also kills the Windows `cmd /c start` `&`-injection hazard, because the URL then contains no `&`.
4. First `GET /s/<token>/` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free.
5. `Origin` check on every mutating request.
6. Strict CSP with no `unsafe-inline`, which is why JS and CSS are separate files rather than one inlined HTML.
**On whether XSS matters here.** The tempting argument is "it is the user's own machine and the model would not write `<script>`". That misses the real risk. The page is same-origin with a server that reads and writes the user's files and holds the session token, so script in that page can post arbitrary answers back to the agent, which then acts on them with the agent's full tool permissions. And the markdown is only nominally agent-authored: in practice the agent is summarising a dependency README, a scraped page, a PR description, a log. Treat it as attacker-controlled.
The structural fix, rather than a filter: **vendor `marked` for `lexer()` only and render tokens to the DOM with `createElement` and `textContent`.** No HTML string is ever produced, so there is nothing for a sanitiser bypass to bypass, and the strict CSP holds. Roughly 120 lines of renderer. Hand-rolling the parser instead is a trap: hand-rolled markdown fails exactly where agent-authored technical documents live (a table inside a list item, a fenced block containing backticks) and its failure mode is usually an injection hole.
### 3.4 Browser transport
SSE primary (about fifteen lines on Node's built-in `http`), with automatic fallback to 3s interval polling after three consecutive errors. **Exactly one `EventSource` per page, ever**: browsers cap HTTP/1.1 at ~6 connections per origin, and a second stream per tab across three tabs wedges the origin with no error and no timeout. Multiplex everything through one stream with a `type` field.
The page shows the **agent's** liveness, not the server's. If the agent's turn crashed, the server is still happily up and a naive spinner lies forever. Stamp `agentLastSeen` on every waiter ping; when stale past two minutes the page says so plainly: "The agent has not checked in for 4 minutes. Your answers are saved. Check your terminal."
### 3.5 State on disk
The filesystem is the database and the result transport.
```
~/.plan2code/console/sessions/<sid>/
session.json sid, cwd, workflow, title, phase
request-<rev>.json the agent's payload, immutable per revision
draft.json in-progress answers, debounced ~500ms write
result.json written ATOMICALLY on submit (temp + fsync + rename)
events.ndjson append-only, doubles as SSE Last-Event-ID replay
```
Deliberately **not** under `specs/`: that keeps the console clear of the metrics scraper and the loop's marker parser, and survives a `git clean`.
Draft persistence is the highest-value feature in the tool and among the cheapest. Twenty minutes of a product manager's structured answers must never be lost to a closed tab. Server-side debounced write plus a `localStorage` mirror keyed by `sid + rev`.
Recovery matrix:
| Failure | Recovery |
| --- | --- |
| Tab closed or browser crashed | Reopen the URL, draft restored, agent never notices |
| Server died, agent alive | `wait` returns exit 20, agent runs `start --resume <sid>`, new port, same session dir |
| **Agent session died, human still working** | Human submits, `result.json` lands on disk. A fresh session runs `status`, finds the unconsumed result, picks up where it left off |
| Machine rebooted | Handle file is gone (correct), session dir survives, `--resume` works |
---
## 4. The interaction contract
### 4.1 Item envelope
```jsonc
{
"id": "i7", "topic": "t2", "kind": "choice",
"title": "Export format", // PLAIN 2-4 words, never internal jargon
"body": "markdown: the probe plus its why-it-matters",
"options": [ { "k": "A", "text": "CSV", "detail": "trade-off", "recommended": true } ],
"allowOther": true,
"required": true,
"status": "open",
"answer": null,
"thread": [],
"fallbackText": "the exact terminal phrasing",
"token": { "A": "a", "B": "b" } // maps a click back to the literal reply
}
```
Note `recommended` is **optional per option**. Handoff explicitly wants its inferred task offered as the recommendation; the `.gitignore` question in handoff explicitly does not ("present it, don't force it").
### 4.2 Primitives
Tier 1, needed for pathfinder and plan, build now:
| Kind | Covers |
| --- | --- |
| `choice` | Step 0 intent gate, all six destination probes, the 14 frontier axes, plan's coverage and scope questions |
| `multi` | plan's testing types (Unit / Integration / E2E / None) |
| `text` | sacrificial boundary, the embarrassment question, kebab-case feature name **with live pattern validation the terminal cannot do** |
| `confirm` | the Tier-2 sketch gate, the lock offer, abort confirmations |
| `recap` | the recap-and-confirm turn. Non-skippable by design |
| `review` | plan's four approval gates, `1b`'s spec-update gate, paper-sketch reactions |
| `checklist` | `legwork · HITL`: numbered steps plus Done / Blocked / Need help / Defer plus a values field |
| `menu` | the fork menu: up to three takeable questions plus Start fresh, one recommended, with the resume command as copy-to-clipboard |
| `list` | orderable and editable rows, for plan Phase 6's implementation phases |
Tier 2, design the schema to admit them but do not build yet: `findings-triage`, `table-review`, `form`, `path-picker`, `command-handoff`, `notice`, `progress`.
### 4.3 Rules the server enforces mechanically
Several prose rules become checks, which is the quiet advantage of routing through a server at all:
- **Reject a patch leaving more than three open required items.** Grilling says "the cap is three regardless of what the environment allows. The ceiling is the human's attention, not the tool's schema." A web UI tempts you to show ten. Make the rule mechanical.
- **Reject internal jargon in `title`**: `grill`, `frontier`, `fog`, `HITL`, `Locked:`, `Blocked by:`. There is an explicit do-not-say list in `grilling.md`; this is where to enforce it.
- **One authoritative gate per session.** `plan2code-3-implement-review` proves several prompts each carry an approval gate while only one may fire when composed. A `gate: { id, authoritative }` field plus a server guard.
- **Defer is a third verb**, distinct from reject.
- Reject forbidden tokens and bare confidence-word-plus-number patterns in anything written under `specs/`.
- Stamp every timestamp server-side. Models do not reliably know the time.
---
## 5. The UI
Three panes, plus view tabs, closer to pathfinder's own vocabulary than to a grilling UI.
```
┌──────────────────────────────────────────────────────────────────────┐
│ 🧭 audit-export · Pathfinder · Working 4 of 9 cleared ▓▓▓▓░░░░░ │
│ ● Waiting on you · 3 questions [Questions] [Map] [Draft] │
├───────────────┬──────────────────────────────┬───────────────────────┤
│ THE MAP │ What you end up with │ DISCUSSION │
│ │ │ │
│ ✓ Destination │ Why this matters: ... │ thread on this item │
│ ✓ Codebase │ │ │
│ ● Export fmt │ ○ A CSV, ... │ │
│ ○ Size cap │ ◉ B Parquet RECOMMENDED │ │
│ ⊘ Retention │ ○ C Both, ... │ │
│ │ ○ Something else ______ │ │
│ NOT YET CLEAR │ │ │
│ · fog item │ Not sure, skip for now │ │
├───────────────┴──────────────────────────────┴───────────────────────┤
│ 2 staged · Export format → B · +1 comment ⌘↩ [Send to Agent] │
└──────────────────────────────────────────────────────────────────────┘
```
### What to take from grill-with-ui
- **Batch staging with one explicit Send.** Everything is local and reversible until one deliberate press. For a non-technical user this removes the terror of "did I just commit to that?"
- **The three-tier commitment vocabulary**: staged (amber, removable) → sent and pending (dashed, spinner) → recorded (green check). Honoured consistently on every surface.
- **The whole stuck-agent apparatus**: live elapsed counter, disabled Send while working, a five-minute grace that re-enables Send with an explanation, server-gone detection with self-reconnect. About 40 lines, and more honest about agent latency than most commercial agent UIs.
- **Assumed regions.** The best idea in that repo: the generated artifact marks regions that depend on still-open questions with a dashed outline and "assumed, pending Q3". This transplants directly onto a plan taking shape.
- **Versioned artifacts with a staleness flag** and a one-line change note.
- `withInputs()` focus preservation, raw-string diffing before re-render, and the `prefers-reduced-motion` handling that keeps progress indicators legible rather than freezing them.
### What to change
- **Topics, not rounds.** Grill groups the nav by round, which is a temporal artifact: "questions the agent happened to ask on turn 4". Its own sample data has one round containing three unrelated subjects. Product people cannot use that. Group by topic, stable and nameable.
- **Show real progress.** Grill has no "N of M" counter at all. Pathfinder's trail footer already computes `4/9 cleared` and a plain-English confidence line. Put both in the header. In a 45-minute session with a PM, "how much longer is this" is the first question asked.
- **Recommendations become optional.** Grill always leads with one, which is right when the agent has an opinion and you are pushing on it. In discovery the agent frequently should not have an opinion, and pre-filling one anchors a PM into rubber-stamping. Neutral mode: no `rec`, or reframed as "what similar products do".
- **Real, accessible form controls.** Grill's options are `<li>` with `onclick`, so they are unreachable by keyboard and invisible to screen readers. Non-negotiable to fix if non-technical stakeholders are in scope.
- **Markdown actually renders.** Grill escapes everything and sets `white-space: pre-line`; there is no markdown at all. A plan document cannot be shown that way.
- **Rename everything.** "Grill", "durable", "Defer", "Reopen", "Why A." is a vocabulary for interrogating an engineer who already has a plan.
- **Do not dim rejected options to 45%.** In discovery the rejected options are often the most valuable thing in the room, and an engineer joining late needs to see why B lost.
### Two things the console unlocks that the terminal cannot
- **Tier-2 UI sketches.** `resolve.md` already sanctions building 3 to 5 structurally different UI variants switched by "a URL search param plus a small floating bar". The console can host them in a sandboxed iframe with a proper variant switcher. This is already in the methodology and currently awkward.
- **Anchored reactions.** `resolve.md` insists every sketch probe "names its row or element". With `anchors: { "row5": "b3" }`, clicking the probe highlights the row. That is the inline-commenting capability, scoped to something the methodology already demands.
### Room-screen polish (v2.4.0)
Built for a mixed product and engineering room reading one screen together.
- **One width variable.** `--card-width` on `:root` in `app.css` sets the column the card, the pager and the document tabs share (`max-width: min(var(--card-width), 100%)`, so a narrow window still wins); no fixed `720px` column rule is left outside a media query. Three presets, picked under *Card width* in the looks panel and saved as `looks.width`: `narrow` 720px, `comfortable` 880px (the default, and the variable's own value), `wide` 1080px, applied as `:root[data-width="…"]`. `CARD_WIDTHS` in `palette.js` is the same list for the page's validation and the server's first-paint `data-width`; **`palette.js` and `app.css` must agree**, which is the one place the number is written twice. The dashboard keeps its own 860px layout. Inside the card the `62ch` / `68ch` measure caps come off (`.card .md, .card .prompt { max-width: none; }`) so a wider card is not a narrow column in a wide frame; documents keep `.md`'s 68ch.
- **One box grows.** On the primary card, the answer box that is being typed in — a `text` question's box, a choice's *Something else* box once picked, or the note under a verdict / confirm / recap once shown — is `textarea.grow`, and the card takes the column's full height above the pager (`.card.is-primary.has-grow { flex: 1 1 auto; }`). `fitGrowBox()` in `app.js` writes the card's free height as the box's `min-height`, **never under 160px**; a `ResizeObserver` watches the main column rather than the box, so the box growing can never retrigger it, and it writes only on a change over 1px. `resize: vertical` with that moving floor makes the handle taller-only; past the fill the card scrolls. Every other box keeps its ordinary size, and the notes panel is untouched.
- **A switch per sound.** Every cue is an event in `SOUND_EVENTS` (`palette.js`), each naming its file and rank: `startSkill` (`start-skill.mp3`, played once the dashboard's **Start** is accepted) 5, `bootup` 4, `sessionStart` / `sessionEnd` (`start-stop.mp3`) 3, `question` / `skillReady` / `chatReply` (`next.mp3`) 2, `newTab` (`insert.mp3`) 1, `snore` (`sleeping.mp3`, looped by the wake-up outside the queue) 0. The queue, the held slot and the one-at-a-time rule in `app.js` work on events, one `Audio` per file shared by the events that use it. User Preferences shows a *Play sounds* master (`looks.sound`) over one box per event, saved flat as `sound<Event>` (`soundStartSkill`, …) because `looks.json` only holds flat values; `soundPrefs()` turns any missing or non-boolean switch on, so a file from before the switches keeps every sound. A cue plays only while the master and its own switch are both on; the master off greys the boxes but keeps their ticks, and ticking a box plays it.
- **Send breathes.** `#btn-send:not(:disabled)` runs `send-pulse`, a soft accent ring that spreads and fades every 2.4s; a disabled Send is still, and reduced motion switches it off.
- **Per-tab scroll memory.** An in-memory `Map` keyed by view id holds the scroller's position (the main column on a document or the Overview, the card on the questions view, with the item it belonged to), restored when the tab comes back. Page-local, never persisted, cleared when the session turns into or out of the dashboard.
- **The Overview tab.** Appears only while `GET /overview` returns a file for the session's spec (on the dashboard: the picker's spec; gone for *start from scratch*), fetched with `no-store` on load, on a spec change and on every tab click, so it always shows the file as it is on disk. Rendered through the same DOM-only markdown path as every doc, captioned read-only. It never becomes a doc: the page is not the record.
- **The footer slot.** The workspace label sits centred in the footer's middle track, 12px and muted: `footerLabel()` in `public/workspace.js` builds `folder · branch` (from the workspace's original folder and `state.branch`), or `folder + N folders · branch` once folders are added, and `renderWhere()` steps down through its narrower tiers (`FOOTER_TIERS`) until the text fits. A warning dot marks a missing or unreadable folder. A click opens the Workspace dialog (`#workspace-modal`), where each folder has its own **Copy path**. The notification pill is fixed over the same spot and covers it while it shows, on purpose: nothing there needs pressing while the pill is up. The dashboard keeps the footer for this label alone: `renderFooter()` puts `is-dash` on it, which hides the summary and Send (and on a narrow screen keeps the label, the one thing left in the bar); the footer only disappears there when there is no label to show.
- **The wake-up.** A fresh dashboard (`state.wake`, plus a per-sid `sessionStorage` guard) plays Planny powering on centre stage, as proven in `pathfinder/sketch-01`. The wake layer hides the dashboard behind a solid `var(--bg)` backdrop (`.wake::before`, so it follows the theme) whose opacity fades out over the same 0.6s as the glide, revealing the menu as he lands; the notification pill (`.banner`, z-index 46) stays above the layer (45). Before the first click or key he sleeps there on loop under a "Click to wake Planny" hint (`.wake.dormant`): Z's rising, slow breathing, slack arms swaying out of step, his feet pulsing like a standby light. While he sleeps the page tries to loop `sleeping.mp3` (browsers usually refuse until the first click, so this is normally silent). That click fades the hint and nudges him (`.wake.stirring`): he rocks gently about his feet (`wake-nudge`) while exactly one snore plays from the top, via the `stir()` callback `playWake()` awaits — timed by the snore's `ended`, capped at 6s, or a 2.6s timer when sounds are off or refused. Then the boot starts to `bootup.mp3` (in place of the opening chime; outranked only by the Start-skill cue, which cannot coincide with it because the wake layer swallows every click and key until the run ends), which fades out over 0.5s the moment the run ends or is aborted. The boot pops the Z's outward: 0.4s power-on and his feet blink · 1.35s feet plant · 1.5s / 1.9s arms lift off his sides · 2.5s the star opens lit, with a scan · 2.85s he glances left, right, then ahead · 3.2s smile · 3.6s hop and a cheer, star back to ink · 4.3s a 0.6s glide into the rail, measured once by `boot.js` and handed to CSS as `--wake-glide` · the menu groups rise in 60ms apart as he lands, and the note types in. Done by 5s (a fallback timer covers a hidden tab whose transition never fires). The beats are CSS keyframes on delays under `.wake.booting`, all inside `@media (prefers-reduced-motion: no-preference)`; there is no skip: from the waking click on, clicks and plain keys (no Ctrl/Meta/Alt) are swallowed so the nudge, boot and sound always play out; only a launch mid-run aborts it (snore stopped, boot-up faded), and under reduced motion `playWake()` resolves at once and the awake dashboard is simply there.
---
## 6. The startup question
Both prompts open with one ask. Pathfinder already uses `AskUserQuestion`, so this costs almost nothing:
> Run this session in the **web console** (a local page in your browser, better for walking through decisions with someone) or **here in the terminal**?
Recommended default is an open decision (see §8). Because the markdown files stay the source of truth, the user can switch either way mid-session at no cost, and the prompt should say so.
---
## 7. Work plan
| # | Task | Notes |
| --- | --- | --- |
| 0 | **Trim `plan2code-0-pathfinder.md` by ~250 characters** | Hard prerequisite. 5 characters of headroom today. Candidates: the `grilling.md` fallback blockquote, the Rules list. |
| 1 | `src/web-console/` skeleton: `console.mjs` start/wait/status/stop, detached spawn, handle file, reap sweep | The transport is the risky part, build and prove it first |
| 2 | `server.mjs`: the six security controls, SSE, atomic result write with Windows `EPERM` retry | |
| 3 | `index.html` + `app.js` + `app.css` + vendored `marked` lexer, token-to-DOM renderer | |
| 4 | Tier 1 primitives, staging, drafts, Send | |
| 5 | `console.md`: the agent contract | The only file the prompts point at |
| 6 | `SOURCE_PROMPTS` entries + `npm run build:skills` + commit `skills/` | Zero installer code changes |
| 7 | Pathfinder integration: startup ask, channel rule, `Read` line | ~250 chars, funded by task 0 |
| 8 | Plan integration | 324 chars headroom, fits, trim ~150 for margin |
| 9 | CHANGELOG + `version.json` + `package.json` in lockstep | `plan2code-publish` refuses to release on mismatch |
### Three things most likely to bite during implementation
1. **Forgetting `windowsHide: true` on the detached spawn.** It defaults to `false`, and `detached` on Windows forces a console window that "once enabled, cannot be disabled". Every handoff flashes a black box at the user.
2. **`fs.rename` `EPERM` from antivirus and search indexers on Windows.** Intermittent, unreproducible on demand, looks exactly like a logic bug. Retry three times with backoff from day one.
3. **Relying on `SIGTERM` for cleanup on Windows.** It does not arrive. Build the idle deadline first, not last, and comment why.
### Non-obvious portability notes
- grill-with-ui's heredoc idiom (`patch <<'EOF'`) is **not portable to PowerShell**, which is the default shell for Claude Code on Windows. Use a `--file <path>` form as the primary documented interface.
- `nohup ... &` is bash-only. Backgrounding happens inside `console.mjs start`, never in the shell command the agent writes.
- Always emit `node "<abs>/console.mjs"` quoted. Install paths contain spaces.
---
## 8. Open decisions
1. **Default channel.** Terminal (lower ceremony for an engineer working solo) or console (better for the cross-functional sessions that motivated this)? Recommendation: console marked as recommended in the ask, terminal as the low-ceremony alternative.
2. **Vendoring `marked`.** It is MIT and dependency-free, but it is the first vendored third-party code in the repo, against a house style of "Node built-ins only". The alternative, a hand-rolled parser, is materially worse on both correctness and security. Recommendation: vendor it, pin the version, record the SHA-256.
3. **Single-driver or multi-user.** Everything above assumes one browser, one driver, no identity or attribution. A facilitated workshop with one person at the keyboard works fine. Two people answering independently is a different product and reaches into the state model. Recommendation: single-driver for v1, say so explicitly.
4. **Third consumer.** After pathfinder and plan, `/plan2code-review` is the strongest case: two of its rules exist only because output goes to a terminal ("for 15+ findings, present top 10", "output tables as direct markdown, NOT inside code blocks") and a browser deletes both. Its `S 1,3,5` fix selection is literally a checkbox list compressed into a CLI token, and one findings UI serves both `/plan2code-review` and `/plan2code-3-implement-review`.
---
## 9. Honest assessment of size
This is not a weekend. Rough shape: `console.mjs` plus `server.mjs` around 700 to 900 lines, the client around 900 to 1,200, the contract file 300 to 400 lines of prose, plus the prompt trims and build wiring. The transport and lifecycle work (tasks 1 and 2) is where the risk concentrates, and it is worth proving end to end on one primitive before building the other eight.
A smaller first cut that still tests the whole idea: pathfinder only, `choice` and `text` and `recap` only, no artifact pane. That exercises the transport, the token mapping, the fallback path and the three-probe cap, which are the parts most likely to be wrong.
---
## Credits
The architecture owes a large debt to `grill-with-ui`, whose file-ownership model, staged-then-send interaction, commitment tiers and assumed-region idea are all borrowed here. The implementation is independent.
+672
View File
@@ -0,0 +1,672 @@
# The Web Console
A local page in your browser for working through a Plan2Code session instead
of answering everything in the terminal. Every skill has one — and `/plan2code`
is the front door: it opens a dashboard of all of them, and whichever you pick
starts right there on the same page.
It exists because the hardest part of adopting Plan2Code is not the engineering.
It is getting the person who actually knows what the product should do into the
room. Pathfinder and Planning are the two steps where that person matters most,
and they were the two steps that looked like a wall of terminal text.
---
## What you get
- **Every question laid out**, with the trade-offs written next to each option
instead of scrolling past in your history.
- **A progress bar.** "4 of 9 settled" answers the first thing anybody asks.
- **Previous and Next under each card**, walking the questions still waiting, so
the list on the left is somewhere to jump from rather than the only way round.
- **An example you can accept.** Where a question comes with one, an *Autofill
suggestion* button puts it in the box as a real answer for you to edit. It
disappears as soon as you have typed anything of your own.
- **Answers you have settled read as answers**, not as a form you might still be
able to change: what you chose, stated in words, with everything else locked.
- **A question you have sent is held** until Plan2Code answers it, showing
what you sent. The rest of the page carries on working, so you can read ahead
or answer the next question while you wait.
- **The document taking shape**, in a tab, with the parts that are still guesses
clearly marked as guesses.
- **A brief, on demand** (Pathfinder). Press *Write a brief*, choose how far back,
and what comes back is a plain-English report of what has been decided, what is
still open and what happens next, in its own tab with Print and Save buttons.
It is the thing you take to a meeting.
- **Nothing is sent until you press Send.** Everything before that is local and
reversible, so nobody has to worry about committing to something by accident.
- **Nothing gets lost.** Close the tab, reload, restart your machine: your
half-typed answers are still there. Once you press Send, what you sent is
held until Plan2Code actually collects it, so it cannot be written over.
- **It tells you when the other half stops listening.** The terminal and this
page are two programs that fail separately, and a page that sat there saying
"one moment" forever was the worst way to find that out. Now it says so, and
says what to do: answering anyway still works, because what you send is held
on disk until something comes for it.
- **Starters picked for your role.** Tell *User Preferences* what you do
(engineer, product lead, architect, designer, QA, engineering manager) and
the starter templates on an idea card and the starter questions on the Ask
tab put the most useful ones first. It changes the order, never the
questions a skill asks (see *Your role* below).
- **Light or dark, and a highlight color you pick.** The swatch button at the
top right opens *User Preferences*: your role first, then these. It follows
your system by default; set it to one or the other if
you would rather it stayed put. Remembered on your machine, so it carries
over to every session.
- **A card as wide as you want it.** The same swatch panel has a *Card width*
setting — **Narrow** (720px), **Comfortable** (880px, the default) or
**Wide** (1080px) — that widens the question card, the Previous / Next pager
and the document tabs together. The dashboard keeps its own layout, and on a
small window the column simply fits the window. Remembered with the colors,
so it follows you into every session.
- **Text that uses the card.** A question's text runs the full width of the
card rather than stopping in a narrow column, and the answer box you are
typing in grows to fill the card's free height: the box of a text question,
the *Something else* box once you pick it, or the note under a verdict,
yes/no or recap once it shows. Other boxes stay small. Drag the handle to
make it taller; it never shrinks below the space it was given, and on a short
window the card scrolls instead of squeezing the box under 160px.
- **Send tells you it is ready.** While there is something to send, the Send
button pulses gently; it goes still when there is nothing to send.
- **Each tab remembers where you were.** Scroll halfway down a document,
jump to the questions, come back: you are where you left off. The same goes
for a long question card. It lasts as long as the tab is open.
- **The spec's overview, one click away.** When the session is working on a
spec that has an `overview.md`, an **Overview** tab shows it — read-only,
and read fresh from disk each time you open the tab, so an edit shows up
straight away. No file, no tab. On the dashboard it follows the spec picked
at the top, and disappears for *start from scratch*.
- **Where you are, at the bottom.** The footer names the folder the session
was launched from and its git branch (`plan2code · feature/…`), muted in
the middle. Click it to open the Workspace dialog (see *Your workspace*).
Outside a git repo it shows only the folder.
- **A chime when it's your turn.** The page plays a sound when new questions
arrive, when a new tab (a document, the overview) joins the strip, and when
the session opens or closes, so you can look away without missing your cue.
Starting a skill from the dashboard plays its own sound too. The same panel
has a *Play sounds* switch for all of them, and a box per moment (Planny
snoring, Planny waking up, starting a skill, session opens, skill is ready,
session ends, new questions, a reply on Ask, a new tab), so you can keep only
the ones you want. Ticking a box plays its sound; everything is remembered
like the colors.
- **Files in your notes.** Show instead of describe: attach a screenshot, a
photo or a document to any note or quick question (see *Attachments in notes
and questions* below).
- **A nudge when it might be waiting on you.** Your agent may stop in the
terminal to ask permission for something, and the page cannot see that. So
the dashboard and every starting screen carry a one-line tip about hands-off
modes (`auto` mode in Claude Code, `smart` mode in Devin) that can cut down
on those stops, though they may still need your attention, and when the agent
has been working and silent for about 30 seconds, Planny's line asks
*"Still working, or waiting on an approval in your terminal?"* — well before
the three-minute "has not checked in" message.
- **The tab icon says whose turn it is.** A bar along the bottom of Planny's
favicon follows the line beside him: dashed amber while Plan2Code is
working or picking up your answers, solid green when it is your move, solid
red when it has gone quiet or the connection is lost (busy is dashed so the
states differ by pattern, not only color). A finished session goes back to
the plain icon, so a console left in a background tab can be checked at a
glance.
- **Help.** The **?** at the top right opens a Help dialog with 16 topics,
one per tab down the left (across the top on a narrow window), opening on
the one for where you are. It is part of the page itself, so it still reads
fully when the page has lost its program.
- Works offline, on your own machine only. No account, no install, no network.
## Using it
The easy way in is the dashboard:
```
/plan2code
```
A page opens with every skill laid out as cards — the setup pair, the pipeline
in order, and the utilities alongside — with a note about what it made of your
project (no AGENTS.md yet, a spec waiting on Phase 2) and a *Suggested* flag on
the card it would pick. Click one 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.
A freshly opened dashboard starts with Planny asleep in the middle of the page.
Click to wake him: he snores once while he gets a gentle shake side to side,
then about five seconds of him powering on to a boot-up sound (arms lifting
off his sides, his star opening, a hop and a cheer) before he glides into his spot at
the top and the menu rises in. (Browsers stay silent until your first click,
so the snoring usually starts with it; with *Sounds* off, the same wake-up
plays without audio.)
It plays only on a fresh `/plan2code`: not on a reload, not when you come
back with **Back to the dashboard**, and not after a launch. Once he is
stirring, another click or any key skips straight to the menu, and with reduced
motion switched on in your system settings you get the awake dashboard at once.
Or start any step directly, as usual:
```
/plan2code-init
/plan2code-init-update
/plan2code-0-pathfinder
/plan2code-1-plan
/plan2code-1b-revise-plan
/plan2code-2-document
/plan2code-3-implement
/plan2code-3-implement-review
/plan2code-quick-task
/plan2code-review
/plan2code-4-finalize
/plan2code-handoff
```
The first thing it asks is how you would like to work:
> **How would you like to work through this?**
>
> - **In your browser** (suggested)
> - **Here in the terminal**
Pick the browser and a page opens at a `127.0.0.1` address, straight away:
opening the page is the first thing the skill does, before it reads your
project, so for the first few seconds you see a starting screen naming the step
("Starting Pathfinder") while it gets its bearings — for the core steps, with
Planny acting that step out. The questions replace it the
moment they are ready. Answer what is there, press **Send to Plan2Code**, and
it carries on. You can switch back to the
terminal at any point by saying so: the files under `specs/` are the same either
way, and neither side owns them.
While the page is open, the agent's messages in the terminal end with a
pointer back to it — `→ Look at the web console: http://127.0.0.1:…` — and
while it is waiting on you it says so in those words: *Waiting on your answer
in the web console*. Glance at the terminal, and it always tells you where to
look.
Know you want the page already? Pass `--web` with the command —
`/plan2code-1-plan --web plan a lunch voting app` — and it opens the console
without asking. The flag is dropped before the rest of the argument is read, so
it never becomes part of the request.
Sharing the link with a colleague on another machine will not work, and that is
deliberate. It is bound to your own machine only. To work through a session
together, share your screen.
For the same reason, the browser page is only offered when the agent is running
on your own machine. An agent working in a cloud VM, a container or over SSH
stays in the terminal: a `127.0.0.1` link from somewhere else is a link you
cannot open.
### Your role
The first control in *User Preferences* (the swatch button) is **Role**:
Engineer, Product lead / PM, Architect / tech lead, Designer (UX), QA / test
engineer, Engineering manager, or **Not set / none of these**, the default.
It only reorders things: the starter templates on an idea card and the starter
questions on the Ask tab. It never changes what a skill asks or does. It is
kept in `looks.json` with your colors, so it follows you into every session,
and **Back to default** sets it back to *Not set*.
Until you have chosen, the dashboard shows a one-line banner at the top —
*Pick your role to get starter templates ordered for you.* — with **Set up
preferences** and **Not now**. Choosing any role, *Not set* included, or
pressing *Not now* puts it away for good.
### Starter templates
The first "What's the idea?" box in Pathfinder, Plan and Quick Task has a row
of starter templates above it: **Blank** first, then outlines to fill in (an
engineering spec, product requirements, a design decision, a bug
investigation, and so on), in the order your role puts
them. With a role chosen, the first one carries a *For your role* pill. Pick
one and the box fills with editable text, `[blanks]` marked; if you have
already typed something, a strip asks **Replace** or **Keep mine** first.
Only what is in the box is sent, exactly as if you had typed it.
The templates live in the page (`public/starters.js`), not in the prompts. A
skill only marks its fresh-idea card with `"templates": "idea"`, and `post`
refuses that flag on anything but a `text` card. A resumed map or plan asks
no idea question, so it shows no templates, and the terminal never has them.
### Leave for later (Pathfinder)
Pathfinder's scope question is **Leave for later** — *"Which of these features
are we leaving out this time?"* It is a tick-any list of 3–5 features someone
might expect, each ending with what leaving it out means ("Scheduled exports
(Leaving this out = someone runs each export by hand)"), with a recommended
set to tick in one go. The features you tick become the first lines of the
map's *Out of scope*. Every option names a feature, never a rule to keep, so a
tick always means "not this time".
### Skipping a question
**Skip this one**, on an optional question, now moves you straight on: the card
reads *Skipped* for a beat (about a quarter of a second) and the next open
question comes up. On the last one, focus goes to **Send to Plan2Code**
instead. A click or a key press in that beat cancels the move. **Do not skip**
on a skipped card brings it back.
### Your workspace
The folder label in the middle of the footer — `shop · main`, or
`shop + 2 folders · main` once you have added some (shorter on a narrow
window) — opens the **Workspace** dialog: the folders the agent uses as
context for this console session.
- **The folder you started in** is always first. It can be renamed and given a
description, but not removed.
- **Add a folder** by pasting a path (`../shared-ui` counts from the folder
you started in; `~` is your home folder) or with **Browse…**, which opens
your system's own folder picker. Browse… is hidden when the page looks like
it is being reached from another machine (SSH, a dev container, a
Codespace). A path that is not a folder, one already in the list, and a name
already taken are each refused with a message (a taken name comes with a
**Use @name-2** button); a folder inside another one in the list is
accepted, with a note.
- **Every folder has an `@name`** (lowercase letters, numbers and hyphens) and
an optional one-line *What is it?*. Type `@` in the Ask box, a note or a
typed answer and a list of names pops up; the agent reads `@shared-ui` as
that folder.
- **What the agent does with them.** It is told the list when its session
opens and each change once after that. Added folders are read-only
reference: it reads them, reads each one's `AGENTS.md` (or `CLAUDE.md`)
before first using it, and changes one only if you ask. Your harness may
ask permission the first time it reads outside the project.
- **Marks.** *This folder no longer exists* when it is gone from disk; *The
agent can't read this yet* when the agent reported a failed read (in Claude
Code with a copyable `/add-dir <path>` to run); *Inside another folder in
the list* for a nested one.
The workspace carries across skills you start from the dashboard and back. A
new console session starts with just the folder you started in.
### Session meter
A small ring pill in the top bar — **Session: fresh** (green), **Session:
getting long** (yellow), **Session: time for a fresh start** (red) — counts the
work this console session has done. Click it for the count and a **What is
this?** link to Help.
Each skill run adds points (`WEIGHTS` in `public/meter.js`): Plan, Document,
Review, Init and Init update 2; Revise plan, Quick task and Finalize 1; a
Pathfinder map 2 and each question it resolves 1; an Implement phase 2, an
Implement + Review phase 3; Handoff and the dashboard 0. A review run on the
page after a quick task or a phase sign-off counts as a Review too. Green is
under 4, yellow from 4, red from 6, and the ring is full at 8. At red the dashboard
also shows a banner: starting a **new console session** keeps the agent sharp
(resuming this one carries the count along). It is a rule of thumb, not a
reading of the agent's real context, and it never blocks anything.
### While something is being built
Implementation, Implement + Review and a Quick Task spend most of their time
building rather than asking, so the page shows the build instead:
- **What it is doing right now**, beside Planny ("Task 5 of 9: the rate
limiter"), and the progress bar counting tasks done. Tasks are counted
within the phase, to match the bar — the phase is already named in the
headline — so you never see "Task 4.2 of 6"; the page rewrites that form if
an agent still sends it.
- **The phase's task list** in its own tab, ticking as each task lands on
disk, and **the phase file itself** (`phase-3.md`) rendered in the next —
the prerequisites and task specs, not just the checklist.
- **Any question the build needs answered** (which phase, a spec conflict,
failing tests) appears as an ordinary question, and the sign-off is a
**Completion report** tab with an *Approve this phase* card.
- A long task is not mistaken for a stall. The build says how long it may go
quiet, and the page only calls it stuck after that.
### Review before you approve
The *Approve this phase* card carries a **Review the code first** button beside
the approval. Press it and the same session runs a focused code review of
exactly the files the phase changed, before you are asked to approve anything.
The findings come back as a tab, and a *Which to fix* card lists every one with
its severity: tick the ones to fix (or use the *Critical and warnings* / *All
of them* quick picks), press Send, and it fixes and re-checks them before the
approval card comes back.
A quick task has no approval step, so its offer sits on the finished screen
instead: a large **Review it now** button above the next step, with **No
thanks, I am done** beside it. If the session has already closed, the button
turns into the `/plan2code-review` command to run in the terminal.
Implement + Review shows neither: it reviews every phase before sign-off
already.
### When a session ends
A finished session says so, and ends in one of three shapes:
- **A next step.** What happened, and the exact command to run next (with a
Copy button) — the next phase, Finalize, a commit.
- **All done.** Nothing is left to run, so there is no command to copy:
*"All done, nothing left to run."* Init, Init update and Handoff end this
way, and so do Review and Finalize when nothing landed that needs committing.
- **Paused.** You pressed *Stop session*. The card names what was saved and
gives the command that picks it up later. Nothing else is offered.
The first two also carry a **Back to the dashboard** button (beside the next
step, or as the main button under "All done"). Press it and the same page turns
back into the skill menu, in the same conversation, so the next skill starts
right there. The agent keeps listening for it for about ten minutes after the
session ends; after that, or once the session has closed, the button turns into
the `/plan2code` command instead. That command is on both of these screens
anyway, for starting the dashboard in a fresh conversation — the better choice
after a long skill, since a fresh conversation starts with a clean context.
You don't have to finish first. On every skill but the dashboard itself, a
small **triangle** pointing left, in your highlight color, sits beside *Stop
session*. Press it, confirm, and the agent saves your place exactly as a stop
would, with any answers you have ready going along. Then the page turns into
the dashboard instead of showing a finish card. Pick the same skill again to
carry on, or pick another one. Like Stop, it only works on your turn, and where
nothing is saved yet (early in a plan) the confirm says what would be lost.
### Attachments in notes and questions
Any note, and any quick question on the Ask tab, can carry files, three ways:
- the **+ Attach file** button beside the box (pick one or more files),
- **paste** a screenshot or a copied file straight into the box,
- **drag and drop** files onto the notes panel or the Ask composer.
Two kinds are allowed:
- **Images.** Each is shrunk and re-encoded in your browser (JPEG, 2000 px on
the long edge at most, phone-photo rotation kept) and shows as a thumbnail.
- **Documents**: text, code and PDF (`.md`, `.txt`, `.json`, `.yaml`, `.csv`,
`.log`, `.js`, `.ts`, `.py`, `.sql`, `.pdf` and the like), up to 10 MB each.
They upload exactly as they are and show as a chip with the file type, name
and size. The server checks the contents match the type (a PDF header, or
UTF-8 text with no NUL bytes), and a document is never opened from the page.
Up to 5 attachments per note and 5 per question, images and documents counted
together. Anything else (`.docx`, a file over 10 MB, a dotfile such as `.env`)
picked or dropped is refused with a message naming the file; a paste only
picks up the files it can attach, and leaves any text to paste as usual. Each
file uploads straight away while you carry on typing, and sits in a tray with a
remove button; removing one deletes its file. A failed upload offers retry or
remove and holds back only that note, so the rest of your answers still send.
The files are stored with the session, in
`~/.plan2code/console/sessions/<id>/uploads/`, never in your project, under a
random name the server picks. When you send, each note is followed by one line
per attachment:
```
Note on Header row: Please keep the header row.
Image: /home/sam/.plan2code/console/sessions/<id>/uploads/<uuid>.jpg (header.png)
File: /home/sam/.plan2code/console/sessions/<id>/uploads/<uuid>.pdf (api-spec.pdf)
```
and the agent opens those paths with its own file reader. Uploads from sessions
untouched for 30 days are swept away the next time a session opens.
**Keeping the ones a spec cites.** When the agent is about to write a file
under `specs/<idea>/` that links to one of your note attachments (a plan, the
overview, a phase file, a Pathfinder question or the map), it first copies the
attachment into `specs/<idea>/attachments/` with `console.mjs keep` and links
the copy, so the spec still shows it after the session is swept. The copy is
named `<slug of your file name>-<8 characters of the upload id>.<ext>`, so
keeping the same upload twice reuses it. Attachments nothing cites stay in the
session, and quick-question attachments are never kept. `keep` is run by the
agent, in its own shell; the server itself still never writes into your
project.
### Ask a quick question
The **Ask** tab, always the last tab, on the dashboard and in every skill,
opens a **Quick question** chat. Ask anything about the project's files, or
anything at all, without waiting for a card. The agent running the skill
answers at its next check-in (in a build, after the task it is on), and the
workflow carries on meanwhile. Asking never holds up a card send, and a card
send never holds up a question.
- **Context only when you add it.** A question starts with no context, so it
reads as a general question. **+ Add context**, beside *+ Attach file*,
lists the last 3 places you visited (question cards, document sections, a
spec picked on the dashboard) plus *This spec*; pick one and an *About: …*
chip sits above the box. × removes it, and it clears after the question is
sent.
- **Starter questions.** An empty conversation offers a few questions to start
from, chosen for the skill you are in and ordered by your role; the ones
that need context appear once you have added some. Clicking one fills the
box without sending it.
- **Pictures.** The same as notes: the button, paste, or drag and drop, up to 5
per question.
- **Ten questions per conversation.** The `N of 10` counter is always in view.
After the tenth is answered, **New conversation** starts a clean one. So does
switching skills through the dashboard.
- **Edits need your approval.** Ask for a change to a file and the agent
replies with a summary and the list of files it would touch, with
**Approve** and **Decline**. Nothing changes until you approve. Afterwards
it lists what changed, with line counts, and nothing is committed. It never
edits the running skill's own files under `specs/`, and a chat message never
answers a card or moves the workflow on: that is what the cards are for.
- **When you cannot send.** Two different lines explain it: "That's 10
questions in this conversation" means start a new one, and "No agent is
connected right now" means the session has finished or the agent has gone
quiet, so resume it to ask. Either way the conversation above stays
readable.
A reply that lands while you are on another tab puts a dot on **Ask** and
chimes once (if sounds are on).
### Keyboard
| Key | Does |
| --- | --- |
| `Ctrl` + `Enter` (`⌘` + `Enter` on a Mac) | Send |
| `Tab` / `Space` | Move between options and pick one |
| In the Ask box: `Enter` / `Ctrl` + `Enter` (`⌘` + `Enter`) | `Enter` is a new line; `Ctrl` + `Enter` sends the quick question, never the cards |
| `Esc` | Closes whichever dialog is open; on the dashboard, backs out of a pick |
| In Help: arrow keys, `Home`, `End` | Move between topics (the arrows wrap). `Ctrl` + `Enter` does nothing inside Help |
Every control is a real button, radio or checkbox, so screen readers and
keyboard-only navigation work.
---
## How it works
Nothing is installed. The skills ship a small zero-dependency Node server
(`references/web-console/`), and the workflow step starts it when you say yes.
```
agent server (detached) your browser
| | |
|-- open (binds the port, starts ->| |
| the server AND the browser) ---|---------------------------->|
|<-- http://127.0.0.1:PORT/s/TOK/ |<---- the page, first state -|
| | already inside it |
|-- post the first questions ----->|---- pushed to the page ---->|
|-- wait --seconds 240 ----------->| |
| (returns every 4 minutes with | |
| progress, then waits again) |<---- you press Send --------|
|<-- your answers -----------------| |
```
The server runs detached rather than as a background task of the agent, because
agent background tasks get killed at various timeouts, and that would take your
half-finished answers with them.
**It is built to show you something fast.** A browser takes most of a second to
turn up after it is asked, so `open` binds the page's port itself and sends the
browser there before the server has even finished starting; the server takes
the port over a moment later, and the browser's request waits for it rather
than being refused. The page arrives with the session already inside it, so it
draws the real screen without asking for anything first, in your own theme and
colors from the first frame. On a Windows laptop the page is in front of you in
roughly the time the browser itself takes to open.
**It stays up while the page is open.** The page pings it every few seconds, so
the idle clock never runs down while you are there. Close the tab and it shuts
itself down about two minutes later; it stops after four hours regardless, and
the agent stops it outright when the session ends.
That also means **the server routinely outlives the agent**. It is the agent, not
the server, that reads your answers, and the two fail separately. The page tells
the two apart: the **?** button at the top right opens Help, whose *What this
page is* tab says which halves are talking right now (and *When something
looks stuck* covers what to check), and Planny stops looking busy once
nothing is listening rather than spinning at you indefinitely.
**State lives in three places**, and none of them is your repository (the one
exception being the note attachments the agent keeps for a spec, above):
| Where | What | Survives |
| --- | --- | --- |
| `~/.plan2code/console/sessions/<id>/` | the questions, your draft, your answers | 30 days after the session was last touched |
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
| your system temp directory | the port, process id and session token | until reboot |
Each of the workspace and meter files has exactly one writer: the server owns
`workspace.json` (the page changes it only through the `/workspace` routes
under Security), and `console.mjs` owns `ledger.ndjson` and
`workspace-cursor.json`. The meter's count is never stored; it is folded from
the ledger every time (`public/meter.js`), so a repeated `post` never counts
twice. The logic lives in small pure modules the tests import directly —
`public/workspace.js` (names, the footer label, the change lines the agent
reads), `public/meter.js` and `public/mentions.js` (the `@name` popover) — and
**Browse…** runs the per-OS picker in `picker.mjs`, copied from the
`plan2code` launcher and kept in step with it by a test.
**Old sessions clean themselves up.** Each time a session opens, whole session
folders nobody has touched for 30 days are deleted — questions, drafts,
answers, uploads and all, paused or not — along with stray scratch files
(`.json` / `.mjs`) left at the top of `~/.plan2code/console/` for as long.
Your `looks.json` and the `console-dir` pointer are never touched, and neither
is the session being opened. Nothing of value goes with them: the page is
never the record, `specs/` in your project is.
### Recovering from things going wrong
| What happened | What to do |
| --- | --- |
| You closed the tab | Open the link again. Everything is where you left it. |
| The link stopped working | Tell the agent. It restarts the session and gives you a new link. |
| Your agent session died while you were mid-answer | Press Send anyway. Your answers are written to disk and are never discarded, including when the session is restarted. The next session picks them up. |
| The page says Plan2Code is not running | It has not checked in for a few minutes. Look at the terminal: it may have finished its turn, hit an error, or be waiting on you there. Answering here still works, and what you send is held for it. |
| You are not sure anything is connected | The **?** at the top right opens Help. Its *What this page is* tab says what keeps the page alive and whether both halves are talking at that moment, and *When something looks stuck* covers what to check. |
| You would rather use the terminal after all | Say so. Nothing is lost. |
---
## Security
It is a local dev server that reads files in your project (never writing to it)
and keeps its own state in your home folder, so it is built to be boring about
this:
- Bound to `127.0.0.1` only, never `0.0.0.0`. Not reachable from your network.
- A `Host` header allow-list, which is what stops a website you happen to be
visiting from talking to it through a DNS rebinding trick.
- A 128-bit token in the link, swapped for an `HttpOnly; SameSite=Strict` cookie
on first load so it leaves your address bar, your history and any screenshot.
- A strict Content Security Policy with no inline script allowed.
- Markdown written by the agent is turned into page elements directly and never
into an HTML string, so a document that quotes a hostile README cannot run
anything. It shows up as text, which is what it is.
- Uploads are named by the server (`<uuid>.jpg`, or `<uuid>.<ext>` with the
extension taken from the allow-list, via `crypto.randomUUID()`), never by the
file name you sent, and live only under the session's own `uploads/`. The
server checks the bytes: a JPEG header for images (4 MB cap), and for
documents a `%PDF-` header or strict UTF-8 with no NUL byte (10 MB cap).
Documents are never served back to the browser. A send may only point at
uploads inside that session's `uploads/`, images in `images` and documents
in `files`.
### Routes
The upload routes, the send, the overview read and the workspace. Like every page route, they are on `127.0.0.1`
behind the session cookie, and the ones that write also check the request's
origin.
| Route | Does |
| --- | --- |
| `POST /upload` | Raw bytes, original name in `x-p2c-name`. `Content-Type: image/jpeg`: writes `uploads/<uuid>.jpg` and answers `{ ok, id, kind: "image", path, url, name, size }`; not a JPEG → 415, over 4 MB → 413. `Content-Type: application/octet-stream`: a document, its extension from the name's allow-listed extension; writes `uploads/<uuid>.<ext>` and answers `{ ok, id, kind: "file", path, name, size }` with no `url`; not an allowed extension or contents that do not match → 415 `type`, over 10 MB → 413. Any other content type → 415. |
| `GET /uploads/<id>.jpg` | Serves an uploaded image (for the thumbnail after a reload). Only `<uuid>.jpg` names under `uploads/`; documents are never served (404). |
| `DELETE /uploads/<id>.<ext>` | Deletes an image or document removed before sending. 204, or 404 if it is not there. |
| `POST /submit` | The Send. A note may carry `images` and `files`, each `[{ path, name }]`: at most 5 together, images in `images` and documents in `files`, every path inside this session's `uploads/`, otherwise 400. |
| `POST /chat` | A Quick question `{ text, about?, images?, files?, conversation }`, or `{ reset: true, conversation }` for New conversation. Appended to the session's `chat.ndjson`. 400 `too-long` (over 4,000 characters), `image`, `file` or `bad`; 409 `offline`, `stale` or `limit` (10 per conversation). Never refused because a card send is still uncollected. |
| `POST /chat/decision` | Approve or Decline on an edit the agent proposed: `{ re, decision, text?, conversation }`. Once per proposal; does not count toward the 10. |
| `GET /overview?spec=specs/<name>` | The Overview tab's read of `<spec>/overview.md`, as `text/markdown` with `cache-control: no-store`. On the dashboard `spec` must be one of the scanned specs; elsewhere the session's own spec is used. The file's real path must stay inside the project, so `../`, absolute paths and symlinks pointing out all get 404. |
| `GET /workspace` | The Workspace dialog's list: folders, `missing`, `remote` and the agent's folder `issues`. `?check=1` re-checks every folder on disk first. |
| `POST /workspace/add` | `{ path, name?, description? }`. The path is resolved against the folder the session started in (`~` expanded) and must be a folder: 400 `not-a-folder`, `duplicate` (with its `name`; compared case-insensitively on Windows and macOS), `bad-name`, or `name-taken` with a `suggest`. Answers the new entry, `nested: true` when it sits inside another folder in the list. |
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
| `POST /workspace/remove` | `{ id }`. 400 `original` for the folder the session started in, 404 `unknown`. |
| `POST /workspace/browse` | Opens the system folder picker and answers `{ path }` or `{ cancelled: true }`; never adds anything itself. 409 `busy` while one is open, 404 `no-picker` when the session looks remote or no picker exists. |
## For maintainers
| | |
| --- | --- |
| Source | `src/web-console/` |
| Ships as | `skills/<every skill>/references/web-console/` |
| Wiring | one `additionalReferences` entry per skill in `install.js`; the dashboard's menu lives in `public/answers.js` (`SKILL_CATALOG`) |
| Agent contract | `src/web-console/console.md`, plus `building.md` for the build steps |
| Tests | `node --test scripts/test-web-console.mjs`, also run by `npm test` |
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs `puppeteer-core` and a local Chrome or Edge for the paint columns; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only |
Edit `src/` only. `skills/` is a committed build artifact: regenerate it with
`npm run build:skills` and commit it with the source change, since `npm test`
(via `--verify-skills`) fails when it drifts from `src/`.
### Driving it by hand
You do not need an agent to poke at the console. Point `PLAN2CODE_CONSOLE_HOME`
somewhere disposable first, so you never touch a real session:
```bash
export PLAN2CODE_CONSOLE_HOME=/tmp/p2c-play # Windows: $env:PLAN2CODE_CONSOLE_HOME
cat > /tmp/payload.json <<'JSON'
{ "workflow": "pathfinder", "title": "Playing about",
"items": [ { "id": "q1", "kind": "choice", "title": "Export format",
"body": "Pick one.",
"options": [ { "k": "A", "text": "CSV", "recommended": true },
{ "k": "B", "text": "Excel" } ],
"token": { "A": "a", "B": "b" } } ],
"agent": { "status": "waiting" } }
JSON
node src/web-console/console.mjs open --file /tmp/payload.json # prints the URL, opens the browser
node src/web-console/console.mjs wait --session <sid> --seconds 60
node src/web-console/console.mjs stop --all
```
`node src/web-console/console.mjs help` prints the same command summary an
agent gets when it finds the binary before the docs.
`wait` exits `0` with the answers, `10` if nobody has finished yet, `20` if the
server died, `30` on Cancel. Pick `--seconds` to sit under whatever your harness
allows a single command: it is a poller, so killing it costs nothing, and a
collected result is printed before it is marked collected, which means an
interrupted handover can only repeat itself, never lose an answer. `status`
lists sessions and flags any whose answers were submitted but never collected.
When something misbehaves, the session directory is the whole story:
`state.json` (what the agent published), `draft.json` (what the person has typed
but not sent), `result.json` (what they sent), `events.ndjson` (an append-only
log you can `cat`), and `server.log`.
Set `--idle-ms 60000` on `open` if you want the server to shut itself down
quickly while experimenting.
Two environment variables help when the start is what you are looking at:
| Variable | Does |
| --- | --- |
| `PLAN2CODE_CONSOLE_TRACE=1` | `open` prints a timeline of its steps to stderr (roots found, server spawned, port bound, browser sent, state written, server listening). |
| `PLAN2CODE_BROWSER` | The command that opens the link instead of the system default, run through the shell with the link appended, e.g. `PLAN2CODE_BROWSER='firefox --new-tab'`. |
Every `console.mjs` invocation also writes its own directory to
`$PLAN2CODE_CONSOLE_HOME/console-dir` (or `~/.plan2code/console/console-dir`
when the override is unset): it is how an agent finds the console on a later
session without searching the skill install dirs.
The vendored file is `src/web-console/public/vendor/marked.esm.js`,
sha256 `7a7d9a521ac9384e0c3a075120a7c486cbd0c3c32cc5601bbb79a23e97403690`.
Only `marked.lexer()` is used; the rendering is ours, in `public/render.js`, and
builds DOM nodes rather than HTML so nothing needs sanitising.
+13 -4
View File
@@ -38,6 +38,12 @@ Optional CLI status bar (`src/statusline-claude/`) for Claude Code. Displays mod
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line section)
## Web Console
Optional local browser UI (`src/web-console/`) that every skill offers at the start of a session, so questions, sign-off gates, build progress and the document taking shape can be worked through in a page instead of the terminal. The bare `plan2code` skill is the front door: it opens the console's dashboard — a card menu of every skill — and a pick launches that skill on the same page by resuming the session under its workflow. A phase's sign-off card offers to run the code review first — before approval — and a finished quick task's hand-off offers a **Review it now** button; either runs `plan2code-review` on the page in the same session. Finished (not paused) screens offer **Back to the dashboard**, and notes and quick questions can carry image and document (text, code, PDF) attachments (stored in the session dir, never the project). An **Ask** tab, always last, opens a Quick question chat the running agent answers at its next check-in, on its own channel beside the cards (edits only after the person approves them); context is attached only on purpose, through **+ Add context**, and an empty conversation offers starter questions. A Role in User Preferences (asked for by a dashboard banner until set) orders the starter templates on Pathfinder, Plan and Quick Task's fresh-idea card (`"templates": "idea"`, wording in `public/starters.js`) and the Ask starters; it never changes what a skill asks. Note attachments a spec file cites are copied into `specs/<idea>/attachments/` by the agent with `console.mjs keep`; the server itself never writes into a project. The footer's folder label opens a **Workspace** dialog where the person adds more folders as read-only context for the whole console session, each addressed as `@name` in answers, notes and Ask (contract in `console.md` → Workspace). A green / yellow / red **session meter** in the top bar counts weighted points as one console session chains skill runs (`public/meter.js`; agents report per-unit work with `run` in a post) and suggests a fresh console session at red. The **?** at the top right opens a 16-topic Help dialog built into the page, so it reads even with the server gone. Zero dependencies, detached `node` server on `127.0.0.1`, bundled into each skill via `additionalReferences`.
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
## Development Commands
Build commands, installer menu options, non-interactive skill-build verification, skills CLI delegation, skill format, and how to edit workflow prompts.
@@ -52,13 +58,15 @@ Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
## Mascot
The project has a mascot called "Planny" — an ASCII art robot that appears in installer output and workflow prompts. Mascot variants are defined in the `MASCOT` constant in `install.js` and appear in workflow markdown files.
The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` (and `plan2code-loop/src/utils/logger.ts`) and appear in workflow markdown files: arms down at rest, one arm waving when he is asking something, both arms up when he is celebrating. The eye is always the star.
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight colour and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `app.js` switches mood with a single class, so the drawing stays in the markup and the styling in `app.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
```
╭───╮
│ ● │
│ ◡ │
╰───╯
│ ★ │╱
╱│ ◡ │
╰┬─┬╯
```
## Keeping this file current
@@ -75,3 +83,4 @@ When you make a mistake, get corrected, or discover something about this codebas
## Failure log
- Do not audit `CHANGELOG.md` headings through PowerShell — the emoji come back as `?`. See the gotcha for the correct approach.
- Sync upstream only through `/sync-repo`, and verify its baseline against the real tree before porting: an earlier sync silently skipped a whole upstream release (the `3-implement-review` skill) while the recorded version froze. Update the baseline with `.claude/skills/sync-repo/set-synced.mjs`, never with a shell pipe over the decrypted body.
+25
View File
@@ -2,6 +2,31 @@
All notable changes to Plan2Code will be documented in this file.
## v2.4.0
### ✨ Added
- **Web console**: an optional local browser UI that every skill offers at the start of a session ("web console or terminal?"). Questions, recaps, sign-off gates, build progress and the document taking shape are laid out in a page instead of scrolling past in the terminal, so the workflow is usable by product people and not only engineers. Zero dependencies, no build step: a detached `node server.mjs` bound to `127.0.0.1`, bundled into each skill as `references/web-console/`. Answers carry the literal terminal token they stand for (`approved`, `a`, `skip`), so declining the console or losing it mid-session falls straight back to the terminal with nothing lost. Full guide in `.readme/web-console.md`.
- **`plan2code` dashboard skill**: a new bare-named skill that opens the console as a card menu of every skill, with a spec picker, and launches the pick on the same page. **Back to the dashboard** works from finished screens and, mid-workflow, from a triangle beside **Stop session**.
- **Global `plan2code` command**: installed with the skills (`I` and `A`; alone via Custom → `D`; removed by `U`). Typed in any project it opens the dashboard in Claude Code or Devin, asking which when both are installed and remembering the last pick in `~/.plan2code/launcher.json`. `--cli claude|devin` skips the question and `--model <name>` skips the model notice; other arguments are forwarded. It starts the agent with permission prompts off (`--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass` in Devin); run `claude /plan2code` yourself if you want prompts. The launcher lives in `~/.plan2code/bin/` with npm-style shims (sh, plus `.cmd` and `.ps1` on Windows).
- **Desktop shortcut** (opt-in, asked after the command installs): `Plan2Code.lnk` on Windows, `Plan2Code.command` on macOS, `plan2code.desktop` on Linux. It opens a native folder picker first, starting on the last folder picked.
- **`plan2code-3-implement-review`**: a quality-gated Step 3 that implements one phase, runs a focused review and the selected fixes before sign-off, and marks the phase complete only after the reviewed result is approved. Step 2's hand-off now offers it first, with `/plan2code-3-implement` as the review-free alternative.
- **`--web` flag**: `/plan2code-1-plan --web plan a lunch voting app` opens the console without asking. Every next-step command the workflow prints (resume footers, NEXT STEP lines, the loop's completion banner) now carries `--web`.
- **Console pages for builds and reviews**: a build shows the current task, a task-count progress bar and the phase's task list ticking as tasks land. After an approved phase or a finished quick task, **Review it now** runs `/plan2code-review` on the page, with *Which to fix* presets for critical-and-warnings or everything.
- **Console conveniences**: nine question shapes with live validation and drag-to-reorder phases; drafts that survive a closed tab, reload, server restart or agent crash; an **Ask** tab for quick questions the agent answers at its next check-in (file edits need approval); image and document attachments; a read-only **Overview** tab; a **Workspace** of extra read-only folders addressed as `@name`; a green / yellow / red **session meter**; a **Role** preference that orders starter templates; nineteen highlight colours, light / dark themes and card widths; audio cues with per-event toggles; and a 16-topic Help dialog.
- **Planny in the console**: drawn in SVG in his own dock above the question list, where he carries the page's state: his star lights and he waves when it is your turn, the star turns and he walks on the spot while the agent works, it goes green when all is caught up, he shows no arms when the agent is not answering, and he fades with his star shut when disconnected. He flies through a starfield while the agent thinks, wakes up on a fresh dashboard, and acts out each skill on its starting screen, arms holding that step's prop. The tab icon adds a busy, ready or attention bar, and the desktop shortcut uses him too.
- **Tests**: `scripts/test-web-console.mjs` and `scripts/test-launcher.mjs` (run by `node --test`), `scripts/parse-check.mjs` (every shipped browser module parses as an ES module) and `scripts/check-skill-table.mjs` (the dashboard's "What each skill reads and writes" table matches the skills), all wired into `npm test`. `scripts/bench-web-console.mjs` measures time to first paint.
- **install.js**: an animated progress indicator during the two long install phases, so the installer no longer looks hung.
### 🔧 Changed
- **Planny has a new look everywhere**: a box with a star for an eye, stick arms and two small feet, chosen from twenty studies. Every ASCII Planny in the workflow prompts, the installer, `plan2code-loop` and the Claude Code status line is redrawn to match: the eye is always the star, one arm waves when he is asking something, both go up when he is celebrating, and the status line shows his box, star and feet without arms.
- **Character limit raised from 11,000 to 11,500** for `src/plan2code-*.md` (`scripts/validate-char-count.js`, and the same number in `plan2code-metrics`'s `improver.ts` and `applier.ts`), so the console's Interface lines fit without cutting workflow rules.
- **package.json**: the installer's bin is renamed `plan2code` → `plan2code-install`, leaving the `plan2code` name to the launcher. The `npx` install command is unchanged.
- **install.js**: skills bundle the shared `src/web-console/` directory through `additionalReferences`, copied as bytes so the bundled chimes survive the build. Installed skills are listed by reading the skills store directly instead of `skills list` (seconds instead of over a minute on Windows), and removal is one variadic `skills remove`.
- **plan2code-0-pathfinder**: the duplicated Trail Footer forms fold into the fallback line, since `references/trail.md` defines them in full; the GitHub Issues backend is unchanged.
- **`.gitattributes`**: `*.mp3` is binary. `.editorconfig` pins LF for editors. `prototypes/` is gitignored.
## v2.3.0
### ✨ Added
+14 -7
View File
@@ -3,7 +3,8 @@
## Commands
| Step | Command | Input | Output |
| ------- | ----------------------------- | --------------- | -------------------------------------------------- |
| -------- | ------------------------------- | --------------- | --------------------------------------------------------------------------------------- |
| — | /plan2code | None | Web console dashboard — a menu of every skill below, launched on the page |
| Init | /plan2code-init | None | AGENTS.md file |
| Update | /plan2code-init-update | AGENTS.md | Updated AGENTS.md |
| 0 | /plan2code-0-pathfinder | A foggy idea | pathfinder/map.md *or* GitHub Issues + PLAN-DRAFT-<date>.md |
@@ -13,9 +14,12 @@
| 1b | /plan2code-1b-revise-plan | Specs + changes | Updated specs |
| 2 | /plan2code-2-document | PLAN-DRAFT.md | overview.md + Phase files |
| 3 | /plan2code-3-implement | overview.md | Implemented code |
| 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 in handoffs/ |
Append ` --web` to any step to work through it in the browser web console instead of the terminal — or run `/plan2code` with nothing for the dashboard, a menu of every skill that launches your pick on the same page. See [.readme/web-console.md](.readme/web-console.md).
## File Structure
```
@@ -24,7 +28,7 @@ specs/
├── pathfinder/ # From Step 0 (optional, if charted locally)
│ ├── map.md # the map: destination, decisions, fog
│ ├── questions/NN-<slug>.md # one decision question per file
│ └── briefs/brief-<date>.md # plain-English decision summaries
│ └── briefs/brief-<date>.md # on-demand plain-English decision briefs
│ # (GitHub Issues backend: map issue + sub-issues instead)
├── PLAN-DRAFT-<date>.md # From Step 1 (verified plan)
├── PLAN-CONVERSATION-<date>.md # From Step 1 (conversation log)
@@ -65,7 +69,7 @@ When phases have no file conflicts or dependencies, they can run simultaneously:
## Quick Troubleshooting
| Issue | Solution |
| ---------------------- | ------------------------------------------------- |
| ---------------------- | ------------------------------------------------ |
| Lost context mid-phase | Attach spec files, say "resume from Task X.Y" |
| Wrong phase started | Say "abort", start correct phase |
| Need to change plan | Use `/plan2code-1b-revise-plan` |
@@ -83,8 +87,9 @@ New to a project?
Learned something during a session?
└── /plan2code-init-update → Add learnings to AGENTS.md
Too unclaer to plan? (big idea, don't yet know what the questions are)
└── /plan2code-0-pathfinder → chart it, clear the decisions one at a time
Too foggy to plan? (big idea, don't yet know what the questions are)
└── /plan2code-0-pathfinder → chart it, clear one decision at a time
├── continue-or-stop menu between decisions; fresh session recommended after ~3
└── then → /plan2code-1-plan (resumes at Phase 4)
Is it a quick, small task?
@@ -92,6 +97,7 @@ Is it a quick, small task?
└── No → /plan2code-1-plan (full workflow)
├── /plan2code-2-document
├── /plan2code-3-implement (repeat per phase)
│ ├── OR: /plan2code-3-implement-review (review gate before approval)
│ └── OR: plan2code-loop (autonomous alternative)
└── /plan2code-4-finalize
@@ -104,8 +110,9 @@ Need to revise mid-implementation?
The `plan2code-loop` CLI is an **alternative** to Step 3, not a replacement.
| Approach | Use When |
|----------|----------|
|-----------------------------------|-------------------------------------------------|
| `/plan2code-3-implement` | You want interactive control per phase |
| `/plan2code-3-implement-review` | You want review and fixes before phase approval |
| `plan2code-loop` | You want hands-off autonomous execution |
```bash
@@ -115,7 +122,7 @@ plan2code-loop # Fully interactive - auto-detects specs, prompts for options
### Loop Modes
| Mode | Description |
|------|-------------|
|---------------------------------|----------------------------------------------------------------------------------------------------------|
| **One task per loop** (default) | One task per agent invocation. Node handles git commits. |
| **One phase per loop** | All tasks in a phase per invocation. LLM handles git commits. Best for smart models with larger context. |
+20 -1
View File
@@ -12,7 +12,7 @@ agent, and the next engineer all start from the same specs.
Six commands, each posted separately. Two of them are optional.
Version 2.3.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
Version 2.4.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
---
@@ -50,6 +50,15 @@ 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. Update later with `npx skills update -g`.
The installer also adds a global `plan2code` command. Run it from any project and the Plan2Code
dashboard opens right there, in **Claude Code** or **Devin**. With both installed it asks which and
remembers your pick; `plan2code --cli claude` or `--cli devin` skips the question, and `--model <name>`
chooses the model. It works in cmd, PowerShell, Git Bash, macOS and Linux shells, and needs the
Claude Code or Devin CLI on your `PATH`. It starts the agent with permission prompts off
(`--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass` in Devin); run
`claude /plan2code` yourself if you want prompts. The installer then offers a desktop shortcut (answer `y`),
which opens a folder picker first. Uninstalling (`U`) removes both.
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/`
explicitly.
@@ -90,10 +99,12 @@ implementation is where most agent drift starts.
| Command | Use it when |
|---------|-------------|
| `/plan2code` | Open the web console dashboard: every skill below as a card, launched on the page |
| `/plan2code-0-pathfinder` | The idea is too big and unclear to plan. Charts it as decisions, clears them one at a time, hands a hot plan draft to Step 1 |
| `/plan2code-1-plan` | Starting a feature. Full requirements → architecture pass |
| `/plan2code-2-document` | Planning is done. Turn the plan into phase specs |
| `/plan2code-3-implement` | Build the next phase (one per conversation) |
| `/plan2code-3-implement-review` | Build the next phase and review it before you approve it (instead of `/plan2code-3-implement`) |
| `/plan2code-review` | Independent second opinion on local changes, then optional fixes |
| `/plan2code-4-finalize` | All phases done. Validate, summarize, archive |
| `/plan2code-init` | Generate this repo's `AGENTS.md` so every agent starts informed |
@@ -102,6 +113,10 @@ implementation is where most agent drift starts.
| `/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 |
Every skill asks at the start whether to work in the terminal or in the **web console**, a local
browser page for the questions, sign-offs, build progress and the document taking shape. Add `--web`
to any command to skip the question: `/plan2code-1-plan --web plan a lunch voting app`.
---
## The four rules that do most of the work
@@ -232,6 +247,9 @@ One phase per conversation. It won't run tests unless the phase says to.
**In:** `specs/<feature>/overview.md`. **Out:** working code, and updated checkboxes.
Want a second pair of eyes before you sign off? `/plan2code-3-implement-review` builds the phase the
same way, runs a focused review and the fixes you pick, and only then asks for approval.
### Review 🔬 — optional, any time
An independent second opinion, not a rubber stamp. It figures out its own scope (conversation
@@ -313,6 +331,7 @@ Core reference:
Optional tooling — none of it is required to use the workflow:
- **[.readme/web-console.md](.readme/web-console.md)**: the browser dashboard, and working through every step on one page
- **[.readme/autonomous-loop.md](.readme/autonomous-loop.md)** — `plan2code-loop`, a hands-off alternative to Step 3
- **[.readme/status-line.md](.readme/status-line.md)** — three-line Claude Code status bar: model, context, quota, diff
- **[.readme/metrics.md](.readme/metrics.md)** — `plan2code-metrics`, measuring and improving the prompts themselves
+595 -66
View File
@@ -81,29 +81,30 @@ const MASCOT = {
// Full mascot for headers
full: [
' ╭───╮ ',
' │ ● │ ',
' ╱│ ★ │╲ ',
' │ ◡ │ ',
' ╰───╯ ',
' ╰┬─┬╯ ',
],
// Mini mascot for inline use
mini: '(◉‿◉)',
mini: '╱[★]╲',
// Waving mascot for greetings
wave: [
' ╭───╮ ',
' │ ● │ /',
' │ ◡ │ ',
' ╰───╯ ',
' │ ★ │╱ ',
' ╱│ ◡ │ ',
' ╰┬─┬╯ ',
],
// Thinking mascot for prompts
thinking: [
' ╭───╮ ',
' │ ● │ ?',
' │ ~ │ ',
' ╰───╯ ',
' ╭───╮ ?',
' │ ★ │╱ ',
' ╱│ ~ │ ',
' ╰┬─┬╯ ',
],
};
// Generated skills directory — the committed, canonical Agent Skills build of src/.
// Generated skills directory: the committed, canonical Agent Skills build of src/.
// `npm run build:skills` regenerates it and `npm test` (`--verify-skills`) fails on drift.
// `skills add` consumes this directory; nothing else is platform-specific any more.
const SKILLS_DIR_NAME = 'skills';
const SKILLS_DIR = path.join(__dirname, SKILLS_DIR_NAME);
@@ -117,13 +118,25 @@ const SRC_DIR = path.join(__dirname, 'src');
// Configuration for source prompts
const SOURCE_PROMPTS = [
{
source: 'plan2code.md',
stepNumber: 'dashboard',
name: 'dashboard',
// `bare` builds the skill name without a suffix: this one installs as
// `plan2code`, the hub that opens the console menu for every other skill.
bare: true,
displayName: 'Dashboard Mode',
description: 'Open the web console dashboard and launch any Plan2Code skill from the menu',
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-init.md',
stepNumber: 'init',
name: 'init',
displayName: 'Init Mode',
description: 'Generate AGENTS.md file for project-specific guidance',
isUtility: true
isUtility: true,
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-init-update.md',
@@ -131,14 +144,16 @@ const SOURCE_PROMPTS = [
name: 'init-update',
displayName: 'Init Update Mode',
description: 'Update existing AGENTS.md with new learnings',
isUtility: true
isUtility: true,
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-0-pathfinder.md',
stepNumber: '0',
name: 'pathfinder',
displayName: 'Pathfinder Mode',
description: 'charting of a foggy idea as a map of decision questions, cleared one at a time'
description: 'charting of a foggy idea as a map of decision questions, cleared one at a time',
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-quick-task.md',
@@ -146,35 +161,65 @@ const SOURCE_PROMPTS = [
name: 'quick-task',
displayName: 'Quick Task Mode',
description: 'Lightweight planning for small tasks',
isUtility: true
isUtility: true,
// review.md rides along for the web console's "Review it now" button, which
// runs the review in the same session once the quick task is built.
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'plan2code-review.md', target: 'review.md' },
{ source: 'plan2code-review-references' }
]
},
{
source: 'plan2code-1-plan.md',
stepNumber: 1,
name: 'plan',
displayName: 'Planning Mode',
description: 'Requirements analysis and architecture design'
description: 'Requirements analysis and architecture design',
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-1b-revise-plan.md',
stepNumber: '1b',
name: 'revise-plan',
displayName: 'Revision Mode',
description: 'Modify specs mid-implementation when requirements change'
description: 'Modify specs mid-implementation when requirements change',
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-2-document.md',
stepNumber: 2,
name: 'document',
displayName: 'Documentation Mode',
description: 'Transform planning output into structured implementation docs'
description: 'Transform planning output into structured implementation docs',
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-3-implement.md',
stepNumber: 3,
name: 'implement',
displayName: 'Implementation Mode',
description: 'Execute implementation phase by phase'
description: 'Execute implementation phase by phase',
// review.md rides along for the web console's review offer on the sign-off
// card, which runs the review in the same session before the phase is approved.
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'plan2code-review.md', target: 'review.md' },
{ source: 'plan2code-review-references' }
]
},
{
source: 'plan2code-3-implement-review.md',
stepNumber: 3,
name: 'implement-review',
displayName: 'Implementation + Review Mode',
description: 'Implement one phase, review it, then request sign-off',
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'plan2code-3-implement.md', target: 'implement.md' },
{ source: 'plan2code-review.md', target: 'review.md' },
{ source: 'plan2code-review-references' }
]
},
{
source: 'plan2code-review.md',
@@ -182,14 +227,16 @@ const SOURCE_PROMPTS = [
name: 'review',
displayName: 'Review Mode',
description: 'Comprehensive post-implementation review with spec compliance checking',
isUtility: true
isUtility: true,
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-4-finalize.md',
stepNumber: 4,
name: 'finalize',
displayName: 'Finalization Mode',
description: 'Validate, summarize, and archive completed work'
description: 'Validate, summarize, and archive completed work',
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-handoff.md',
@@ -197,12 +244,16 @@ const SOURCE_PROMPTS = [
name: 'handoff',
displayName: 'Handoff Mode',
description: 'Compact the conversation into a self-contained handoff document for a fresh session',
isUtility: true
isUtility: true,
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
}
];
// Helper function to generate destination filename based on stepNumber
function generateFilename(prompt, extension = '.md') {
// `bare` is for the dashboard: `plan2code`, no suffix — it is the hub the
// numbered and utility skills hang off, not a step among them.
if (prompt.bare) return `plan2code${extension}`;
if (prompt.isUtility || prompt.stepNumber === 0 || prompt.stepNumber === 'init') {
return `plan2code-${prompt.name}${extension}`;
}
@@ -216,6 +267,7 @@ function generateSkillName(prompt) {
// Helper function to generate step label for descriptions
function generateStepLabel(prompt) {
if (prompt.bare) return 'Dashboard';
if (prompt.stepNumber === 'init') return 'Init';
if (prompt.stepNumber === 'update') return 'Update';
if (prompt.stepNumber === 'review') return 'Review';
@@ -338,9 +390,9 @@ function displayHeader() {
console.log(`${COLORS.CYAN}${COLORS.BRIGHT}`);
console.log('╔═════════════════════════════════════════════════════════╗');
console.log('║ ╭───╮ ║');
console.log('║ │ ● │ Hi! I\'m Planny! ║');
console.log('║ │ ◡ │ Nice to meet you ║');
console.log('║ ╰───╯ Welcome to Plan2Code! ║');
console.log('║ │ ★ │╱ Hi! I\'m Planny! ║');
console.log('║ ╱│ ◡ │ Nice to meet you ║');
console.log('║ ╰┬─┬╯ Welcome to Plan2Code! ║');
console.log('║ ║');
console.log('║ G L O B A L I N S T A L L A T I O N S Y S T E M ║');
console.log('║ https://github.com/jparkerweb/plan2code ║');
@@ -411,6 +463,24 @@ function displayProgress(current, total, label) {
process.stdout.write(`\r${COLORS.CYAN}[${bar}${COLORS.CYAN}]${COLORS.RESET} ${percent}% ${label}`);
}
/**
* Animated spinner that works with synchronous operations
* Shows visible progress indicator
*/
function createSpinner() {
return {
start: function() {
process.stdout.write('\n ⏳ ');
},
tick: function() {
process.stdout.write('█');
},
stop: function() {
process.stdout.write(' ✓\n');
}
};
}
// ============================================================================
// SYNC PROMPTS FUNCTIONS
// ============================================================================
@@ -459,21 +529,47 @@ function computeExpectedSkills() {
}
const skillName = generateSkillName(prompt);
expected.set(
`${SKILLS_DIR_NAME}/${skillName}/SKILL.md`,
generateSkillHeader(prompt, true) + '\n\n' + sourceContent
);
// disable-model-invocation is always set: these are user-initiated workflow steps, and
// one SKILL.md now serves every agent, so the strictest setting is the correct one.
const skillContent = generateSkillHeader(prompt, true) + '\n\n' + sourceContent;
// Buffers, not utf8 strings: reference dirs can hold binary files (the
// console's chime mp3s), and a utf8 round-trip would mangle them.
expected.set(`${SKILLS_DIR_NAME}/${skillName}/SKILL.md`, Buffer.from(skillContent));
const srcRefDir = path.join(SRC_DIR, prompt.source.replace(/\.md$/, '-references'));
if (!fs.existsSync(srcRefDir)) continue;
if (fs.existsSync(srcRefDir)) {
for (const relPath of listFilesRecursive(srcRefDir)) {
const absPath = path.join(srcRefDir, relPath);
expected.set(
`${SKILLS_DIR_NAME}/${skillName}/references/${relPath.split(path.sep).join('/')}`,
fs.readFileSync(path.join(srcRefDir, relPath), 'utf8')
fs.readFileSync(absPath)
);
}
}
for (const reference of prompt.additionalReferences || []) {
const absSource = path.join(SRC_DIR, reference.source);
try {
if (fs.statSync(absSource).isDirectory()) {
for (const relPath of listFilesRecursive(absSource)) {
const targetPath = reference.target ? path.join(reference.target, relPath) : relPath;
expected.set(
`${SKILLS_DIR_NAME}/${skillName}/references/${targetPath.split(path.sep).join('/')}`,
fs.readFileSync(path.join(absSource, relPath))
);
}
} else {
expected.set(
`${SKILLS_DIR_NAME}/${skillName}/references/${reference.target}`,
fs.readFileSync(absSource)
);
}
} catch (err) {
errors.push(`Could not include src/${reference.source} for ${skillName}: ${err.message}`);
}
}
}
return { expected, errors };
}
@@ -510,15 +606,20 @@ function buildSkills(quiet = false) {
const absPath = path.join(__dirname, relPath.split('/').join(path.sep));
let current = null;
if (fs.existsSync(absPath)) {
try { current = fs.readFileSync(absPath, 'utf8'); } catch {}
try {
current = fs.readFileSync(absPath);
} catch (err) {
// Unreadable — fall through and overwrite
}
if (current === content) {
}
if (current && current.equals(content)) {
stats.unchanged++;
continue;
}
try {
fs.mkdirSync(path.dirname(absPath), { recursive: true });
fs.writeFileSync(absPath, content, 'utf8');
fs.writeFileSync(absPath, content);
stats.written++;
if (!quiet) console.log(` ${COLORS.GREEN}▰▰▰${COLORS.RESET} ${relPath}`);
} catch (err) {
@@ -540,8 +641,13 @@ function verifySkillsSync() {
const problems = [...errors];
for (const [relPath, content] of expected) {
const absPath = path.join(__dirname, relPath.split('/').join(path.sep));
if (!fs.existsSync(absPath)) problems.push(`missing: ${relPath}`);
else if (fs.readFileSync(absPath, 'utf8') !== content) problems.push(`out of date: ${relPath}`);
if (!fs.existsSync(absPath)) {
problems.push(`missing: ${relPath}`);
continue;
}
if (!fs.readFileSync(absPath).equals(content)) {
problems.push(`out of date: ${relPath}`);
}
}
if (fs.existsSync(SKILLS_DIR)) {
for (const relPath of listFilesRecursive(SKILLS_DIR)) {
@@ -650,36 +756,51 @@ function ensureSkillsCli() {
return false;
}
/**
* List installed Plan2Code skill names for a scope ('global' or 'project').
*
* Reads the skills CLI's canonical store directory directly instead of running `skills list`.
* The list command cross-references every installed skill against every agent directory it
* can find — an O(skills × agents) scan that takes over a minute on Windows. The store is
* just a directory of skill folders, so a readdir answers the same question instantly.
*/
function listInstalledSkills(scope) {
const json = runSkillsCli(`list ${scope === 'global' ? '-g' : ''} --json`.trim());
if (!json) return [];
const store = path.join(scope === 'global' ? os.homedir() : process.cwd(), '.agents', 'skills');
let entries;
try {
const parsed = JSON.parse(json);
if (!Array.isArray(parsed)) return [];
return parsed.map(skill => skill && skill.name)
.filter(name => typeof name === 'string' && name.startsWith('plan2code-'));
} catch {
entries = fs.readdirSync(store);
} catch (err) {
return [];
}
return entries.filter(name =>
(name === 'plan2code' || name.startsWith('plan2code-')) && fs.existsSync(path.join(store, name, 'SKILL.md'))
);
}
/**
* Remove every installed Plan2Code skill for a scope. Returns the number removed, or -1 when
* the skills CLI call fails.
*/
function removeInstalledSkills(scope, { quiet = false } = {}) {
const installed = listInstalledSkills(scope);
if (installed.length === 0) {
if (!quiet) console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No Plan2Code skills currently installed${COLORS.RESET}`);
return 0;
}
// `skills remove` is variadic and silently skips names that aren't installed, so one call
// clears the store and unlinks every agent. Passing the full build list alongside what was
// found also sweeps stray copies an earlier version left outside the store.
const names = [...new Set([...installed, ...SOURCE_PROMPTS.map(generateSkillName)])];
const scopeFlag = scope === 'global' ? '-g ' : '';
let removed = 0;
for (const name of installed) {
if (runSkillsCli(`remove ${name} ${scopeFlag}-y`) === null) {
if (!quiet) console.log(` ${COLORS.RED}✖✖✖${COLORS.RESET} Could not remove ${name}`);
continue;
if (runSkillsCli(`remove ${names.join(' ')} ${scopeFlag}-y`) === null) {
if (!quiet) console.log(` ${COLORS.RED}✖✖✖${COLORS.RESET} Could not remove installed skills`);
return -1;
}
removed++;
for (const name of installed) {
if (!quiet) console.log(` ${COLORS.YELLOW}░░░${COLORS.RESET} Removed: ${name}`);
}
return removed;
return installed.length;
}
// ============================================================================
@@ -706,18 +827,40 @@ async function install() {
`${COLORS.CYAN}Store:${COLORS.RESET} ${path.join(os.homedir(), '.agents', 'skills')}`,
`${COLORS.CYAN}Mode:${COLORS.RESET} INSTALL`,
]);
console.log(`\n${COLORS.YELLOW}${SYMBOLS.ACTIVE} CLEANING PREVIOUS INSTALLS (PLEASE WAIT ⌛)${COLORS.RESET}\n`);
removeInstalledSkills('global');
const legacy = cleanLegacyPaths();
if (legacy.removed > 0) console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Cleaned ${legacy.removed} legacy file(s) from pre-2.2 installs`);
console.log('');
console.log(`\n${COLORS.YELLOW}${SYMBOLS.ACTIVE} INSTALLING VIA SKILLS.SH${COLORS.RESET}\n`);
// Clear previous installs before writing anything new. The CLI goes first so it can unwind
// its own store and links properly; the legacy sweep then picks up pre-2.2 remnants.
console.log(`${COLORS.YELLOW}${SYMBOLS.ACTIVE} CLEANING PREVIOUS INSTALLS ${COLORS.GREEN}[please wait...]${COLORS.RESET}`);
const spinner1 = createSpinner();
spinner1.start();
removeInstalledSkills('global', { quiet: true });
spinner1.tick();
const legacy = cleanLegacyPaths(true);
spinner1.tick();
spinner1.stop();
if (legacy.removed > 0) {
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Cleaned ${legacy.removed} legacy file(s) from pre-2.2 installs`);
}
console.log('');
console.log(`${COLORS.YELLOW}${SYMBOLS.ACTIVE} INSTALLING VIA SKILLS.SH ${COLORS.GREEN}[please wait...]${COLORS.RESET}`);
console.log(` ${COLORS.DIM}Installing ${SOURCE_PROMPTS.length} skills...${COLORS.RESET}`);
const spinner2 = createSpinner();
spinner2.start();
const result = execSkillsCli(`add "${SKILLS_DIR}" -g ${skillNameArgs()} -y`);
spinner2.tick();
spinner2.stop();
console.log('');
reportSkillsOutput(result);
const failed = !result.ok;
console.log(`\n${COLORS.CYAN}╔═══════════════════════════════════════════════════════════════════════════╗${COLORS.RESET}`);
// 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;
// Summary
console.log(`${COLORS.CYAN}╔═══════════════════════════════════════════════════════════════════════════╗${COLORS.RESET}`);
console.log(`${COLORS.CYAN}║${COLORS.RESET}${' '.repeat(75)}${COLORS.CYAN}║${COLORS.RESET}`);
console.log(`${COLORS.CYAN}║${COLORS.RESET}${' '.repeat(31)}${COLORS.BRIGHT}S U M M A R Y${COLORS.RESET}${' '.repeat(31)}${COLORS.CYAN}║${COLORS.RESET}`);
console.log(`${COLORS.CYAN}║${COLORS.RESET}${' '.repeat(75)}${COLORS.CYAN}║${COLORS.RESET}`);
@@ -728,6 +871,10 @@ async function install() {
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${statusColor}Status:${COLORS.RESET} ${statusColor}${statusText}${COLORS.RESET}`, 76) + `${COLORS.CYAN}║${COLORS.RESET}`);
const installedNames = failed ? [] : listInstalledSkills('global');
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} Skills Installed: ${COLORS.GREEN}${installedNames.length}${COLORS.RESET}`, 76) + `${COLORS.CYAN}║${COLORS.RESET}`);
if (!failed) {
const commandStatus = launcherFailed ? `${COLORS.RED}FAILED (see above)` : `${COLORS.GREEN}${LAUNCHER_COMMAND}`;
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} Global Command: ${commandStatus}${COLORS.RESET}`, 76) + `${COLORS.CYAN}║${COLORS.RESET}`);
}
console.log(`${COLORS.CYAN}║${COLORS.RESET}${' '.repeat(75)}${COLORS.CYAN}║${COLORS.RESET}`);
console.log(`${COLORS.CYAN}╚═══════════════════════════════════════════════════════════════════════════╝${COLORS.RESET}\n`);
@@ -738,11 +885,17 @@ async function install() {
}
console.log(`${COLORS.GREEN} ╭───╮${COLORS.RESET} ${COLORS.BRIGHT}All done! Happy coding!${COLORS.RESET}`);
console.log(`${COLORS.GREEN} │ ${COLORS.CYAN}★${COLORS.GREEN} │${COLORS.RESET} ${COLORS.BRIGHT}If this is your first time using Plan2Code, read the docs here:${COLORS.RESET}`);
console.log(`${COLORS.GREEN} ╲│ ${COLORS.CYAN}★${COLORS.GREEN} │╱${COLORS.RESET} ${COLORS.BRIGHT}If this is your first time using Plan2Code, read the docs here:${COLORS.RESET}`);
console.log(`${COLORS.GREEN} │ ${COLORS.BRIGHT}◡${COLORS.GREEN} │${COLORS.RESET} ${COLORS.BRIGHT}https://github.com/jparkerweb/plan2code${COLORS.RESET}`);
console.log(`${COLORS.GREEN} ╰───╯${COLORS.RESET}`);
console.log(`\n${COLORS.DIM} Update later with:${COLORS.RESET} ${COLORS.CYAN}npx skills update -g${COLORS.RESET}\n`);
return 0;
console.log(`${COLORS.GREEN} ╰┬─┬╯${COLORS.RESET}`);
console.log('');
if (!launcherFailed) {
console.log(`${COLORS.DIM} Open the dashboard in Claude Code or Devin from any project:${COLORS.RESET} ${COLORS.CYAN}${LAUNCHER_COMMAND}${COLORS.RESET}`);
}
console.log(`${COLORS.DIM} Update later with:${COLORS.RESET} ${COLORS.CYAN}npx skills update -g${COLORS.RESET}`);
console.log('');
return launcherFailed ? 1 : 0;
}
// ============================================================================
@@ -765,7 +918,9 @@ function uninstallSkills() {
let errors = 0;
if (ensureSkillsCli()) {
console.log(`\n${COLORS.YELLOW}${SYMBOLS.ACTIVE} REMOVING SKILLS${COLORS.RESET}\n`);
removed += removeInstalledSkills('global');
const skillsRemoved = removeInstalledSkills('global');
if (skillsRemoved < 0) errors++;
else removed += skillsRemoved;
} else {
errors++;
}
@@ -901,9 +1056,9 @@ function runInteractive() {
if (input === 'U') {
console.log('');
console.log(`${COLORS.RED} ╭───╮${COLORS.RESET}`);
console.log(`${COLORS.RED} │ ${COLORS.YELLOW}○${COLORS.RED} │${COLORS.RESET} ${COLORS.YELLOW}!${COLORS.RESET}`);
console.log(`${COLORS.RED} ╲│ ${COLORS.YELLOW}★${COLORS.RED} │╱${COLORS.RESET} ${COLORS.YELLOW}!${COLORS.RESET}`);
console.log(`${COLORS.RED} │ ${COLORS.YELLOW}~${COLORS.RED} │${COLORS.RESET} ${COLORS.DIM}Are you sure? This will remove Plan2Code from all platforms.${COLORS.RESET}`);
console.log(`${COLORS.RED} ╰───╯${COLORS.RESET}`);
console.log(`${COLORS.RED} ╰┬─┬╯${COLORS.RESET}`);
console.log('');
const confirmAnswer = await question(`${COLORS.RED}${SYMBOLS.SELECT} CONFIRM UNINSTALL${COLORS.RESET} (Y/N) [N]: `);
const confirmInput = confirmAnswer.trim().toUpperCase() || 'N';
@@ -915,7 +1070,8 @@ function runInteractive() {
const metricsResult = uninstallPlan2CodeMetrics();
const botResult = uninstallPlan2CodeBot();
const statusLineResult = uninstallStatusLine();
const exitCode = uninstallResult !== 0 ? uninstallResult : loopResult !== 0 ? loopResult : metricsResult !== 0 ? metricsResult : botResult !== 0 ? botResult : statusLineResult;
const launcherResult = uninstallLauncher();
const exitCode = uninstallResult !== 0 ? uninstallResult : loopResult !== 0 ? loopResult : metricsResult !== 0 ? metricsResult : botResult !== 0 ? botResult : statusLineResult !== 0 ? statusLineResult : launcherResult;
process.exit(exitCode);
} else {
console.log(`\n${COLORS.YELLOW}${SYMBOLS.WARNING} CANCELLED${COLORS.RESET}\n`);
@@ -935,10 +1091,11 @@ function runInteractive() {
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}M.${COLORS.RESET} ${COLORS.GREEN}METRICS${COLORS.RESET} Install plan2code-metrics CLI only`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}S.${COLORS.RESET} ${COLORS.GREEN}STATUS${COLORS.RESET} Install Claude Code status line`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}B.${COLORS.RESET} ${COLORS.GREEN}BOT${COLORS.RESET} Install plan2code-bot CLI only`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}D.${COLORS.RESET} ${COLORS.GREEN}P2C CMD${COLORS.RESET} Install the plan2code command only`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}Q.${COLORS.RESET} ${COLORS.DIM}BACK${COLORS.RESET} Return to main menu`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(`${COLORS.CYAN}╚════════════════════════════════════════════════════════════════╝${COLORS.RESET}`);
console.log('');
const customAnswer = await question(`${COLORS.CYAN}${SYMBOLS.SELECT} SELECT OPTION${COLORS.RESET} (L, O, M, S, B, Q) [Q]: `);
const customAnswer = await question(`${COLORS.CYAN}${SYMBOLS.SELECT} SELECT OPTION${COLORS.RESET} (L, O, M, S, B, D, Q) [Q]: `);
const customInput = customAnswer.trim().toUpperCase() || 'Q';
// C > L — install skills into the current project
@@ -975,6 +1132,12 @@ function runInteractive() {
process.exit(result);
}
// C > D — install the global `plan2code` command (opens the dashboard in Claude Code or Devin)
if (customInput === 'D') {
rl.close();
process.exit(await installLauncher());
}
// C > Q — back to main menu
return main();
}
@@ -1002,7 +1165,7 @@ function runInteractive() {
// PLAN2CODE-LOOP INSTALLATION
// ============================================================================
const { execSync } = require('child_process');
const { execSync, execFileSync } = require('child_process');
/**
* Build plan2code-loop package
@@ -1953,6 +2116,372 @@ function uninstallPlan2CodeBot() {
return 0;
}
// ============================================================================
// PLAN2CODE COMMAND (global `plan2code` → dashboard in Claude Code or Devin)
// ============================================================================
/**
* `plan2code` typed in any directory opens the dashboard skill there in Claude Code
* (`claude /plan2code --permission-mode bypassPermissions`) or Devin
* (`devin --permission-mode bypass -- /plan2code`), asking which when both are installed.
* The launcher is copied out of the package into ~/.plan2code/bin/ because the installer
* normally runs from an npx cache directory that npm is free to delete; the shims in the bin
* directory point at that stable copy.
*/
const LAUNCHER_COMMAND = 'plan2code';
const LAUNCHER_MARKER = 'plan2code-launcher';
const LAUNCHER_SRC = path.join(__dirname, 'src', 'launcher', 'plan2code.js');
const LAUNCHER_DEST = path.join(os.homedir(), '.plan2code', 'bin', 'plan2code.js');
const LAUNCHER_STATE = path.join(os.homedir(), '.plan2code', 'launcher.json');
const LAUNCHER_PICK_FOLDER_FLAG = '--pick-folder';
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');
const SHORTCUT_PNG_SRC = path.join(__dirname, 'src', 'web-console', 'public', 'favicon.png');
const SHORTCUT_PNG_DEST = path.join(path.dirname(LAUNCHER_DEST), 'plan2code.png');
function getNpmGlobalBinDir() {
try {
const prefix = execSync('npm config get prefix', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
if (!prefix) return null;
return process.platform === 'win32' ? prefix : path.join(prefix, 'bin');
} catch {
return null;
}
}
function isDirOnPath(dir) {
const normalize = (p) => {
const resolved = path.resolve(p.replace(/^"|"$/g, '')).replace(/[\\/]+$/, '');
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
};
const target = normalize(dir);
return (process.env.PATH || '').split(path.delimiter).filter(Boolean).some((entry) => normalize(entry) === target);
}
function isDirWritable(dir) {
try {
fs.mkdirSync(dir, { recursive: true });
fs.accessSync(dir, fs.constants.W_OK);
return true;
} catch {
return false;
}
}
/**
* Where the command can live: npm's global bin first (on PATH wherever Node was installed
* normally), then ~/.local/bin on macOS/Linux for a system Node whose prefix needs sudo.
*/
function getLauncherBinCandidates() {
const dirs = [getNpmGlobalBinDir()];
if (process.platform !== 'win32') dirs.push(path.join(os.homedir(), '.local', 'bin'));
return [...new Set(dirs.filter(Boolean))];
}
/**
* Shims written into the bin directory — the same trio npm creates for a global bin on
* Windows (sh for Git Bash, .cmd for cmd.exe, .ps1 for PowerShell), just the sh one elsewhere.
*/
function getLauncherShims(binDir) {
const base = path.join(binDir, LAUNCHER_COMMAND);
const posixDest = LAUNCHER_DEST.replace(/\\/g, '/');
// The sh shim also runs from the desktop shortcut, where a version manager's (nvm, fnm)
// PATH is not set up, so it prefers the Node that ran the installer and falls back to
// `node` on PATH if that one is gone (a version switched or removed since).
const posixNode = process.execPath.replace(/\\/g, '/');
const shims = [
{
file: base,
content: `#!/bin/sh\n# ${LAUNCHER_MARKER}\nNODE="${posixNode}"\n[ -x "$NODE" ] || NODE=node\nexec "$NODE" "${posixDest}" "$@"\n`,
},
];
if (process.platform === 'win32') {
shims.push(
{ file: `${base}.cmd`, content: `@echo off\r\nrem ${LAUNCHER_MARKER}\r\nnode "${LAUNCHER_DEST}" %*\r\n` },
{
file: `${base}.ps1`,
content: `#!/usr/bin/env pwsh\r\n# ${LAUNCHER_MARKER}\r\n& node '${LAUNCHER_DEST.replace(/'/g, "''")}' $args\r\nexit $LASTEXITCODE\r\n`,
}
);
}
return shims;
}
function isOurLauncherShim(file) {
try {
return fs.readFileSync(file, 'utf8').includes(LAUNCHER_MARKER);
} catch {
return false;
}
}
function isCommandOnPath(command) {
try {
execSync(process.platform === 'win32' ? `where ${command}` : `command -v ${command}`, { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
function runPowerShell(script, env = {}) {
return execFileSync(
'powershell.exe',
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
{ encoding: 'utf8', env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }
).trim();
}
/**
* The person's desktop folder. Windows asks the shell, because OneDrive and group policy
* often move it off ~/Desktop; Linux asks xdg-user-dir, which knows localized names.
*/
function getDesktopDir() {
try {
if (process.platform === 'win32') {
const dir = runPowerShell("[Console]::OutputEncoding = [Text.Encoding]::UTF8\n[Environment]::GetFolderPath('Desktop')");
if (dir) return dir;
} else if (process.platform !== 'darwin') {
const dir = execFileSync('xdg-user-dir', ['DESKTOP'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
if (dir && path.resolve(dir) !== os.homedir()) return dir;
}
} catch {}
return path.join(os.homedir(), 'Desktop');
}
/**
* Where the desktop shortcut lives: a .lnk on Windows, a .command Terminal opens on macOS,
* a .desktop entry on Linux.
*/
function getShortcutFile(desktopDir = getDesktopDir()) {
if (process.platform === 'win32') return path.join(desktopDir, `${SHORTCUT_NAME}.lnk`);
if (process.platform === 'darwin') return path.join(desktopDir, `${SHORTCUT_NAME}.command`);
return path.join(desktopDir, `${SHORTCUT_NAME.toLowerCase()}.desktop`);
}
/**
* The macOS/Linux shortcuts carry the launcher marker as a comment. A .lnk has nowhere to hide
* one (its Description is the hover tooltip), so it is recognized by what it runs: the
* `plan2code.ps1` shim with `--pick-folder`, both stored in the .lnk as UTF-16. The
* `plan2code.cmd` target of earlier shortcuts still counts, so a reinstall upgrades them.
*/
function isOurShortcut(file) {
try {
const content = fs.readFileSync(file);
if (file.endsWith('.lnk')) {
const has = (text) => content.includes(Buffer.from(text, 'utf16le'));
return has(LAUNCHER_PICK_FOLDER_FLAG) && (has(`${LAUNCHER_COMMAND}.ps1`) || has(`${LAUNCHER_COMMAND}.cmd`));
}
return content.includes(LAUNCHER_MARKER);
} catch {
return false;
}
}
/**
* Put a shortcut on the desktop that runs `plan2code --pick-folder` through the shim in
* `binDir`, so the person picks the project folder in a native dialog before the CLI opens.
* On Windows it opens in PowerShell — PowerShell 7 (`pwsh`) when installed, Windows
* PowerShell otherwise — running the `.ps1` shim, rather than cmd.exe running the `.cmd` one.
*/
function installDesktopShortcut(binDir, file) {
const shim = path.join(binDir, LAUNCHER_COMMAND);
try {
if (!fs.statSync(path.dirname(file)).isDirectory()) throw new Error('not a folder');
} catch {
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} No desktop folder found at ${path.dirname(file)} — skipped the shortcut`);
return 1;
}
try {
if (process.platform === 'win32') {
let icon = '';
try {
fs.copyFileSync(SHORTCUT_ICON_SRC, SHORTCUT_ICON_DEST);
icon = SHORTCUT_ICON_DEST;
} catch {}
runPowerShell(
[
'$pwsh = Get-Command pwsh.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1',
"$target = if ($pwsh) { $pwsh.Source } else { Join-Path $env:SystemRoot 'System32\\WindowsPowerShell\\v1.0\\powershell.exe' }",
'$shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut($env:P2C_FILE)',
'$shortcut.TargetPath = $target',
`$shortcut.Arguments = "-NoLogo -ExecutionPolicy Bypass -File \`"$($env:P2C_SCRIPT)\`" $($env:P2C_ARGS)"`,
'$shortcut.WorkingDirectory = $env:USERPROFILE',
'$shortcut.Description = $env:P2C_DESCRIPTION',
'if ($env:P2C_ICON) { $shortcut.IconLocation = "$($env:P2C_ICON),0" }',
'$shortcut.Save()',
].join('\n'),
{
P2C_FILE: file,
P2C_SCRIPT: `${shim}.ps1`,
P2C_ARGS: LAUNCHER_PICK_FOLDER_FLAG,
P2C_DESCRIPTION: 'Open the Plan2Code dashboard in Claude Code or Devin',
P2C_ICON: icon,
}
);
} else if (process.platform === 'darwin') {
fs.writeFileSync(file, `#!/bin/sh\n# ${LAUNCHER_MARKER}\nexec "${shim}" ${LAUNCHER_PICK_FOLDER_FLAG}\n`);
fs.chmodSync(file, 0o755);
} else {
let icon = '';
try {
fs.copyFileSync(SHORTCUT_PNG_SRC, SHORTCUT_PNG_DEST);
icon = SHORTCUT_PNG_DEST;
} catch {}
fs.writeFileSync(
file,
[
'[Desktop Entry]',
`# ${LAUNCHER_MARKER}`,
'Type=Application',
`Name=${SHORTCUT_NAME}`,
'Comment=Open the Plan2Code dashboard in Claude Code or Devin',
`Exec="${shim}" ${LAUNCHER_PICK_FOLDER_FLAG}`,
...(icon ? [`Icon=${icon}`] : []),
'Terminal=true',
'Categories=Development;',
'',
].join('\n')
);
fs.chmodSync(file, 0o755);
// GNOME only launches a desktop file once it is marked trusted; elsewhere this is a no-op.
try {
execFileSync('gio', ['set', file, 'metadata::trusted', 'true'], { stdio: 'ignore' });
} catch {}
}
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Created: ${file}`);
return 0;
} catch (error) {
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} Failed to create the desktop shortcut: ${error.message}`);
return 1;
}
}
/**
* Offer the desktop shortcut after the command is in place. One that is already there is
* refreshed without asking, since the shim it points at may have moved.
*/
async function offerDesktopShortcut(binDir) {
const file = getShortcutFile();
if (isOurShortcut(file)) return installDesktopShortcut(binDir, file);
if (!process.stdin.isTTY) return 0;
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((resolve) => {
rl.question(` ${COLORS.CYAN}Also add a ${SHORTCUT_NAME} shortcut to your desktop?${COLORS.RESET} (y/N): `, resolve);
});
rl.close();
return answer.trim().toLowerCase().startsWith('y') ? installDesktopShortcut(binDir, file) : 0;
}
/**
* 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.
*/
async function installLauncher({ quiet = false } = {}) {
if (quiet) {
console.log(`${COLORS.YELLOW}${SYMBOLS.ACTIVE} INSTALLING THE ${LAUNCHER_COMMAND.toUpperCase()} COMMAND${COLORS.RESET}`);
} else {
displaySectionHeader('PLAN2CODE COMMAND', '[ INSTALL ]');
}
if (!fs.existsSync(LAUNCHER_SRC)) {
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} src/launcher/plan2code.js not found`);
return 1;
}
try {
fs.mkdirSync(path.dirname(LAUNCHER_DEST), { recursive: true });
fs.copyFileSync(LAUNCHER_SRC, LAUNCHER_DEST);
if (process.platform !== 'win32') fs.chmodSync(LAUNCHER_DEST, 0o755);
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Installed: ${LAUNCHER_DEST}`);
} catch (error) {
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Failed to copy launcher: ${error.message}`);
return 1;
}
const candidates = getLauncherBinCandidates();
const binDir =
candidates.find((dir) => isDirWritable(dir) && isDirOnPath(dir)) || candidates.find((dir) => isDirWritable(dir));
if (!binDir) {
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} No writable bin directory found (tried: ${candidates.join(', ') || 'none'})`);
console.log(` ${COLORS.DIM}Link it by hand:${COLORS.RESET} ${COLORS.CYAN}sudo ln -sf "${LAUNCHER_DEST}" /usr/local/bin/${LAUNCHER_COMMAND}${COLORS.RESET}`);
return 1;
}
try {
for (const shim of getLauncherShims(binDir)) {
const replacingForeign = fs.existsSync(shim.file) && !isOurLauncherShim(shim.file);
fs.rmSync(shim.file, { force: true });
fs.writeFileSync(shim.file, shim.content);
if (!shim.file.endsWith('.cmd') && !shim.file.endsWith('.ps1')) fs.chmodSync(shim.file, 0o755);
const note = replacingForeign ? ` ${COLORS.DIM}(replaced an existing command)${COLORS.RESET}` : '';
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Created: ${shim.file}${note}`);
}
} catch (error) {
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Failed to create the ${LAUNCHER_COMMAND} command: ${error.message}`);
return 1;
}
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`);
}
if (!isCommandOnPath('claude') && !isCommandOnPath('devin')) {
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} Neither the ${COLORS.BRIGHT}claude${COLORS.RESET} nor the ${COLORS.BRIGHT}devin${COLORS.RESET} CLI is on your PATH — install one before running ${COLORS.BRIGHT}${LAUNCHER_COMMAND}${COLORS.RESET}`);
}
// The shortcut is a convenience on top of the command, so a failure here only warns.
await offerDesktopShortcut(binDir);
console.log(` ${COLORS.DIM}Run '${LAUNCHER_COMMAND}' in any project to open the Plan2Code dashboard in Claude Code or Devin${COLORS.RESET}`);
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} It starts the agent with permission prompts off (${COLORS.CYAN}--permission-mode bypassPermissions${COLORS.RESET} in Claude Code, ${COLORS.CYAN}bypass${COLORS.RESET} in Devin). Run ${COLORS.CYAN}claude /plan2code${COLORS.RESET} yourself if you want prompts.`);
console.log('');
return 0;
}
/**
* Remove the global `plan2code` command. Only shims carrying the launcher marker are
* touched, so a `plan2code` bin from anything else is left alone.
*/
function uninstallLauncher() {
displaySectionHeader('PLAN2CODE COMMAND', '[ UNINSTALL ]');
let removedCount = 0;
const remove = (file) => {
try {
fs.rmSync(file, { force: true });
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Removed: ${file}`);
removedCount++;
} catch (error) {
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Failed to remove ${file}: ${error.message}`);
}
};
for (const binDir of getLauncherBinCandidates()) {
for (const { file } of getLauncherShims(binDir)) {
if (isOurLauncherShim(file)) remove(file);
}
}
const shortcut = getShortcutFile();
if (isOurShortcut(shortcut)) remove(shortcut);
for (const file of [LAUNCHER_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE]) {
if (fs.existsSync(file)) remove(file);
}
try {
fs.rmdirSync(path.dirname(LAUNCHER_DEST));
} catch {}
if (removedCount === 0) {
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No ${LAUNCHER_COMMAND} command found${COLORS.RESET}`);
}
console.log('');
return 0;
}
// ============================================================================
// MAIN
// ============================================================================
+3 -3
View File
@@ -1,14 +1,14 @@
{
"name": "plan2code",
"version": "2.3.0",
"version": "2.4.0",
"private": true,
"bin": {
"plan2code": "./install.js"
"plan2code-install": "./install.js"
},
"scripts": {
"prepare": "husky",
"build:skills": "node install.js --build-skills",
"test": "node scripts/validate-char-count.js && node install.js --verify-skills"
"test": "node scripts/validate-char-count.js && node install.js --verify-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-web-console.mjs scripts/test-launcher.mjs"
},
"devDependencies": {
"husky": "^9.0.0"
+9 -9
View File
@@ -6,25 +6,25 @@ export const MASCOT = {
// Full mascot for headers
full: [
' ╭───╮ ',
' │ ● │ ',
' ╱│ ★ │╲ ',
' │ ◡ │ ',
' ╰───╯ ',
' ╰┬─┬╯ ',
],
// Mini mascot for inline use
mini: '(◉‿◉)',
mini: '╱[★]╲',
// Waving mascot for greetings
wave: [
' ╭───╮ ',
' │ ● │ ',
' │ ◡ │ ',
' ╰───╯ ',
' │ ★ │╱ ',
' ╱│ ◡ │ ',
' ╰┬─┬╯ ',
],
// Celebration mascot for completion
celebrate: [
' ╭───╮ ',
' │ ★ │ ',
' ╲│ ★ │╱ ',
' │ ◡ │ ',
' ╰───╯ ',
' ╰┬─┬╯ ',
],
};
@@ -117,7 +117,7 @@ export const logger = {
console.log(chalk.green.bold('═'.repeat(50)));
console.log();
console.log(chalk.cyan.bold('Next Step:'));
console.log(chalk.white(' Return to your AI Agent and run the'), chalk.yellow.bold('/plan2code-4-finalize'), chalk.white('step.'));
console.log(chalk.white(' Return to your AI Agent and run the'), chalk.yellow.bold('/plan2code-4-finalize --web'), chalk.white('step.'));
console.log(chalk.dim(' This will ensure quality, completeness, and proper documentation.'));
console.log();
},
+1 -1
View File
@@ -226,7 +226,7 @@ Output: `.plan2code-metrics/proposals/<timestamp>-diagnosis.md`
Sends the diagnosis plus current prompt file contents to an AI model. The AI proposes surgical `old_text -> new_text` edits, each validated against:
- The `old_text` actually exists in the target file
- The edited file stays under the 11,000 character limit
- The edited file stays under the 11,500 character limit
Output: `.plan2code-metrics/proposals/prop-<timestamp>.json`
+1 -1
View File
@@ -11,7 +11,7 @@ import chalk from 'chalk';
import type { PromptEdit, PromptProposal } from './types.js';
import { validateEdit } from './improver.js';
const CHAR_LIMIT = 11_000;
const CHAR_LIMIT = 11_500;
// ── Diff display ──────────────────────────────────────────────────────────────
+2 -2
View File
@@ -69,12 +69,12 @@ describe('validateEdit', () => {
expect(result.warnings.some(w => /appears.*times/i.test(w))).toBe(true);
});
it('errors when edit would exceed 11,000 char limit', () => {
it('errors when edit would exceed 11,500 char limit', () => {
const bigText = 'x'.repeat(12_000);
const edit = makeEdit({ new_text: bigText });
const result = validateEdit(edit, PROMPT_CONTENTS);
expect(result.valid).toBe(false);
expect(result.errors.some(e => /exceed.*11.?000/i.test(e))).toBe(true);
expect(result.errors.some(e => /exceed.*11.?500/i.test(e))).toBe(true);
});
it('warns when reported char counts diverge from actual (>10 chars off)', () => {
+1 -1
View File
@@ -9,7 +9,7 @@ import path from 'path';
import type { PromptEdit, PromptProposal } from './types.js';
import { invokeLLM, type AgentType } from './invoke-llm.js';
const CHAR_LIMIT = 11_000;
const CHAR_LIMIT = 11_500;
const IMPROVE_PROMPT_PATH = new URL('../src/prompts/improve.md', import.meta.url).pathname
.replace(/^\/([A-Za-z]:)/, '$1'); // Fix Windows path
+2 -2
View File
@@ -26,7 +26,7 @@ The following diagnosis was produced by the analysis step:
## Hard Constraints — ALL must be satisfied:
1. **Char limit:** Each target file MUST stay under 11,000 characters after your edit is applied. This is enforced by code — edits that violate it will be automatically rejected.
1. **Char limit:** Each target file MUST stay under 11,500 characters after your edit is applied. This is enforced by code — edits that violate it will be automatically rejected.
2. **Maximum 5 edits per cycle.** Focus on the highest-impact changes only.
3. **Each edit must cite a specific metric** in its `expected_metric_impact` field (e.g., "avg_task_completion_rate", "avg_blocker_count").
4. **`old_text` must be verbatim** from the file. Copy-paste exactly — include surrounding whitespace/newlines as they appear. Edits with mismatched old_text will be automatically rejected.
@@ -85,7 +85,7 @@ Set `char_count_before`, `char_count_after`, and `char_count_delta` to your best
A table with columns: File | Before | Projected After | Delta | Limit | Status (✓/✗)
Verify that NO file exceeds 11,000 characters after your proposed edits.
Verify that NO file exceeds 11,500 characters after your proposed edits.
---
+319
View File
@@ -0,0 +1,319 @@
#!/usr/bin/env node
// Start-up benchmark for the web console. Dev-only: lives in scripts/ so it
// never ships inside a skill.
//
// node scripts/bench-web-console.mjs [--runs 7] [--workflow dashboard]
// [--browser <path> | --browser none] [--cwd <repo>] [--json <out.json>]
//
// Every run starts from nothing, the way a person's first `/plan2code` does:
// no server, a fresh browser context (each session gets a new port, so a new
// origin, so the HTTP cache is always cold). It measures, from the moment the
// agent runs `console.mjs open`:
//
// url the CLI has printed the link (what the agent hands over)
// cliExit the CLI process has exited (when the agent's next step can start)
// response the browser has the page's HTML
// fcp first contentful paint: the person sees something
// ready the session is drawn from real state (the menu, or a question)
//
// plus the bytes and request count the page cost. Needs puppeteer-core in
// node_modules and a local Chrome or Edge for the browser columns; without
// them it still reports url/cliExit and an HTTP-only waterfall.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
const args = {};
for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i];
if (a.startsWith("--")) args[a.slice(2)] = process.argv[i + 1] && !process.argv[i + 1].startsWith("--") ? process.argv[++i] : true;
}
const RUNS = Number(args.runs || 7);
const WORKFLOW = args.workflow || "dashboard";
const CWD = path.resolve(args.cwd || ROOT);
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-bench-"));
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
function findBrowser() {
if (args.browser === "none") return null;
if (typeof args.browser === "string") return args.browser;
const candidates = [
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/usr/bin/google-chrome",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
];
return candidates.find((p) => fs.existsSync(p)) || null;
}
// Resolves at the first stdout line carrying a url, and again at exit.
// --launch hook (default): `open` launches "the browser" the way it would for
// a person, through PLAN2CODE_BROWSER, and the hook just writes the link to
// a file; the bench points its ready-made tab there the instant it appears.
// That measures everything but the real browser's own start-up, which is
// about 900ms on Windows and runs alongside the rest.
// --launch url: navigate only once `open` prints the link. For comparing
// against versions of console.mjs that predate the hook.
const LAUNCH = args.launch || "hook";
// --browser-delay <ms>: how long "the browser" takes to show up after it is
// asked. 0 is a browser that is instant; ~900 is Chrome on Windows through
// `start`, measured on this machine, and is what a person actually waits.
const BROWSER_DELAY = Number(args["browser-delay"] || 0);
const OPEN_LOG = path.join(HOME, "opened.txt");
function runOpen() {
fs.rmSync(OPEN_LOG, { force: true });
const hook = LAUNCH === "hook";
const env = hook
? { ...ENV, PLAN2CODE_NO_BROWSER: "", PLAN2CODE_BROWSER: `echo>>"${OPEN_LOG}"` }
: ENV;
const t0 = Date.now();
const child = spawn(
process.execPath,
[CONSOLE_CLI, "open", "--workflow", WORKFLOW, "--title", "Bench", ...(hook ? [] : ["--no-open"])],
{ cwd: CWD, env, stdio: ["ignore", "pipe", "pipe"] }
);
let out = "";
let err = "";
let urlResolve;
const urlP = new Promise((r) => (urlResolve = r));
child.stdout.on("data", (c) => {
out += c;
const m = out.match(/"url":"([^"]+)"/);
if (m) urlResolve({ url: m[1], at: Date.now() });
});
child.stderr.on("data", (c) => (err += c));
const exitP = new Promise((r) =>
child.on("exit", (code) => {
urlResolve({ url: null, at: Date.now() });
r({ code, at: Date.now(), out, err });
})
);
// The moment "the browser" was asked to open, and with what.
const openP = hook
? new Promise((resolve) => {
const poll = setInterval(() => {
let text = "";
try {
text = fs.readFileSync(OPEN_LOG, "utf8");
} catch {}
const m = text.match(/http:\/\/127\.0\.0\.1:\d+\/s\/[\w-]+\//);
if (m) {
clearInterval(poll);
resolve({ url: m[0], at: Date.now() });
}
}, 2);
exitP.then(() => setTimeout(() => (clearInterval(poll), resolve({ url: null, at: Date.now() })), 500));
})
: urlP;
return { t0, urlP, exitP, openP };
}
function stopAll() {
spawnSync(process.execPath, [CONSOLE_CLI, "stop", "--all"], { cwd: CWD, env: ENV });
}
async function httpWaterfall(url) {
// What the page costs without a browser: the redirect, the HTML, every
// asset it names, then the modules those import. Sequential levels, like a
// browser without preload hints would discover them.
const t = Date.now();
const r1 = await fetch(url, { redirect: "manual" });
const cookie = (r1.headers.get("set-cookie") || "").split(";")[0];
const base = new URL(url).origin;
const get = async (p) => {
const res = await fetch(base + p, { headers: { cookie } });
const body = Buffer.from(await res.arrayBuffer());
return { p, status: res.status, bytes: body.length, text: body.toString("utf8") };
};
const html = await get("/");
let bytes = html.bytes;
let requests = 2;
const seen = new Set();
let level = [...html.text.matchAll(/(?:href|src)="(\/[^"#]+\.(?:css|js))"/g)].map((m) => m[1]);
let levels = 1;
while (level.length) {
const fresh = level.filter((p) => !seen.has(p));
fresh.forEach((p) => seen.add(p));
if (!fresh.length) break;
const got = await Promise.all(fresh.map(get));
requests += got.length;
bytes += got.reduce((n, g) => n + g.bytes, 0);
level = got
.filter((g) => g.p.endsWith(".js"))
.flatMap((g) => [...g.text.matchAll(/from\s+"\.\/([^"]+)"/g)].map((m) => "/" + path.posix.join(path.posix.dirname(g.p.slice(1)), m[1])));
levels++;
}
return { ms: Date.now() - t, bytes, requests, levels };
}
// --roundtrip: the two hops of a live session, rather than the start.
// send the person presses Send -> the agent's `wait` returns the answers
// post the agent runs `post` -> the page's stream delivers the new state
async function roundtrip() {
const payload = path.join(HOME, "rt.json");
const item = { id: "q1", kind: "text", title: "Anything", body: "Say something." };
fs.writeFileSync(payload, JSON.stringify({ workflow: "pathfinder", items: [item], agent: { status: "waiting" } }));
const out = spawnSync(process.execPath, [CONSOLE_CLI, "open", "--file", payload, "--no-open"], { cwd: CWD, env: ENV, encoding: "utf8" });
const opened = JSON.parse(out.stdout.trim().split("\n").pop());
const [, base, token] = opened.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
const headers = { cookie: `p2c_console_${new URL(base).port}=${token}`, "content-type": "application/json" };
const sends = [];
const posts = [];
for (let i = -1; i < RUNS; i++) {
// send: a waiter already sitting in its slice, then the press.
const waiter = spawn(process.execPath, [CONSOLE_CLI, "wait", "--session", opened.sid, "--seconds", "30"], { cwd: CWD, env: ENV });
const done = new Promise((r) => waiter.on("exit", () => r(Date.now())));
await new Promise((r) => setTimeout(r, 700));
const t = Date.now();
await fetch(base + "/submit", { method: "POST", headers, body: JSON.stringify({ actions: [{ i: "q1", type: "answer", kind: "text", text: "x" + i }], reply: "x" }) });
const sendMs = (await done) - t;
// post: a page listening on the stream, then the agent's update.
const ctrl = new AbortController();
const res = await fetch(base + "/events", { headers, signal: ctrl.signal });
const reader = res.body.getReader();
const dec = new TextDecoder();
await reader.read();
const patch = path.join(HOME, "rt-patch.json");
fs.writeFileSync(patch, JSON.stringify({ items: [{ id: "q1", status: "open", body: "Again " + i }], agent: { status: "waiting" } }));
const tp = Date.now();
spawnSync(process.execPath, [CONSOLE_CLI, "post", "--session", opened.sid, "--file", patch], { cwd: CWD, env: ENV });
const postCli = Date.now() - tp;
let buf = "";
while (!buf.includes("Again " + i)) buf += dec.decode((await reader.read()).value);
const postMs = Date.now() - tp;
ctrl.abort();
if (i >= 0) {
sends.push(sendMs);
posts.push({ total: postMs, cli: postCli });
}
}
spawnSync(process.execPath, [CONSOLE_CLI, "stop", "--all"], { cwd: CWD, env: ENV });
const med = (v) => v.sort((a, b) => a - b)[Math.floor(v.length / 2)];
console.log(`web console round trips, ${RUNS} runs`);
console.log(`send -> wait returns median ${med(sends)} ms (min ${Math.min(...sends)}, max ${Math.max(...sends)})`);
console.log(`post -> page has it median ${med(posts.map((p) => p.total))} ms (of which the post CLI ${med(posts.map((p) => p.cli))} ms)`);
fs.rmSync(HOME, { recursive: true, force: true });
}
async function main() {
if (args.roundtrip) return roundtrip();
const browserPath = findBrowser();
let puppeteer = null;
if (browserPath) {
try {
puppeteer = (await import("puppeteer-core")).default;
} catch {
console.error("puppeteer-core not installed; browser columns skipped");
}
}
const browser = puppeteer
? await puppeteer.launch({ executablePath: browserPath, headless: true, args: ["--no-first-run", "--no-default-browser-check"] })
: null;
const rows = [];
// One throwaway run so disk caches and the Node binary are warm; the person
// running this has run node before too.
for (let i = -1; i < RUNS; i++) {
stopAll();
// The tab exists before the clock starts: a person's browser is already
// running, and creating a context is the harness's cost, not the page's.
const ctx = browser ? await browser.createBrowserContext() : null;
const page = ctx ? await ctx.newPage() : null;
const { t0, urlP, exitP, openP } = runOpen();
const o = await openP;
if (!o.url) {
const e = await exitP;
throw new Error(`open failed (${e.code}): ${e.err}`);
}
const row = { open: o.at - t0 };
if (browser) {
let bytes = 0;
let requests = 0;
page.on("response", async (res) => {
requests++;
try {
bytes += (await res.buffer()).length;
} catch {}
});
if (BROWSER_DELAY) await new Promise((r) => setTimeout(r, Math.max(0, o.at + BROWSER_DELAY - Date.now())));
await page.goto(o.url, { waitUntil: "domcontentloaded" });
const timing = await page.evaluate(async () => {
// "ready" = drawn from real state: a dashboard card, a question card,
// the starting screen or the waiting pane a real state produces.
const readySel = ".dash-card, .card.question, .waiting-pane, .launching.starting, .handoff";
await new Promise((resolve) => {
const check = () => (document.querySelector(readySel) ? resolve() : requestAnimationFrame(check));
check();
});
const readyAt = performance.timeOrigin + performance.now();
// The real screen can be drawn before the first paint happens at all,
// so wait for the paint rather than reading an entry not yet made.
const fcp = await new Promise((resolve) => {
const got = () => performance.getEntriesByName("first-contentful-paint")[0];
if (got()) return resolve(got());
new PerformanceObserver(() => got() && resolve(got())).observe({ type: "paint", buffered: true });
setTimeout(() => resolve(got() || null), 3000);
});
const nav = performance.getEntriesByType("navigation")[0];
return {
origin: performance.timeOrigin,
fcp: fcp ? performance.timeOrigin + fcp.startTime : null,
response: nav ? performance.timeOrigin + nav.responseEnd : null,
ready: readyAt,
};
});
// The origin here is the redirected document, so the 302 is inside
// `response`, not before it.
row.response = Math.round(timing.response - t0);
row.fcp = timing.fcp ? Math.round(timing.fcp - t0) : null;
row.ready = Math.round(timing.ready - t0);
await new Promise((r) => setTimeout(r, 150));
row.requests = requests;
row.kb = Math.round(bytes / 1024);
await ctx.close();
}
const e = await exitP;
row.url = (await urlP).at - t0;
row.cliExit = e.at - t0;
if (!browser) Object.assign(row, await httpWaterfall(o.url));
if (i >= 0) rows.push(row);
}
stopAll();
if (browser) await browser.close();
const cols = Object.keys(rows[0]);
const stat = (k) => {
const v = rows.map((r) => r[k]).filter((x) => typeof x === "number").sort((a, b) => a - b);
if (!v.length) return null;
return { median: v[Math.floor(v.length / 2)], min: v[0], max: v[v.length - 1] };
};
const summary = Object.fromEntries(cols.map((k) => [k, stat(k)]));
console.log(`web console start-up, ${RUNS} runs, workflow=${WORKFLOW}, cwd=${CWD}`);
console.log(`browser: ${browser ? browserPath : "none (HTTP-only waterfall)"}`);
console.log("metric".padEnd(10) + "median".padStart(9) + "min".padStart(9) + "max".padStart(9));
for (const k of cols) {
const s = summary[k];
if (!s) continue;
const unit = k === "kb" ? " KB" : k === "requests" || k === "levels" ? "" : " ms";
console.log(k.padEnd(10) + `${s.median}${unit}`.padStart(9) + `${s.min}`.padStart(9) + `${s.max}`.padStart(9));
}
if (args.json) fs.writeFileSync(path.resolve(args.json), JSON.stringify({ runs: rows, summary }, null, 2));
fs.rmSync(HOME, { recursive: true, force: true });
}
main().catch((e) => {
stopAll();
console.error(e);
process.exit(1);
});
+91
View File
@@ -0,0 +1,91 @@
// Check the dashboard's "What each skill reads and writes" table against the
// skills it describes.
//
// The table is what the dashboard and the Ask tab treat as ground truth for a
// skill's files. Every backticked name in a row must appear in that skill's own
// prompt or its references, so a rename in a skill fails here instead of the
// table quietly going stale. `<placeholder>` segments match any placeholder,
// so `PLAN-DRAFT-<date>.md` accepts the skill's `PLAN-DRAFT-<YYYYMMDD>.md`.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const SRC = path.join(ROOT, "src");
const HEADING = "## What each skill reads and writes";
function readTree(dir) {
if (!fs.existsSync(dir)) return "";
return fs
.readdirSync(dir, { withFileTypes: true })
.map((entry) => {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) return readTree(full);
return entry.name.endsWith(".md") ? fs.readFileSync(full, "utf8") : "";
})
.join("\n");
}
function skillCorpus(skill) {
const file = path.join(SRC, `plan2code-${skill}.md`);
if (!fs.existsSync(file)) return null;
return fs.readFileSync(file, "utf8") + "\n" + readTree(path.join(SRC, `plan2code-${skill}-references`));
}
// "3-implement(-review)" names both 3-implement and 3-implement-review.
function expandSkills(cell) {
const optional = cell.match(/^(.*)\((.+)\)$/);
return optional ? [optional[1], optional[1] + optional[2]] : [cell];
}
function tokenPattern(token) {
const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return new RegExp(escaped.replace(/<[^>]+>/g, "<[^>]+>"));
}
function mentions(corpus, token) {
if (tokenPattern(token).test(corpus)) return true;
const leaf = token.slice(token.lastIndexOf("/") + 1);
return leaf !== "" && leaf !== token && tokenPattern(leaf).test(corpus);
}
const prompt = fs.readFileSync(path.join(SRC, "plan2code.md"), "utf8");
const start = prompt.indexOf(HEADING);
if (start === -1) {
console.error(` FAIL src/plan2code.md has no "${HEADING}" section.`);
process.exit(1);
}
const section = prompt.slice(start + HEADING.length).split(/\n## /)[0];
const rows = section
.split("\n")
.filter((line) => line.startsWith("|") && !/^\|\s*(skill|---)/.test(line))
.map((line) => line.split("|").slice(1, -1).map((cell) => cell.trim()));
if (rows.length === 0) {
console.error(` FAIL "${HEADING}" has no table rows.`);
process.exit(1);
}
let bad = 0;
for (const [skillCell, ...cells] of rows) {
const skills = expandSkills(skillCell);
const corpora = skills.map(skillCorpus);
if (corpora.some((corpus) => corpus === null)) {
bad++;
console.error(` FAIL ${skillCell}: no src/plan2code-<skill>.md for ${skills.join(" / ")}`);
continue;
}
const corpus = corpora.join("\n");
const tokens = cells.join(" ").match(/`[^`]+`/g) ?? [];
const missing = tokens.map((t) => t.slice(1, -1)).filter((token) => !mentions(corpus, token));
if (missing.length) {
bad++;
console.error(` FAIL ${skillCell}: not in the skill's source: ${missing.join(", ")}`);
} else {
console.log(` ok ${skillCell} (${tokens.length} name(s))`);
}
}
if (bad) {
console.error(`${bad} row(s) of "${HEADING}" disagree with their skill.`);
process.exit(1);
}
+36
View File
@@ -0,0 +1,36 @@
// Parse every shipped browser module as a real ES module.
//
// `node --check` is not enough: it parses a .js file as a CommonJS script, and
// it let a string literal containing a raw newline through to the browser,
// where the page died at import with nothing rendered. Importing the source as
// a data: module is the same parse the browser does.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const DIR = path.join(ROOT, "src", "web-console", "public");
const FILES = ["app.js", "answers.js", "render.js", "palette.js", "starters.js", "favicon.js"];
let bad = 0;
for (const name of FILES) {
const src = fs.readFileSync(path.join(DIR, name), "utf8");
try {
await import("data:text/javascript," + encodeURIComponent(src));
console.log(` ok ${name}`);
} catch (err) {
// A module that parses but cannot run here (app.js touches `document` at
// import) is fine; only a parse failure is a real problem.
const parseFailure = err instanceof SyntaxError;
if (parseFailure) {
bad++;
console.error(` FAIL ${name}: ${err.message}`);
} else {
console.log(` ok ${name} (parsed; not runnable outside a browser)`);
}
}
}
if (bad) {
console.error(`${bad} file(s) would not parse in a browser.`);
process.exit(1);
}
+152
View File
@@ -0,0 +1,152 @@
// Tests for the global `plan2code` launcher. Run with: node --test scripts/test-launcher.mjs
//
// The launcher is a script that runs on load, so each test spawns it for real: a temp home
// for ~/.plan2code/launcher.json, and stand-in `claude` / `devin` commands on PATH that
// record the arguments they were started with. stdin is a pipe, never a TTY, so the launcher
// takes its no-prompt path: no menu and no wait at the model notice.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
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) {
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 recorder = path.join(bin, "record.js");
fs.writeFileSync(
recorder,
'require("fs").writeFileSync(require("path").join(__dirname, process.argv[2] + ".json"), JSON.stringify(process.argv.slice(3)));\n' +
"process.exitCode = Number(process.env.P2C_TEST_EXIT || 0);\n"
);
for (const cli of clis) {
if (IS_WINDOWS) {
fs.writeFileSync(path.join(bin, `${cli}.cmd`), `@"${process.execPath}" "${recorder}" ${cli} %*\r\n`);
} else {
const file = path.join(bin, cli);
fs.writeFileSync(file, `#!/bin/sh\nexec "${process.execPath}" "${recorder}" ${cli} "$@"\n`);
fs.chmodSync(file, 0o755);
}
}
return {
home,
stateFile: path.join(home, ".plan2code", "launcher.json"),
run: (args, env = {}) =>
spawnSync(process.execPath, [LAUNCHER, ...args], {
cwd: dir,
input: "",
encoding: "utf8",
env: { ...process.env, PATH: bin, HOME: home, USERPROFILE: home, ...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 }),
};
}
test("launcher: Claude Code gets the prompt first, then bypassPermissions and the forwarded args", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
const result = box.run(["--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions", "--verbose"]);
assert.match(result.stdout, new RegExp(`Claude Code ${NOTICE}`));
});
test("launcher: Devin keeps its args ahead of the -- and the prompt", (t) => {
const box = sandbox(["devin"]);
t.after(box.cleanup);
const result = box.run(["--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("devin"), ["--permission-mode", "bypass", "--verbose", "--", "/plan2code"]);
});
test("launcher: a forwarded --model skips the model notice", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
for (const args of [["--model", "opus"], ["--model=opus"]]) {
const result = box.run(args);
assert.equal(result.status, 0, result.stderr);
assert.doesNotMatch(result.stdout, new RegExp(NOTICE));
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions", ...args]);
}
});
test("launcher: --cli picks the CLI and is never forwarded; the pick is merged into launcher.json", (t) => {
const box = sandbox(["claude", "devin"]);
t.after(box.cleanup);
fs.mkdirSync(path.dirname(box.stateFile), { recursive: true });
fs.writeFileSync(box.stateFile, JSON.stringify({ lastFolder: box.home }));
for (const args of [["--cli", "devin"], ["--cli=DEVIN"]]) {
const result = box.run(args);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("devin"), ["--permission-mode", "bypass", "--", "/plan2code"]);
}
assert.equal(box.argsOf("claude"), null);
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), { lastFolder: box.home, lastCli: "devin" });
});
test("launcher: with both installed and no terminal to ask in, the last pick wins", (t) => {
const box = sandbox(["claude", "devin"]);
t.after(box.cleanup);
fs.mkdirSync(path.dirname(box.stateFile), { recursive: true });
fs.writeFileSync(box.stateFile, JSON.stringify({ lastCli: "devin" }));
assert.equal(box.run([]).status, 0);
assert.notEqual(box.argsOf("devin"), null);
assert.equal(box.argsOf("claude"), null);
});
test("launcher: an unknown --cli exits 2, a missing CLI 127, and nothing is started", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
const unknown = box.run(["--cli", "bogus"]);
assert.equal(unknown.status, 2);
assert.match(unknown.stderr, /--cli takes claude or devin, not "bogus"/);
const missing = box.run(["--cli", "devin"]);
assert.equal(missing.status, 127);
assert.match(missing.stderr, /the `devin` CLI was not found/);
assert.equal(box.argsOf("claude"), null);
});
test("launcher: with neither CLI installed it exits 127 naming both", (t) => {
const box = sandbox([]);
t.after(box.cleanup);
const result = box.run([]);
assert.equal(result.status, 127);
assert.match(result.stderr, /neither `claude` nor `devin` was found/);
});
test("launcher: a forwarded argument with a space and a cmd metacharacter arrives unchanged", (t) => {
// On Windows the stand-in is a .cmd, so this goes through the cmd.exe quoting in quoteForCmd.
const box = sandbox(["claude"]);
t.after(box.cleanup);
const result = box.run(["--append-system-prompt", "a b&c"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions", "--append-system-prompt", "a b&c"]);
});
test("launcher: the CLI's non-zero exit code is passed through", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
const result = box.run([], { P2C_TEST_EXIT: "7" });
assert.equal(result.status, 7, result.stderr);
assert.notEqual(box.argsOf("claude"), null);
});
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -3,14 +3,14 @@
const fs = require('fs');
const path = require('path');
const CHAR_LIMIT = 11000;
const CHAR_LIMIT = 11500;
const srcDir = path.join(__dirname, '..', 'src');
// Note: readdirSync is non-recursive, so files in subdirectories like
// plan2code-review-references/ are automatically excluded from
// the character limit check. Reference files have no char limit.
const files = fs.readdirSync(srcDir)
.filter(f => f.startsWith('plan2code-') && f.endsWith('.md'))
.filter(f => /^plan2code(-.*)?\.md$/.test(f))
.sort();
const failures = [];
+9 -5
View File
@@ -16,6 +16,10 @@ Read references/grilling.md
> Fallback: ≤3 independent probes/turn, each with a recommendation, re-ask any skipped; AskUserQuestion for every question, prose only if unavailable; plain English; facts you look up, decisions are the human's.
## Interface
The FIRST thing you do, before anything else in this file — before Step 0: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow pathfinder` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then <D>/console.md → Pathfinder notes. Switchable anytime. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console.md → Launches), then Step 0.
## Backend
The map lives in ONE of two places — the human's pick at Chart Step 1, never yours:
@@ -126,20 +130,20 @@ Any failing: name it, keep working. All passing: follow the handoff playbook, se
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, one closer.
Once the map exists the trail closes EVERY response, then ONE closer by turn type. Asking anything → Form B: `WAITING ON YOU · answer here, in this conversation:` + open items, no command. Menu after a decision → Form C: `NEXT UP` picks + `OR START FRESH`. Session end → Form A: `NEXT STEP · start a new conversation and run:` + `/plan2code-0-pathfinder specs/<idea>/pathfinder` (map issue URL on `github`), or `/plan2code-1-plan` once `Cleared`.
> 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`).
## 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.
**Web console:** at session end or on a `__stop`, post `finish` (Form A's command) BEFORE `stop` (console.md → Pathfinder).
```
⋅
╭───╮
│ ★ │
╲│ ★ │╱
│ ◡ │ One more decision down. The fog is thinner!
╰───╯
╰┬─┬╯
```
**When the map cleared**, the mascot says `The way is clear! Time to plan!` and the footer routes to `/plan2code-1-plan` — or `/plan2code-init` FIRST if `## Ground rules` records `AGENTS.md` absent.
@@ -98,5 +98,5 @@ Nothing decided in the range? Keep the file honest: "No decisions were recorded
- **Scraper safety, same as the PLAN-DRAFT:** no `%`, no raw `NN/25` scores, and no bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number anywhere in the file. The plain-English confidence line is the only rendering permitted.
- **Standing `specs/` rules apply:** no loop tokens, no `- [ ]` checkboxes, no `METRICS_JSON`.
- **Rejections are one line each.** The brief summarizes; the question file argues. The closing pointer line covers readers who want the full reasoning.
- **BRIEF mode does not count as question work.** One-question-per-session accounting is untouched; no claim is ever taken.
- **BRIEF mode does not count as question work.** It does not count toward the session's decision cadence; no claim is ever taken.
- **Do not edit an old brief to "update" it.** Yesterday's brief reflects yesterday's map — write today's instead. Same-day overwrite only.
@@ -52,11 +52,11 @@ Two round trips, not six. Three probes each — exactly the cap, so neither batc
Batch 2 bends the independence test on purpose. The arrival signal (5) can shift under the smallest arrival (4), so strictly it should be held back — but holding it costs a third round trip to catch a conflict that is rare and cheap to spot. The trade is to send them together and reconcile at the recap: if the smallest arrival comes back materially smaller than the artifact you were told about, re-check the arrival signal against it before writing the destination. A knowing trade here, not a licence to batch dependent probes elsewhere.
**Both batches go through the structured question tool.** Give each probe genuine candidate options with trade-offs and a recommendation; the built-in `Other` path is where the human composes the actor, boundary, arrival signal, or forcing-function detail in their own words. A clicked option is not written verbatim as the destination — the recap-confirmation tool call turns all six answers into the agreed one-or-two-line destination before disk write.
**Both batches go through the structured question tool.** Give each probe genuine candidate options with trade-offs and a recommendation; the built-in `Other` path is where the human composes the actor, a further feature to leave out, the arrival signal, or forcing-function detail in their own words. A clicked option is not written verbatim as the destination — the recap-confirmation tool call turns all six answers into the agreed one-or-two-line destination before disk write.
**Probe 1 — the artifact**
> "When this map is cleared, what exists that does not exist now: a plan you hand to `/plan2code-1-plan`, a decision locked before anyone plans, or a change already made in the codebase? My guess: a plan."
> "When we are done here, what exists that does not exist now: a plan you hand to `/plan2code-1-plan`, a decision recorded before anyone plans, or a change already made in the codebase? My guess: a plan."
*Fishing for:* the shape of the destination. Push back if the answer is "the feature working" — that is past the edge of every pathfinder map. Say so plainly: "That is the build. The map ends at the plan for the build."
@@ -68,29 +68,31 @@ Batch 2 bends the independence test on purpose. The arrival signal (5) can shift
**Probe 3 — the sacrificial boundary**
> "Name one thing a reasonable person would assume is part of this that you are willing to say is NOT part of it."
> "Which of these features are we leaving out this time?"
*Fishing for:* the first `## Out of scope` bullet. This probe does more work than any other. A destination nobody has excluded anything from has not been thought about. If the human cannot name one, offer two candidates and make them reject one.
Deliver it as a multi-select (`multi` on the web console) of 3–5 features a reasonable person might expect to be included. Every option names a feature ("Scheduled exports"), never a rule to keep ("Exports stay manual"). Each option's description ends "(Leaving this out = …)", naming what that leaves. Offer a recommended preset of the ones you would leave out; the free-text path lets them name another feature.
*Fishing for:* the first `## Out of scope` bullets — the ticked features become them. This probe does more work than any other. If nothing is ticked, push once: a destination nobody has excluded anything from has not been thought about. The preset is the push.
**Probe 4 — the smallest arrival**
> "What is the smallest version that would still count as arriving? If only that existed, would you call it done or would you feel cheated?"
> "What is the smallest version that would still count? If only that existed, would you call it done or would you feel cheated?"
*Fishing for:* the difference between the destination and the wish list. Everything above the smallest arrival is a candidate for out of scope or for a later effort.
**Probe 5 — the arrival signal**
> "How do you know you have arrived — what do you look at?"
> "How will you know it's done — what do you look at?"
*Fishing for:* a checkable condition. "It feels right" is not one. "Every open decision has an answer and I can hand the draft to planning without re-litigating format" is one.
**Probe 6 — the forcing function**
> "What made this surface now? A deadline, an incident, an audit, a customer?"
> "What made this come up now? A deadline, an incident, an audit, a customer?"
*Fishing for:* constraints that will shape half the questions and that nobody volunteers unprompted. A regulatory deadline changes the delivery question, the testing posture question, and the out-of-scope line all at once.
**The probe names above are internal labels, not headings the human reads.** Head each Q block plainly — *What you end up with*, *Who uses it*, *What's not included*, *Smallest version that counts*, *How you know it's done*, *Why now* — and keep the probe text itself as plain as the quotes above. "The sacrificial boundary" and "the arrival signal" mean something to this playbook and nothing to the person answering. Full rule in the grilling playbook, *Say it in plain English*.
**The probe names above are internal labels, not headings the human reads.** Head each Q block plainly — *What you end up with*, *Who uses it*, *Leave for later*, *Smallest version that counts*, *How you know it's done*, *Why now* — and keep the probe text itself as plain as the quotes above. "The sacrificial boundary" and "the arrival signal" mean something to this playbook and nothing to the person answering. Full rule in the grilling playbook, *Say it in plain English*.
### Worked example — same idea, two destinations
@@ -65,7 +65,7 @@ Every probe gets read once, by a busy human, in a terminal. Write it the way you
| "this is a `grill · HITL`" | "this one is yours to call" |
| "the frontier holds two takeable questions" | "two things we can decide right now" |
| "graduating this out of the fog" | "this is sharp enough to write down as a real question now" |
| "the sacrificial boundary" | "name one thing people would assume is included that you are willing to cut" |
| "the sacrificial boundary" | "which of these features are we leaving out this time?" |
| "shall I set `Locked: yes`?" | "worth recording why we picked this, so nobody re-opens it in six months?" |
| "Q3 is blocked by 02" | "the export format question has to land before this one" |
| "the UI cannot handle this question" | nothing — put context before the tool and preserve `Other` |
@@ -74,6 +74,8 @@ Every probe gets read once, by a busy human, in a terminal. Write it the way you
**No metaphor where a fact fits.** Maps, fog, and trails belong in the footer and the mascot. Inside a probe they cost a translation step: "three things here are still undecided" beats "the fog is thick in this quarter of the map."
**On a what-to-drop question, name the thing dropped.** Whenever a question asks what gets dropped, left out or cut, every option names the thing being dropped, never a rule to keep. Otherwise ticking an option reads as a double negative, and the person has to work out whether a tick means yes or no. Bad: "☐ Exports stay manual" · Good: "☐ Scheduled exports (Leaving this out = someone runs each export by hand)"
The same discipline covers everything else the human reads — the recap turn in *Landing the grill*, the option labels and descriptions in the structured tool, the sketch probes, and the HITL checklists in the resolution playbook. Plain in the question, precise in the term that carries the decision.
### The independence test
@@ -125,7 +127,7 @@ Fallback ONLY when the structured question tool does not exist or its call fails
**Copy this shape exactly.** The blank lines are load-bearing, not decoration:
````markdown
Three independent decisions are open. Answer in any order, skip any you want to punt — "Q2: b, Q3: the hybrid" is a perfectly good reply.
Three independent decisions are open. Answer in any order, skip any you want to punt — "Q2: a, c; Q3: the hybrid" is a perfectly good reply.
---
@@ -143,15 +145,18 @@ When a custodian exports a year of a channel, what do they get back?
---
**Q2 — What's not included**
**Q2 — Leave for later**
Name one thing a reasonable person would assume is part of this that you are willing to say is NOT part of it.
Which of these features are we leaving out this time? Tick any number.
*Why it matters:* this becomes the first thing written down as out of scope, and every later "is that in or out?" call is measured against it. A destination nobody has excluded anything from has not been thought about.
*Why it matters:* the ones you tick become the first things written down as out of scope, and every later "is that in or out?" call is measured against them. A destination nobody has excluded anything from has not been thought about.
*Recommendation:* none — this one is yours. If nothing comes to mind, I will offer two candidates and you reject one.
*Recommendation:* **(a)** and **(c)** — neither is needed for the first review hand-off.
*(free text — no options on this one)*
- **a)** Scheduled exports (Leaving this out = someone runs each export by hand)
- **b)** Exports of deleted messages (Leaving this out = anything already purged stays out of the file)
- **c)** Export to a cloud bucket (Leaving this out = the file downloads to the custodian's machine only)
- **d)** Redaction inside the export (Leaving this out = the review vendor redacts after ingest)
````
Number them, keep the numbers stable across turns and sessions, and say out loud that partial answers are welcome — the invitation is what makes the skip visible instead of silent.
@@ -77,7 +77,7 @@ Part 2 answers exactly one question for the human: **is this turn over, or is it
```
NEXT STEP · start a new conversation and run:
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder`
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder --web`
```
The path is always relative and always ends `/pathfinder` — that is exactly the argument this skill's Auto-Discovery resolves an idea from, so the human pastes it back with zero edits. Fill `<idea>` from the active map's directory; never leave the `<spec-folder>` placeholder in a rendered footer.
@@ -86,9 +86,9 @@ The command target follows the map's status, but the sentence is always the same
| Status | Command |
|---|---|
| `Charting` / `Working` | `/plan2code-0-pathfinder specs/<idea>/pathfinder` |
| `Cleared` | `/plan2code-1-plan` — point at the PLAN-DRAFT the Clearing Gate wrote |
| `Cleared`, but `## Ground rules` records `AGENTS.md` **absent** | `/plan2code-init` FIRST (offer `questions/00-codebase-context.md`), then `/plan2code-1-plan` |
| `Charting` / `Working` | `/plan2code-0-pathfinder specs/<idea>/pathfinder --web` |
| `Cleared` | `/plan2code-1-plan --web` — point at the PLAN-DRAFT the Clearing Gate wrote |
| `Cleared`, but `## Ground rules` records `AGENTS.md` **absent** | `/plan2code-init` FIRST (offer `questions/00-codebase-context.md`), then `/plan2code-1-plan --web` |
#### Form B — the turn asks the human something
@@ -113,7 +113,7 @@ First print the stop branch, clearly labeled:
```
OR START FRESH · new conversation, paste:
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder`
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder --web`
```
Then invoke the structured question tool (header `Next step`) asking: "Continue here, or start fresh? Everything is saved." Options: up to three takeable question names, then `Start fresh`. Put each question's gist / newly-unblocked note in its description. The automatic `Other` path lets the human name another frontier question not shown. Mark one option's description `RECOMMENDED` — early in the session that is a question; at the checkpoint it is `Start fresh`.
@@ -168,7 +168,7 @@ Q2 Ceiling behaviour past the cap (re-ask) · Q3 Who sees the truncation warning
Confidence: not yet — Feasibility, Risk still need work.
NEXT STEP · start a new conversation and run:
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder`
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder --web`
```
**Cleared** — every stop walked, fog empty, command hands off:
@@ -179,7 +179,7 @@ NEXT STEP · start a new conversation and run:
Confidence: solid.
NEXT STEP · start a new conversation and run:
`/plan2code-1-plan`
`/plan2code-1-plan --web`
```
At `Cleared` the named legend is optional — the destination is reached and the PLAN-DRAFT is the thing to point at. Keep the confidence line; the Clearing Gate leaned on it.
@@ -0,0 +1,444 @@
# Build Sessions on the Web Console
For `/plan2code-3-implement`, `/plan2code-3-implement-review` and
`/plan2code-quick-task`. Read `console.md` first: everything there still
applies (the wait loop, one post per send, `finish` before `stop`, the house
rules). This file adds what a build needs, because a build is mostly you
working, and the page has to be told so.
**The console changes where you ask, not what you build.** Every rule of the
workflow stands: the same specs, the same checkbox writes to disk after every
task, the same sign-off wording, the same "no git commands". The files under
`specs/` and the code are the record. The page is a window onto them.
---
## Opening
Open first, before reading the spec — the page shows a starting screen while
you work out the phase:
```
node "<CONSOLE>" open --workflow implement
```
| Workflow you are running | `--workflow` | `--spec` |
| --- | --- | --- |
| `/plan2code-3-implement` | `implement` | `specs/<feature>` |
| `/plan2code-3-implement-review` | `implement-review` | `specs/<feature>` |
| `/plan2code-quick-task` | `quick-task` | leave it out |
`--spec` is what the page builds a resume command from if you ever cannot
answer a stop yourself. Pass it to `open` when you already know the spec;
otherwise post `"specDir": "specs/<feature>"` and a real `title` ("<feature>:
Phase 3") in your first update, once the phase is chosen, or with the phase
question as its first item if there is one to ask. `--file` works on `open`
too, but opening bare and posting the task list as your first update gets
them the page while you are still composing.
**Launched from the dashboard?** Then the session is already open and the
person is watching it — `open --resume <sid> --no-open --workflow <yours>`
(plus `--spec` once known) instead of a fresh `open`, exactly as console.md →
Launches says. Everything below is unchanged; the only difference is whose
session it was a minute ago.
The first payload for a phase you are about to build:
```jsonc
{
"headline": { "stage": "Phase 3: API layer", "cleared": 0, "total": 9 },
"docs": [
{ "id": "phase", "title": "Phase 3 tasks", "version": 1, "blocks": [
{ "id": "tasks", "state": "settled", "md": "- [ ] **Task 3.1:** ...\n- [ ] **Task 3.2:** ..." }
]},
{ "id": "phasefile", "title": "phase-3.md", "version": 1, "blocks": [
{ "id": "body", "state": "settled", "md": "...the whole phase-3.md file, verbatim..." }
]}
],
"agent": { "status": "working", "activity": "Checking the prerequisites", "quietMinutes": 15 }
}
```
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
progress bar is the first thing someone watching a build looks at.
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
the person can read the prerequisites and task specs while you build. Re-post
it whenever the file changes, which is every task: the checkbox write that
ticks the list above ticks the file too, and the Phase Completion Summary
lands in it at the end. It renders as markdown, so the file's checkboxes show
as ticks exactly as they stand on disk.
---
## While you build
Post after every task, in the same breath as writing its checkbox to disk.
Write the patch file into the session's own folder (the `session` path `open`
printed), never into the project or into `~/.plan2code/console/` directly:
```jsonc
{
"headline": { "cleared": 4 },
"docs": [
{ "id": "phase", "version": 5, "blocks": [ { "id": "tasks", "state": "settled", "md": "...the whole list, 4 ticked..." } ] },
{ "id": "phasefile", "version": 5, "blocks": [ { "id": "body", "state": "settled", "md": "...phase-3.md as it now stands on disk..." } ] }
],
"agent": { "activity": "Task 5 of 9: the rate limiter" }
}
```
- **`activity`** is one plain sentence saying what you are doing now. The page
shows it beside Planny and in place of "questions coming". No internal
vocabulary, no loop completion markers. Number tasks by their position in
the phase, of the phase's task count (`Task 5 of 9`), not by the file's
`5.5`-style labels: the phase is already in the headline. The page rewrites
the old form as a safety net.
- **`quietMinutes`** is how long you might go without posting (1 to 60). The
page calls a working agent stuck after two minutes of silence unless you say
otherwise, and a build task can honestly take twenty. Set it to the longest
gap you expect, usually 10 to 30. Every post is also a heartbeat. **Clear it
(`"quietMinutes": null`) whenever you go back to waiting**: it only counts
while you are `working`, but leaving it set invites a stale value later.
- `blocks` inside a doc are replaced whole, so post the whole task list each
time. It is small. The same goes for `phasefile`: re-read `phase-X.md` and
post it fresh, because the checkbox write just changed it.
- If the task list grows mid-build, raise `headline.total` in the same post;
the page never shows more done than the total, but the bar reads truer when
you keep it current.
- Do not call `wait` while building. There is nothing to collect, and the page
holds anything the person sends until you next look.
### Quick questions between tasks
The person can ask a Quick question on the Ask tab at any point in a build
(console.md → Quick questions). After each task's progress post, check for
one before starting the next task:
```
node "<CONSOLE>" chat --session <sid>
```
| Exit | What you do |
| --- | --- |
| `0` | Answer everything waiting, under console.md → Quick questions, in one post, then start the next task. A `workspace` list in the output is a change to the session's folders (console.md → Workspace): take it into account from the next task on; it needs no reply. |
| `10` | Nothing waiting. Carry on. |
| `20` | The server is gone: `open --resume <sid>` as usual, then carry on. |
This is an instant check, not a wait: it never sleeps and never touches card
sends. It does not replace `wait` at a gate, and no build calls `wait`
mid-build for cards. An approved chat edit is made here, between tasks, never
in the middle of one.
A blocker (`[!]`), a `SPEC NOTE` and a verified or assumed prerequisite are
not questions. Put them in the phase doc as they happen, and in the report.
### When the workflow asks something
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }`, and
go into the wait loop. When the answer lands, set `working` again and carry on.
| Moment | `kind` | Notes |
| --- | --- | --- |
| Several phases can be picked | `choice` | One option per phase, `detail` = status and task count, `token` = the phase number. Put the "run another agent on a different phase" tip in `body`. |
| A phase is already in progress | `confirm` | "Resume Phase 3?" `yes` / `no`. |
| `SPEC CONFLICT` | `choice` or `text` | The conflict in `body`, the readings as options where there are clear ones. Never guess on architecture. |
| Test failures | `choice` | `1` Fix now, `2` Document and proceed, `3` Investigate first. |
| A small phase, continue with the next? | `confirm` | |
| A spec gap only they can close | `text` | |
| Something learned for AGENTS.md | `confirm` | The proposed lines in `consequences`. |
Titles stay plain: "Which phase next", "Tests are failing", "Keep going?".
---
## Sign-off
Put the Completion Report on the page as a doc, then ask for approval as a
`review` item pointing at it. The review offer rides on this card, as a verdict
ahead of the approval buttons — not on the finish after it, where it could
only ever be offered once nothing could come of it:
```jsonc
{
"docs": [{ "id": "report", "title": "Completion report", "version": 1, "blocks": [
{ "id": "summary", "state": "settled", "md": "## Summary\n\n..." },
{ "id": "files", "state": "settled", "md": "## Files\n\n..." },
{ "id": "verify", "state": "settled", "md": "## How to check it\n\n..." }
]}],
"items": [{
"id": "signoff", "kind": "review", "title": "Approve this phase", "doc": "report",
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, or say what to change.",
"verdicts": [
{ "id": "review", "label": "Review the code first" },
{ "id": "approve", "label": "Approve this phase" },
{ "id": "changes", "label": "I want changes" }
],
"token": { "review": "review", "approve": "approved", "changes": "needs changes" },
"nothingYet": "Nothing is marked complete until you approve.",
"gate": { "id": "signoff", "authoritative": true },
"fallbackText": "Reply \"approved\" to mark this phase complete, \"review\" to run the code review first, or describe any issues."
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
`reply` carries `Approve this phase: approved`, which is the terminal's
`approved`. If the note that came with an approval asks for a change, treat it
as "describe any issues": do the change first and ask again. `changes` means
exactly what it says: address it, bump the report's version, 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 — see "The
review, mid-session" below.
`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
sign-off twice.
---
## After approval: the finish
Do everything the workflow does on approval (the checkboxes, the summary, the
upcoming phases, the commit command) and print it in the terminal as usual.
Then post the finish, wait for the dashboard button as console.md → Finishing
says, and `stop`:
```jsonc
{
"items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "approve" } }],
"run": { "event": "implement-phase", "id": "phase-3" },
"finish": {
"headline": "Phase 3 is done",
"body": "9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```",
"command": "/plan2code-3-implement specs/lunch-vote/overview.md",
"doc": "report",
"dashboard": true
},
"agent": { "status": "waiting" }
}
```
`finish.command` is the next pipeline step, the same one the terminal names:
the next `/plan2code-3-implement`, or `/plan2code-4-finalize` after the last
phase. An `implement` finish never carries `review`: the offer was on the
sign-off card, and approving past it was the answer. `implement-review` ends
the same way; that phase was reviewed already. Only a finished `quick-task`
still offers the review on its finish — see below.
`run` scores the approved phase on the session meter (console.md → Posting an
update → Session meter), in the same post that records the approval:
`implement-phase` for Implement, `implement-review-phase` for Implement +
Review, id `phase-N`. Quick task and a standalone Review are counted when
their session opens, so they post no `run` for that; a review run on the page
after a build reports its own (below).
---
## The review, mid-session
The same focused review runs from either of two doors:
- **`implement`:** the `review` verdict on the sign-off card, before anything
is approved. A note sent with it is theirs — read it as focus for the
review. Settle the card with it in the same post that goes back to work:
```jsonc
{
"items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "review" } }],
"headline": { "stage": "Reviewing Phase 3", "cleared": 0, "total": 0 },
"run": { "event": "review", "id": "review" },
"agent": { "status": "working", "activity": "Reviewing the 7 files this phase changed", "quietMinutes": 15 }
}
```
- **`quick-task`:** the **Review it now** button on the finished screen, which
`finish.review` puts there. It arrives through the wait loop as an action
`{ "i": "__review", "type": "review" }`, like any send. Take it up with the
same post minus the `items` line, plus `"finish": null` — that takes the
session off its ending and back to work.
Either way, the post that takes the review up carries `"run": { "event":
"review", "id": "review" }`: the review runs inside this skill's session, so no
launch scores it on the session meter. Never resume the session under
`--workflow review` for it as well, or it counts twice.
A finish carrying `review` keeps the session alive for the answer, so a
`quick-task` that just posted one keeps waiting, for up to about ten minutes.
A quick-task finish carries both `review` and `"dashboard": true` and waits
for whichever comes first:
| What arrives | What you do |
| --- | --- |
| An action `{ "i": "__review", "type": "review" }` | Take the review up (below). |
| An action `{ "i": "__dashboard", "type": "dashboard" }` | Take the session back as the dashboard (console.md → Finishing). |
| An action `{ "i": "__done", "type": "done" }` | `stop` the server. The session is over. |
| `wait` exit `20` | They closed the tab. Do not resume: the session is over. |
| Nothing after about ten minutes | `stop` the server. The page then shows the terminal command for a review instead of a button that would go nowhere. |
**Read references/review.md** and run Review Mode with these overrides:
- **Scope is Focused, and already decided:** the exact change set of this
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.
- **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,
and tables go in the doc.
### The findings
The full Review Mode report as a doc, and the fix choice as one `multi` item:
```jsonc
{
"docs": [{ "id": "review", "title": "Review findings", "version": 1, "blocks": [
{ "id": "report", "state": "settled", "md": "## Overview\n\n...\n\n## Findings\n\n| # | Severity | Issue | File |\n..." }
]}],
"items": [{
"id": "fixes", "kind": "multi", "title": "Which to fix", "required": false, "doc": "review",
"body": "Tick what should be fixed now. Anything left unticked is written up as still open. Nothing changes until you send.",
"options": [
{ "k": "1", "text": "Critical: token is logged in plain text", "detail": "src/auth.ts:42. Fix: redact before logging." },
{ "k": "2", "text": "Warning: missing null check on the user lookup", "detail": "src/users.ts:88. Fix: ..." },
{ "k": "3", "text": "Suggestion: repeated query could be batched", "detail": "src/report.ts:17. Fix: ..." }
],
"presets": [
{ "label": "Critical and warnings", "ks": ["1", "2"] },
{ "label": "All of them", "ks": ["1", "2", "3"] }
],
"token": { "1": "1", "2": "2", "3": "3" },
"fallbackText": "Reply H to fix Critical + Warning findings, A to fix all findings, or S 1,3,5 to fix specific findings."
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
`"doc": "review"` puts a **Read "Review findings" in full** button on the
card, so the report is one click from the list rather than behind a tab
nobody notices. Always carry it.
Read the reply as Review Mode's fix choice: `Which to fix: 1, 2` is `S 1,2`,
every finding ticked is `A`, and `skip` (or nothing ticked) is "fix none,
keep them as unresolved". Leave out `presets` a set would not change (no
warnings, one finding). With **zero findings** there is no item: say so in the
doc and go straight to the way back out.
### Fixing
Settle the `fixes` item in the same post that goes back to work —
`"status": "answered"` with the `answer` they sent (`{ "ks": ["1", "2"] }`,
or `{ "ks": [] }` when nothing was ticked). The server records their send on
the item, but only you decide it is settled; left open it stays on the page
as an outstanding question, beside the card you ask next. Then follow Review
Mode's Post-Fix Flow, posting `activity` per fix ("Fix 2 of 3: the null
check") and `quietMinutes` as in a build.
### The way back out
**`implement` — back to the sign-off.** The review was the preamble to an
approval that has not happened yet, so this is where it lands. Fold the review
results and any still-open findings into the report doc and bump it, then
reopen the sign-off **without the review verdict** — re-offering a review that
just ran reads as though nothing happened:
```jsonc
{
"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": "approve", "label": "Approve this phase" },
{ "id": "changes", "label": "I want changes" }
],
"thread": [{ "who": "agent", "text": "Review done: 2 of 3 findings fixed; the rest is written up in the findings tab." }]
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
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 "After approval: the finish".
**`quick-task` — the closing gate, then the finish.** Review Mode's closing
gate ("Reply approved to commit, or request changes") becomes a `review` item
titled "Check the fixes", `doc: "review"`, verdicts `approve` ("The fixes look
right") and `changes`, token `approved` / `needs changes`. When it clears,
settle it in the same post as the new finish — `"status": "answered"` plus
`"answer": { "verdict": "approve" }` (or `"changes"`) — post the finish
**without** `review`, then `stop`. An item left open survives on the page as
a question still owed, above the ending itself:
- `headline`: "The review is done"
- `body`: findings by severity, what was fixed, what is still open, and the
commit command for the fixes, in the project's commit format.
- `command`: the same next step as the finish before it.
- `doc`: `"review"`.
---
## Implement + Review (`implement-review`)
The same build, then Stage 2 publishes the findings exactly as above (the
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
item: Stage 4 is the only gate. Stage 4 is the sign-off above **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": "implement-review-phase", "id": "phase-N" }`.
---
## Quick task (`quick-task`)
- Open with the first clarifying question. Clarifying questions go out as
`text` or `choice`, at most three at a time.
- Post `"stopWarning": "A quick task saves nothing until it is built, so stopping now loses what we have worked out."`
at the start, and `"stopWarning": ""` once the build is under way.
- **Scope check:** a `choice`, "Too big for a quick task?", options
`1` Continue (lightweight format) and `2` Escalate to a full plan, with the
measured counts against the thresholds in `body`.
- **Feature name** (escalating): `text` with
`"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"` and a kebab-case placeholder.
- **The plan:** a `plan` doc (Summary, Files to change, Steps, Verify) and a
`review` item "Build this plan?" with verdicts `yes` ("Build it"), `modify`
("Change the plan"), `escalate` ("Plan it properly instead") and `abort`
("Stop here", `"danger": true`), token equal to the ids.
- **Building** after `yes`: settle the verdict (`"status": "answered"` plus
`"answer": { "verdict": "yes" }`) in the post that starts the build, then
exactly as "While you build", with the plan's steps
as the task list and `total` = the number of steps.
- **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
`review` on offer — the **Review it now** button, since a quick task has no
sign-off card to put it on. Keep waiting for the answer, and everything
after that is "The review, mid-session" above.
- **Escalated / aborted:** settle the verdict the same way in the finish post —
finish with `"command": "/plan2code-1-plan"` and the
PLAN-DRAFT's path in `body`, no review; or `"command": "/plan2code-quick-task"`.
Both set `"dashboard": true`: an abort of a quick task saves nothing to
resume, so it is not a pause.
---
## Stop requests during a build
The Stop button only works on the person's turn, so it never lands mid-task.
When `__stop` arrives:
- **implement / implement-review:** Implementation Mode's abort, without the
"are you sure" (the page asked): the phase stays `[/]`, list completed and
remaining tasks, post `finish` with the resume command
(`/plan2code-3-implement specs/<feature>/overview.md`), then `stop`. An
implement abort is a pause: a headline starting "Paused", no `dashboard`,
`stop` at once.
- **quick-task:** say in `finish.body` what was worked out, and that nothing was
saved unless it was built; `"command": "/plan2code-quick-task"`.
A mid-build `__dashboard` (the top bar's triangle, console.md → Stop requests →
"Back to the dashboard, mid-workflow") lands the same way, only on the person's
turn. Save exactly as for `__stop` above (an implement phase stays `[/]`), but
post no finish and do not `stop`: resume as the dashboard instead, with one
terminal line naming what was saved and the resume command.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,233 @@
// Plan2Code Web Console - the native folder picker behind Workspace's Browse…
//
// A port of the launcher's picker (src/launcher/plan2code.js). The launcher
// is self-contained CommonJS copied alone to ~/.plan2code/bin/, and this
// console is ESM bundled into every skill, so the two cannot share a module:
// this is a copy, and a drift test in scripts/test-web-console.mjs fails the
// moment the launcher's picker changes without it. The prompt is a parameter
// here rather than the launcher's constant.
//
// Always spawned asynchronously: spawnSync would freeze the server's polling,
// chat and wait for as long as the dialog stayed open.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
const IS_WINDOWS = process.platform === "win32";
const IS_MAC = process.platform === "darwin";
export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace";
// Copied verbatim from src/launcher/plan2code.js; see the drift test.
export const WINDOWS_PICKER_SOURCE = `
using System;
using System.Runtime.InteropServices;
public static class Plan2CodeFolderPicker {
[ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
private class FileOpenDialog {}
[ComImport, Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IFileOpenDialog {
[PreserveSig] int Show(IntPtr owner);
void SetFileTypes(uint count, IntPtr specs);
void SetFileTypeIndex(uint index);
void GetFileTypeIndex(out uint index);
void Advise(IntPtr events, out uint cookie);
void Unadvise(uint cookie);
void SetOptions(uint options);
void GetOptions(out uint options);
void SetDefaultFolder(IShellItem item);
void SetFolder(IShellItem item);
void GetFolder(out IShellItem item);
void GetCurrentSelection(out IShellItem item);
void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
void GetResult(out IShellItem item);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem {
void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
void GetParent(out IShellItem parent);
void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name);
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
private static extern void SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid iid, out IShellItem item);
private const uint FOS_PICKFOLDERS = 0x20;
private const uint FOS_FORCEFILESYSTEM = 0x40;
private const uint FOS_PATHMUSTEXIST = 0x800;
private const uint SIGDN_FILESYSPATH = 0x80058000;
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
public static string Pick(IntPtr owner, string title, string start) {
IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
try {
uint options;
dialog.GetOptions(out options);
dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
dialog.SetTitle(title);
if (!string.IsNullOrEmpty(start)) {
try {
Guid iid = typeof(IShellItem).GUID;
IShellItem folder;
SHCreateItemFromParsingName(start, IntPtr.Zero, ref iid, out folder);
dialog.SetFolder(folder);
} catch (Exception) {}
}
int hr = dialog.Show(owner);
if (hr == ERROR_CANCELLED) return null;
Marshal.ThrowExceptionForHR(hr);
IShellItem result;
dialog.GetResult(out result);
string path;
result.GetDisplayName(SIGDN_FILESYSPATH, out path);
return path;
} finally {
Marshal.ReleaseComObject(dialog);
}
}
}
`;
// Resolve a command on PATH the way the shell would, including PATHEXT on Windows.
function findOnPath(command) {
const dirs = (process.env.PATH || "").split(path.delimiter).filter(Boolean);
const extensions = IS_WINDOWS ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [""];
for (const dir of dirs) {
for (const ext of extensions) {
const candidate = path.join(dir.replace(/^"|"$/g, ""), command + ext);
try {
if (fs.statSync(candidate).isFile()) return candidate;
} catch {}
}
}
return null;
}
/**
* The native folder picker for this OS, as a command to run: it prints the
* chosen folder, or nothing when the person cancels. Null when this OS has no
* picker we can drive.
*/
export function pickerCommand(start, prompt) {
if (IS_WINDOWS) {
const script = [
"$ErrorActionPreference = 'Stop'",
"try {",
" [Console]::OutputEncoding = [Text.Encoding]::UTF8",
" Add-Type -AssemblyName System.Windows.Forms",
" [System.Windows.Forms.Application]::EnableVisualStyles()",
// A TopMost owner keeps the dialog in front of the console window that launched it.
" $owner = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true; ShowInTaskbar = $false }",
" try {",
" Add-Type -TypeDefinition $env:PLAN2CODE_PICKER_SOURCE",
" $picked = [Plan2CodeFolderPicker]::Pick($owner.Handle, $env:PLAN2CODE_PICKER_PROMPT, $env:PLAN2CODE_PICKER_START)",
" } catch {",
// Add-Type is blocked under Constrained Language Mode and some AppLocker policies; the
// old tree dialog still works there.
" $dialog = New-Object System.Windows.Forms.FolderBrowserDialog",
" $dialog.Description = $env:PLAN2CODE_PICKER_PROMPT",
" $dialog.SelectedPath = $env:PLAN2CODE_PICKER_START",
" $picked = if ($dialog.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { $dialog.SelectedPath } else { $null }",
" }",
" if ($picked) { $picked }",
"} catch { exit 3 }",
].join("\n");
return {
command: "powershell.exe",
args: [
"-NoProfile",
"-NonInteractive",
"-STA",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
Buffer.from(script, "utf16le").toString("base64"),
],
env: {
PLAN2CODE_PICKER_PROMPT: prompt,
PLAN2CODE_PICKER_START: start,
PLAN2CODE_PICKER_SOURCE: WINDOWS_PICKER_SOURCE,
},
};
}
if (IS_MAC) {
return {
command: "osascript",
args: [
"-e",
"on run argv",
"-e",
`POSIX path of (choose folder with prompt "${prompt}" default location (POSIX file (item 1 of argv)))`,
"-e",
"end run",
start,
],
};
}
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return null;
if (findOnPath("zenity")) {
return {
command: "zenity",
args: ["--file-selection", "--directory", `--title=${prompt}`, `--filename=${start}${path.sep}`],
};
}
if (findOnPath("kdialog")) {
return { command: "kdialog", args: ["--title", prompt, "--getexistingdirectory", start] };
}
return null;
}
/**
* Show the picker and settle on what the person did: `{ path }` for a pick,
* `{ cancelled: true }` when they closed it, `{ error }` when the picker
* itself failed or this OS has none. Pickers exit 0 or 1 with nothing printed
* when cancelled.
*/
export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
const picker = pickerCommand(start, prompt);
if (!picker) return Promise.resolve({ error: "picker-failed" });
return new Promise((resolve) => {
let settled = false;
const settle = (result) => {
if (settled) return;
settled = true;
resolve(result);
};
let child;
try {
child = spawnImpl(picker.command, picker.args, {
env: { ...process.env, ...(picker.env || {}) },
// stderr is ignored, not piped: a pipe nobody reads fills up and
// blocks a chatty picker (GTK warnings) before it can exit.
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
});
} catch {
return settle({ error: "picker-failed" });
}
let stdout = "";
if (child.stdout) {
child.stdout.setEncoding?.("utf8");
child.stdout.on("data", (chunk) => (stdout += chunk));
}
child.on("error", () => settle({ error: "picker-failed" }));
child.on("close", (code) => {
const folder = stdout.trim();
if (code === 0 && folder) return settle({ path: path.resolve(folder) });
if (!folder && (code === 0 || code === 1)) return settle({ cancelled: true });
settle({ error: "picker-failed" });
});
});
}
@@ -0,0 +1,971 @@
// The page's pure logic: what the person answered, and what they asked for, in
// the words those things have to reach the agent as.
//
// Everything here is a pure function of an item and a value. That is the point
// of the file: app.js cannot be loaded outside a browser (it touches `document`
// at module scope and starts a session on import), so any logic that stays in
// it is logic no test can reach. Three defects in this exact code got as far as
// the screen before anyone noticed. It lives here so `node --test` can see it.
//
// No DOM, no `local`, no fetch. If a function in here needs any of those, it
// belongs in app.js instead.
/* ----------------------------------------------------- the sent answer */
/**
* The value an in-flight send carries, or null if it carries no answer.
*
* A send can be a note on its own: someone asks a question about the question
* before answering it. That still goes in `local.sent`, because the note really
* is on its way, but it must NOT make the page treat the question as answered
* and lock the form. They have not answered it yet, and locking them out is how
* an open question becomes unanswerable.
*/
export function sentAnswer(sent) {
return sent && sent.value ? sent.value : null;
}
/**
* What the person settled on, for a question that is no longer open.
*
* `answer` is what the agent recorded when it settled the question. `submitted`
* is what the server wrote down the moment Send was pressed. The second exists
* because the first depends on the agent remembering to do it, and a card that
* says "Settled" above an empty form is the worst thing this page can show.
*/
export function recordedAnswer(item) {
const a = item && item.answer && typeof item.answer === "object" ? item.answer : null;
const s = item && item.submitted && typeof item.submitted === "object" ? item.submitted : null;
if (!a && !s) return null;
return { ...(s || {}), ...(a || {}) };
}
/**
* A send the person made that the agent never settled, still sitting on an
* OPEN question.
*
* `local.sent` covers this while the same tab is alive; `submitted` is the
* server's own record of the send and survives a reload, a resume onto a new
* port, and a second tab. An open item that carries one, and has had no agent
* reply since, is "sent, waiting on Plan2Code" — not a question still
* waiting for them, which is what it reads as when an agent takes the answer
* and moves on without marking the item settled.
*
* Two ways out, both meaning the question is theirs again:
*
* - an agent message in the item's thread AFTER the send means the question
* is being asked again — the person gets a live form back, not a locked
* record of what they already said;
* - a recorded `answer` means the agent did settle it at some point (the
* status is just stale or the question was re-asked), so the leftover
* `submitted` is the old send, not one in flight.
*/
export function submittedAwaiting(item) {
const s = item && item.submitted;
if (!s || typeof s !== "object") return null;
if (item.answer && typeof item.answer === "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
return replied ? null : s;
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
const o = ((item && item.options) || []).find((x) => x.k === k);
if (!o) return String(k);
return o.k ? `${o.k} · ${o.text}` : o.text;
}
export function verdictLabel(item, id) {
const list = (item && item.verdicts) || [
{ id: "approve", label: "Looks good, go ahead" },
{ id: "changes", label: "I want changes" },
];
const v = list.find((x) => x.id === id);
return v ? verdictText(v) : String(id);
}
// A verdict's button text. `label` is the contract; `text` is what menu
// options use, and an agent that borrows it must not get blank buttons.
export function verdictText(v) {
return v.label || v.text || v.id;
}
export const CHECK_STATE_LABEL = {
done: "All done",
blocked: "I am stuck",
help: "I need help",
defer: "Later",
};
/**
* The answer as lines to show back, in the page's words rather than the
* agent's shorthand: "A · Run the setup first", not "a".
*/
export function answerLines(item, v) {
const out = [];
if (!v) return out;
if (v.skipped) out.push("Skipped");
if (v.k) out.push(optionLabel(item, v.k));
if (Array.isArray(v.ks)) for (const k of v.ks) out.push(optionLabel(item, k));
if (typeof v.yes === "boolean") out.push(v.yes ? item.yesLabel || "Yes" : item.noLabel || "No");
if (typeof v.ok === "boolean") {
out.push(v.ok ? item.yesLabel || "Yes, that is right" : item.noLabel || "Not quite");
}
if (v.verdict) out.push(verdictLabel(item, v.verdict));
if (v.state) out.push(CHECK_STATE_LABEL[v.state] || String(v.state));
if (Array.isArray(v.done) && v.done.length) {
out.push(`Steps done: ${v.done.map((n) => n + 1).join(", ")}`);
}
if (Array.isArray(v.rows) && v.rows.length) {
out.push(`${v.rows.length} steps, in the order you set`);
}
return out;
}
/**
* A single-choice answer, which is one thing or the other and never both.
*
* Picking an option and then writing "none of these, because…" used to send
* both, joined, with the pick first: an answer that argued with itself. The
* rule lives here rather than in the two click handlers that apply it, so it
* is one statement that a test can hold to.
*
* Returns null when there is nothing to stage, which is what "they have not
* answered yet" looks like everywhere else in the page.
*/
export function choiceAnswer({ k, text } = {}) {
if (k) return { type: "answer", kind: "choice", k };
const said = String(text || "").trim();
return said ? { type: "answer", kind: "choice", text: said } : null;
}
/* -------------------------------------------------------- the brief ask */
/**
* The words a brief request reaches the agent as.
*
* This is not an answer, but it is the same kind of thing and it belongs to the
* same rule: a string the agent parses, so it has to be exactly right, so it
* has to be somewhere a test can see it. `range` is the Pathfinder brief
* playbook's own grammar -- `today`, `this week`, `since <YYYY-MM-DD>`, `full`.
*/
export function briefPhrase(range) {
const r = String(range || "today").trim();
if (r === "full") return "Write a full brief.";
if (r.startsWith("since ")) return `Write a brief covering everything ${r}.`;
return `Write a brief for ${r}.`;
}
/* ---------------------------------------------------- the autofill text */
// A placeholder is a suggestion nobody can edit, and it vanishes the moment you
// type. On a question whose example is most of a good answer, retyping it is
// busywork, so offer it as a value instead. The lead-in ("For example:") is the
// agent talking about the example, not part of it, so it is stripped.
//
// Two rules keep the stripping from mangling a real answer:
//
// The lead-in must be FOLLOWED by a separator. Without that, "Egypt office"
// loses its "Eg" and "Exampled output" loses its "Example".
//
// A bare hyphen only separates when it has space around it. "For example - a"
// is a lead-in; the hyphen in "example-name-here" is part of the name, and a
// kebab-case suggestion must survive intact for a field with a `pattern`.
//
// "Say" is deliberately not in the list: "Say when you need it by" is a
// question far more often than it is a preamble.
const EXAMPLE_LEAD =
/^\s*(?:for\s+(?:example|instance)|examples?|such\s+as|e\.?\s?g\.?|i\.?\s?e\.?)(?:\s+-\s+|\s*[:,.]\s*|\s+)/i;
/**
* The placeholder, as a value someone could accept as their own answer.
* Empty string when there is nothing worth offering.
*/
export function suggestionFrom(item) {
const raw = String((item && item.placeholder) || "").trim();
if (!raw) return "";
const stripped = raw.replace(EXAMPLE_LEAD, "").trim();
if (!stripped) return "";
// Recapitalise only when a lead-in was actually removed, and never on a
// field with a shape to match: "audit-export" must not become "Audit-export".
if (stripped !== raw && !item.pattern && /^[a-z]/.test(stripped)) {
return stripped[0].toUpperCase() + stripped.slice(1);
}
return stripped;
}
/* ------------------------------------------------------ the hand-off */
// The badge each workflow wears. Shared with the server, which writes it into
// the page it serves so the first paint already names the session instead of
// flashing a placeholder until the script arrives.
export const WORKFLOW_LABEL = {
dashboard: "Dashboard",
init: "Setting up",
"init-update": "Refreshing",
pathfinder: "Pathfinder",
plan: "Planning",
"revise-plan": "Revising the plan",
document: "Documenting",
implement: "Building",
"implement-review": "Building + review",
review: "Review",
"quick-task": "Quick task",
finalize: "Wrapping up",
handoff: "Handoff",
};
export function workflowLabel(workflow) {
return WORKFLOW_LABEL[workflow] || workflow || "Session";
}
// The workflows that ship the console (install.js bundles it into every
// skill as `additionalReferences`). Any other next step has no browser page
// to open, and asking for one would send the next session looking for
// something that is not there.
export const CONSOLE_WORKFLOWS = [
"/plan2code",
"/plan2code-init",
"/plan2code-init-update",
"/plan2code-0-pathfinder",
"/plan2code-quick-task",
"/plan2code-1-plan",
"/plan2code-1b-revise-plan",
"/plan2code-2-document",
"/plan2code-3-implement",
"/plan2code-3-implement-review",
"/plan2code-review",
"/plan2code-4-finalize",
"/plan2code-handoff",
];
// Rides on the end of the command as part of the skill's argument. Every
// console skill takes it as the answer to "web console or terminal?" instead
// of asking again. It must stay clear of "brief", "recap" and "minutes":
// pathfinder reads any of those in its argument as a request for a brief.
export const CONTINUE_IN_CONSOLE = "--web";
// The long form the skills still accept. A command that carries it is copied
// with the flag instead, which is shorter and reads as the parameter it is.
const CONSOLE_SENTENCE = /\s*Use the web console for this session\.?/gi;
/**
* What the Copy button on the finished screen puts on the clipboard.
*
* Someone who worked the whole session in the browser should land back in the
* browser, not be asked the interface question as though they were new. The
* `--web` flag goes on the same line as the command, because what follows a
* slash command is its argument, and a pasted second line is not reliably that.
* A command written with the long sentence is copied with the flag instead.
*
* `fin.console` overrides the inference either way; otherwise it follows from
* whether the next step is a workflow that has a console at all.
*/
export function handoffText(fin) {
const raw = String((fin && fin.command) || "").trim();
if (!raw) return "";
const cmd = raw.replace(CONSOLE_SENTENCE, "").trim();
const capable =
typeof fin.console === "boolean"
? fin.console
: cmd !== raw || CONSOLE_WORKFLOWS.some((w) => cmd === w || cmd.startsWith(w + " "));
// An agent that already wrote the flag should not get it twice.
if (!capable || /(^|\s)--web\b/.test(cmd)) return cmd;
return `${cmd} ${CONTINUE_IN_CONSOLE}`;
}
/**
* A finish is a pause when its headline says so. There is no flag to read:
* the stop playbook asks the agent to write "a headline that says it is
* paused rather than done", so the page reads the same words the person
* does. A session that ends on its own says nothing of the sort.
*/
export function finishPaused(fin) {
return /^\s*paused\b/i.test(String((fin && fin.headline) || ""));
}
// The line a finished session shows when it has nothing left to run. Split so
// the page can render the backticked command as code; joined with a space they
// read as one sentence.
export const ALL_DONE_LEAD = "All done, nothing left to run.";
export const ALL_DONE_REST = "To start something else, run `/plan2code` in a new conversation to open the dashboard.";
export const DASHBOARD_COMMAND = "/plan2code";
/**
* Which hand-off a finish gets: a pause always offers its resume command, a
* finish with a command offers it as the next step, and one without has
* nothing left to run.
*/
export function handoffShape(fin) {
if (finishPaused(fin)) return "paused";
return String((fin && fin.command) || "").trim() ? "next" : "all-done";
}
/* ------------------------------------------------------------ stopping */
// What a stop request reads as, the way a typed message would. It goes to the
// agent as part of `reply`, so the same caution applies as to the hand-off
// sentence: nothing Pathfinder would read as asking for a brief.
export const STOP_REPLY = "Stop here and save my place, so I can pick this up later.";
/**
* Why a session-level button (Stop session, Back to the dashboard) cannot be
* pressed right now, or null when it can. Both wait for the person's turn:
* while Plan2Code has the ball it may be halfway through writing their last
* answers into the files, and a request landing then is how a question ends up
* half recorded. `waiting` is the caller's "the agent is working or a reply is
* owed, and it has not gone adrift" -- an agent that has stopped checking in
* never replies, and a button greyed out forever would lock the person in. An
* uncollected send still blocks even then, because the server takes one at a
* time.
*/
export function turnGate({ gone = false, pendingResult = false, waiting = false } = {}) {
if (gone) return "gone";
if (pendingResult) return "pending";
if (waiting) return "waiting";
return null;
}
// What the top bar's Back to the dashboard button reads as to the agent. It
// goes in `reply` like the stop, so the same caution applies: nothing
// Pathfinder would read as asking for a brief.
export const HOME_REPLY = "Save my place and take me back to the dashboard, right here in this session.";
const HOME_TITLES = {
gone: "Not connected right now.",
pending: "Your last answers are still being picked up. You can leave once they have been.",
waiting: "Plan2Code is working on your answers. You can leave once it replies.",
};
/**
* The top bar's Back to the dashboard button. Hidden on the dashboard itself,
* on a finished screen (which carries its own way back) and while a stop is
* under way; otherwise pressable on the person's turn, like Stop session.
* Once pressed it waits for the page to turn, unless the agent has gone
* adrift: then it comes back, and a second press is safe because the server
* refuses a duplicate while the first is uncollected.
*/
export function homeButtonState({ workflow, finished = false, stopping = false, homeward = false, adrift = false, ...turn } = {}) {
if (!workflow || workflow === "dashboard" || finished || stopping) return { hidden: true, disabled: true, title: "" };
if (homeward && !adrift) return { hidden: false, disabled: true, title: "Opening the dashboard…" };
const gate = turnGate(turn);
return {
hidden: false,
disabled: Boolean(gate),
title: gate ? HOME_TITLES[gate] : "Back to the dashboard. Your place is saved first.",
};
}
/**
* The resume command the PAGE can offer when the agent cannot: it stopped
* listening, or went away without posting a finish. Built only from what the
* session state says, never guessed.
*
* Pathfinder resumes from its folder, so it needs `specDir` (`specs/<idea>`),
* which the workflow posts once the folder exists. Without one the bare
* command still works: Pathfinder asks which idea. Planning finds its own
* draft and takes no path. The implementation steps, Revision and
* Finalization take the spec's overview.md, and without it they ask which
* spec (or find the only one). A quick task keeps nothing on disk to resume
* from, so its command starts it again.
*/
export function resumeCommand({ workflow, specDir } = {}) {
const raw = String(specDir || "").trim().replace(/\\/g, "/").replace(/\/+$/, "");
// Only a real relative specs/ path. Anything else would be run verbatim by
// someone with no way to tell it was wrong.
const dir = /^specs\/[a-z0-9][a-z0-9._-]*$/i.test(raw) ? raw : "";
const withOverview = (cmd) => (dir ? `${cmd} ${dir}/overview.md` : cmd);
switch (workflow) {
case "dashboard":
return "/plan2code";
case "init":
return "/plan2code-init";
case "init-update":
return "/plan2code-init-update";
case "plan":
return "/plan2code-1-plan";
case "quick-task":
return "/plan2code-quick-task";
case "document":
return withOverview("/plan2code-2-document");
case "implement":
return withOverview("/plan2code-3-implement");
case "implement-review":
return withOverview("/plan2code-3-implement-review");
case "review":
return "/plan2code-review";
case "revise-plan":
return withOverview("/plan2code-1b-revise-plan");
case "finalize":
return withOverview("/plan2code-4-finalize");
case "handoff":
return "/plan2code-handoff";
default:
return dir ? `/plan2code-0-pathfinder ${dir}/pathfinder` : "/plan2code-0-pathfinder";
}
}
/* ------------------------------------------------ after a build is done */
// What the two buttons on a finished build's hand-off reach the agent as. They
// go in `reply` like any typed message, so the same caution applies as to the
// other session phrases: plain words, nothing Pathfinder would read as a brief.
export const REVIEW_REPLY =
"Review what was just built before I go: run the focused code review on this session's changes, here on the page.";
export const DONE_REPLY = "No review, thanks. I am done: close the session.";
export const DASHBOARD_REPLY = "Take me back to the dashboard, right here in this session.";
// Shown under the Back to the dashboard button: the press picks up in the same
// conversation, which carries a long skill's context into the next one.
export const DASHBOARD_NOTE =
"This picks up in the same conversation. That's fine after a quick or small skill; after a long one, type `/clear` in your terminal and run `/plan2code` for a clean start.";
/**
* Whether a finish offers the way back to the dashboard. The agent opts in
* with `finish.dashboard: true`, so a skill that predates the button never
* shows one nobody answers; a pause never offers it.
*/
export function dashboardOffer(fin) {
return Boolean(fin && fin.dashboard === true && !finishPaused(fin));
}
/**
* Whether a finish carries the offer to review what was just built. The agent
* posts `finish.review` as `true` or as `{ "label": "..." }` on a finished
* quick task (an implementation phase offers the review earlier, as a verdict
* on its sign-off card).
*/
export function reviewOffer(fin) {
const r = fin && fin.review;
if (!r) return null;
const label = typeof r === "object" && typeof r.label === "string" ? r.label.trim() : "";
return { label: label || "Review what was just built" };
}
/* ------------------------------------------------------- the dashboard */
// The skills the dashboard offers, in the order it offers them. The page owns
// this list rather than the session state: the catalog is product UI, fixed
// for everyone, and the alternative — the agent posting it — would put a dozen
// cards of boilerplate through the patch channel every time the menu opened.
// `menu` in the state can still say what the agent knows: a `recommend` skill
// to highlight and a `details` line per card ("Phase 2 of 4 is next").
//
// `workflow` is the name the skill resumes the session under: the dashboard
// hands its session over, and this is what turns the page into that skill's
// console. A test holds this list against the skills install.js builds, so a
// new skill cannot ship without a card here.
export const CATALOG_GROUPS = [
{ id: "setup", title: "First, the project" },
{ id: "pipeline", title: "The steps, in order" },
{ id: "extra", title: "Useful any time" },
];
// `spec: true` marks the cards that take a spec folder as their target: when
// the picker has a spec selected, its `dir` rides along in the `__launch`
// action so the launched skill knows which spec it was picked for.
export const SKILL_CATALOG = [
{
skill: "plan2code-init",
command: "/plan2code-init",
workflow: "init",
group: "setup",
chip: "Set up",
title: "Set up this project",
blurb: "Reads your project and writes AGENTS.md, the guide every later step works from.",
about:
"Plan2Code reads the whole project: how it is organized, how it runs, and where the sharp edges are. Then it writes AGENTS.md, the guide every later step steers by. It asks a few questions as it goes, so nothing important gets guessed. Run this once per project, or again when the project has moved on.",
},
{
skill: "plan2code-init-update",
command: "/plan2code-init-update",
workflow: "init-update",
group: "setup",
chip: "Set up",
title: "Refresh AGENTS.md",
blurb: "Brings AGENTS.md and its notes up to date with what the project has learned lately.",
about:
"The project moved on since AGENTS.md was written: new commands, new habits, new gotchas. This re-reads the project, asks what changed, and folds it into AGENTS.md and the notes beside it. Cheaper than a fresh setup, and whatever is still right is kept.",
},
{
skill: "plan2code-0-pathfinder",
command: "/plan2code-0-pathfinder",
workflow: "pathfinder",
group: "pipeline",
chip: "Step 0",
spec: true,
title: "Pathfinder",
blurb: "A foggy idea becomes a clear list of decisions, settled one question at a time.",
about:
"You have a rough idea and a lot of unknowns. Pathfinder asks one question at a time: who it is for, what it must do, what could go wrong. Each answer is written down in a spec folder. It ends with a list of decisions clear enough to plan from, and nothing gets built yet.",
},
{
skill: "plan2code-1-plan",
command: "/plan2code-1-plan",
workflow: "plan",
group: "pipeline",
chip: "Step 1",
spec: true,
title: "Plan",
blurb: "Requirements, technical design and your approval: the shape of what gets built.",
about:
"Turns what you bring into a real plan: a finished Pathfinder map, a folder of design notes, or just the idea in your head. You get requirements, a technical design, a phase-by-phase breakdown, and a final version to approve before anything is built. This is where 'what are we building' becomes 'how it gets built'.",
},
{
skill: "plan2code-1b-revise-plan",
command: "/plan2code-1b-revise-plan",
workflow: "revise-plan",
group: "pipeline",
chip: "Step 1b",
spec: true,
title: "Revise the plan",
blurb: "Requirements changed mid-build? Adjust the plan without starting over.",
about:
"Requirements moved mid-build: a feature added, a rule dropped, a deadline pulled in. This adjusts the existing spec for the change, shows you what it affects, and only rewrites what actually has to move. The approved plan stays the plan.",
},
{
skill: "plan2code-2-document",
command: "/plan2code-2-document",
workflow: "document",
group: "pipeline",
chip: "Step 2",
spec: true,
title: "Document",
blurb: "The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do.",
about:
"Writes the plan as numbered phase files. Each phase is a checklist of tasks small enough to just do, with the details a builder needs right there. This is the file the build step works from, and the thing a later session can pick up cold.",
},
{
skill: "plan2code-3-implement",
command: "/plan2code-3-implement",
workflow: "implement",
group: "pipeline",
chip: "Step 3",
spec: true,
title: "Implement",
blurb: "Builds the next phase, task by task, with a report and your sign-off at the end.",
about:
"Builds the next phase of the spec. Tasks get checked off one by one, with progress and the occasional decision landing on this page as it goes. It ends with a report of what was built and a sign-off card you approve before the phase counts as done.",
},
{
skill: "plan2code-3-implement-review",
command: "/plan2code-3-implement-review",
workflow: "implement-review",
group: "pipeline",
chip: "Step 3",
spec: true,
title: "Implement + review",
blurb: "One phase built, then a careful review of the changes, then your sign-off. All in one run.",
about:
"The same build as Implement, with a review folded in before sign-off. The phase is built, then a fresh pass hunts for problems in exactly what changed, you pick what gets fixed, and only then does the sign-off card arrive.",
},
{
skill: "plan2code-4-finalize",
command: "/plan2code-4-finalize",
workflow: "finalize",
group: "pipeline",
chip: "Step 4",
spec: true,
title: "Finalize",
blurb: "Checks the work, writes the summary, files the specs away and suggests the commit message.",
about:
"The closer. Checks every task against the spec, makes sure the build actually works, writes the summary into overview.md, updates the project docs, and suggests the commit message. Run it when the feature is done. It leaves the project tidy behind it.",
},
{
skill: "plan2code-quick-task",
command: "/plan2code-quick-task",
workflow: "quick-task",
group: "extra",
chip: "Utility",
title: "Quick task",
blurb: "Too small for the full process? A quick plan, then it just builds it.",
about:
"A fix, a tweak, a small feature. Not worth a spec folder. Describe it, confirm the one-line plan, and it builds it right there, with a report at the end. The fast lane for work the full process would over-plan.",
},
{
skill: "plan2code-review",
command: "/plan2code-review",
workflow: "review",
group: "extra",
chip: "Utility",
title: "Review",
blurb: "A second opinion on the changes. Problems ranked, and you pick what gets fixed.",
about:
"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",
group: "extra",
chip: "Utility",
title: "Handoff",
blurb: "Pack this conversation 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
// screens that speak of it as a thing being started rather than as a badge.
export function workflowTitle(workflow) {
const entry = SKILL_CATALOG.find((e) => e.workflow === workflow);
return entry ? entry.title : workflowLabel(workflow);
}
// Every skill gets its own Planny on the starting and waiting screens, drawn
// as a <template data-pose> in index.html. A skill that is a variant of
// another borrows its pose. Anything else (the dashboard) keeps the flight.
export const START_POSES = [
"init",
"pathfinder",
"plan",
"document",
"implement",
"finalize",
"quick-task",
"review",
"handoff",
];
const POSE_ALIASES = { "init-update": "init", "revise-plan": "plan", "implement-review": "implement" };
export function startPose(workflow) {
const pose = POSE_ALIASES[workflow] || workflow;
return START_POSES.includes(pose) ? pose : null;
}
export function catalogEntry(skill) {
return SKILL_CATALOG.find((e) => e.skill === skill) || null;
}
/* ------------------------------------------- dashboard card availability */
// 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 = {
exploring: "Exploring",
mapped: "Ready to plan",
planned: "Ready to document",
documented: "Ready to build",
building: "Building",
built: "Ready to finalize",
unrecognized: "Files on disk",
};
// 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 = {
exploring: "plan2code-0-pathfinder",
mapped: "plan2code-1-plan",
planned: "plan2code-2-document",
documented: "plan2code-3-implement",
building: "plan2code-3-implement",
built: "plan2code-4-finalize",
};
const ON = { on: true };
const off = (reason) => ({ on: false, reason });
/**
* Whether a catalog card is clickable for the current picker selection.
*
* `scan` is the server's project scan ({ hasAgents, specs }); `sel` is the
* picked spec object or null for "start from scratch". A spec whose files
* match no pipeline shape ("unrecognized") behaves like no spec at all for
* availability — but its folder still goes along on a Pathfinder or Plan
* launch, since the files may be reference docs.
*
* Returns { on, reason?, next? } — `reason` is the one line a greyed card
* shows, `next` marks the state's natural step.
*/
export function cardAvailability(entry, scan, sel) {
const hasAgents = Boolean(scan && scan.hasAgents);
const state = sel && sel.state && sel.state !== "unrecognized" ? sel.state : null;
const next = sel ? Boolean(state) && NEXT_FOR_STATE[state] === entry.skill : entry.skill === "plan2code-0-pathfinder";
switch (entry.skill) {
case "plan2code-init":
return hasAgents ? off("AGENTS.md is already written. Refresh it instead.") : ON;
case "plan2code-init-update":
return hasAgents ? ON : off("Needs an AGENTS.md. Set the project up first.");
case "plan2code-quick-task":
case "plan2code-review":
case "plan2code-handoff":
return ON;
case "plan2code-0-pathfinder":
if (!state || state === "exploring") return { ...ON, next };
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 === "documented" || state === "building" || state === "built")
return off("The plan is written. Revise it instead if it moved.");
return { ...ON, next };
case "plan2code-1b-revise-plan":
if (state === "documented" || state === "building") return ON;
return off(state === "built" ? "The spec is fully built" : "Needs a spec that is already written up");
case "plan2code-2-document":
if (state === "planned") return { ...ON, next };
if (state === "documented" || state === "building" || state === "built")
return off("The phases are already written up");
return off("Needs a drafted plan first");
case "plan2code-3-implement":
case "plan2code-3-implement-review":
if (state === "documented" || state === "building") return { ...ON, next };
return off(state === "built" ? "All tasks are already done" : "Needs the phase checklists written up first");
case "plan2code-4-finalize":
if (state === "built") return { ...ON, next };
return off("Needs a spec that is fully built");
default:
return ON;
}
}
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 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);
const supplied = initial && menu.details && typeof menu.details[entry.skill] === "string" ? menu.details[entry.skill] : "";
const detail = availability.on && supplied ? supplied : !initial && availability.next && sel && sel.detail ? sel.detail : "";
return { ...availability, recommended, detail };
}
/**
* What a card click reaches the agent as, in `reply`. The action itself
* carries `skill`, which is what the dashboard parses; this line is the
* human-readable record of the ask. Like the other session phrases it keeps
* clear of "brief", "recap" and "minutes", which Pathfinder would read as a
* brief request.
*/
export function launchReply(entry, spec) {
const target = spec && spec.dir ? ` for ${spec.dir}` : "";
return `Start ${entry.title} (${entry.command})${target}, right here in this session.`;
}
export function staleLaunchFeedback(title, adrift) {
if (!adrift) return null;
return {
kicker: "Saved",
title: `${title || "Your workflow"} is saved and waiting`,
quip: "Plan2Code is not running right now.",
hint: "Return to the terminal and send any message. Plan2Code will collect this launch and continue here.",
};
}
/* ------------------------------------------------------------ progress */
// The label must never read "7 of 5", whatever the agent posted: a build that
// grew tasks mid-phase can post a `cleared` past its `total`. Guarded here on
// the page only; the server takes the numbers as sent.
export function progressTotal(cleared, total) {
return Math.max(Number(cleared) || 0, Number(total) || 0);
}
/* --------------------------------------------------------- attachments */
// Attachments on a note or a quick question: at most five, images and
// documents together. Images are re-encoded in the browser to a JPEG whose
// long edge fits IMAGE_LONG_EDGE, with a small data: URL copy for the tray.
// Documents upload byte for byte, and the server checks their contents itself.
export const MAX_ATTACHMENTS = 5;
export const MAX_NOTE_IMAGES = MAX_ATTACHMENTS;
export const MAX_DOC_BYTES = 10 * 1024 * 1024;
// The documents an agent can read with its own file tool, keyed by lower-case
// extension. A hard-coded list, like the server's TYPES: it is the picker's
// `accept`, the server's allow-list and the chip's label, so they can never
// disagree.
const textDoc = (label) => Object.freeze({ kind: "text", label });
export const DOC_TYPES = Object.freeze({
md: textDoc("Markdown"),
txt: textDoc("Text"),
json: textDoc("JSON"),
yaml: textDoc("YAML"),
yml: textDoc("YAML"),
toml: textDoc("TOML"),
ini: textDoc("INI"),
csv: textDoc("CSV"),
tsv: textDoc("TSV"),
log: textDoc("Log"),
xml: textDoc("XML"),
html: textDoc("HTML"),
css: textDoc("CSS"),
scss: textDoc("SCSS"),
js: textDoc("JavaScript"),
mjs: textDoc("JavaScript"),
cjs: textDoc("JavaScript"),
ts: textDoc("TypeScript"),
tsx: textDoc("TypeScript"),
jsx: textDoc("JavaScript"),
py: textDoc("Python"),
java: textDoc("Java"),
cs: textDoc("C#"),
go: textDoc("Go"),
rs: textDoc("Rust"),
rb: textDoc("Ruby"),
php: textDoc("PHP"),
sh: textDoc("Shell"),
ps1: textDoc("PowerShell"),
sql: textDoc("SQL"),
pdf: Object.freeze({ kind: "pdf", label: "PDF" }),
});
// A file name's document extension, or null. A name whose only dot leads it
// (`.env`, `.gitignore`) has no extension: dotfiles are where secrets live.
export function docExt(name) {
const s = String(name || "");
const dot = s.lastIndexOf(".");
if (dot <= 0 || dot === s.length - 1) return null;
const ext = s.slice(dot + 1).toLowerCase();
return Object.prototype.hasOwnProperty.call(DOC_TYPES, ext) ? ext : null;
}
// The file picker's `accept`: any image, plus every document extension.
export function pickerAccept() {
return "image/*," + Object.keys(DOC_TYPES).map((ext) => "." + ext).join(",");
}
export function formatBytes(n) {
const bytes = Number(n) || 0;
if (bytes < 1024) return `${bytes} B`;
const mb = bytes >= 1024 * 1024;
return new Intl.NumberFormat(undefined, {
style: "unit",
unit: mb ? "megabyte" : "kilobyte",
maximumFractionDigits: mb ? 1 : 0,
}).format(mb ? bytes / (1024 * 1024) : bytes / 1024);
}
// An entry saved before documents existed has no `kind`: it is an image.
export function attachmentKind(entry) {
return entry && entry.kind === "file" ? "file" : "image";
}
// Files the person picked, pasted or dropped, sorted by what they will be.
// The extension decides first: browsers report `""` for `.md` and
// `video/mp2t` for `.ts`, so `type` only settles what has no document
// extension. Each list keeps the order given.
export function sortAttachments(files) {
const images = [];
const docs = [];
const refused = [];
for (const file of files || []) {
if (docExt(file.name)) {
if (file.size > MAX_DOC_BYTES) refused.push({ name: file.name, reason: "too-large" });
else docs.push(file);
} else if (typeof file.type === "string" && file.type.startsWith("image/")) images.push(file);
else refused.push({ name: file.name, reason: "type" });
}
return { images, docs, refused };
}
export const IMAGE_LONG_EDGE = 2000;
export const IMAGE_QUALITY = 0.85;
export const THUMB_EDGE = 160;
// Scaled so the longer side is at most `max`, aspect kept, never upscaled.
export function fitWithin(w, h, max) {
const scale = Math.min(1, max / Math.max(w, h));
return { w: Math.round(w * scale), h: Math.round(h * scale) };
}
// A note's action, its attachments split into `images` and `files`. Only
// `path` and `name` go: the page's own bookkeeping (`id`, `url`, `status`) is
// nothing the agent can use. A key with nothing in it is left out.
export function noteAction(id, text, attachments) {
const action = { i: id, type: "comment", text };
const list = attachments || [];
const pick = (kind) => list.filter((a) => attachmentKind(a) === kind).map(({ path, name }) => ({ path, name }));
const images = pick("image");
const files = pick("file");
if (images.length) action.images = images;
if (files.length) action.files = files;
return action;
}
// A note as `reply` lines, one indented `Image:` or `File:` line per
// attachment in the order attached, so the agent can open each path with its
// file-read tool. An image-only note reads exactly as it always did.
export function noteReplyLines(title, text, attachments) {
const list = attachments || [];
const anyFile = list.some((a) => attachmentKind(a) === "file");
const said = text || (list.length ? (anyFile ? "(attachments only)" : "(images only)") : "");
return [
`Note on ${title}: ${said}`,
...list.map((a) => ` ${attachmentKind(a) === "file" ? "File" : "Image"}: ${a.path} (${a.name})`),
];
}
/* ------------------------------------------------------------ patience */
/**
* How long the agent may go quiet before the page calls it stuck.
*
* Every workflow before the build steps was a conversation: the agent was
* either thinking about a reply or sitting in `wait`, so two or three minutes
* of silence really did mean something had gone wrong. A build is different.
* One task can take twenty minutes of honest work with nothing to post, and a
* page that said "has not checked in, look at your terminal" every time would
* be crying wolf. So the agent says how long quiet is normal right now
* (`agent.quietMinutes`), and it counts only while the agent is `working`: a
* waiting agent is polling, and a silent poller is still a stuck one. Never
* below the page's own threshold, and capped at an hour so a typo cannot hide
* a dead session.
*/
export function quietLimitMs(agent, baseMs) {
if (!agent || agent.status !== "working") return baseMs;
const m = Number(agent.quietMinutes);
if (!Number.isFinite(m) || m <= 0) return baseMs;
return Math.max(baseMs, Math.min(m, 60) * 60 * 1000);
}
/* ---------------------------------------------------------- skip moves on */
// "Skip this one" moves the person on by itself. `staged` and `sent` are maps
// keyed by item id: a card staged or already sent no longer needs them.
const needsPerson = (id, staged, sent) => !(staged && staged[id]) && !(sent && sent[id]);
/** True when no open card other than `currentId` still needs the person. */
export function lastOpenCard(openIds, staged, sent, currentId) {
return openIds.every((id) => id === currentId || !needsPerson(id, staged, sent));
}
/**
* The next open card after `currentId` that still needs the person, wrapping
* to the start; null when there is none.
*/
export function nextOpenAfter(openIds, staged, sent, currentId) {
const at = openIds.indexOf(currentId);
for (let step = 1; step <= openIds.length; step++) {
const id = openIds[(at + step) % openIds.length];
if (id !== currentId && needsPerson(id, staged, sent)) return id;
}
return null;
}
/* ------------------------------------------------------------ approvals */
// The page cannot see a harness's permission prompt, so it nudges instead: a
// quiet tip line where a session starts, and a soft line beside Planny once a
// working agent has gone quiet for a while. Mode names verified 2026-09-23.
export const APPROVAL_TIP =
"Your agent may pause for approvals in the terminal. A hands-off mode (e.g. `auto` mode in Claude Code, `smart` mode in Devin) can help avoid that, but additional attention may still be required.";
export const APPROVAL_HINT = "Still working, or waiting on an approval in your terminal?";
export const APPROVAL_HINT_MS = 30_000;
// When a working agent's silence turns into "has not checked in".
export const STALE_MS = 2 * 60 * 1000;
// The soft line, shown before the stale message takes over. It sits at a fixed
// share of the stale limit (30 s of 2 min) rather than stretching on its own:
// stretched separately, a build's quietMinutes lifted both to the same moment
// and the soft line never showed where approvals stall most.
export function approvalHint(agent, quietMs) {
if (!agent || agent.status !== "working") return "";
const at = quietLimitMs(agent, STALE_MS) * (APPROVAL_HINT_MS / STALE_MS);
return quietMs >= at ? APPROVAL_HINT : "";
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,117 @@
// Planny's wake-up on a freshly opened dashboard: he sits powered down centre
// stage until the first click or key, gets nudged awake (he rocks side to side
// for one snore), then about five seconds of him powering on, then a glide
// into the rail as the menu comes in.
//
// The beats before the glide are pure CSS (keyframes on delays under
// `.wake.booting`, see app.css). The glide is the one part CSS cannot know on
// its own, because it ends wherever the rail's Planny sits right now, so this
// measures it once and hands CSS a single transform through --wake-glide.
//
// No DOM access at module scope, so `node --test` can import it.
// When the glide starts, and when the run is over at the latest. The CSS
// delays are the beats before GLIDE_AT_MS; the glide itself is 0.6 s.
export const GLIDE_AT_MS = 4300;
export const DONE_AT_MS = 5000;
// Plays the wake-up and resolves `{ skipped }` once the dashboard is fully
// awake. He waits powered down until the first click or key anywhere, which
// nudges him (`.stirring`) and calls `stir()` -- the page's cue to play one
// full snore, since a browser only lets a page make noise after a real click
// or keypress. The boot starts once the promise `stir()` returns settles (at
// once without one), and calls `onStart()`, the page's cue for the boot-up
// sound. `onGlide({ instant })` is the page's cue to bring the menu in: called
// at the glide, or with `instant: true` if the run ends before one (a skip).
// From the nudge on, clicks and keys are swallowed, so the run always plays
// out to the end with its sound; only `signal` aborting (the page leaving the
// dashboard, dormant or mid-run) cuts it short, as a skip. Under reduced
// motion nothing is shown and it resolves at once.
export function playWake({ stage, bot, target, stir, onStart, onGlide, signal }) {
return new Promise((resolve) => {
if (matchMedia("(prefers-reduced-motion: reduce)").matches || signal?.aborted) {
resolve({ skipped: false });
return;
}
const timers = [];
let glided = false;
let over = false;
const onGlideEnd = (e) => {
if (e.target === bot && e.propertyName === "transform") end(false);
};
const skip = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through.
const swallow = (e) => {
if (e.ctrlKey || e.metaKey || e.altKey) return;
e.preventDefault();
e.stopPropagation();
};
function glide() {
glided = true;
// Measured untransformed, as the sketch's glideToSlot() does: the
// transform-origin is the drawing's top-left, so the move is the gap
// between the two top-left corners and the scale is the width ratio.
// The target's own box, not its bounding rect: the rail's Planny is
// usually tilted mid-flight, and a tilted box measures wider than he
// is. Centred on the rect, which the tilt barely moves.
const from = bot.getBoundingClientRect();
const rect = target.getBoundingClientRect();
const w = target.clientWidth || rect.width;
const h = target.clientHeight || rect.height;
const left = rect.left + (rect.width - w) / 2;
const top = rect.top + (rect.height - h) / 2;
const scale = from.width ? w / from.width : 1;
bot.style.setProperty("--wake-glide", `translate(${left - from.left}px, ${top - from.top}px) scale(${scale})`);
bot.addEventListener("transitionend", onGlideEnd);
stage.classList.add("gliding");
onGlide({ instant: false });
}
function end(skipped) {
if (over) return;
over = true;
for (const t of timers) clearTimeout(t);
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
document.removeEventListener("pointerdown", swallow, true);
document.removeEventListener("keydown", swallow, true);
bot.removeEventListener("transitionend", onGlideEnd);
signal?.removeEventListener("abort", skip);
stage.hidden = true;
stage.classList.remove("dormant", "stirring", "booting", "gliding");
bot.style.removeProperty("--wake-glide");
if (!glided) onGlide({ instant: true });
resolve({ skipped });
}
// The waking click is the only input the run takes: from here on every
// click and key is swallowed until it ends.
function start(e) {
e.preventDefault();
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
stage.classList.replace("dormant", "stirring");
document.addEventListener("pointerdown", swallow, true);
document.addEventListener("keydown", swallow, true);
Promise.resolve(stir?.()).then(boot);
}
function boot() {
if (over) return;
stage.classList.replace("stirring", "booting");
onStart?.();
timers.push(setTimeout(glide, GLIDE_AT_MS));
// The glide's transitionend normally ends the run a touch earlier; this
// is the fallback for a transition that never fires (a hidden tab).
timers.push(setTimeout(() => end(false), DONE_AT_MS));
}
document.addEventListener("pointerdown", start, true);
document.addEventListener("keydown", start, true);
signal?.addEventListener("abort", skip);
stage.hidden = false;
stage.classList.add("dormant");
});
}
@@ -0,0 +1,224 @@
// Plan2Code Web Console - the Quick question chat's shared rules.
//
// Imported by the server (its guards) and by the page (its composer), so the
// two can never disagree about a limit. No DOM access at module scope, and no
// imports but answers.js: the server and `node --test` import this file too.
import { MAX_ATTACHMENTS, STALE_MS, quietLimitMs } from "./answers.js";
// Typed messages per conversation. Approve / Decline and resets never count.
export const CHAT_LIMIT = 10;
export const CHAT_MAX_CHARS = 4000;
// Images and documents together. The old name stays for existing imports.
export const CHAT_MAX_ATTACHMENTS = MAX_ATTACHMENTS;
export const CHAT_MAX_IMAGES = CHAT_MAX_ATTACHMENTS;
export const CHAT_LIMIT_TEXT = "That's 10 questions in this conversation — start a new one to keep going.";
export const CHAT_OFFLINE_TEXT = "No agent available — wait for one to become available (your terminal might be working on a task or waiting a permission approval)";
export const CHAT_LAST_WAIT_TEXT = "That was the last question in this conversation — its answer will land here.";
export const CHAT_WAITING_TEXT = "Plan2Code will answer at its next check-in";
export const CHAT_WORKING_TEXT = "Plan2Code is working on the answer…";
const EMPTY_CHAT = { conversation: 0, messages: [], typed: 0, limit: CHAT_LIMIT, offline: false, pickedUp: 0 };
const chatOf = (frameChat) => ({ ...EMPTY_CHAT, ...(frameChat || {}) });
// Person messages in the frame, each marked with whether an agent reply comes
// after it. The server puts a reply straight after the entry it answers, so a
// reply further down also covers the follow-ups sent before it.
function answeredFlags(messages) {
const flags = new Map();
let replyLater = false;
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m.from === "agent") replyLater = true;
else if (m.kind === "message") flags.set(m.seq, replyLater);
}
return flags;
}
/**
* What the Ask pane draws, in order: the conversation from the frame, then
* any send of this page's the server has not echoed yet.
*/
export function chatView(frameChat, ui = {}) {
const chat = chatOf(frameChat);
const messages = Array.isArray(chat.messages) ? chat.messages : [];
const answered = answeredFlags(messages);
const decisions = new Map(
messages.filter((m) => m.from === "person" && m.kind === "decision").map((m) => [m.re, m.decision])
);
const activity = typeof ui.agentActivity === "string" ? ui.agentActivity.trim() : "";
// The last seq the agent collected: an unanswered message at or below it is
// in the agent's hands, not still waiting for a check-in.
const pickedUp = Number.isInteger(chat.pickedUp) ? chat.pickedUp : 0;
const rows = [];
for (const m of messages) {
if (m.from === "agent") {
rows.push({
kind: "agent",
id: m.id,
md: m.md,
proposal: m.proposal || null,
changed: m.changed || null,
decided: decisions.get(m.id) || null,
});
} else if (m.kind === "decision") {
rows.push({ kind: "decision", decision: m.decision, text: m.text || "", re: m.re });
} else if (m.kind === "message") {
const row = {
kind: "person",
seq: m.seq,
text: m.text,
about: m.about || null,
images: m.images || [],
files: m.files || [],
};
if (!answered.get(m.seq)) {
row.waiting = true;
row.working = m.seq <= pickedUp;
row.waitingText = row.working ? CHAT_WORKING_TEXT : CHAT_WAITING_TEXT;
if (activity) row.activity = activity;
}
rows.push(row);
}
}
// A pending send is echoed once the server has it: by the seq its POST came
// back with, or, while that response is still on its way, by its text
// against a server message no other pending send has claimed.
const serverPerson = messages.filter((m) => m.from === "person" && m.kind === "message");
const serverSeqs = new Set(serverPerson.map((m) => m.seq));
const claimed = new Set((ui.pendingSends || []).filter((p) => p.seq).map((p) => p.seq));
for (const p of ui.pendingSends || []) {
if (p.seq) {
if (serverSeqs.has(p.seq)) continue;
} else {
const echo = serverPerson.find((m) => m.text === p.text && !claimed.has(m.seq));
if (echo) {
claimed.add(echo.seq);
continue;
}
}
rows.push({
kind: "person",
pending: true,
tempId: p.tempId,
text: p.text,
about: p.about || null,
images: p.images || [],
files: p.files || [],
failed: Boolean(p.failed),
});
}
return {
conversation: chat.conversation,
rows,
counterText: `${chat.typed} of ${chat.limit}`,
typed: chat.typed,
limit: chat.limit,
};
}
/**
* Whether the composer can take a message, and what to say when it cannot.
* Offline first, so a finished page never talks about the limit. The limit
* lands once the 10th question is answered; until then the 10th is simply
* waiting, and nothing more can be typed.
*/
export function sendState({ frameChat, gone, pendingSendCount = 0 }) {
const chat = chatOf(frameChat);
if (chat.offline || gone) return { state: "offline", text: CHAT_OFFLINE_TEXT, canType: false };
if (chat.typed + pendingSendCount >= chat.limit) {
const allAnswered = pendingSendCount === 0 && [...answeredFlags(chat.messages || []).values()].every(Boolean);
if (allAnswered) return { state: "limit", text: CHAT_LIMIT_TEXT, canType: false };
return { state: "ok", text: CHAT_LAST_WAIT_TEXT, canType: false };
}
return { state: "ok", text: "", canType: true };
}
const ABOUT_HISTORY = 3;
/**
* What a message is about, attached on purpose. Visiting a question card, doc
* section or spec only records it in `history` (the last 3 places, newest
* first, one entry per place); `about` is set only when the person picks one
* from + Add context, and × or a send clears it.
*
* The tracker is `{ history, about }`; each entry and `about` are
* `{ kind, id, label }` (`about` may be null), in the exact shape POST /chat
* takes. An old `{ about, frozen, dropped }` tracker normalises to an empty
* history.
*/
export function nextAbout(prev, event) {
const p = prev || {};
const state = { history: Array.isArray(p.history) ? [...p.history] : [], about: p.about ?? null };
const visit = (entry) => ({
...state,
history: [entry, ...state.history.filter((h) => h.kind !== entry.kind || h.id !== entry.id)].slice(0, ABOUT_HISTORY),
});
switch (event && event.type) {
case "card":
return visit({ kind: "card", id: String(event.id), label: String(event.label || "") });
case "section":
return visit({ kind: "section", id: `${event.docId}#${event.blockId}`, label: String(event.label || "") });
case "spec":
return visit({ kind: "spec", id: String(event.dir), label: String(event.label || "") });
case "pick":
return event.about ? { ...state, about: event.about } : state;
case "drop":
case "sent":
return { ...state, about: null };
default:
return state;
}
}
// What + Add context lists: the recent places, then "This spec" unless it is
// already one of them.
export function contextOptions(state, spec) {
const options = [...((state && state.history) || [])];
if (spec && spec.dir && !options.some((o) => o.kind === "spec" && o.id === spec.dir)) {
options.push({ kind: "spec", id: spec.dir, label: "This spec" });
}
return options;
}
const newestReply = (frameChat) => {
const messages = chatOf(frameChat).messages || [];
for (let i = messages.length - 1; i >= 0; i--) if (messages[i].from === "agent") return messages[i];
return null;
};
// The Ask tab's dot: a reply landed that the person has not seen.
export function unreadDot({ lastSeenReplyId, frameChat, viewIsAsk }) {
if (viewIsAsk) return false;
const reply = newestReply(frameChat);
return Boolean(reply) && reply.id !== lastSeenReplyId;
}
export function newestReplyId(frameChat) {
const reply = newestReply(frameChat);
return reply ? reply.id : null;
}
// One chime per reply: only the moment the dot appears.
export function shouldChime(prevDot, nextDot) {
return !prevDot && Boolean(nextDot);
}
// The page's own "has drifted away" threshold for an agent that is waiting.
const ADRIFT_MS = 3 * 60 * 1000;
/**
* Whether nobody is there to answer a chat message. A finished or paused
* session has no agent coming back to it; otherwise the agent is offline once
* it has been silent longer than the page would tolerate before calling it
* stuck (working) or adrift (anything else).
*/
export function chatOffline({ finish, agent, agentLastSeenMs, now }) {
if (finish) return true;
const silent = now - agentLastSeenMs;
if (agent && agent.status === "working") return silent > quietLimitMs(agent, STALE_MS);
return silent > quietLimitMs(agent, ADRIFT_MS);
}
@@ -0,0 +1,90 @@
// Plan2Code Web Console - the tab icon's status bar.
//
// The favicon follows the status line with a bar along its bottom edge: dashed
// amber while Plan2Code is busy, solid green when it is the person's move,
// solid red when it needs attention, and none (the plain Planny) once the
// session is finished. It reads from the same calls
// renderStatus() already makes for Planny's mood, so the icon and the line
// beside him can never disagree. No DOM access at module scope: `node --test`
// imports this file.
// Planny exactly as public/favicon.svg draws him (a test keeps the two in
// step), minus the <svg> wrapper so the bar can be layered on top.
export const FAVICON_BODY = `<rect x="4" y="4.6" width="24" height="30" rx="5" fill="#fff4ef" stroke="#3b332c" stroke-width="2.2" />
<path d="M16 9.8 L17.41 13.26 L21.14 13.53 L18.28 15.94 L19.17 19.57 L16 17.6 L12.83 19.57 L13.72 15.94 L10.86 13.53 L14.59 13.26 Z" fill="#ae4f2b" />
<path d="M11.6 22.2 Q16 26.4 20.4 22.2" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />`;
// The bar's color per state. `plain` has none.
export const FAVICON_COLORS = Object.freeze({
busy: "#f5a524",
ready: "#22c55e",
attention: "#e5484d",
});
/**
* Which icon a status line calls for. `mood` and `spin` are what renderStatus()
* handed to say(): `spin` marks something really happening at the other end
* right now, so that is busy. A working mood without the spin is the stale
* line ("has not checked in for a few minutes"), which, like adrift and gone,
* needs attention. `point` is the person's move. A finished session is plain
* unless it is visibly busy again (opening the dashboard, starting a review).
*/
export function faviconState({ mood, spin = false, finished = false } = {}) {
if (spin) return "busy";
if (finished) return "plain";
if (mood === "adrift" || mood === "gone" || mood === "work") return "attention";
if (mood === "point") return "ready";
return "plain";
}
/**
* The whole SVG for a state: Planny, plus a bar across the bottom edge, where
* he is cropped anyway. Busy's bar is dashed on a white strip (a progress bar
* mid-run) and the others solid, so busy differs by pattern as well as color:
* amber and green are close to one color for red-green color-blind eyes.
*/
export function faviconSvg(state) {
const color = FAVICON_COLORS[state];
let badge = "";
if (state === "busy") {
badge = `\n <rect x="0" y="27" width="32" height="5" fill="#ffffff" />\n <path d="M1.5 29.5 L30.5 29.5" stroke="${color}" stroke-width="4" stroke-dasharray="4 2.5" />`;
} else if (color) {
badge = `\n <rect x="0" y="27" width="32" height="5" rx="1" fill="${color}" />`;
}
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">\n ${FAVICON_BODY}${badge}\n</svg>\n`;
}
let shown = "plain";
/**
* Point the page's two icon links at `state`'s icon, only when it changed. The
* SVG link takes the variant as a data URL; the PNG link, for browsers that
* pick the bitmap, gets the same variant drawn through a canvas. Plain goes
* back to the served files.
*/
export function setFavicon(state) {
if (state === shown || typeof document === "undefined") return;
shown = state;
const svgLink = document.querySelector('link[rel="icon"][type="image/svg+xml"]');
const pngLink = document.querySelector('link[rel="icon"][type="image/png"]');
if (state === "plain") {
if (svgLink) svgLink.href = "/favicon.svg";
if (pngLink) pngLink.href = "/favicon.png";
return;
}
const url = "data:image/svg+xml," + encodeURIComponent(faviconSvg(state));
if (svgLink) svgLink.href = url;
if (!pngLink) return;
const img = new Image();
img.onload = () => {
// A newer state won the race while this one was loading.
if (shown !== state) return;
try {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 64;
canvas.getContext("2d").drawImage(img, 0, 0, 64, 64);
pngLink.href = canvas.toDataURL("image/png");
} catch {}
};
img.src = url;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<rect x="4" y="4.6" width="24" height="30" rx="5" fill="#fff4ef" stroke="#3b332c" stroke-width="2.2" />
<path d="M16 9.8 L17.41 13.26 L21.14 13.53 L18.28 15.94 L19.17 19.57 L16 17.6 L12.83 19.57 L13.72 15.94 L10.86 13.53 L14.59 13.26 Z" fill="#ae4f2b" />
<path d="M11.6 22.2 Q16 26.4 20.4 22.2" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />
</svg>

After

Width:  |  Height:  |  Size: 443 B

@@ -0,0 +1,65 @@
// Plan2Code Web Console - the Help dialog's tab list and rules.
//
// The source of truth for which tabs Help has, in what order, and which one
// opens. The content itself is HTML in <template id="help-content">
// in index.html. No DOM access at module scope and no imports: the page and
// `node --test` both import this file.
const tab = (id, label, diagram) => Object.freeze({ id, label, diagram });
export const HELP_TABS = Object.freeze([
tab("about", "What this page is", true),
tab("around", "Finding your way around", true),
tab("workspace", "Your workspace", false),
tab("planny", "Reading Planny", true),
tab("answering", "Answering questions", false),
tab("sending", "Sending and what happens next", true),
tab("notes", "Notes and attachments", false),
tab("docs", "Documents and printing", false),
tab("dashboard", "The dashboard", true),
tab("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("ask", "Ask a quick question", false),
tab("finishing", "Stopping and finishing", false),
tab("stuck", "When something looks stuck", true),
tab("prefs", "Keyboard and preferences", false),
tab("privacy", "Privacy and where things are saved", false),
]);
// Not labels.js's BUILD_WORKFLOWS: that one leaves out quick-task, which is a
// build as far as the person watching it is concerned.
const HELP_BUILD_WORKFLOWS = new Set(["implement", "implement-review", "quick-task"]);
// Which tab Help opens on, from where the person is. First match wins.
export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow, workspace, meterRed } = {}) {
const v = view || "";
// Finished comes first: a finished session's server is stopped on purpose,
// which also sets `gone`, and that is not something being stuck.
if (finished || v === "end") return "finishing";
if (gone || adrift) return "stuck";
if (workspace) return "workspace";
if (v === "ask") return "ask";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v.startsWith("doc:")) return "docs";
if (HELP_BUILD_WORKFLOWS.has(workflow)) return "build";
return "about";
}
// The tab index a key moves to, or -1 when the key is not a tab key.
export function helpKeyTarget(key, index, count) {
switch (key) {
case "ArrowDown":
case "ArrowRight":
return (index + 1) % count;
case "ArrowUp":
case "ArrowLeft":
return (index - 1 + count) % count;
case "Home":
return 0;
case "End":
return count - 1;
default:
return -1;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,31 @@
// Activity-line wording the page corrects on the way in. Kept out of app.js so
// `node --test` can import it: no DOM access at module scope.
//
// A build numbers its tasks "Task 4.2" after the phase, but a person watching
// the page counts within the phase, so "Task 4.2 of 6" reads as nonsense
// beside a progress bar that says 2 of 6.
// The only workflows whose activity lines get rewritten.
export const BUILD_WORKFLOWS = new Set(["implement", "implement-review"]);
const PHASE_TASK = /^Task (\d+)\.(\d+) of (\d+)/;
export function taskLabel(text) {
if (typeof text !== "string" || !PHASE_TASK.test(text)) return text;
return text.replace(PHASE_TASK, (_, _phase, n, total) => `Task ${n} of ${total}`);
}
// An activity line as the page shows it: rewritten in a build, as sent
// everywhere else (a plan's "Task 2.1" is a real section number).
export function activityLabel(text, workflow) {
return BUILD_WORKFLOWS.has(workflow) ? taskLabel(text) : text;
}
// What a working agent is doing, for a page with nothing asked yet: its
// activity line, or the headline note it posted instead. Either one means the
// skill has started, so the page leaves its starting screen.
export function workingLine(agent, headline, workflow) {
if (!agent || agent.status !== "working") return "";
if (typeof agent.activity === "string" && agent.activity.trim()) return activityLabel(agent.activity.trim(), workflow);
return typeof headline?.note === "string" ? headline.note.trim() : "";
}
@@ -0,0 +1,41 @@
// Plan2Code Web Console - `@name` suggestions in a text box.
//
// Finds the `@partial` the caret sits in, filters the workspace's folder
// names against it, and splices a pick back into the text. The page owns the
// popover; this file owns the rules. No DOM access at module scope and no
// imports: the page and `node --test` both import this file.
const NAME_CHAR = /[a-z0-9-]/;
const MAX_MATCHES = 6;
/**
* The mention the caret is in: `{ start, query }`, where `start` is the index
* of the `@`, or null. The `@` must open the text or follow whitespace or
* `(`, so an email address never offers suggestions.
*/
export function mentionAt(text, caret) {
let i = caret;
while (i > 0 && NAME_CHAR.test(text[i - 1])) i--;
const at = i - 1;
if (at < 0 || text[at] !== "@") return null;
if (at > 0 && !/[\s(]/.test(text[at - 1])) return null;
return { start: at, query: text.slice(i, caret) };
}
// Names starting with the query first, then names containing it, in the
// order given, at most six.
export function matchNames(names, query) {
const q = String(query || "");
const prefix = names.filter((n) => n.startsWith(q));
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
return [...prefix, ...inside].slice(0, MAX_MATCHES);
}
// The text with `@partial` replaced by `@name `, and the caret after the space.
export function applyMention(text, caret, mention, name) {
const insert = `@${name} `;
return {
text: text.slice(0, mention.start) + insert + text.slice(caret),
caret: mention.start + insert.length,
};
}
@@ -0,0 +1,98 @@
// Plan2Code Web Console - the session meter's weights, count and wording.
//
// The source of truth for how much each piece of work weighs, how the count
// is folded out of ledger.ndjson, and what the pill says at each level. The
// count is never stored: it is always pointsFrom() over the ledger. No DOM
// access at module scope and no imports: the server, console.mjs, the page
// and `node --test` all import this file.
// The one place the weights live (FR-12). Tune here.
export const WEIGHTS = Object.freeze({
"pathfinder-chart": 2,
"pathfinder-question": 1,
plan: 2,
"revise-plan": 1,
document: 2,
"implement-phase": 2,
"implement-review-phase": 3,
review: 2,
"quick-task": 1,
init: 2,
"init-update": 2,
finalize: 1,
handoff: 0,
});
// 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.
export const LAUNCH_COUNTED = Object.freeze(
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize"])
);
// The event names an agent may report in `run`.
export const RUN_EVENTS = new Set(Object.keys(WEIGHTS));
const weightOf = (key) => (Object.prototype.hasOwnProperty.call(WEIGHTS, key) ? WEIGHTS[key] : 0);
/**
* The session's points, folded from ledger entries in order. An id seen
* before is skipped, so a repeated `post` never counts twice.
*/
export function pointsFrom(entries) {
const seen = new Set();
let points = 0;
for (const entry of Array.isArray(entries) ? entries : []) {
if (!entry || typeof entry !== "object") continue;
if (entry.id !== undefined) {
if (seen.has(entry.id)) continue;
seen.add(entry.id);
}
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) points += weightOf(entry.workflow);
else if (entry.kind === "run") points += weightOf(entry.event);
}
return points;
}
export const YELLOW_AT = 4;
export const RED_AT = 6;
export const RING_FULL = 8;
export function levelFor(points) {
if (points < YELLOW_AT) return "green";
if (points < RED_AT) return "yellow";
return "red";
}
// How much of the ring is filled: full at RING_FULL, never below empty.
export function ringFraction(points) {
return Math.max(0, Math.min(points, RING_FULL)) / RING_FULL;
}
export const WORDS = Object.freeze({
green: "Session: fresh",
yellow: "Session: getting long",
red: "Session: time for a fresh start",
});
export function tooltipFor(points) {
const count = `${points} ${points === 1 ? "point" : "points"}`;
switch (levelFor(points)) {
case "green":
return `This session is fresh (${count}).`;
case "yellow":
return `This session is getting long (${count}). A fresh one will soon be sharper.`;
default:
return `This session has done a lot (${count}). The agent may start missing things.`;
}
}
export const RED_BANNER =
"This console session has done a lot. Starting a new console session will keep the agent sharp.";
// Everything the pill draws, from the ledger alone.
export function meterView(entries) {
const points = pointsFrom(entries);
const level = levelFor(points);
return { points, level, fraction: ringFraction(points), words: WORDS[level], tooltip: tooltipFor(points) };
}
@@ -0,0 +1,3 @@
{
"type": "module"
}
@@ -0,0 +1,238 @@
// The highlight colors, as data. Kept out of app.js for one reason: app.js
// cannot be imported outside a browser, and thirty-two colors each with four
// shades in two themes is far too many to trust to eyeballing. The test suite
// imports this and checks every one.
//
// The palette has three colors that MEAN something -- green settled, amber
// waiting, red careful. The reds, golds and greens here are offered anyway,
// because people asked for them; the help text in the dialog says what they
// share a hue with, and the choice is theirs.
//
// Each accent is four values, not one, because one color cannot do four jobs:
// fill the highlight itself: filled buttons, the marker on the open step
// soft a tint faint enough to sit behind body text
// ink what is legible ON the fill. Dark mode's accents are light shades,
// where a white label falls to about 2:1; they take a near-black.
// line the secondary: borders, badge edges, the dashed drop target.
//
// Every pair clears 4.5:1 for ink on fill and for fill on soft (the fill is
// also badge text on the soft tint). Everything after the first five was
// found by stepping lightness until both held, not picked by eye.
//
// Order is the order of the picker: round the wheel, then the greys. Sixteen
// a row, so the warm half and the greens sit on the first, the blues, purples,
// pinks and greys on the second.
export const ACCENTS = {
// name fill soft ink line
crimson: {
name: "Crimson",
light: ["#cd1d41", "#fbe9ed", "#ffffff", "#dcaab4"],
dark: ["#e75874", "#321b1f", "#140b0d", "#743e49"],
},
scarlet: {
name: "Scarlet",
light: ["#cf2317", "#fbebe9", "#ffffff", "#ddaaa7"],
dark: ["#eb594e", "#321c1b", "#140b0b", "#74403c"],
},
coral: {
name: "Coral",
light: ["#c83510", "#fbede9", "#ffffff", "#dcaca0"],
dark: ["#ef5b37", "#321f1b", "#140d0b", "#6f4237"],
},
rust: {
name: "Rust",
light: ["#ae4f2b", "#fbeee7", "#ffffff", "#dd9b7e"],
dark: ["#e8825a", "#34211a", "#1a120e", "#8a4f36"],
},
tangerine: {
name: "Tangerine",
light: ["#b15209", "#fbf1e9", "#ffffff", "#d9af8f"],
dark: ["#f2700d", "#32251b", "#140f0b", "#664830"],
},
copper: {
name: "Copper",
light: ["#a2592f", "#f9f0eb", "#ffffff", "#cdb2a2"],
dark: ["#cb7a4b", "#32231b", "#140e0b", "#5f493d"],
},
clay: {
name: "Clay",
light: ["#8d644c", "#f5f2f0", "#ffffff", "#bfafa6"],
dark: ["#ba957f", "#2b2521", "#17100c", "#62544b"],
},
marigold: {
name: "Marigold",
light: ["#9a6406", "#fbf5e9", "#ffffff", "#d3b279"],
dark: ["#f59f0a", "#32291b", "#14110b", "#5e4c2c"],
},
gold: {
name: "Gold",
light: ["#896b09", "#fbf7e9", "#ffffff", "#ccb66d"],
dark: ["#f0bb0f", "#322c1b", "#14120b", "#584d2a"],
},
mustard: {
name: "Mustard",
light: ["#806f1b", "#fbf8ea", "#ffffff", "#c3b881"],
dark: ["#d2b72d", "#322e1b", "#14120b", "#544e31"],
},
olive: {
name: "Olive",
light: ["#72742c", "#f8f8ed", "#ffffff", "#b8ba8c"],
dark: ["#b5b946", "#31321b", "#14140b", "#4f5037"],
},
lime: {
name: "Lime",
light: ["#577a1a", "#f4fbea", "#ffffff", "#a6c07a"],
dark: ["#96d22d", "#29321b", "#11140b", "#465230"],
},
moss: {
name: "Moss",
light: ["#577740", "#f2f6ee", "#ffffff", "#acbca1"],
dark: ["#79a659", "#24321b", "#0f140b", "#475140"],
},
emerald: {
name: "Emerald",
light: ["#207e47", "#ebfaf1", "#ffffff", "#8ac4a2"],
dark: ["#33cc73", "#1b3224", "#0b140f", "#345542"],
},
jade: {
name: "Jade",
light: ["#297c61", "#ecf9f4", "#ffffff", "#92c1b1"],
dark: ["#40bf95", "#1b322a", "#0b1411", "#38544b"],
},
teal: {
name: "Teal",
light: ["#0f766e", "#e2f1ef", "#ffffff", "#6fb3aa"],
dark: ["#5ecfc0", "#14302c", "#0b1a18", "#3a7d74"],
},
cyan: {
name: "Cyan",
light: ["#0f798a", "#ebf7f9", "#ffffff", "#75bec9"],
dark: ["#19cae6", "#183034", "#0c1617", "#305f66"],
},
sky: {
name: "Sky",
light: ["#0e74a7", "#ebf5fa", "#ffffff", "#85b9d3"],
dark: ["#21a9ed", "#182b35", "#0c1417", "#325c71"],
},
ocean: {
name: "Ocean",
light: ["#206cc3", "#ecf2f9", "#ffffff", "#9ab4d3"],
dark: ["#619fe5", "#1a2533", "#0c1117", "#3d5978"],
},
navy: {
name: "Navy",
light: ["#24396b", "#eef0f7", "#ffffff", "#a7b3cd"],
dark: ["#819ad5", "#1e232f", "#0c1017", "#4a5775"],
},
cobalt: {
name: "Cobalt",
light: ["#405ce7", "#ebeef9", "#ffffff", "#a8b0dc"],
dark: ["#7b8fef", "#191d34", "#0c0e17", "#465392"],
},
indigo: {
name: "Indigo",
light: ["#4f46e5", "#ecebfb", "#ffffff", "#9b95ef"],
dark: ["#a5a0ff", "#1e1d3a", "#121129", "#5f5ba8"],
},
violet: {
name: "Violet",
light: ["#7f4dd5", "#f1edf8", "#ffffff", "#bbabd6"],
dark: ["#a785e2", "#231c31", "#100c17", "#624c87"],
},
lilac: {
name: "Lilac",
light: ["#8b51b8", "#f3eff6", "#ffffff", "#beaccb"],
dark: ["#b189cf", "#271f2d", "#130c17", "#634f73"],
},
orchid: {
name: "Orchid",
light: ["#a141b9", "#f5eef7", "#ffffff", "#c5a8cc"],
dark: ["#c281d3", "#2b1e2f", "#150c17", "#6c4b74"],
},
magenta: {
name: "Magenta",
light: ["#b82eaa", "#f8edf7", "#ffffff", "#d1a3cc"],
dark: ["#dc72d1", "#311c2f", "#170c16", "#784573"],
},
plum: {
name: "Plum",
light: ["#8a3b6b", "#f8eaf2", "#ffffff", "#c88cb0"],
dark: ["#e08ab8", "#331a29", "#1d1017", "#8a5570"],
},
rose: {
name: "Rose",
light: ["#c42e6a", "#f8edf1", "#ffffff", "#d3a6b8"],
dark: ["#df77a0", "#311c24", "#170c11", "#7c465b"],
},
steel: {
name: "Steel",
light: ["#50737c", "#f0f3f4", "#ffffff", "#a5b5b8"],
dark: ["#7fa4ad", "#22292a", "#0c1517", "#4c595c"],
},
slate: {
name: "Slate",
light: ["#5b6e88", "#f0f2f4", "#ffffff", "#acb3bc"],
dark: ["#8e9eb4", "#23262a", "#0c1117", "#515861"],
},
mauve: {
name: "Mauve",
light: ["#816281", "#f4f1f4", "#ffffff", "#bbafbb"],
dark: ["#ae93ae", "#292329", "#170c17", "#5f545f"],
},
graphite: {
name: "Graphite",
light: ["#4a4640", "#eeedea", "#ffffff", "#a8a196"],
dark: ["#cfc7bb", "#2b2a28", "#161513", "#7a7369"],
},
};
export const DEFAULT_ACCENT = "rust";
// The card-width presets. Here for the same reason the accents are: the page
// validates a saved `looks.width` with cardWidth(), and the server uses it to
// paint the first-load `data-width` attribute before app.js runs. One list,
// two readers, no drift.
export const CARD_WIDTHS = {
narrow: { label: "Narrow", px: 720 },
comfortable: { label: "Comfortable", px: 880 },
wide: { label: "Wide", px: 1080 },
};
export const DEFAULT_CARD_WIDTH = "comfortable";
export function cardWidth(value) {
return typeof value === "string" && Object.hasOwn(CARD_WIDTHS, value) ? value : DEFAULT_CARD_WIDTH;
}
// Every moment the page makes a noise, each switchable on its own in User
// Preferences (the `data-sound` boxes in index.html). Several share a file;
// the event, not the file, is what a person turns off. `rank` settles which
// wins when two ask at once (see the sounds section in app.js). Stored flat as
// `soundQuestion` and so on, because looks.json only holds flat values.
export const SOUND_EVENTS = {
startSkill: { file: "start-skill", rank: 5 },
bootup: { file: "bootup", rank: 4 },
sessionStart: { file: "start-stop", rank: 3 },
sessionEnd: { file: "start-stop", rank: 3 },
question: { file: "next", rank: 2 },
skillReady: { file: "next", rank: 2 },
chatReply: { file: "next", rank: 2 },
newTab: { file: "insert", rank: 1 },
snore: { file: "sleeping", rank: 0 },
};
export const soundKey = (event) => "sound" + event[0].toUpperCase() + event.slice(1);
// The per-event switches out of a saved looks object: each one as saved when
// it is a boolean, on otherwise. A looks.json from before the switches has
// none of these keys, so it keeps every sound.
export function soundPrefs(saved) {
const source = saved && typeof saved === "object" ? saved : {};
return Object.fromEntries(
Object.keys(SOUND_EVENTS).map((event) => {
const value = source[soundKey(event)];
return [soundKey(event), typeof value === "boolean" ? value : true];
})
);
}
@@ -0,0 +1,278 @@
// Markdown to DOM, safely.
//
// The rule this file exists to enforce: NO HTML STRING IS EVER PRODUCED.
// We take marked's token tree and build nodes with createElement/textContent.
//
// Why that matters more than it looks: this page is same-origin with a server
// that reads and writes the user's files and holds the session cookie. Script
// running here could post arbitrary answers back to the agent, which would then
// act on them with the agent's full tool permissions. And the markdown is only
// nominally agent-authored: in practice the agent is summarising a dependency
// README, a scraped page, a PR description, a log. Treat it as hostile.
//
// Building nodes rather than parsing a string makes injection structurally
// impossible instead of filtered, so there is nothing for a sanitiser bypass to
// bypass. `html` tokens render as visible text, on purpose.
import { marked } from "./vendor/marked.esm.js";
// A bare `/` path stays on this origin; `//host` (and `/\host`, which browsers
// read the same way) is protocol-relative and would not, so it is refused.
const SAFE_PROTOCOL = /^(https?:|mailto:|#|\/(?![/\\]))/i;
function safeHref(href) {
if (!href) return null;
const trimmed = String(href).trim();
// Blocks javascript: and data: hrefs before they can reach the DOM.
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
}
function el(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text != null) node.textContent = text;
return node;
}
function inlineInto(parent, tokens) {
for (const t of tokens || []) {
switch (t.type) {
case "text":
// Nested inline tokens (a link inside emphasis, say) arrive here.
if (t.tokens && t.tokens.length) inlineInto(parent, t.tokens);
else parent.appendChild(document.createTextNode(t.text ?? t.raw ?? ""));
break;
case "escape":
parent.appendChild(document.createTextNode(t.text));
break;
case "strong": {
const n = el("strong");
inlineInto(n, t.tokens);
parent.appendChild(n);
break;
}
case "em": {
const n = el("em");
inlineInto(n, t.tokens);
parent.appendChild(n);
break;
}
case "del": {
const n = el("s");
inlineInto(n, t.tokens);
parent.appendChild(n);
break;
}
case "codespan":
parent.appendChild(el("code", "md-code", t.text));
break;
case "br":
parent.appendChild(document.createElement("br"));
break;
case "link": {
const href = safeHref(t.href);
if (!href) {
inlineInto(parent, t.tokens);
break;
}
const a = el("a");
a.href = href;
a.rel = "noopener noreferrer";
if (/^https?:/i.test(href)) a.target = "_blank";
if (t.title) a.title = t.title;
inlineInto(a, t.tokens);
parent.appendChild(a);
break;
}
case "image": {
const src = safeHref(t.href);
if (!src) {
parent.appendChild(document.createTextNode(t.text || ""));
break;
}
const img = el("img", "md-img");
img.src = src;
img.alt = t.text || "";
parent.appendChild(img);
break;
}
default:
// Includes `html`: rendered as literal text, never parsed.
parent.appendChild(document.createTextNode(t.raw ?? t.text ?? ""));
}
}
}
function blockInto(parent, tokens) {
for (const t of tokens || []) {
switch (t.type) {
case "space":
break;
case "heading": {
const level = Math.min(6, Math.max(2, (t.depth || 1) + 1)); // never an h1: the page owns that
const h = el("h" + level, "md-h");
inlineInto(h, t.tokens);
parent.appendChild(h);
break;
}
case "paragraph": {
const p = el("p", "md-p");
inlineInto(p, t.tokens);
parent.appendChild(p);
break;
}
case "text": {
const p = el("p", "md-p");
if (t.tokens) inlineInto(p, t.tokens);
else p.textContent = t.text || "";
parent.appendChild(p);
break;
}
case "blockquote": {
const q = el("blockquote", "md-quote");
blockInto(q, t.tokens);
parent.appendChild(q);
break;
}
case "code": {
const wrap = el("div", "md-pre-wrap");
const pre = el("pre", "md-pre");
// textContent, so a fenced block containing markup is inert.
pre.appendChild(el("code", null, t.text));
wrap.appendChild(copyButton(t.text, "md-copy"));
wrap.appendChild(pre);
parent.appendChild(wrap);
break;
}
case "hr":
parent.appendChild(el("hr", "md-hr"));
break;
case "list": {
const list = el(t.ordered ? "ol" : "ul", "md-list");
if (t.ordered && typeof t.start === "number" && t.start !== 1) list.start = t.start;
for (const item of t.items || []) {
const li = el("li", "md-li" + (item.task ? " is-task" : ""));
if (item.task) {
const box = el("span", "md-task" + (item.checked ? " is-done" : ""));
box.textContent = item.checked ? "✓" : "·";
box.setAttribute("aria-label", item.checked ? "done" : "not done");
li.appendChild(box);
}
blockInto(li, item.tokens);
list.appendChild(li);
}
parent.appendChild(list);
break;
}
case "table": {
const scroll = el("div", "md-table-wrap");
const table = el("table", "md-table");
const thead = el("thead");
const hr = el("tr");
(t.header || []).forEach((cell, i) => {
const th = el("th");
if (t.align && t.align[i]) th.style.textAlign = t.align[i];
inlineInto(th, cell.tokens);
hr.appendChild(th);
});
thead.appendChild(hr);
table.appendChild(thead);
const tbody = el("tbody");
for (const row of t.rows || []) {
const tr = el("tr");
row.forEach((cell, i) => {
const td = el("td");
if (t.align && t.align[i]) td.style.textAlign = t.align[i];
inlineInto(td, cell.tokens);
tr.appendChild(td);
});
tbody.appendChild(tr);
}
table.appendChild(tbody);
scroll.appendChild(table);
parent.appendChild(scroll);
break;
}
default: {
// Unknown or raw html block: show the source, do not interpret it.
const p = el("p", "md-p");
p.textContent = t.raw ?? t.text ?? "";
parent.appendChild(p);
}
}
}
}
/** Render markdown into a fresh element. Returns the element. */
export function md(source, className = "md") {
const host = el("div", className);
if (!source) return host;
let tokens;
try {
tokens = marked.lexer(String(source));
} catch {
host.appendChild(el("p", "md-p", String(source)));
return host;
}
blockInto(host, tokens);
return host;
}
/** Render markdown into an existing element, replacing its contents. */
export function mdInto(node, source) {
node.replaceChildren();
const rendered = md(source);
while (rendered.firstChild) node.appendChild(rendered.firstChild);
return node;
}
// The page's only clipboard action, in one place. writeText can be refused --
// a browser that has not granted the permission, a page that was not focused
// when the click landed -- and a button that silently does nothing is worse
// than one that says what to press instead.
//
// It lives here rather than in app.js because app.js imports this file and not
// the other way round, and a fenced code block needed it first.
//
// copyText() is the action itself: `button` reads "Copied" for a moment, then
// `label` again. `label` may be a function, read when the moment is up, for a
// button whose text can change in the meantime. `onRefused` is what the caller
// offers instead when the browser says no -- usually a selection to press
// Ctrl+C on.
async function copyText(text, button, label, onRefused) {
try {
await navigator.clipboard.writeText(text);
button.textContent = "Copied";
setTimeout(() => (button.textContent = typeof label === "function" ? label() : label), 1400);
} catch {
onRefused();
}
}
function selectContents(node) {
try {
const range = document.createRange();
range.selectNodeContents(node);
const sel = getSelection();
sel.removeAllRanges();
sel.addRange(range);
} catch {}
}
function copyButton(text, className, source) {
const b = el("button", className || "btn small", "Copy");
b.type = "button";
b.addEventListener("click", () =>
copyText(text, b, "Copy", () => {
// "Press Ctrl+C" on its own asks them to copy a selection that does not
// exist. Select the text for them, so the instruction is one they can
// actually follow.
const node = source || b.parentNode.querySelector("pre, code");
if (node) selectContents(node);
b.textContent = "Press Ctrl+C";
})
);
return b;
}
export { el, copyButton, copyText, selectContents };
@@ -0,0 +1,254 @@
// Plan2Code Web Console - roles, starter templates and Ask starter questions.
//
// The source of truth for the Role list in User Preferences, the starter
// templates on the first "What's the idea?" card of Pathfinder, Plan and Quick
// Task, the order each role sees them in, and the starter questions an empty
// Ask conversation offers. No DOM access at module scope and no imports: the
// page and `node --test` both import this file.
const role = (id, label) => Object.freeze({ id, label });
export const ROLES = Object.freeze([
role("engineer", "Engineer"),
role("pm", "Product lead / PM"),
role("architect", "Architect / tech lead"),
role("designer", "Designer (UX)"),
role("qa", "QA / test engineer"),
role("em", "Engineering manager"),
]);
export const ROLE_NOT_SET = "none";
export const ROLE_NOT_SET_LABEL = "Not set / none of these";
export const TEMPLATE_WORKFLOWS = Object.freeze(["pathfinder", "plan", "quick-task"]);
const ROLE_IDS = new Set(ROLES.map((r) => r.id));
// A known role id, or "none" for anything else (missing, unknown, not a string).
export function normalizeRole(value) {
return ROLE_IDS.has(value) ? value : ROLE_NOT_SET;
}
// The dashboard nudge shows until looks.json carries a role of any value:
// choosing Not set, or pressing Not now, ends it just as a real role does.
export function needsRoleNudge(looks) {
if (!looks || typeof looks !== "object") return true;
return !Object.hasOwn(looks, "role");
}
// The wording is approved (PLAN-DRAFT Appendix A); a change is a page change.
const template = (id, label, lines) => Object.freeze({ id, label, text: lines.join("\n") });
export const TEMPLATES = Object.freeze({
"engineering-spec": template("engineering-spec", "Engineering spec", [
"Engineering spec for: [the feature or change, in a sentence]",
"Who reads it: the engineers who will build and review it.",
"What it should pin down: the behaviour, the parts of the code it touches, the interfaces between them, and how we'll know it works.",
"What I already know: [constraints, links, earlier attempts]",
]),
"product-requirements": template("product-requirements", "Product requirements", [
"Product requirements for: [the feature, in a sentence]",
"Who it's for: [the users], and the product, design and engineering people deciding on it.",
"What it should pin down: the problem, who has it, what success looks like, and what waits for later.",
"What I already know: [customer asks, data, deadlines]",
]),
"design-decision": template("design-decision", "Design decision", [
"A design decision to work out: [the choice we're facing, in a sentence]",
"Who it's for: the engineers and architects who will live with it.",
"What it should pin down: the options, the trade-offs of each, the one we pick and why, and what it costs us later.",
"Constraints: [performance, compatibility, deadlines, team skills]",
]),
"test-strategy": template("test-strategy", "Test strategy", [
"Test strategy for: [the feature or area]",
"Who reads it: QA and the engineers writing the tests.",
'What it should pin down: what\'s risky, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
"What exists today: [current tests, known gaps]",
]),
"scoping-rollout": template("scoping-rollout", "Scoping & rollout", [
"Scoping and rollout for: [the feature or project]",
"Who reads it: the engineering manager, the product lead and the team.",
"What it should pin down: what's in the first release and what waits, the build order, risks to the timeline, and how it reaches users (flags, stages, who goes first).",
"Constraints: [dates, people, dependencies]",
]),
"brainstorm-notes": template("brainstorm-notes", "Brainstorm → curated notes", [
"Brainstorm to turn into curated notes: [the topic or rough idea]",
"Who reads the notes: [the team or people this goes to]",
"What I want out of it: the ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
"Starting thoughts: [anything already on your mind]",
]),
"bug-investigation": template("bug-investigation", "Bug investigation", [
"Bug to investigate: [what's going wrong, in a sentence]",
"Steps to reproduce: [1. ... 2. ...]",
"Expected: [what should happen]. Actual: [what happens instead]",
"Where and since when: [environment, version, first seen]",
]),
"small-change": template("small-change", "Small change", [
"Small change: [what to change, in a sentence]",
"Where: [the file, screen or command, if you know it]",
"Done when: [how you'll tell it worked]",
]),
"copy-tweak": template("copy-tweak", "Copy / content tweak", [
"Change the wording of: [the screen, message, email or doc]",
"Current text: [paste it]",
"New text: [paste it, or describe the tone you want]",
"Who reads it: [the people who see it]",
]),
"ui-polish": template("ui-polish", "UI polish", [
"UI polish on: [the screen or component]",
"What looks or feels off: [spacing, alignment, colour, states, small screens]",
"What good looks like: [a reference, screenshot or description]",
"Leave alone: [anything that must not move]",
]),
"visual-prototype": template("visual-prototype", "Visual prototype", [
"A throwaway visual prototype of: [the screen or component]",
"What to show: [the states or flows to click through]",
"What I want to learn: [the question it should answer]",
"Where it lives: a prototypes/ folder [or its own branch], never wired into the real code.",
]),
"add-a-test": template("add-a-test", "Add a test", [
"Add a test for: [the function, behaviour or bug]",
"Cases to cover: [the normal case, the edge cases, the bug it guards against]",
"Where tests live: [the test file or folder, if you know it]",
]),
"record-decision": template("record-decision", "Record a decision", [
"Record a decision we've already made: [the decision, in a sentence]",
"Why: [the reasons, and what we turned down]",
"What it commits us to: [the consequences]",
"Save it as an ADR in: docs/adr/ [or wherever this repo keeps them]",
]),
});
const orders = (byRole) => Object.freeze(Object.fromEntries(Object.entries(byRole).map(([r, ids]) => [r, Object.freeze(ids)])));
// One full order per role per skill. No "none" row: Not set reads Engineer's.
export const TEMPLATE_ORDERS = Object.freeze({
pathfinder: orders({
engineer: ["engineering-spec", "design-decision", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "engineering-spec", "design-decision", "test-strategy"],
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
designer: ["brainstorm-notes", "product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy"],
qa: ["test-strategy", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision", "brainstorm-notes"],
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "design-decision", "brainstorm-notes"],
}),
plan: orders({
engineer: ["engineering-spec", "bug-investigation", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "test-strategy", "design-decision", "bug-investigation"],
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "bug-investigation"],
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "bug-investigation"],
qa: ["test-strategy", "bug-investigation", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision"],
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "bug-investigation", "design-decision"],
}),
"quick-task": orders({
engineer: ["small-change", "bug-investigation", "add-a-test", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "add-a-test", "record-decision"],
architect: ["record-decision", "small-change", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "add-a-test", "record-decision"],
qa: ["add-a-test", "bug-investigation", "small-change", "ui-polish", "copy-tweak", "visual-prototype", "record-decision"],
em: ["small-change", "record-decision", "add-a-test", "bug-investigation", "copy-tweak", "ui-polish", "visual-prototype"],
}),
});
const roleRow = (role) => {
const r = normalizeRole(role);
return r === ROLE_NOT_SET ? "engineer" : r;
};
/**
* The idea card's template row for a skill: Blank first, then the skill's
* templates in the role's order. The first template carries `forYou` only for
* a chosen role, never for Not set. `[]` for a skill with no templates.
*/
export function templatesFor(workflow, role) {
if (!TEMPLATE_WORKFLOWS.includes(workflow)) return [];
const chosen = normalizeRole(role) !== ROLE_NOT_SET;
const ordered = TEMPLATE_ORDERS[workflow][roleRow(role)].map((id, i) => {
const { label, text } = TEMPLATES[id];
return { id, label, text, forYou: chosen && i === 0 };
});
return [{ id: "blank", label: "Blank", text: "" }, ...ordered];
}
// Swapping templates: an empty box, or one untouched since the last pick,
// swaps silently; anything the person typed asks first.
export function templateSwap({ selectedText, boxText, nextText } = {}) {
const box = typeof boxText === "string" ? boxText : "";
const selected = typeof selectedText === "string" ? selectedText : "";
return { text: typeof nextText === "string" ? nextText : "", confirm: box.trim() !== "" && box !== selected };
}
// Ask starter questions (PLAN-DRAFT Appendix B, approved). `lead` names the
// roles that see a starter first; `needsContext` starters wait for
// + Add context.
const starter = (id, text, lead, needsContext = false) =>
Object.freeze({ id, text, lead: Object.freeze(lead), needsContext });
export const STARTER_SETS = Object.freeze({
pathfinder: Object.freeze([
starter("pathfinder-files", "Which files or parts of the code does this decision touch?", ["engineer", "architect"], true),
starter("pathfinder-prior-art", "Has anything like this been done elsewhere in the repo?", ["engineer", "architect"]),
starter("pathfinder-decided", "What have we already decided, and what's still open?", ["pm", "em", "architect"]),
starter("pathfinder-plain", "What does this question mean, in plain words?", ["pm", "designer", "em"], true),
]),
plan: Object.freeze([
starter("plan-files", "Which existing files would this plan change?", ["engineer", "architect"]),
starter("plan-test", "How would we test this?", ["qa", "engineer"], true),
starter("plan-risks", "What are the biggest risks or unknowns in this plan?", ["architect", "em", "qa"]),
starter("plan-plain", "Explain this section as if I'm not an engineer.", ["pm", "designer", "em"], true),
]),
document: Object.freeze([
starter("document-touch", "Where does this phase touch existing code?", ["engineer"], true),
starter("document-guesses", "Which parts of this phase are still guesses?", ["architect", "engineer"], true),
starter("document-users", "What will users notice once every phase ships?", ["designer", "pm", "qa"]),
starter("document-summary", "Summarize the phases written so far in three bullets.", ["pm", "em"]),
]),
build: Object.freeze([
starter("build-last-task", "What changed in the last task, and why?", ["engineer", "em", "qa"]),
starter("build-finding", "Where exactly is this finding in the code?", ["engineer", "qa"], true),
starter("build-progress", "How far along are we, and what's next?", ["em", "pm"]),
starter("build-check", "What should I check by hand after this phase?", ["qa", "designer"]),
]),
"quick-task": Object.freeze([
starter("quick-task-files", "Which files will this touch?", ["engineer"]),
starter("quick-task-pattern", "Is there a similar pattern in the code I should follow?", ["engineer", "architect"]),
starter("quick-task-size", "Is this bigger than a quick task?", ["em", "architect"]),
starter("quick-task-try", "How do I try this out once it's done?", ["qa", "designer", "pm"]),
]),
dashboard: Object.freeze([
starter("dashboard-project", "What does this project do, in a paragraph?", ["pm", "designer", "em"]),
starter("dashboard-which-skill", "Which skill should I use for my idea?", ["pm", "designer", "em"]),
starter("dashboard-difference", "What's the difference between Pathfinder, Plan and Quick Task?", []),
starter("dashboard-spec", "Where does this spec stand?", ["pm", "em"], true),
]),
general: Object.freeze([
starter("general-step", "What is this step going to do, and what will it change?", []),
starter("general-summary", "Summarize this session so far.", ["em", "pm"]),
starter("general-left", "What's left to do after this?", ["em", "pm"]),
]),
});
// Workflows missing here (init, init-update, revise-plan, finalize, handoff,
// anything unknown) use the general set.
export const STARTER_SET_FOR = Object.freeze({
pathfinder: "pathfinder",
plan: "plan",
document: "document",
implement: "build",
"implement-review": "build",
review: "build",
"quick-task": "quick-task",
dashboard: "dashboard",
});
/**
* The starters an empty Ask conversation offers: the workflow's set, minus
* those that need context until some is attached, with the role's leads
* first and written order kept inside each group. Not set leads as Engineer.
*/
export function startersFor(workflow, role, { hasContext } = {}) {
const setId = Object.hasOwn(STARTER_SET_FOR, workflow) ? STARTER_SET_FOR[workflow] : "general";
const lead = roleRow(role);
const shown = STARTER_SETS[setId].filter((s) => hasContext || !s.needsContext);
const first = shown.filter((s) => s.lead.includes(lead));
const rest = shown.filter((s) => !s.lead.includes(lead));
return [...first, ...rest].map(({ id, text }) => ({ id, text }));
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,92 @@
// Plan2Code Web Console - the Workspace's naming and wording rules.
//
// The source of truth for what a folder may be called, the name a new folder
// gets by default, and the suggestion offered when a name is taken. Imported
// by the server (its guards), lib.mjs and the page, so they can never disagree.
// No DOM access at module scope and no imports: the page and `node --test`
// both import this file.
export const NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
export const NAME_MAX = 40;
const trimDashes = (s) => s.replace(/^-+|-+$/g, "");
/**
* The name a folder gets before anyone renames it: its last path segment,
* lowercased, with every run of other characters turned into one `-`.
*/
export function defaultName(folderPath) {
const segments = String(folderPath || "")
.split(/[\\/]/)
.filter(Boolean);
const last = segments.length ? segments[segments.length - 1] : "";
const name = trimDashes(trimDashes(last.toLowerCase().replace(/[^a-z0-9]+/g, "-")).slice(0, NAME_MAX));
return name || "folder";
}
// null when the name can be used, "bad-name" when it cannot.
export function nameProblem(name) {
if (typeof name !== "string" || !name || name.length > NAME_MAX || !NAME_PATTERN.test(name)) return "bad-name";
return null;
}
/**
* `base` when nobody has it, else the first free `base-2`, `base-3`, ...
* `base` is shortened first so the suffixed name still fits NAME_MAX.
*/
export function freeName(base, taken) {
if (!taken.has(base)) return base;
for (let n = 2; ; n++) {
const suffix = `-${n}`;
const candidate = trimDashes(base.slice(0, NAME_MAX - suffix.length)) + suffix;
if (!taken.has(candidate)) return candidate;
}
}
// How many footer label tiers there are: the page tries 0..FOOTER_TIERS-1,
// widest first, until the text fits.
export const FOOTER_TIERS = 4;
/**
* The footer's workspace label. `folders[0]` is the original folder.
* 0 plan2code + 2 folders · main
* 1 plan2code + 2 folders
* 2 plan2code +2
* 3 plan2code
*/
export function footerLabel({ folders, branch }, tier = 0) {
const list = Array.isArray(folders) ? folders : [];
const name = list.length ? list[0].name : "";
const n = Math.max(0, list.length - 1);
if (tier >= 3) return name;
let label = name;
if (n > 0) label += tier === 2 ? ` +${n}` : ` + ${n} ${n === 1 ? "folder" : "folders"}`;
if (tier === 0 && branch) label += ` · ${branch}`;
return label;
}
/**
* The reply line an agent is handed for one workspace.json change entry
* (`{ kind, name, path, description?, from? }`).
*/
export function changeLine(change) {
const { kind, name, path, description, from } = change || {};
switch (kind) {
case "added":
return `Workspace: added @${name} — ${path}` + (description ? ` (${description})` : "");
case "renamed":
return `Workspace: renamed @${from} to @${name} — ${path}`;
case "described":
return description
? `Workspace: @${name} is now described as "${description}"`
: `Workspace: @${name} description cleared`;
case "removed":
return `Workspace: removed @${name} — ${path}`;
case "missing":
return `Workspace: @${name} is missing — ${path} no longer exists`;
case "found":
return `Workspace: @${name} is back — ${path}`;
default:
return `Workspace: @${name} changed — ${path}`;
}
}
File diff suppressed because it is too large. Load diff
+17 -16
View File
@@ -10,7 +10,11 @@ Start all PLANNING MODE responses with '🤔 [PLANNING PHASE X: Phase Name]'
## Role
Senior software architect and technical PM. Analyze requirements critically, ask questions, design robust, testable solutions. Output: SOW and Implementation Plan. Do NOT write code - focus on planning and architecture.
Senior software architect and technical PM. Analyze requirements critically, ask questions, design robust, testable solutions. Output: SOW and Implementation Plan. Do NOT write code - plan and architect only.
## Interface
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before looking for a draft: ask **web console** (suggested — far easier for sign-offs with a non-engineer) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow plan` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then <D>/console.md → Planning notes. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console.md → Launches), then the AGENTS.md check.
## Project Context (BLOCKING)
@@ -21,10 +25,10 @@ Check if `./AGENTS.md` exists:
> ```
> ⋅
> ╭───╮
> │ ● │ ?
> │ ~ │ Hmm, I don't see an AGENTS.md...
> ╰───╯
> ╭───╮ ?
> │ ★ │╱
> ╱│ ~ │ Hmm, I don't see an AGENTS.md...
> ╰┬─┬╯
> ```
>
> "No `AGENTS.md` found. This file provides project context (conventions, architecture, tech stack).
@@ -50,11 +54,11 @@ Check if `./AGENTS.md` exists:
### Check for Existing Progress
Before Phase 1, check for existing `PLAN-DRAFT-*.md` under `specs/` (`ls specs/` via shell — never Glob; `specs/` is gitignored):
Before Phase 1, check for existing `PLAN-DRAFT-*.md` under `specs/` (`ls specs/` via shell — never Glob; it is gitignored):
- 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
- No PLAN-DRAFT: Begin at Phase 1
- No PLAN-DRAFT: Begin at Phase 1. Console: its idea card carries `"templates": "idea"` (console.md → Starter templates)
---
@@ -82,7 +86,6 @@ Four dimensions (0-25% each):
Report each sub-score with overall percentage.
## Process
### PHASE 1: Requirements Analysis
@@ -163,7 +166,7 @@ State assessment and ask user to confirm.
3. Create `specs/<feature-name>/PLAN-DRAFT-<YYYYMMDD>.md` with Phases 1-3
4. Set status: `Phase 3 Complete - Resume at Phase 4`
5. Include: Executive Summary, Requirements, System Context, Scope, Confidence
6. Instruct: "Large project. Progress saved. Start NEW conversation with `/plan2code-1-plan` to resume at Phase 4."
6. Instruct: "Large project. Progress saved. Start NEW conversation with `/plan2code-1-plan --web` to resume at Phase 4." On the web console, post `finish` with that command first, then `stop`.
7. STOP
### PHASE 4: Tech Stack
@@ -272,6 +275,8 @@ When complete (PLAN-DRAFT created), tell user:
2. **Next: `/plan2code-2-document`** (NOT implementation)
3. Documentation auto-discovers planning files
**On the web console:** at every session end, and on a `__stop`, post `finish` BEFORE `stop`, per console.md → Planning.
**Closing example:**
> "Planning complete. Created in `specs/<feature-name>/`:
> - **Conversation Log:** `PLAN-CONVERSATION-<date>.md`
@@ -280,12 +285,12 @@ When complete (PLAN-DRAFT created), tell user:
> ```
> ⋅
> ╭───╮
> │ ★ │
> ╲│ ★ │╱
> │ ◡ │ Planning done! Ready for documentation!
> ╰───╯
> ╰┬─┬╯
> =============================================
> NEXT STEP: Start a NEW conversation then run:
> `/plan2code-2-document`
> `/plan2code-2-document --web`
> ```"
## Abort / Recovery
@@ -298,7 +303,3 @@ When complete (PLAN-DRAFT created), tell user:
- Final phase: PLANNING PHASE 7: Transition Decision
- Do NOT implement - design and present plan only
- Responses start with: `🤔 [PLANNING PHASE X: Name]`
- **Workflow:** Plan -> Document -> Implement -> Finalize. After planning: `/plan2code-2-document`
- Save conversation log (7A) before PLAN-DRAFT (7B), run verification (7C) after
- Run verification (7C) after PLAN-DRAFT - conversation log is source of truth
@@ -0,0 +1,444 @@
# Build Sessions on the Web Console
For `/plan2code-3-implement`, `/plan2code-3-implement-review` and
`/plan2code-quick-task`. Read `console.md` first: everything there still
applies (the wait loop, one post per send, `finish` before `stop`, the house
rules). This file adds what a build needs, because a build is mostly you
working, and the page has to be told so.
**The console changes where you ask, not what you build.** Every rule of the
workflow stands: the same specs, the same checkbox writes to disk after every
task, the same sign-off wording, the same "no git commands". The files under
`specs/` and the code are the record. The page is a window onto them.
---
## Opening
Open first, before reading the spec — the page shows a starting screen while
you work out the phase:
```
node "<CONSOLE>" open --workflow implement
```
| Workflow you are running | `--workflow` | `--spec` |
| --- | --- | --- |
| `/plan2code-3-implement` | `implement` | `specs/<feature>` |
| `/plan2code-3-implement-review` | `implement-review` | `specs/<feature>` |
| `/plan2code-quick-task` | `quick-task` | leave it out |
`--spec` is what the page builds a resume command from if you ever cannot
answer a stop yourself. Pass it to `open` when you already know the spec;
otherwise post `"specDir": "specs/<feature>"` and a real `title` ("<feature>:
Phase 3") in your first update, once the phase is chosen, or with the phase
question as its first item if there is one to ask. `--file` works on `open`
too, but opening bare and posting the task list as your first update gets
them the page while you are still composing.
**Launched from the dashboard?** Then the session is already open and the
person is watching it — `open --resume <sid> --no-open --workflow <yours>`
(plus `--spec` once known) instead of a fresh `open`, exactly as console.md →
Launches says. Everything below is unchanged; the only difference is whose
session it was a minute ago.
The first payload for a phase you are about to build:
```jsonc
{
"headline": { "stage": "Phase 3: API layer", "cleared": 0, "total": 9 },
"docs": [
{ "id": "phase", "title": "Phase 3 tasks", "version": 1, "blocks": [
{ "id": "tasks", "state": "settled", "md": "- [ ] **Task 3.1:** ...\n- [ ] **Task 3.2:** ..." }
]},
{ "id": "phasefile", "title": "phase-3.md", "version": 1, "blocks": [
{ "id": "body", "state": "settled", "md": "...the whole phase-3.md file, verbatim..." }
]}
],
"agent": { "status": "working", "activity": "Checking the prerequisites", "quietMinutes": 15 }
}
```
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
progress bar is the first thing someone watching a build looks at.
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
the person can read the prerequisites and task specs while you build. Re-post
it whenever the file changes, which is every task: the checkbox write that
ticks the list above ticks the file too, and the Phase Completion Summary
lands in it at the end. It renders as markdown, so the file's checkboxes show
as ticks exactly as they stand on disk.
---
## While you build
Post after every task, in the same breath as writing its checkbox to disk.
Write the patch file into the session's own folder (the `session` path `open`
printed), never into the project or into `~/.plan2code/console/` directly:
```jsonc
{
"headline": { "cleared": 4 },
"docs": [
{ "id": "phase", "version": 5, "blocks": [ { "id": "tasks", "state": "settled", "md": "...the whole list, 4 ticked..." } ] },
{ "id": "phasefile", "version": 5, "blocks": [ { "id": "body", "state": "settled", "md": "...phase-3.md as it now stands on disk..." } ] }
],
"agent": { "activity": "Task 5 of 9: the rate limiter" }
}
```
- **`activity`** is one plain sentence saying what you are doing now. The page
shows it beside Planny and in place of "questions coming". No internal
vocabulary, no loop completion markers. Number tasks by their position in
the phase, of the phase's task count (`Task 5 of 9`), not by the file's
`5.5`-style labels: the phase is already in the headline. The page rewrites
the old form as a safety net.
- **`quietMinutes`** is how long you might go without posting (1 to 60). The
page calls a working agent stuck after two minutes of silence unless you say
otherwise, and a build task can honestly take twenty. Set it to the longest
gap you expect, usually 10 to 30. Every post is also a heartbeat. **Clear it
(`"quietMinutes": null`) whenever you go back to waiting**: it only counts
while you are `working`, but leaving it set invites a stale value later.
- `blocks` inside a doc are replaced whole, so post the whole task list each
time. It is small. The same goes for `phasefile`: re-read `phase-X.md` and
post it fresh, because the checkbox write just changed it.
- If the task list grows mid-build, raise `headline.total` in the same post;
the page never shows more done than the total, but the bar reads truer when
you keep it current.
- Do not call `wait` while building. There is nothing to collect, and the page
holds anything the person sends until you next look.
### Quick questions between tasks
The person can ask a Quick question on the Ask tab at any point in a build
(console.md → Quick questions). After each task's progress post, check for
one before starting the next task:
```
node "<CONSOLE>" chat --session <sid>
```
| Exit | What you do |
| --- | --- |
| `0` | Answer everything waiting, under console.md → Quick questions, in one post, then start the next task. A `workspace` list in the output is a change to the session's folders (console.md → Workspace): take it into account from the next task on; it needs no reply. |
| `10` | Nothing waiting. Carry on. |
| `20` | The server is gone: `open --resume <sid>` as usual, then carry on. |
This is an instant check, not a wait: it never sleeps and never touches card
sends. It does not replace `wait` at a gate, and no build calls `wait`
mid-build for cards. An approved chat edit is made here, between tasks, never
in the middle of one.
A blocker (`[!]`), a `SPEC NOTE` and a verified or assumed prerequisite are
not questions. Put them in the phase doc as they happen, and in the report.
### When the workflow asks something
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }`, and
go into the wait loop. When the answer lands, set `working` again and carry on.
| Moment | `kind` | Notes |
| --- | --- | --- |
| Several phases can be picked | `choice` | One option per phase, `detail` = status and task count, `token` = the phase number. Put the "run another agent on a different phase" tip in `body`. |
| A phase is already in progress | `confirm` | "Resume Phase 3?" `yes` / `no`. |
| `SPEC CONFLICT` | `choice` or `text` | The conflict in `body`, the readings as options where there are clear ones. Never guess on architecture. |
| Test failures | `choice` | `1` Fix now, `2` Document and proceed, `3` Investigate first. |
| A small phase, continue with the next? | `confirm` | |
| A spec gap only they can close | `text` | |
| Something learned for AGENTS.md | `confirm` | The proposed lines in `consequences`. |
Titles stay plain: "Which phase next", "Tests are failing", "Keep going?".
---
## Sign-off
Put the Completion Report on the page as a doc, then ask for approval as a
`review` item pointing at it. The review offer rides on this card, as a verdict
ahead of the approval buttons — not on the finish after it, where it could
only ever be offered once nothing could come of it:
```jsonc
{
"docs": [{ "id": "report", "title": "Completion report", "version": 1, "blocks": [
{ "id": "summary", "state": "settled", "md": "## Summary\n\n..." },
{ "id": "files", "state": "settled", "md": "## Files\n\n..." },
{ "id": "verify", "state": "settled", "md": "## How to check it\n\n..." }
]}],
"items": [{
"id": "signoff", "kind": "review", "title": "Approve this phase", "doc": "report",
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, or say what to change.",
"verdicts": [
{ "id": "review", "label": "Review the code first" },
{ "id": "approve", "label": "Approve this phase" },
{ "id": "changes", "label": "I want changes" }
],
"token": { "review": "review", "approve": "approved", "changes": "needs changes" },
"nothingYet": "Nothing is marked complete until you approve.",
"gate": { "id": "signoff", "authoritative": true },
"fallbackText": "Reply \"approved\" to mark this phase complete, \"review\" to run the code review first, or describe any issues."
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
`reply` carries `Approve this phase: approved`, which is the terminal's
`approved`. If the note that came with an approval asks for a change, treat it
as "describe any issues": do the change first and ask again. `changes` means
exactly what it says: address it, bump the report's version, 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 — see "The
review, mid-session" below.
`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
sign-off twice.
---
## After approval: the finish
Do everything the workflow does on approval (the checkboxes, the summary, the
upcoming phases, the commit command) and print it in the terminal as usual.
Then post the finish, wait for the dashboard button as console.md → Finishing
says, and `stop`:
```jsonc
{
"items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "approve" } }],
"run": { "event": "implement-phase", "id": "phase-3" },
"finish": {
"headline": "Phase 3 is done",
"body": "9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```",
"command": "/plan2code-3-implement specs/lunch-vote/overview.md",
"doc": "report",
"dashboard": true
},
"agent": { "status": "waiting" }
}
```
`finish.command` is the next pipeline step, the same one the terminal names:
the next `/plan2code-3-implement`, or `/plan2code-4-finalize` after the last
phase. An `implement` finish never carries `review`: the offer was on the
sign-off card, and approving past it was the answer. `implement-review` ends
the same way; that phase was reviewed already. Only a finished `quick-task`
still offers the review on its finish — see below.
`run` scores the approved phase on the session meter (console.md → Posting an
update → Session meter), in the same post that records the approval:
`implement-phase` for Implement, `implement-review-phase` for Implement +
Review, id `phase-N`. Quick task and a standalone Review are counted when
their session opens, so they post no `run` for that; a review run on the page
after a build reports its own (below).
---
## The review, mid-session
The same focused review runs from either of two doors:
- **`implement`:** the `review` verdict on the sign-off card, before anything
is approved. A note sent with it is theirs — read it as focus for the
review. Settle the card with it in the same post that goes back to work:
```jsonc
{
"items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "review" } }],
"headline": { "stage": "Reviewing Phase 3", "cleared": 0, "total": 0 },
"run": { "event": "review", "id": "review" },
"agent": { "status": "working", "activity": "Reviewing the 7 files this phase changed", "quietMinutes": 15 }
}
```
- **`quick-task`:** the **Review it now** button on the finished screen, which
`finish.review` puts there. It arrives through the wait loop as an action
`{ "i": "__review", "type": "review" }`, like any send. Take it up with the
same post minus the `items` line, plus `"finish": null` — that takes the
session off its ending and back to work.
Either way, the post that takes the review up carries `"run": { "event":
"review", "id": "review" }`: the review runs inside this skill's session, so no
launch scores it on the session meter. Never resume the session under
`--workflow review` for it as well, or it counts twice.
A finish carrying `review` keeps the session alive for the answer, so a
`quick-task` that just posted one keeps waiting, for up to about ten minutes.
A quick-task finish carries both `review` and `"dashboard": true` and waits
for whichever comes first:
| What arrives | What you do |
| --- | --- |
| An action `{ "i": "__review", "type": "review" }` | Take the review up (below). |
| An action `{ "i": "__dashboard", "type": "dashboard" }` | Take the session back as the dashboard (console.md → Finishing). |
| An action `{ "i": "__done", "type": "done" }` | `stop` the server. The session is over. |
| `wait` exit `20` | They closed the tab. Do not resume: the session is over. |
| Nothing after about ten minutes | `stop` the server. The page then shows the terminal command for a review instead of a button that would go nowhere. |
**Read references/review.md** and run Review Mode with these overrides:
- **Scope is Focused, and already decided:** the exact change set of this
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.
- **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,
and tables go in the doc.
### The findings
The full Review Mode report as a doc, and the fix choice as one `multi` item:
```jsonc
{
"docs": [{ "id": "review", "title": "Review findings", "version": 1, "blocks": [
{ "id": "report", "state": "settled", "md": "## Overview\n\n...\n\n## Findings\n\n| # | Severity | Issue | File |\n..." }
]}],
"items": [{
"id": "fixes", "kind": "multi", "title": "Which to fix", "required": false, "doc": "review",
"body": "Tick what should be fixed now. Anything left unticked is written up as still open. Nothing changes until you send.",
"options": [
{ "k": "1", "text": "Critical: token is logged in plain text", "detail": "src/auth.ts:42. Fix: redact before logging." },
{ "k": "2", "text": "Warning: missing null check on the user lookup", "detail": "src/users.ts:88. Fix: ..." },
{ "k": "3", "text": "Suggestion: repeated query could be batched", "detail": "src/report.ts:17. Fix: ..." }
],
"presets": [
{ "label": "Critical and warnings", "ks": ["1", "2"] },
{ "label": "All of them", "ks": ["1", "2", "3"] }
],
"token": { "1": "1", "2": "2", "3": "3" },
"fallbackText": "Reply H to fix Critical + Warning findings, A to fix all findings, or S 1,3,5 to fix specific findings."
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
`"doc": "review"` puts a **Read "Review findings" in full** button on the
card, so the report is one click from the list rather than behind a tab
nobody notices. Always carry it.
Read the reply as Review Mode's fix choice: `Which to fix: 1, 2` is `S 1,2`,
every finding ticked is `A`, and `skip` (or nothing ticked) is "fix none,
keep them as unresolved". Leave out `presets` a set would not change (no
warnings, one finding). With **zero findings** there is no item: say so in the
doc and go straight to the way back out.
### Fixing
Settle the `fixes` item in the same post that goes back to work —
`"status": "answered"` with the `answer` they sent (`{ "ks": ["1", "2"] }`,
or `{ "ks": [] }` when nothing was ticked). The server records their send on
the item, but only you decide it is settled; left open it stays on the page
as an outstanding question, beside the card you ask next. Then follow Review
Mode's Post-Fix Flow, posting `activity` per fix ("Fix 2 of 3: the null
check") and `quietMinutes` as in a build.
### The way back out
**`implement` — back to the sign-off.** The review was the preamble to an
approval that has not happened yet, so this is where it lands. Fold the review
results and any still-open findings into the report doc and bump it, then
reopen the sign-off **without the review verdict** — re-offering a review that
just ran reads as though nothing happened:
```jsonc
{
"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": "approve", "label": "Approve this phase" },
{ "id": "changes", "label": "I want changes" }
],
"thread": [{ "who": "agent", "text": "Review done: 2 of 3 findings fixed; the rest is written up in the findings tab." }]
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
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 "After approval: the finish".
**`quick-task` — the closing gate, then the finish.** Review Mode's closing
gate ("Reply approved to commit, or request changes") becomes a `review` item
titled "Check the fixes", `doc: "review"`, verdicts `approve` ("The fixes look
right") and `changes`, token `approved` / `needs changes`. When it clears,
settle it in the same post as the new finish — `"status": "answered"` plus
`"answer": { "verdict": "approve" }` (or `"changes"`) — post the finish
**without** `review`, then `stop`. An item left open survives on the page as
a question still owed, above the ending itself:
- `headline`: "The review is done"
- `body`: findings by severity, what was fixed, what is still open, and the
commit command for the fixes, in the project's commit format.
- `command`: the same next step as the finish before it.
- `doc`: `"review"`.
---
## Implement + Review (`implement-review`)
The same build, then Stage 2 publishes the findings exactly as above (the
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
item: Stage 4 is the only gate. Stage 4 is the sign-off above **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": "implement-review-phase", "id": "phase-N" }`.
---
## Quick task (`quick-task`)
- Open with the first clarifying question. Clarifying questions go out as
`text` or `choice`, at most three at a time.
- Post `"stopWarning": "A quick task saves nothing until it is built, so stopping now loses what we have worked out."`
at the start, and `"stopWarning": ""` once the build is under way.
- **Scope check:** a `choice`, "Too big for a quick task?", options
`1` Continue (lightweight format) and `2` Escalate to a full plan, with the
measured counts against the thresholds in `body`.
- **Feature name** (escalating): `text` with
`"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"` and a kebab-case placeholder.
- **The plan:** a `plan` doc (Summary, Files to change, Steps, Verify) and a
`review` item "Build this plan?" with verdicts `yes` ("Build it"), `modify`
("Change the plan"), `escalate` ("Plan it properly instead") and `abort`
("Stop here", `"danger": true`), token equal to the ids.
- **Building** after `yes`: settle the verdict (`"status": "answered"` plus
`"answer": { "verdict": "yes" }`) in the post that starts the build, then
exactly as "While you build", with the plan's steps
as the task list and `total` = the number of steps.
- **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
`review` on offer — the **Review it now** button, since a quick task has no
sign-off card to put it on. Keep waiting for the answer, and everything
after that is "The review, mid-session" above.
- **Escalated / aborted:** settle the verdict the same way in the finish post —
finish with `"command": "/plan2code-1-plan"` and the
PLAN-DRAFT's path in `body`, no review; or `"command": "/plan2code-quick-task"`.
Both set `"dashboard": true`: an abort of a quick task saves nothing to
resume, so it is not a pause.
---
## Stop requests during a build
The Stop button only works on the person's turn, so it never lands mid-task.
When `__stop` arrives:
- **implement / implement-review:** Implementation Mode's abort, without the
"are you sure" (the page asked): the phase stays `[/]`, list completed and
remaining tasks, post `finish` with the resume command
(`/plan2code-3-implement specs/<feature>/overview.md`), then `stop`. An
implement abort is a pause: a headline starting "Paused", no `dashboard`,
`stop` at once.
- **quick-task:** say in `finish.body` what was worked out, and that nothing was
saved unless it was built; `"command": "/plan2code-quick-task"`.
A mid-build `__dashboard` (the top bar's triangle, console.md → Stop requests →
"Back to the dashboard, mid-workflow") lands the same way, only on the person's
turn. Save exactly as for `__stop` above (an implement phase stays `[/]`), but
post no finish and do not `stop`: resume as the dashboard instead, with one
terminal line naming what was saved and the resume command.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,233 @@
// Plan2Code Web Console - the native folder picker behind Workspace's Browse…
//
// A port of the launcher's picker (src/launcher/plan2code.js). The launcher
// is self-contained CommonJS copied alone to ~/.plan2code/bin/, and this
// console is ESM bundled into every skill, so the two cannot share a module:
// this is a copy, and a drift test in scripts/test-web-console.mjs fails the
// moment the launcher's picker changes without it. The prompt is a parameter
// here rather than the launcher's constant.
//
// Always spawned asynchronously: spawnSync would freeze the server's polling,
// chat and wait for as long as the dialog stayed open.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
const IS_WINDOWS = process.platform === "win32";
const IS_MAC = process.platform === "darwin";
export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace";
// Copied verbatim from src/launcher/plan2code.js; see the drift test.
export const WINDOWS_PICKER_SOURCE = `
using System;
using System.Runtime.InteropServices;
public static class Plan2CodeFolderPicker {
[ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
private class FileOpenDialog {}
[ComImport, Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IFileOpenDialog {
[PreserveSig] int Show(IntPtr owner);
void SetFileTypes(uint count, IntPtr specs);
void SetFileTypeIndex(uint index);
void GetFileTypeIndex(out uint index);
void Advise(IntPtr events, out uint cookie);
void Unadvise(uint cookie);
void SetOptions(uint options);
void GetOptions(out uint options);
void SetDefaultFolder(IShellItem item);
void SetFolder(IShellItem item);
void GetFolder(out IShellItem item);
void GetCurrentSelection(out IShellItem item);
void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
void GetResult(out IShellItem item);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem {
void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
void GetParent(out IShellItem parent);
void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name);
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
private static extern void SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid iid, out IShellItem item);
private const uint FOS_PICKFOLDERS = 0x20;
private const uint FOS_FORCEFILESYSTEM = 0x40;
private const uint FOS_PATHMUSTEXIST = 0x800;
private const uint SIGDN_FILESYSPATH = 0x80058000;
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
public static string Pick(IntPtr owner, string title, string start) {
IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
try {
uint options;
dialog.GetOptions(out options);
dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
dialog.SetTitle(title);
if (!string.IsNullOrEmpty(start)) {
try {
Guid iid = typeof(IShellItem).GUID;
IShellItem folder;
SHCreateItemFromParsingName(start, IntPtr.Zero, ref iid, out folder);
dialog.SetFolder(folder);
} catch (Exception) {}
}
int hr = dialog.Show(owner);
if (hr == ERROR_CANCELLED) return null;
Marshal.ThrowExceptionForHR(hr);
IShellItem result;
dialog.GetResult(out result);
string path;
result.GetDisplayName(SIGDN_FILESYSPATH, out path);
return path;
} finally {
Marshal.ReleaseComObject(dialog);
}
}
}
`;
// Resolve a command on PATH the way the shell would, including PATHEXT on Windows.
function findOnPath(command) {
const dirs = (process.env.PATH || "").split(path.delimiter).filter(Boolean);
const extensions = IS_WINDOWS ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [""];
for (const dir of dirs) {
for (const ext of extensions) {
const candidate = path.join(dir.replace(/^"|"$/g, ""), command + ext);
try {
if (fs.statSync(candidate).isFile()) return candidate;
} catch {}
}
}
return null;
}
/**
* The native folder picker for this OS, as a command to run: it prints the
* chosen folder, or nothing when the person cancels. Null when this OS has no
* picker we can drive.
*/
export function pickerCommand(start, prompt) {
if (IS_WINDOWS) {
const script = [
"$ErrorActionPreference = 'Stop'",
"try {",
" [Console]::OutputEncoding = [Text.Encoding]::UTF8",
" Add-Type -AssemblyName System.Windows.Forms",
" [System.Windows.Forms.Application]::EnableVisualStyles()",
// A TopMost owner keeps the dialog in front of the console window that launched it.
" $owner = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true; ShowInTaskbar = $false }",
" try {",
" Add-Type -TypeDefinition $env:PLAN2CODE_PICKER_SOURCE",
" $picked = [Plan2CodeFolderPicker]::Pick($owner.Handle, $env:PLAN2CODE_PICKER_PROMPT, $env:PLAN2CODE_PICKER_START)",
" } catch {",
// Add-Type is blocked under Constrained Language Mode and some AppLocker policies; the
// old tree dialog still works there.
" $dialog = New-Object System.Windows.Forms.FolderBrowserDialog",
" $dialog.Description = $env:PLAN2CODE_PICKER_PROMPT",
" $dialog.SelectedPath = $env:PLAN2CODE_PICKER_START",
" $picked = if ($dialog.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { $dialog.SelectedPath } else { $null }",
" }",
" if ($picked) { $picked }",
"} catch { exit 3 }",
].join("\n");
return {
command: "powershell.exe",
args: [
"-NoProfile",
"-NonInteractive",
"-STA",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
Buffer.from(script, "utf16le").toString("base64"),
],
env: {
PLAN2CODE_PICKER_PROMPT: prompt,
PLAN2CODE_PICKER_START: start,
PLAN2CODE_PICKER_SOURCE: WINDOWS_PICKER_SOURCE,
},
};
}
if (IS_MAC) {
return {
command: "osascript",
args: [
"-e",
"on run argv",
"-e",
`POSIX path of (choose folder with prompt "${prompt}" default location (POSIX file (item 1 of argv)))`,
"-e",
"end run",
start,
],
};
}
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return null;
if (findOnPath("zenity")) {
return {
command: "zenity",
args: ["--file-selection", "--directory", `--title=${prompt}`, `--filename=${start}${path.sep}`],
};
}
if (findOnPath("kdialog")) {
return { command: "kdialog", args: ["--title", prompt, "--getexistingdirectory", start] };
}
return null;
}
/**
* Show the picker and settle on what the person did: `{ path }` for a pick,
* `{ cancelled: true }` when they closed it, `{ error }` when the picker
* itself failed or this OS has none. Pickers exit 0 or 1 with nothing printed
* when cancelled.
*/
export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
const picker = pickerCommand(start, prompt);
if (!picker) return Promise.resolve({ error: "picker-failed" });
return new Promise((resolve) => {
let settled = false;
const settle = (result) => {
if (settled) return;
settled = true;
resolve(result);
};
let child;
try {
child = spawnImpl(picker.command, picker.args, {
env: { ...process.env, ...(picker.env || {}) },
// stderr is ignored, not piped: a pipe nobody reads fills up and
// blocks a chatty picker (GTK warnings) before it can exit.
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
});
} catch {
return settle({ error: "picker-failed" });
}
let stdout = "";
if (child.stdout) {
child.stdout.setEncoding?.("utf8");
child.stdout.on("data", (chunk) => (stdout += chunk));
}
child.on("error", () => settle({ error: "picker-failed" }));
child.on("close", (code) => {
const folder = stdout.trim();
if (code === 0 && folder) return settle({ path: path.resolve(folder) });
if (!folder && (code === 0 || code === 1)) return settle({ cancelled: true });
settle({ error: "picker-failed" });
});
});
}
@@ -0,0 +1,971 @@
// The page's pure logic: what the person answered, and what they asked for, in
// the words those things have to reach the agent as.
//
// Everything here is a pure function of an item and a value. That is the point
// of the file: app.js cannot be loaded outside a browser (it touches `document`
// at module scope and starts a session on import), so any logic that stays in
// it is logic no test can reach. Three defects in this exact code got as far as
// the screen before anyone noticed. It lives here so `node --test` can see it.
//
// No DOM, no `local`, no fetch. If a function in here needs any of those, it
// belongs in app.js instead.
/* ----------------------------------------------------- the sent answer */
/**
* The value an in-flight send carries, or null if it carries no answer.
*
* A send can be a note on its own: someone asks a question about the question
* before answering it. That still goes in `local.sent`, because the note really
* is on its way, but it must NOT make the page treat the question as answered
* and lock the form. They have not answered it yet, and locking them out is how
* an open question becomes unanswerable.
*/
export function sentAnswer(sent) {
return sent && sent.value ? sent.value : null;
}
/**
* What the person settled on, for a question that is no longer open.
*
* `answer` is what the agent recorded when it settled the question. `submitted`
* is what the server wrote down the moment Send was pressed. The second exists
* because the first depends on the agent remembering to do it, and a card that
* says "Settled" above an empty form is the worst thing this page can show.
*/
export function recordedAnswer(item) {
const a = item && item.answer && typeof item.answer === "object" ? item.answer : null;
const s = item && item.submitted && typeof item.submitted === "object" ? item.submitted : null;
if (!a && !s) return null;
return { ...(s || {}), ...(a || {}) };
}
/**
* A send the person made that the agent never settled, still sitting on an
* OPEN question.
*
* `local.sent` covers this while the same tab is alive; `submitted` is the
* server's own record of the send and survives a reload, a resume onto a new
* port, and a second tab. An open item that carries one, and has had no agent
* reply since, is "sent, waiting on Plan2Code" — not a question still
* waiting for them, which is what it reads as when an agent takes the answer
* and moves on without marking the item settled.
*
* Two ways out, both meaning the question is theirs again:
*
* - an agent message in the item's thread AFTER the send means the question
* is being asked again — the person gets a live form back, not a locked
* record of what they already said;
* - a recorded `answer` means the agent did settle it at some point (the
* status is just stale or the question was re-asked), so the leftover
* `submitted` is the old send, not one in flight.
*/
export function submittedAwaiting(item) {
const s = item && item.submitted;
if (!s || typeof s !== "object") return null;
if (item.answer && typeof item.answer === "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
return replied ? null : s;
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
const o = ((item && item.options) || []).find((x) => x.k === k);
if (!o) return String(k);
return o.k ? `${o.k} · ${o.text}` : o.text;
}
export function verdictLabel(item, id) {
const list = (item && item.verdicts) || [
{ id: "approve", label: "Looks good, go ahead" },
{ id: "changes", label: "I want changes" },
];
const v = list.find((x) => x.id === id);
return v ? verdictText(v) : String(id);
}
// A verdict's button text. `label` is the contract; `text` is what menu
// options use, and an agent that borrows it must not get blank buttons.
export function verdictText(v) {
return v.label || v.text || v.id;
}
export const CHECK_STATE_LABEL = {
done: "All done",
blocked: "I am stuck",
help: "I need help",
defer: "Later",
};
/**
* The answer as lines to show back, in the page's words rather than the
* agent's shorthand: "A · Run the setup first", not "a".
*/
export function answerLines(item, v) {
const out = [];
if (!v) return out;
if (v.skipped) out.push("Skipped");
if (v.k) out.push(optionLabel(item, v.k));
if (Array.isArray(v.ks)) for (const k of v.ks) out.push(optionLabel(item, k));
if (typeof v.yes === "boolean") out.push(v.yes ? item.yesLabel || "Yes" : item.noLabel || "No");
if (typeof v.ok === "boolean") {
out.push(v.ok ? item.yesLabel || "Yes, that is right" : item.noLabel || "Not quite");
}
if (v.verdict) out.push(verdictLabel(item, v.verdict));
if (v.state) out.push(CHECK_STATE_LABEL[v.state] || String(v.state));
if (Array.isArray(v.done) && v.done.length) {
out.push(`Steps done: ${v.done.map((n) => n + 1).join(", ")}`);
}
if (Array.isArray(v.rows) && v.rows.length) {
out.push(`${v.rows.length} steps, in the order you set`);
}
return out;
}
/**
* A single-choice answer, which is one thing or the other and never both.
*
* Picking an option and then writing "none of these, because…" used to send
* both, joined, with the pick first: an answer that argued with itself. The
* rule lives here rather than in the two click handlers that apply it, so it
* is one statement that a test can hold to.
*
* Returns null when there is nothing to stage, which is what "they have not
* answered yet" looks like everywhere else in the page.
*/
export function choiceAnswer({ k, text } = {}) {
if (k) return { type: "answer", kind: "choice", k };
const said = String(text || "").trim();
return said ? { type: "answer", kind: "choice", text: said } : null;
}
/* -------------------------------------------------------- the brief ask */
/**
* The words a brief request reaches the agent as.
*
* This is not an answer, but it is the same kind of thing and it belongs to the
* same rule: a string the agent parses, so it has to be exactly right, so it
* has to be somewhere a test can see it. `range` is the Pathfinder brief
* playbook's own grammar -- `today`, `this week`, `since <YYYY-MM-DD>`, `full`.
*/
export function briefPhrase(range) {
const r = String(range || "today").trim();
if (r === "full") return "Write a full brief.";
if (r.startsWith("since ")) return `Write a brief covering everything ${r}.`;
return `Write a brief for ${r}.`;
}
/* ---------------------------------------------------- the autofill text */
// A placeholder is a suggestion nobody can edit, and it vanishes the moment you
// type. On a question whose example is most of a good answer, retyping it is
// busywork, so offer it as a value instead. The lead-in ("For example:") is the
// agent talking about the example, not part of it, so it is stripped.
//
// Two rules keep the stripping from mangling a real answer:
//
// The lead-in must be FOLLOWED by a separator. Without that, "Egypt office"
// loses its "Eg" and "Exampled output" loses its "Example".
//
// A bare hyphen only separates when it has space around it. "For example - a"
// is a lead-in; the hyphen in "example-name-here" is part of the name, and a
// kebab-case suggestion must survive intact for a field with a `pattern`.
//
// "Say" is deliberately not in the list: "Say when you need it by" is a
// question far more often than it is a preamble.
const EXAMPLE_LEAD =
/^\s*(?:for\s+(?:example|instance)|examples?|such\s+as|e\.?\s?g\.?|i\.?\s?e\.?)(?:\s+-\s+|\s*[:,.]\s*|\s+)/i;
/**
* The placeholder, as a value someone could accept as their own answer.
* Empty string when there is nothing worth offering.
*/
export function suggestionFrom(item) {
const raw = String((item && item.placeholder) || "").trim();
if (!raw) return "";
const stripped = raw.replace(EXAMPLE_LEAD, "").trim();
if (!stripped) return "";
// Recapitalise only when a lead-in was actually removed, and never on a
// field with a shape to match: "audit-export" must not become "Audit-export".
if (stripped !== raw && !item.pattern && /^[a-z]/.test(stripped)) {
return stripped[0].toUpperCase() + stripped.slice(1);
}
return stripped;
}
/* ------------------------------------------------------ the hand-off */
// The badge each workflow wears. Shared with the server, which writes it into
// the page it serves so the first paint already names the session instead of
// flashing a placeholder until the script arrives.
export const WORKFLOW_LABEL = {
dashboard: "Dashboard",
init: "Setting up",
"init-update": "Refreshing",
pathfinder: "Pathfinder",
plan: "Planning",
"revise-plan": "Revising the plan",
document: "Documenting",
implement: "Building",
"implement-review": "Building + review",
review: "Review",
"quick-task": "Quick task",
finalize: "Wrapping up",
handoff: "Handoff",
};
export function workflowLabel(workflow) {
return WORKFLOW_LABEL[workflow] || workflow || "Session";
}
// The workflows that ship the console (install.js bundles it into every
// skill as `additionalReferences`). Any other next step has no browser page
// to open, and asking for one would send the next session looking for
// something that is not there.
export const CONSOLE_WORKFLOWS = [
"/plan2code",
"/plan2code-init",
"/plan2code-init-update",
"/plan2code-0-pathfinder",
"/plan2code-quick-task",
"/plan2code-1-plan",
"/plan2code-1b-revise-plan",
"/plan2code-2-document",
"/plan2code-3-implement",
"/plan2code-3-implement-review",
"/plan2code-review",
"/plan2code-4-finalize",
"/plan2code-handoff",
];
// Rides on the end of the command as part of the skill's argument. Every
// console skill takes it as the answer to "web console or terminal?" instead
// of asking again. It must stay clear of "brief", "recap" and "minutes":
// pathfinder reads any of those in its argument as a request for a brief.
export const CONTINUE_IN_CONSOLE = "--web";
// The long form the skills still accept. A command that carries it is copied
// with the flag instead, which is shorter and reads as the parameter it is.
const CONSOLE_SENTENCE = /\s*Use the web console for this session\.?/gi;
/**
* What the Copy button on the finished screen puts on the clipboard.
*
* Someone who worked the whole session in the browser should land back in the
* browser, not be asked the interface question as though they were new. The
* `--web` flag goes on the same line as the command, because what follows a
* slash command is its argument, and a pasted second line is not reliably that.
* A command written with the long sentence is copied with the flag instead.
*
* `fin.console` overrides the inference either way; otherwise it follows from
* whether the next step is a workflow that has a console at all.
*/
export function handoffText(fin) {
const raw = String((fin && fin.command) || "").trim();
if (!raw) return "";
const cmd = raw.replace(CONSOLE_SENTENCE, "").trim();
const capable =
typeof fin.console === "boolean"
? fin.console
: cmd !== raw || CONSOLE_WORKFLOWS.some((w) => cmd === w || cmd.startsWith(w + " "));
// An agent that already wrote the flag should not get it twice.
if (!capable || /(^|\s)--web\b/.test(cmd)) return cmd;
return `${cmd} ${CONTINUE_IN_CONSOLE}`;
}
/**
* A finish is a pause when its headline says so. There is no flag to read:
* the stop playbook asks the agent to write "a headline that says it is
* paused rather than done", so the page reads the same words the person
* does. A session that ends on its own says nothing of the sort.
*/
export function finishPaused(fin) {
return /^\s*paused\b/i.test(String((fin && fin.headline) || ""));
}
// The line a finished session shows when it has nothing left to run. Split so
// the page can render the backticked command as code; joined with a space they
// read as one sentence.
export const ALL_DONE_LEAD = "All done, nothing left to run.";
export const ALL_DONE_REST = "To start something else, run `/plan2code` in a new conversation to open the dashboard.";
export const DASHBOARD_COMMAND = "/plan2code";
/**
* Which hand-off a finish gets: a pause always offers its resume command, a
* finish with a command offers it as the next step, and one without has
* nothing left to run.
*/
export function handoffShape(fin) {
if (finishPaused(fin)) return "paused";
return String((fin && fin.command) || "").trim() ? "next" : "all-done";
}
/* ------------------------------------------------------------ stopping */
// What a stop request reads as, the way a typed message would. It goes to the
// agent as part of `reply`, so the same caution applies as to the hand-off
// sentence: nothing Pathfinder would read as asking for a brief.
export const STOP_REPLY = "Stop here and save my place, so I can pick this up later.";
/**
* Why a session-level button (Stop session, Back to the dashboard) cannot be
* pressed right now, or null when it can. Both wait for the person's turn:
* while Plan2Code has the ball it may be halfway through writing their last
* answers into the files, and a request landing then is how a question ends up
* half recorded. `waiting` is the caller's "the agent is working or a reply is
* owed, and it has not gone adrift" -- an agent that has stopped checking in
* never replies, and a button greyed out forever would lock the person in. An
* uncollected send still blocks even then, because the server takes one at a
* time.
*/
export function turnGate({ gone = false, pendingResult = false, waiting = false } = {}) {
if (gone) return "gone";
if (pendingResult) return "pending";
if (waiting) return "waiting";
return null;
}
// What the top bar's Back to the dashboard button reads as to the agent. It
// goes in `reply` like the stop, so the same caution applies: nothing
// Pathfinder would read as asking for a brief.
export const HOME_REPLY = "Save my place and take me back to the dashboard, right here in this session.";
const HOME_TITLES = {
gone: "Not connected right now.",
pending: "Your last answers are still being picked up. You can leave once they have been.",
waiting: "Plan2Code is working on your answers. You can leave once it replies.",
};
/**
* The top bar's Back to the dashboard button. Hidden on the dashboard itself,
* on a finished screen (which carries its own way back) and while a stop is
* under way; otherwise pressable on the person's turn, like Stop session.
* Once pressed it waits for the page to turn, unless the agent has gone
* adrift: then it comes back, and a second press is safe because the server
* refuses a duplicate while the first is uncollected.
*/
export function homeButtonState({ workflow, finished = false, stopping = false, homeward = false, adrift = false, ...turn } = {}) {
if (!workflow || workflow === "dashboard" || finished || stopping) return { hidden: true, disabled: true, title: "" };
if (homeward && !adrift) return { hidden: false, disabled: true, title: "Opening the dashboard…" };
const gate = turnGate(turn);
return {
hidden: false,
disabled: Boolean(gate),
title: gate ? HOME_TITLES[gate] : "Back to the dashboard. Your place is saved first.",
};
}
/**
* The resume command the PAGE can offer when the agent cannot: it stopped
* listening, or went away without posting a finish. Built only from what the
* session state says, never guessed.
*
* Pathfinder resumes from its folder, so it needs `specDir` (`specs/<idea>`),
* which the workflow posts once the folder exists. Without one the bare
* command still works: Pathfinder asks which idea. Planning finds its own
* draft and takes no path. The implementation steps, Revision and
* Finalization take the spec's overview.md, and without it they ask which
* spec (or find the only one). A quick task keeps nothing on disk to resume
* from, so its command starts it again.
*/
export function resumeCommand({ workflow, specDir } = {}) {
const raw = String(specDir || "").trim().replace(/\\/g, "/").replace(/\/+$/, "");
// Only a real relative specs/ path. Anything else would be run verbatim by
// someone with no way to tell it was wrong.
const dir = /^specs\/[a-z0-9][a-z0-9._-]*$/i.test(raw) ? raw : "";
const withOverview = (cmd) => (dir ? `${cmd} ${dir}/overview.md` : cmd);
switch (workflow) {
case "dashboard":
return "/plan2code";
case "init":
return "/plan2code-init";
case "init-update":
return "/plan2code-init-update";
case "plan":
return "/plan2code-1-plan";
case "quick-task":
return "/plan2code-quick-task";
case "document":
return withOverview("/plan2code-2-document");
case "implement":
return withOverview("/plan2code-3-implement");
case "implement-review":
return withOverview("/plan2code-3-implement-review");
case "review":
return "/plan2code-review";
case "revise-plan":
return withOverview("/plan2code-1b-revise-plan");
case "finalize":
return withOverview("/plan2code-4-finalize");
case "handoff":
return "/plan2code-handoff";
default:
return dir ? `/plan2code-0-pathfinder ${dir}/pathfinder` : "/plan2code-0-pathfinder";
}
}
/* ------------------------------------------------ after a build is done */
// What the two buttons on a finished build's hand-off reach the agent as. They
// go in `reply` like any typed message, so the same caution applies as to the
// other session phrases: plain words, nothing Pathfinder would read as a brief.
export const REVIEW_REPLY =
"Review what was just built before I go: run the focused code review on this session's changes, here on the page.";
export const DONE_REPLY = "No review, thanks. I am done: close the session.";
export const DASHBOARD_REPLY = "Take me back to the dashboard, right here in this session.";
// Shown under the Back to the dashboard button: the press picks up in the same
// conversation, which carries a long skill's context into the next one.
export const DASHBOARD_NOTE =
"This picks up in the same conversation. That's fine after a quick or small skill; after a long one, type `/clear` in your terminal and run `/plan2code` for a clean start.";
/**
* Whether a finish offers the way back to the dashboard. The agent opts in
* with `finish.dashboard: true`, so a skill that predates the button never
* shows one nobody answers; a pause never offers it.
*/
export function dashboardOffer(fin) {
return Boolean(fin && fin.dashboard === true && !finishPaused(fin));
}
/**
* Whether a finish carries the offer to review what was just built. The agent
* posts `finish.review` as `true` or as `{ "label": "..." }` on a finished
* quick task (an implementation phase offers the review earlier, as a verdict
* on its sign-off card).
*/
export function reviewOffer(fin) {
const r = fin && fin.review;
if (!r) return null;
const label = typeof r === "object" && typeof r.label === "string" ? r.label.trim() : "";
return { label: label || "Review what was just built" };
}
/* ------------------------------------------------------- the dashboard */
// The skills the dashboard offers, in the order it offers them. The page owns
// this list rather than the session state: the catalog is product UI, fixed
// for everyone, and the alternative — the agent posting it — would put a dozen
// cards of boilerplate through the patch channel every time the menu opened.
// `menu` in the state can still say what the agent knows: a `recommend` skill
// to highlight and a `details` line per card ("Phase 2 of 4 is next").
//
// `workflow` is the name the skill resumes the session under: the dashboard
// hands its session over, and this is what turns the page into that skill's
// console. A test holds this list against the skills install.js builds, so a
// new skill cannot ship without a card here.
export const CATALOG_GROUPS = [
{ id: "setup", title: "First, the project" },
{ id: "pipeline", title: "The steps, in order" },
{ id: "extra", title: "Useful any time" },
];
// `spec: true` marks the cards that take a spec folder as their target: when
// the picker has a spec selected, its `dir` rides along in the `__launch`
// action so the launched skill knows which spec it was picked for.
export const SKILL_CATALOG = [
{
skill: "plan2code-init",
command: "/plan2code-init",
workflow: "init",
group: "setup",
chip: "Set up",
title: "Set up this project",
blurb: "Reads your project and writes AGENTS.md, the guide every later step works from.",
about:
"Plan2Code reads the whole project: how it is organized, how it runs, and where the sharp edges are. Then it writes AGENTS.md, the guide every later step steers by. It asks a few questions as it goes, so nothing important gets guessed. Run this once per project, or again when the project has moved on.",
},
{
skill: "plan2code-init-update",
command: "/plan2code-init-update",
workflow: "init-update",
group: "setup",
chip: "Set up",
title: "Refresh AGENTS.md",
blurb: "Brings AGENTS.md and its notes up to date with what the project has learned lately.",
about:
"The project moved on since AGENTS.md was written: new commands, new habits, new gotchas. This re-reads the project, asks what changed, and folds it into AGENTS.md and the notes beside it. Cheaper than a fresh setup, and whatever is still right is kept.",
},
{
skill: "plan2code-0-pathfinder",
command: "/plan2code-0-pathfinder",
workflow: "pathfinder",
group: "pipeline",
chip: "Step 0",
spec: true,
title: "Pathfinder",
blurb: "A foggy idea becomes a clear list of decisions, settled one question at a time.",
about:
"You have a rough idea and a lot of unknowns. Pathfinder asks one question at a time: who it is for, what it must do, what could go wrong. Each answer is written down in a spec folder. It ends with a list of decisions clear enough to plan from, and nothing gets built yet.",
},
{
skill: "plan2code-1-plan",
command: "/plan2code-1-plan",
workflow: "plan",
group: "pipeline",
chip: "Step 1",
spec: true,
title: "Plan",
blurb: "Requirements, technical design and your approval: the shape of what gets built.",
about:
"Turns what you bring into a real plan: a finished Pathfinder map, a folder of design notes, or just the idea in your head. You get requirements, a technical design, a phase-by-phase breakdown, and a final version to approve before anything is built. This is where 'what are we building' becomes 'how it gets built'.",
},
{
skill: "plan2code-1b-revise-plan",
command: "/plan2code-1b-revise-plan",
workflow: "revise-plan",
group: "pipeline",
chip: "Step 1b",
spec: true,
title: "Revise the plan",
blurb: "Requirements changed mid-build? Adjust the plan without starting over.",
about:
"Requirements moved mid-build: a feature added, a rule dropped, a deadline pulled in. This adjusts the existing spec for the change, shows you what it affects, and only rewrites what actually has to move. The approved plan stays the plan.",
},
{
skill: "plan2code-2-document",
command: "/plan2code-2-document",
workflow: "document",
group: "pipeline",
chip: "Step 2",
spec: true,
title: "Document",
blurb: "The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do.",
about:
"Writes the plan as numbered phase files. Each phase is a checklist of tasks small enough to just do, with the details a builder needs right there. This is the file the build step works from, and the thing a later session can pick up cold.",
},
{
skill: "plan2code-3-implement",
command: "/plan2code-3-implement",
workflow: "implement",
group: "pipeline",
chip: "Step 3",
spec: true,
title: "Implement",
blurb: "Builds the next phase, task by task, with a report and your sign-off at the end.",
about:
"Builds the next phase of the spec. Tasks get checked off one by one, with progress and the occasional decision landing on this page as it goes. It ends with a report of what was built and a sign-off card you approve before the phase counts as done.",
},
{
skill: "plan2code-3-implement-review",
command: "/plan2code-3-implement-review",
workflow: "implement-review",
group: "pipeline",
chip: "Step 3",
spec: true,
title: "Implement + review",
blurb: "One phase built, then a careful review of the changes, then your sign-off. All in one run.",
about:
"The same build as Implement, with a review folded in before sign-off. The phase is built, then a fresh pass hunts for problems in exactly what changed, you pick what gets fixed, and only then does the sign-off card arrive.",
},
{
skill: "plan2code-4-finalize",
command: "/plan2code-4-finalize",
workflow: "finalize",
group: "pipeline",
chip: "Step 4",
spec: true,
title: "Finalize",
blurb: "Checks the work, writes the summary, files the specs away and suggests the commit message.",
about:
"The closer. Checks every task against the spec, makes sure the build actually works, writes the summary into overview.md, updates the project docs, and suggests the commit message. Run it when the feature is done. It leaves the project tidy behind it.",
},
{
skill: "plan2code-quick-task",
command: "/plan2code-quick-task",
workflow: "quick-task",
group: "extra",
chip: "Utility",
title: "Quick task",
blurb: "Too small for the full process? A quick plan, then it just builds it.",
about:
"A fix, a tweak, a small feature. Not worth a spec folder. Describe it, confirm the one-line plan, and it builds it right there, with a report at the end. The fast lane for work the full process would over-plan.",
},
{
skill: "plan2code-review",
command: "/plan2code-review",
workflow: "review",
group: "extra",
chip: "Utility",
title: "Review",
blurb: "A second opinion on the changes. Problems ranked, and you pick what gets fixed.",
about:
"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",
group: "extra",
chip: "Utility",
title: "Handoff",
blurb: "Pack this conversation 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
// screens that speak of it as a thing being started rather than as a badge.
export function workflowTitle(workflow) {
const entry = SKILL_CATALOG.find((e) => e.workflow === workflow);
return entry ? entry.title : workflowLabel(workflow);
}
// Every skill gets its own Planny on the starting and waiting screens, drawn
// as a <template data-pose> in index.html. A skill that is a variant of
// another borrows its pose. Anything else (the dashboard) keeps the flight.
export const START_POSES = [
"init",
"pathfinder",
"plan",
"document",
"implement",
"finalize",
"quick-task",
"review",
"handoff",
];
const POSE_ALIASES = { "init-update": "init", "revise-plan": "plan", "implement-review": "implement" };
export function startPose(workflow) {
const pose = POSE_ALIASES[workflow] || workflow;
return START_POSES.includes(pose) ? pose : null;
}
export function catalogEntry(skill) {
return SKILL_CATALOG.find((e) => e.skill === skill) || null;
}
/* ------------------------------------------- dashboard card availability */
// 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 = {
exploring: "Exploring",
mapped: "Ready to plan",
planned: "Ready to document",
documented: "Ready to build",
building: "Building",
built: "Ready to finalize",
unrecognized: "Files on disk",
};
// 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 = {
exploring: "plan2code-0-pathfinder",
mapped: "plan2code-1-plan",
planned: "plan2code-2-document",
documented: "plan2code-3-implement",
building: "plan2code-3-implement",
built: "plan2code-4-finalize",
};
const ON = { on: true };
const off = (reason) => ({ on: false, reason });
/**
* Whether a catalog card is clickable for the current picker selection.
*
* `scan` is the server's project scan ({ hasAgents, specs }); `sel` is the
* picked spec object or null for "start from scratch". A spec whose files
* match no pipeline shape ("unrecognized") behaves like no spec at all for
* availability — but its folder still goes along on a Pathfinder or Plan
* launch, since the files may be reference docs.
*
* Returns { on, reason?, next? } — `reason` is the one line a greyed card
* shows, `next` marks the state's natural step.
*/
export function cardAvailability(entry, scan, sel) {
const hasAgents = Boolean(scan && scan.hasAgents);
const state = sel && sel.state && sel.state !== "unrecognized" ? sel.state : null;
const next = sel ? Boolean(state) && NEXT_FOR_STATE[state] === entry.skill : entry.skill === "plan2code-0-pathfinder";
switch (entry.skill) {
case "plan2code-init":
return hasAgents ? off("AGENTS.md is already written. Refresh it instead.") : ON;
case "plan2code-init-update":
return hasAgents ? ON : off("Needs an AGENTS.md. Set the project up first.");
case "plan2code-quick-task":
case "plan2code-review":
case "plan2code-handoff":
return ON;
case "plan2code-0-pathfinder":
if (!state || state === "exploring") return { ...ON, next };
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 === "documented" || state === "building" || state === "built")
return off("The plan is written. Revise it instead if it moved.");
return { ...ON, next };
case "plan2code-1b-revise-plan":
if (state === "documented" || state === "building") return ON;
return off(state === "built" ? "The spec is fully built" : "Needs a spec that is already written up");
case "plan2code-2-document":
if (state === "planned") return { ...ON, next };
if (state === "documented" || state === "building" || state === "built")
return off("The phases are already written up");
return off("Needs a drafted plan first");
case "plan2code-3-implement":
case "plan2code-3-implement-review":
if (state === "documented" || state === "building") return { ...ON, next };
return off(state === "built" ? "All tasks are already done" : "Needs the phase checklists written up first");
case "plan2code-4-finalize":
if (state === "built") return { ...ON, next };
return off("Needs a spec that is fully built");
default:
return ON;
}
}
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 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);
const supplied = initial && menu.details && typeof menu.details[entry.skill] === "string" ? menu.details[entry.skill] : "";
const detail = availability.on && supplied ? supplied : !initial && availability.next && sel && sel.detail ? sel.detail : "";
return { ...availability, recommended, detail };
}
/**
* What a card click reaches the agent as, in `reply`. The action itself
* carries `skill`, which is what the dashboard parses; this line is the
* human-readable record of the ask. Like the other session phrases it keeps
* clear of "brief", "recap" and "minutes", which Pathfinder would read as a
* brief request.
*/
export function launchReply(entry, spec) {
const target = spec && spec.dir ? ` for ${spec.dir}` : "";
return `Start ${entry.title} (${entry.command})${target}, right here in this session.`;
}
export function staleLaunchFeedback(title, adrift) {
if (!adrift) return null;
return {
kicker: "Saved",
title: `${title || "Your workflow"} is saved and waiting`,
quip: "Plan2Code is not running right now.",
hint: "Return to the terminal and send any message. Plan2Code will collect this launch and continue here.",
};
}
/* ------------------------------------------------------------ progress */
// The label must never read "7 of 5", whatever the agent posted: a build that
// grew tasks mid-phase can post a `cleared` past its `total`. Guarded here on
// the page only; the server takes the numbers as sent.
export function progressTotal(cleared, total) {
return Math.max(Number(cleared) || 0, Number(total) || 0);
}
/* --------------------------------------------------------- attachments */
// Attachments on a note or a quick question: at most five, images and
// documents together. Images are re-encoded in the browser to a JPEG whose
// long edge fits IMAGE_LONG_EDGE, with a small data: URL copy for the tray.
// Documents upload byte for byte, and the server checks their contents itself.
export const MAX_ATTACHMENTS = 5;
export const MAX_NOTE_IMAGES = MAX_ATTACHMENTS;
export const MAX_DOC_BYTES = 10 * 1024 * 1024;
// The documents an agent can read with its own file tool, keyed by lower-case
// extension. A hard-coded list, like the server's TYPES: it is the picker's
// `accept`, the server's allow-list and the chip's label, so they can never
// disagree.
const textDoc = (label) => Object.freeze({ kind: "text", label });
export const DOC_TYPES = Object.freeze({
md: textDoc("Markdown"),
txt: textDoc("Text"),
json: textDoc("JSON"),
yaml: textDoc("YAML"),
yml: textDoc("YAML"),
toml: textDoc("TOML"),
ini: textDoc("INI"),
csv: textDoc("CSV"),
tsv: textDoc("TSV"),
log: textDoc("Log"),
xml: textDoc("XML"),
html: textDoc("HTML"),
css: textDoc("CSS"),
scss: textDoc("SCSS"),
js: textDoc("JavaScript"),
mjs: textDoc("JavaScript"),
cjs: textDoc("JavaScript"),
ts: textDoc("TypeScript"),
tsx: textDoc("TypeScript"),
jsx: textDoc("JavaScript"),
py: textDoc("Python"),
java: textDoc("Java"),
cs: textDoc("C#"),
go: textDoc("Go"),
rs: textDoc("Rust"),
rb: textDoc("Ruby"),
php: textDoc("PHP"),
sh: textDoc("Shell"),
ps1: textDoc("PowerShell"),
sql: textDoc("SQL"),
pdf: Object.freeze({ kind: "pdf", label: "PDF" }),
});
// A file name's document extension, or null. A name whose only dot leads it
// (`.env`, `.gitignore`) has no extension: dotfiles are where secrets live.
export function docExt(name) {
const s = String(name || "");
const dot = s.lastIndexOf(".");
if (dot <= 0 || dot === s.length - 1) return null;
const ext = s.slice(dot + 1).toLowerCase();
return Object.prototype.hasOwnProperty.call(DOC_TYPES, ext) ? ext : null;
}
// The file picker's `accept`: any image, plus every document extension.
export function pickerAccept() {
return "image/*," + Object.keys(DOC_TYPES).map((ext) => "." + ext).join(",");
}
export function formatBytes(n) {
const bytes = Number(n) || 0;
if (bytes < 1024) return `${bytes} B`;
const mb = bytes >= 1024 * 1024;
return new Intl.NumberFormat(undefined, {
style: "unit",
unit: mb ? "megabyte" : "kilobyte",
maximumFractionDigits: mb ? 1 : 0,
}).format(mb ? bytes / (1024 * 1024) : bytes / 1024);
}
// An entry saved before documents existed has no `kind`: it is an image.
export function attachmentKind(entry) {
return entry && entry.kind === "file" ? "file" : "image";
}
// Files the person picked, pasted or dropped, sorted by what they will be.
// The extension decides first: browsers report `""` for `.md` and
// `video/mp2t` for `.ts`, so `type` only settles what has no document
// extension. Each list keeps the order given.
export function sortAttachments(files) {
const images = [];
const docs = [];
const refused = [];
for (const file of files || []) {
if (docExt(file.name)) {
if (file.size > MAX_DOC_BYTES) refused.push({ name: file.name, reason: "too-large" });
else docs.push(file);
} else if (typeof file.type === "string" && file.type.startsWith("image/")) images.push(file);
else refused.push({ name: file.name, reason: "type" });
}
return { images, docs, refused };
}
export const IMAGE_LONG_EDGE = 2000;
export const IMAGE_QUALITY = 0.85;
export const THUMB_EDGE = 160;
// Scaled so the longer side is at most `max`, aspect kept, never upscaled.
export function fitWithin(w, h, max) {
const scale = Math.min(1, max / Math.max(w, h));
return { w: Math.round(w * scale), h: Math.round(h * scale) };
}
// A note's action, its attachments split into `images` and `files`. Only
// `path` and `name` go: the page's own bookkeeping (`id`, `url`, `status`) is
// nothing the agent can use. A key with nothing in it is left out.
export function noteAction(id, text, attachments) {
const action = { i: id, type: "comment", text };
const list = attachments || [];
const pick = (kind) => list.filter((a) => attachmentKind(a) === kind).map(({ path, name }) => ({ path, name }));
const images = pick("image");
const files = pick("file");
if (images.length) action.images = images;
if (files.length) action.files = files;
return action;
}
// A note as `reply` lines, one indented `Image:` or `File:` line per
// attachment in the order attached, so the agent can open each path with its
// file-read tool. An image-only note reads exactly as it always did.
export function noteReplyLines(title, text, attachments) {
const list = attachments || [];
const anyFile = list.some((a) => attachmentKind(a) === "file");
const said = text || (list.length ? (anyFile ? "(attachments only)" : "(images only)") : "");
return [
`Note on ${title}: ${said}`,
...list.map((a) => ` ${attachmentKind(a) === "file" ? "File" : "Image"}: ${a.path} (${a.name})`),
];
}
/* ------------------------------------------------------------ patience */
/**
* How long the agent may go quiet before the page calls it stuck.
*
* Every workflow before the build steps was a conversation: the agent was
* either thinking about a reply or sitting in `wait`, so two or three minutes
* of silence really did mean something had gone wrong. A build is different.
* One task can take twenty minutes of honest work with nothing to post, and a
* page that said "has not checked in, look at your terminal" every time would
* be crying wolf. So the agent says how long quiet is normal right now
* (`agent.quietMinutes`), and it counts only while the agent is `working`: a
* waiting agent is polling, and a silent poller is still a stuck one. Never
* below the page's own threshold, and capped at an hour so a typo cannot hide
* a dead session.
*/
export function quietLimitMs(agent, baseMs) {
if (!agent || agent.status !== "working") return baseMs;
const m = Number(agent.quietMinutes);
if (!Number.isFinite(m) || m <= 0) return baseMs;
return Math.max(baseMs, Math.min(m, 60) * 60 * 1000);
}
/* ---------------------------------------------------------- skip moves on */
// "Skip this one" moves the person on by itself. `staged` and `sent` are maps
// keyed by item id: a card staged or already sent no longer needs them.
const needsPerson = (id, staged, sent) => !(staged && staged[id]) && !(sent && sent[id]);
/** True when no open card other than `currentId` still needs the person. */
export function lastOpenCard(openIds, staged, sent, currentId) {
return openIds.every((id) => id === currentId || !needsPerson(id, staged, sent));
}
/**
* The next open card after `currentId` that still needs the person, wrapping
* to the start; null when there is none.
*/
export function nextOpenAfter(openIds, staged, sent, currentId) {
const at = openIds.indexOf(currentId);
for (let step = 1; step <= openIds.length; step++) {
const id = openIds[(at + step) % openIds.length];
if (id !== currentId && needsPerson(id, staged, sent)) return id;
}
return null;
}
/* ------------------------------------------------------------ approvals */
// The page cannot see a harness's permission prompt, so it nudges instead: a
// quiet tip line where a session starts, and a soft line beside Planny once a
// working agent has gone quiet for a while. Mode names verified 2026-09-23.
export const APPROVAL_TIP =
"Your agent may pause for approvals in the terminal. A hands-off mode (e.g. `auto` mode in Claude Code, `smart` mode in Devin) can help avoid that, but additional attention may still be required.";
export const APPROVAL_HINT = "Still working, or waiting on an approval in your terminal?";
export const APPROVAL_HINT_MS = 30_000;
// When a working agent's silence turns into "has not checked in".
export const STALE_MS = 2 * 60 * 1000;
// The soft line, shown before the stale message takes over. It sits at a fixed
// share of the stale limit (30 s of 2 min) rather than stretching on its own:
// stretched separately, a build's quietMinutes lifted both to the same moment
// and the soft line never showed where approvals stall most.
export function approvalHint(agent, quietMs) {
if (!agent || agent.status !== "working") return "";
const at = quietLimitMs(agent, STALE_MS) * (APPROVAL_HINT_MS / STALE_MS);
return quietMs >= at ? APPROVAL_HINT : "";
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,117 @@
// Planny's wake-up on a freshly opened dashboard: he sits powered down centre
// stage until the first click or key, gets nudged awake (he rocks side to side
// for one snore), then about five seconds of him powering on, then a glide
// into the rail as the menu comes in.
//
// The beats before the glide are pure CSS (keyframes on delays under
// `.wake.booting`, see app.css). The glide is the one part CSS cannot know on
// its own, because it ends wherever the rail's Planny sits right now, so this
// measures it once and hands CSS a single transform through --wake-glide.
//
// No DOM access at module scope, so `node --test` can import it.
// When the glide starts, and when the run is over at the latest. The CSS
// delays are the beats before GLIDE_AT_MS; the glide itself is 0.6 s.
export const GLIDE_AT_MS = 4300;
export const DONE_AT_MS = 5000;
// Plays the wake-up and resolves `{ skipped }` once the dashboard is fully
// awake. He waits powered down until the first click or key anywhere, which
// nudges him (`.stirring`) and calls `stir()` -- the page's cue to play one
// full snore, since a browser only lets a page make noise after a real click
// or keypress. The boot starts once the promise `stir()` returns settles (at
// once without one), and calls `onStart()`, the page's cue for the boot-up
// sound. `onGlide({ instant })` is the page's cue to bring the menu in: called
// at the glide, or with `instant: true` if the run ends before one (a skip).
// From the nudge on, clicks and keys are swallowed, so the run always plays
// out to the end with its sound; only `signal` aborting (the page leaving the
// dashboard, dormant or mid-run) cuts it short, as a skip. Under reduced
// motion nothing is shown and it resolves at once.
export function playWake({ stage, bot, target, stir, onStart, onGlide, signal }) {
return new Promise((resolve) => {
if (matchMedia("(prefers-reduced-motion: reduce)").matches || signal?.aborted) {
resolve({ skipped: false });
return;
}
const timers = [];
let glided = false;
let over = false;
const onGlideEnd = (e) => {
if (e.target === bot && e.propertyName === "transform") end(false);
};
const skip = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through.
const swallow = (e) => {
if (e.ctrlKey || e.metaKey || e.altKey) return;
e.preventDefault();
e.stopPropagation();
};
function glide() {
glided = true;
// Measured untransformed, as the sketch's glideToSlot() does: the
// transform-origin is the drawing's top-left, so the move is the gap
// between the two top-left corners and the scale is the width ratio.
// The target's own box, not its bounding rect: the rail's Planny is
// usually tilted mid-flight, and a tilted box measures wider than he
// is. Centred on the rect, which the tilt barely moves.
const from = bot.getBoundingClientRect();
const rect = target.getBoundingClientRect();
const w = target.clientWidth || rect.width;
const h = target.clientHeight || rect.height;
const left = rect.left + (rect.width - w) / 2;
const top = rect.top + (rect.height - h) / 2;
const scale = from.width ? w / from.width : 1;
bot.style.setProperty("--wake-glide", `translate(${left - from.left}px, ${top - from.top}px) scale(${scale})`);
bot.addEventListener("transitionend", onGlideEnd);
stage.classList.add("gliding");
onGlide({ instant: false });
}
function end(skipped) {
if (over) return;
over = true;
for (const t of timers) clearTimeout(t);
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
document.removeEventListener("pointerdown", swallow, true);
document.removeEventListener("keydown", swallow, true);
bot.removeEventListener("transitionend", onGlideEnd);
signal?.removeEventListener("abort", skip);
stage.hidden = true;
stage.classList.remove("dormant", "stirring", "booting", "gliding");
bot.style.removeProperty("--wake-glide");
if (!glided) onGlide({ instant: true });
resolve({ skipped });
}
// The waking click is the only input the run takes: from here on every
// click and key is swallowed until it ends.
function start(e) {
e.preventDefault();
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
stage.classList.replace("dormant", "stirring");
document.addEventListener("pointerdown", swallow, true);
document.addEventListener("keydown", swallow, true);
Promise.resolve(stir?.()).then(boot);
}
function boot() {
if (over) return;
stage.classList.replace("stirring", "booting");
onStart?.();
timers.push(setTimeout(glide, GLIDE_AT_MS));
// The glide's transitionend normally ends the run a touch earlier; this
// is the fallback for a transition that never fires (a hidden tab).
timers.push(setTimeout(() => end(false), DONE_AT_MS));
}
document.addEventListener("pointerdown", start, true);
document.addEventListener("keydown", start, true);
signal?.addEventListener("abort", skip);
stage.hidden = false;
stage.classList.add("dormant");
});
}
@@ -0,0 +1,224 @@
// Plan2Code Web Console - the Quick question chat's shared rules.
//
// Imported by the server (its guards) and by the page (its composer), so the
// two can never disagree about a limit. No DOM access at module scope, and no
// imports but answers.js: the server and `node --test` import this file too.
import { MAX_ATTACHMENTS, STALE_MS, quietLimitMs } from "./answers.js";
// Typed messages per conversation. Approve / Decline and resets never count.
export const CHAT_LIMIT = 10;
export const CHAT_MAX_CHARS = 4000;
// Images and documents together. The old name stays for existing imports.
export const CHAT_MAX_ATTACHMENTS = MAX_ATTACHMENTS;
export const CHAT_MAX_IMAGES = CHAT_MAX_ATTACHMENTS;
export const CHAT_LIMIT_TEXT = "That's 10 questions in this conversation — start a new one to keep going.";
export const CHAT_OFFLINE_TEXT = "No agent available — wait for one to become available (your terminal might be working on a task or waiting a permission approval)";
export const CHAT_LAST_WAIT_TEXT = "That was the last question in this conversation — its answer will land here.";
export const CHAT_WAITING_TEXT = "Plan2Code will answer at its next check-in";
export const CHAT_WORKING_TEXT = "Plan2Code is working on the answer…";
const EMPTY_CHAT = { conversation: 0, messages: [], typed: 0, limit: CHAT_LIMIT, offline: false, pickedUp: 0 };
const chatOf = (frameChat) => ({ ...EMPTY_CHAT, ...(frameChat || {}) });
// Person messages in the frame, each marked with whether an agent reply comes
// after it. The server puts a reply straight after the entry it answers, so a
// reply further down also covers the follow-ups sent before it.
function answeredFlags(messages) {
const flags = new Map();
let replyLater = false;
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m.from === "agent") replyLater = true;
else if (m.kind === "message") flags.set(m.seq, replyLater);
}
return flags;
}
/**
* What the Ask pane draws, in order: the conversation from the frame, then
* any send of this page's the server has not echoed yet.
*/
export function chatView(frameChat, ui = {}) {
const chat = chatOf(frameChat);
const messages = Array.isArray(chat.messages) ? chat.messages : [];
const answered = answeredFlags(messages);
const decisions = new Map(
messages.filter((m) => m.from === "person" && m.kind === "decision").map((m) => [m.re, m.decision])
);
const activity = typeof ui.agentActivity === "string" ? ui.agentActivity.trim() : "";
// The last seq the agent collected: an unanswered message at or below it is
// in the agent's hands, not still waiting for a check-in.
const pickedUp = Number.isInteger(chat.pickedUp) ? chat.pickedUp : 0;
const rows = [];
for (const m of messages) {
if (m.from === "agent") {
rows.push({
kind: "agent",
id: m.id,
md: m.md,
proposal: m.proposal || null,
changed: m.changed || null,
decided: decisions.get(m.id) || null,
});
} else if (m.kind === "decision") {
rows.push({ kind: "decision", decision: m.decision, text: m.text || "", re: m.re });
} else if (m.kind === "message") {
const row = {
kind: "person",
seq: m.seq,
text: m.text,
about: m.about || null,
images: m.images || [],
files: m.files || [],
};
if (!answered.get(m.seq)) {
row.waiting = true;
row.working = m.seq <= pickedUp;
row.waitingText = row.working ? CHAT_WORKING_TEXT : CHAT_WAITING_TEXT;
if (activity) row.activity = activity;
}
rows.push(row);
}
}
// A pending send is echoed once the server has it: by the seq its POST came
// back with, or, while that response is still on its way, by its text
// against a server message no other pending send has claimed.
const serverPerson = messages.filter((m) => m.from === "person" && m.kind === "message");
const serverSeqs = new Set(serverPerson.map((m) => m.seq));
const claimed = new Set((ui.pendingSends || []).filter((p) => p.seq).map((p) => p.seq));
for (const p of ui.pendingSends || []) {
if (p.seq) {
if (serverSeqs.has(p.seq)) continue;
} else {
const echo = serverPerson.find((m) => m.text === p.text && !claimed.has(m.seq));
if (echo) {
claimed.add(echo.seq);
continue;
}
}
rows.push({
kind: "person",
pending: true,
tempId: p.tempId,
text: p.text,
about: p.about || null,
images: p.images || [],
files: p.files || [],
failed: Boolean(p.failed),
});
}
return {
conversation: chat.conversation,
rows,
counterText: `${chat.typed} of ${chat.limit}`,
typed: chat.typed,
limit: chat.limit,
};
}
/**
* Whether the composer can take a message, and what to say when it cannot.
* Offline first, so a finished page never talks about the limit. The limit
* lands once the 10th question is answered; until then the 10th is simply
* waiting, and nothing more can be typed.
*/
export function sendState({ frameChat, gone, pendingSendCount = 0 }) {
const chat = chatOf(frameChat);
if (chat.offline || gone) return { state: "offline", text: CHAT_OFFLINE_TEXT, canType: false };
if (chat.typed + pendingSendCount >= chat.limit) {
const allAnswered = pendingSendCount === 0 && [...answeredFlags(chat.messages || []).values()].every(Boolean);
if (allAnswered) return { state: "limit", text: CHAT_LIMIT_TEXT, canType: false };
return { state: "ok", text: CHAT_LAST_WAIT_TEXT, canType: false };
}
return { state: "ok", text: "", canType: true };
}
const ABOUT_HISTORY = 3;
/**
* What a message is about, attached on purpose. Visiting a question card, doc
* section or spec only records it in `history` (the last 3 places, newest
* first, one entry per place); `about` is set only when the person picks one
* from + Add context, and × or a send clears it.
*
* The tracker is `{ history, about }`; each entry and `about` are
* `{ kind, id, label }` (`about` may be null), in the exact shape POST /chat
* takes. An old `{ about, frozen, dropped }` tracker normalises to an empty
* history.
*/
export function nextAbout(prev, event) {
const p = prev || {};
const state = { history: Array.isArray(p.history) ? [...p.history] : [], about: p.about ?? null };
const visit = (entry) => ({
...state,
history: [entry, ...state.history.filter((h) => h.kind !== entry.kind || h.id !== entry.id)].slice(0, ABOUT_HISTORY),
});
switch (event && event.type) {
case "card":
return visit({ kind: "card", id: String(event.id), label: String(event.label || "") });
case "section":
return visit({ kind: "section", id: `${event.docId}#${event.blockId}`, label: String(event.label || "") });
case "spec":
return visit({ kind: "spec", id: String(event.dir), label: String(event.label || "") });
case "pick":
return event.about ? { ...state, about: event.about } : state;
case "drop":
case "sent":
return { ...state, about: null };
default:
return state;
}
}
// What + Add context lists: the recent places, then "This spec" unless it is
// already one of them.
export function contextOptions(state, spec) {
const options = [...((state && state.history) || [])];
if (spec && spec.dir && !options.some((o) => o.kind === "spec" && o.id === spec.dir)) {
options.push({ kind: "spec", id: spec.dir, label: "This spec" });
}
return options;
}
const newestReply = (frameChat) => {
const messages = chatOf(frameChat).messages || [];
for (let i = messages.length - 1; i >= 0; i--) if (messages[i].from === "agent") return messages[i];
return null;
};
// The Ask tab's dot: a reply landed that the person has not seen.
export function unreadDot({ lastSeenReplyId, frameChat, viewIsAsk }) {
if (viewIsAsk) return false;
const reply = newestReply(frameChat);
return Boolean(reply) && reply.id !== lastSeenReplyId;
}
export function newestReplyId(frameChat) {
const reply = newestReply(frameChat);
return reply ? reply.id : null;
}
// One chime per reply: only the moment the dot appears.
export function shouldChime(prevDot, nextDot) {
return !prevDot && Boolean(nextDot);
}
// The page's own "has drifted away" threshold for an agent that is waiting.
const ADRIFT_MS = 3 * 60 * 1000;
/**
* Whether nobody is there to answer a chat message. A finished or paused
* session has no agent coming back to it; otherwise the agent is offline once
* it has been silent longer than the page would tolerate before calling it
* stuck (working) or adrift (anything else).
*/
export function chatOffline({ finish, agent, agentLastSeenMs, now }) {
if (finish) return true;
const silent = now - agentLastSeenMs;
if (agent && agent.status === "working") return silent > quietLimitMs(agent, STALE_MS);
return silent > quietLimitMs(agent, ADRIFT_MS);
}
@@ -0,0 +1,90 @@
// Plan2Code Web Console - the tab icon's status bar.
//
// The favicon follows the status line with a bar along its bottom edge: dashed
// amber while Plan2Code is busy, solid green when it is the person's move,
// solid red when it needs attention, and none (the plain Planny) once the
// session is finished. It reads from the same calls
// renderStatus() already makes for Planny's mood, so the icon and the line
// beside him can never disagree. No DOM access at module scope: `node --test`
// imports this file.
// Planny exactly as public/favicon.svg draws him (a test keeps the two in
// step), minus the <svg> wrapper so the bar can be layered on top.
export const FAVICON_BODY = `<rect x="4" y="4.6" width="24" height="30" rx="5" fill="#fff4ef" stroke="#3b332c" stroke-width="2.2" />
<path d="M16 9.8 L17.41 13.26 L21.14 13.53 L18.28 15.94 L19.17 19.57 L16 17.6 L12.83 19.57 L13.72 15.94 L10.86 13.53 L14.59 13.26 Z" fill="#ae4f2b" />
<path d="M11.6 22.2 Q16 26.4 20.4 22.2" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />`;
// The bar's color per state. `plain` has none.
export const FAVICON_COLORS = Object.freeze({
busy: "#f5a524",
ready: "#22c55e",
attention: "#e5484d",
});
/**
* Which icon a status line calls for. `mood` and `spin` are what renderStatus()
* handed to say(): `spin` marks something really happening at the other end
* right now, so that is busy. A working mood without the spin is the stale
* line ("has not checked in for a few minutes"), which, like adrift and gone,
* needs attention. `point` is the person's move. A finished session is plain
* unless it is visibly busy again (opening the dashboard, starting a review).
*/
export function faviconState({ mood, spin = false, finished = false } = {}) {
if (spin) return "busy";
if (finished) return "plain";
if (mood === "adrift" || mood === "gone" || mood === "work") return "attention";
if (mood === "point") return "ready";
return "plain";
}
/**
* The whole SVG for a state: Planny, plus a bar across the bottom edge, where
* he is cropped anyway. Busy's bar is dashed on a white strip (a progress bar
* mid-run) and the others solid, so busy differs by pattern as well as color:
* amber and green are close to one color for red-green color-blind eyes.
*/
export function faviconSvg(state) {
const color = FAVICON_COLORS[state];
let badge = "";
if (state === "busy") {
badge = `\n <rect x="0" y="27" width="32" height="5" fill="#ffffff" />\n <path d="M1.5 29.5 L30.5 29.5" stroke="${color}" stroke-width="4" stroke-dasharray="4 2.5" />`;
} else if (color) {
badge = `\n <rect x="0" y="27" width="32" height="5" rx="1" fill="${color}" />`;
}
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">\n ${FAVICON_BODY}${badge}\n</svg>\n`;
}
let shown = "plain";
/**
* Point the page's two icon links at `state`'s icon, only when it changed. The
* SVG link takes the variant as a data URL; the PNG link, for browsers that
* pick the bitmap, gets the same variant drawn through a canvas. Plain goes
* back to the served files.
*/
export function setFavicon(state) {
if (state === shown || typeof document === "undefined") return;
shown = state;
const svgLink = document.querySelector('link[rel="icon"][type="image/svg+xml"]');
const pngLink = document.querySelector('link[rel="icon"][type="image/png"]');
if (state === "plain") {
if (svgLink) svgLink.href = "/favicon.svg";
if (pngLink) pngLink.href = "/favicon.png";
return;
}
const url = "data:image/svg+xml," + encodeURIComponent(faviconSvg(state));
if (svgLink) svgLink.href = url;
if (!pngLink) return;
const img = new Image();
img.onload = () => {
// A newer state won the race while this one was loading.
if (shown !== state) return;
try {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 64;
canvas.getContext("2d").drawImage(img, 0, 0, 64, 64);
pngLink.href = canvas.toDataURL("image/png");
} catch {}
};
img.src = url;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<rect x="4" y="4.6" width="24" height="30" rx="5" fill="#fff4ef" stroke="#3b332c" stroke-width="2.2" />
<path d="M16 9.8 L17.41 13.26 L21.14 13.53 L18.28 15.94 L19.17 19.57 L16 17.6 L12.83 19.57 L13.72 15.94 L10.86 13.53 L14.59 13.26 Z" fill="#ae4f2b" />
<path d="M11.6 22.2 Q16 26.4 20.4 22.2" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />
</svg>

After

Width:  |  Height:  |  Size: 443 B

@@ -0,0 +1,65 @@
// Plan2Code Web Console - the Help dialog's tab list and rules.
//
// The source of truth for which tabs Help has, in what order, and which one
// opens. The content itself is HTML in <template id="help-content">
// in index.html. No DOM access at module scope and no imports: the page and
// `node --test` both import this file.
const tab = (id, label, diagram) => Object.freeze({ id, label, diagram });
export const HELP_TABS = Object.freeze([
tab("about", "What this page is", true),
tab("around", "Finding your way around", true),
tab("workspace", "Your workspace", false),
tab("planny", "Reading Planny", true),
tab("answering", "Answering questions", false),
tab("sending", "Sending and what happens next", true),
tab("notes", "Notes and attachments", false),
tab("docs", "Documents and printing", false),
tab("dashboard", "The dashboard", true),
tab("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("ask", "Ask a quick question", false),
tab("finishing", "Stopping and finishing", false),
tab("stuck", "When something looks stuck", true),
tab("prefs", "Keyboard and preferences", false),
tab("privacy", "Privacy and where things are saved", false),
]);
// Not labels.js's BUILD_WORKFLOWS: that one leaves out quick-task, which is a
// build as far as the person watching it is concerned.
const HELP_BUILD_WORKFLOWS = new Set(["implement", "implement-review", "quick-task"]);
// Which tab Help opens on, from where the person is. First match wins.
export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow, workspace, meterRed } = {}) {
const v = view || "";
// Finished comes first: a finished session's server is stopped on purpose,
// which also sets `gone`, and that is not something being stuck.
if (finished || v === "end") return "finishing";
if (gone || adrift) return "stuck";
if (workspace) return "workspace";
if (v === "ask") return "ask";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v.startsWith("doc:")) return "docs";
if (HELP_BUILD_WORKFLOWS.has(workflow)) return "build";
return "about";
}
// The tab index a key moves to, or -1 when the key is not a tab key.
export function helpKeyTarget(key, index, count) {
switch (key) {
case "ArrowDown":
case "ArrowRight":
return (index + 1) % count;
case "ArrowUp":
case "ArrowLeft":
return (index - 1 + count) % count;
case "Home":
return 0;
case "End":
return count - 1;
default:
return -1;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,31 @@
// Activity-line wording the page corrects on the way in. Kept out of app.js so
// `node --test` can import it: no DOM access at module scope.
//
// A build numbers its tasks "Task 4.2" after the phase, but a person watching
// the page counts within the phase, so "Task 4.2 of 6" reads as nonsense
// beside a progress bar that says 2 of 6.
// The only workflows whose activity lines get rewritten.
export const BUILD_WORKFLOWS = new Set(["implement", "implement-review"]);
const PHASE_TASK = /^Task (\d+)\.(\d+) of (\d+)/;
export function taskLabel(text) {
if (typeof text !== "string" || !PHASE_TASK.test(text)) return text;
return text.replace(PHASE_TASK, (_, _phase, n, total) => `Task ${n} of ${total}`);
}
// An activity line as the page shows it: rewritten in a build, as sent
// everywhere else (a plan's "Task 2.1" is a real section number).
export function activityLabel(text, workflow) {
return BUILD_WORKFLOWS.has(workflow) ? taskLabel(text) : text;
}
// What a working agent is doing, for a page with nothing asked yet: its
// activity line, or the headline note it posted instead. Either one means the
// skill has started, so the page leaves its starting screen.
export function workingLine(agent, headline, workflow) {
if (!agent || agent.status !== "working") return "";
if (typeof agent.activity === "string" && agent.activity.trim()) return activityLabel(agent.activity.trim(), workflow);
return typeof headline?.note === "string" ? headline.note.trim() : "";
}
@@ -0,0 +1,41 @@
// Plan2Code Web Console - `@name` suggestions in a text box.
//
// Finds the `@partial` the caret sits in, filters the workspace's folder
// names against it, and splices a pick back into the text. The page owns the
// popover; this file owns the rules. No DOM access at module scope and no
// imports: the page and `node --test` both import this file.
const NAME_CHAR = /[a-z0-9-]/;
const MAX_MATCHES = 6;
/**
* The mention the caret is in: `{ start, query }`, where `start` is the index
* of the `@`, or null. The `@` must open the text or follow whitespace or
* `(`, so an email address never offers suggestions.
*/
export function mentionAt(text, caret) {
let i = caret;
while (i > 0 && NAME_CHAR.test(text[i - 1])) i--;
const at = i - 1;
if (at < 0 || text[at] !== "@") return null;
if (at > 0 && !/[\s(]/.test(text[at - 1])) return null;
return { start: at, query: text.slice(i, caret) };
}
// Names starting with the query first, then names containing it, in the
// order given, at most six.
export function matchNames(names, query) {
const q = String(query || "");
const prefix = names.filter((n) => n.startsWith(q));
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
return [...prefix, ...inside].slice(0, MAX_MATCHES);
}
// The text with `@partial` replaced by `@name `, and the caret after the space.
export function applyMention(text, caret, mention, name) {
const insert = `@${name} `;
return {
text: text.slice(0, mention.start) + insert + text.slice(caret),
caret: mention.start + insert.length,
};
}
@@ -0,0 +1,98 @@
// Plan2Code Web Console - the session meter's weights, count and wording.
//
// The source of truth for how much each piece of work weighs, how the count
// is folded out of ledger.ndjson, and what the pill says at each level. The
// count is never stored: it is always pointsFrom() over the ledger. No DOM
// access at module scope and no imports: the server, console.mjs, the page
// and `node --test` all import this file.
// The one place the weights live (FR-12). Tune here.
export const WEIGHTS = Object.freeze({
"pathfinder-chart": 2,
"pathfinder-question": 1,
plan: 2,
"revise-plan": 1,
document: 2,
"implement-phase": 2,
"implement-review-phase": 3,
review: 2,
"quick-task": 1,
init: 2,
"init-update": 2,
finalize: 1,
handoff: 0,
});
// 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.
export const LAUNCH_COUNTED = Object.freeze(
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize"])
);
// The event names an agent may report in `run`.
export const RUN_EVENTS = new Set(Object.keys(WEIGHTS));
const weightOf = (key) => (Object.prototype.hasOwnProperty.call(WEIGHTS, key) ? WEIGHTS[key] : 0);
/**
* The session's points, folded from ledger entries in order. An id seen
* before is skipped, so a repeated `post` never counts twice.
*/
export function pointsFrom(entries) {
const seen = new Set();
let points = 0;
for (const entry of Array.isArray(entries) ? entries : []) {
if (!entry || typeof entry !== "object") continue;
if (entry.id !== undefined) {
if (seen.has(entry.id)) continue;
seen.add(entry.id);
}
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) points += weightOf(entry.workflow);
else if (entry.kind === "run") points += weightOf(entry.event);
}
return points;
}
export const YELLOW_AT = 4;
export const RED_AT = 6;
export const RING_FULL = 8;
export function levelFor(points) {
if (points < YELLOW_AT) return "green";
if (points < RED_AT) return "yellow";
return "red";
}
// How much of the ring is filled: full at RING_FULL, never below empty.
export function ringFraction(points) {
return Math.max(0, Math.min(points, RING_FULL)) / RING_FULL;
}
export const WORDS = Object.freeze({
green: "Session: fresh",
yellow: "Session: getting long",
red: "Session: time for a fresh start",
});
export function tooltipFor(points) {
const count = `${points} ${points === 1 ? "point" : "points"}`;
switch (levelFor(points)) {
case "green":
return `This session is fresh (${count}).`;
case "yellow":
return `This session is getting long (${count}). A fresh one will soon be sharper.`;
default:
return `This session has done a lot (${count}). The agent may start missing things.`;
}
}
export const RED_BANNER =
"This console session has done a lot. Starting a new console session will keep the agent sharp.";
// Everything the pill draws, from the ledger alone.
export function meterView(entries) {
const points = pointsFrom(entries);
const level = levelFor(points);
return { points, level, fraction: ringFraction(points), words: WORDS[level], tooltip: tooltipFor(points) };
}
@@ -0,0 +1,3 @@
{
"type": "module"
}
@@ -0,0 +1,238 @@
// The highlight colors, as data. Kept out of app.js for one reason: app.js
// cannot be imported outside a browser, and thirty-two colors each with four
// shades in two themes is far too many to trust to eyeballing. The test suite
// imports this and checks every one.
//
// The palette has three colors that MEAN something -- green settled, amber
// waiting, red careful. The reds, golds and greens here are offered anyway,
// because people asked for them; the help text in the dialog says what they
// share a hue with, and the choice is theirs.
//
// Each accent is four values, not one, because one color cannot do four jobs:
// fill the highlight itself: filled buttons, the marker on the open step
// soft a tint faint enough to sit behind body text
// ink what is legible ON the fill. Dark mode's accents are light shades,
// where a white label falls to about 2:1; they take a near-black.
// line the secondary: borders, badge edges, the dashed drop target.
//
// Every pair clears 4.5:1 for ink on fill and for fill on soft (the fill is
// also badge text on the soft tint). Everything after the first five was
// found by stepping lightness until both held, not picked by eye.
//
// Order is the order of the picker: round the wheel, then the greys. Sixteen
// a row, so the warm half and the greens sit on the first, the blues, purples,
// pinks and greys on the second.
export const ACCENTS = {
// name fill soft ink line
crimson: {
name: "Crimson",
light: ["#cd1d41", "#fbe9ed", "#ffffff", "#dcaab4"],
dark: ["#e75874", "#321b1f", "#140b0d", "#743e49"],
},
scarlet: {
name: "Scarlet",
light: ["#cf2317", "#fbebe9", "#ffffff", "#ddaaa7"],
dark: ["#eb594e", "#321c1b", "#140b0b", "#74403c"],
},
coral: {
name: "Coral",
light: ["#c83510", "#fbede9", "#ffffff", "#dcaca0"],
dark: ["#ef5b37", "#321f1b", "#140d0b", "#6f4237"],
},
rust: {
name: "Rust",
light: ["#ae4f2b", "#fbeee7", "#ffffff", "#dd9b7e"],
dark: ["#e8825a", "#34211a", "#1a120e", "#8a4f36"],
},
tangerine: {
name: "Tangerine",
light: ["#b15209", "#fbf1e9", "#ffffff", "#d9af8f"],
dark: ["#f2700d", "#32251b", "#140f0b", "#664830"],
},
copper: {
name: "Copper",
light: ["#a2592f", "#f9f0eb", "#ffffff", "#cdb2a2"],
dark: ["#cb7a4b", "#32231b", "#140e0b", "#5f493d"],
},
clay: {
name: "Clay",
light: ["#8d644c", "#f5f2f0", "#ffffff", "#bfafa6"],
dark: ["#ba957f", "#2b2521", "#17100c", "#62544b"],
},
marigold: {
name: "Marigold",
light: ["#9a6406", "#fbf5e9", "#ffffff", "#d3b279"],
dark: ["#f59f0a", "#32291b", "#14110b", "#5e4c2c"],
},
gold: {
name: "Gold",
light: ["#896b09", "#fbf7e9", "#ffffff", "#ccb66d"],
dark: ["#f0bb0f", "#322c1b", "#14120b", "#584d2a"],
},
mustard: {
name: "Mustard",
light: ["#806f1b", "#fbf8ea", "#ffffff", "#c3b881"],
dark: ["#d2b72d", "#322e1b", "#14120b", "#544e31"],
},
olive: {
name: "Olive",
light: ["#72742c", "#f8f8ed", "#ffffff", "#b8ba8c"],
dark: ["#b5b946", "#31321b", "#14140b", "#4f5037"],
},
lime: {
name: "Lime",
light: ["#577a1a", "#f4fbea", "#ffffff", "#a6c07a"],
dark: ["#96d22d", "#29321b", "#11140b", "#465230"],
},
moss: {
name: "Moss",
light: ["#577740", "#f2f6ee", "#ffffff", "#acbca1"],
dark: ["#79a659", "#24321b", "#0f140b", "#475140"],
},
emerald: {
name: "Emerald",
light: ["#207e47", "#ebfaf1", "#ffffff", "#8ac4a2"],
dark: ["#33cc73", "#1b3224", "#0b140f", "#345542"],
},
jade: {
name: "Jade",
light: ["#297c61", "#ecf9f4", "#ffffff", "#92c1b1"],
dark: ["#40bf95", "#1b322a", "#0b1411", "#38544b"],
},
teal: {
name: "Teal",
light: ["#0f766e", "#e2f1ef", "#ffffff", "#6fb3aa"],
dark: ["#5ecfc0", "#14302c", "#0b1a18", "#3a7d74"],
},
cyan: {
name: "Cyan",
light: ["#0f798a", "#ebf7f9", "#ffffff", "#75bec9"],
dark: ["#19cae6", "#183034", "#0c1617", "#305f66"],
},
sky: {
name: "Sky",
light: ["#0e74a7", "#ebf5fa", "#ffffff", "#85b9d3"],
dark: ["#21a9ed", "#182b35", "#0c1417", "#325c71"],
},
ocean: {
name: "Ocean",
light: ["#206cc3", "#ecf2f9", "#ffffff", "#9ab4d3"],
dark: ["#619fe5", "#1a2533", "#0c1117", "#3d5978"],
},
navy: {
name: "Navy",
light: ["#24396b", "#eef0f7", "#ffffff", "#a7b3cd"],
dark: ["#819ad5", "#1e232f", "#0c1017", "#4a5775"],
},
cobalt: {
name: "Cobalt",
light: ["#405ce7", "#ebeef9", "#ffffff", "#a8b0dc"],
dark: ["#7b8fef", "#191d34", "#0c0e17", "#465392"],
},
indigo: {
name: "Indigo",
light: ["#4f46e5", "#ecebfb", "#ffffff", "#9b95ef"],
dark: ["#a5a0ff", "#1e1d3a", "#121129", "#5f5ba8"],
},
violet: {
name: "Violet",
light: ["#7f4dd5", "#f1edf8", "#ffffff", "#bbabd6"],
dark: ["#a785e2", "#231c31", "#100c17", "#624c87"],
},
lilac: {
name: "Lilac",
light: ["#8b51b8", "#f3eff6", "#ffffff", "#beaccb"],
dark: ["#b189cf", "#271f2d", "#130c17", "#634f73"],
},
orchid: {
name: "Orchid",
light: ["#a141b9", "#f5eef7", "#ffffff", "#c5a8cc"],
dark: ["#c281d3", "#2b1e2f", "#150c17", "#6c4b74"],
},
magenta: {
name: "Magenta",
light: ["#b82eaa", "#f8edf7", "#ffffff", "#d1a3cc"],
dark: ["#dc72d1", "#311c2f", "#170c16", "#784573"],
},
plum: {
name: "Plum",
light: ["#8a3b6b", "#f8eaf2", "#ffffff", "#c88cb0"],
dark: ["#e08ab8", "#331a29", "#1d1017", "#8a5570"],
},
rose: {
name: "Rose",
light: ["#c42e6a", "#f8edf1", "#ffffff", "#d3a6b8"],
dark: ["#df77a0", "#311c24", "#170c11", "#7c465b"],
},
steel: {
name: "Steel",
light: ["#50737c", "#f0f3f4", "#ffffff", "#a5b5b8"],
dark: ["#7fa4ad", "#22292a", "#0c1517", "#4c595c"],
},
slate: {
name: "Slate",
light: ["#5b6e88", "#f0f2f4", "#ffffff", "#acb3bc"],
dark: ["#8e9eb4", "#23262a", "#0c1117", "#515861"],
},
mauve: {
name: "Mauve",
light: ["#816281", "#f4f1f4", "#ffffff", "#bbafbb"],
dark: ["#ae93ae", "#292329", "#170c17", "#5f545f"],
},
graphite: {
name: "Graphite",
light: ["#4a4640", "#eeedea", "#ffffff", "#a8a196"],
dark: ["#cfc7bb", "#2b2a28", "#161513", "#7a7369"],
},
};
export const DEFAULT_ACCENT = "rust";
// The card-width presets. Here for the same reason the accents are: the page
// validates a saved `looks.width` with cardWidth(), and the server uses it to
// paint the first-load `data-width` attribute before app.js runs. One list,
// two readers, no drift.
export const CARD_WIDTHS = {
narrow: { label: "Narrow", px: 720 },
comfortable: { label: "Comfortable", px: 880 },
wide: { label: "Wide", px: 1080 },
};
export const DEFAULT_CARD_WIDTH = "comfortable";
export function cardWidth(value) {
return typeof value === "string" && Object.hasOwn(CARD_WIDTHS, value) ? value : DEFAULT_CARD_WIDTH;
}
// Every moment the page makes a noise, each switchable on its own in User
// Preferences (the `data-sound` boxes in index.html). Several share a file;
// the event, not the file, is what a person turns off. `rank` settles which
// wins when two ask at once (see the sounds section in app.js). Stored flat as
// `soundQuestion` and so on, because looks.json only holds flat values.
export const SOUND_EVENTS = {
startSkill: { file: "start-skill", rank: 5 },
bootup: { file: "bootup", rank: 4 },
sessionStart: { file: "start-stop", rank: 3 },
sessionEnd: { file: "start-stop", rank: 3 },
question: { file: "next", rank: 2 },
skillReady: { file: "next", rank: 2 },
chatReply: { file: "next", rank: 2 },
newTab: { file: "insert", rank: 1 },
snore: { file: "sleeping", rank: 0 },
};
export const soundKey = (event) => "sound" + event[0].toUpperCase() + event.slice(1);
// The per-event switches out of a saved looks object: each one as saved when
// it is a boolean, on otherwise. A looks.json from before the switches has
// none of these keys, so it keeps every sound.
export function soundPrefs(saved) {
const source = saved && typeof saved === "object" ? saved : {};
return Object.fromEntries(
Object.keys(SOUND_EVENTS).map((event) => {
const value = source[soundKey(event)];
return [soundKey(event), typeof value === "boolean" ? value : true];
})
);
}
@@ -0,0 +1,278 @@
// Markdown to DOM, safely.
//
// The rule this file exists to enforce: NO HTML STRING IS EVER PRODUCED.
// We take marked's token tree and build nodes with createElement/textContent.
//
// Why that matters more than it looks: this page is same-origin with a server
// that reads and writes the user's files and holds the session cookie. Script
// running here could post arbitrary answers back to the agent, which would then
// act on them with the agent's full tool permissions. And the markdown is only
// nominally agent-authored: in practice the agent is summarising a dependency
// README, a scraped page, a PR description, a log. Treat it as hostile.
//
// Building nodes rather than parsing a string makes injection structurally
// impossible instead of filtered, so there is nothing for a sanitiser bypass to
// bypass. `html` tokens render as visible text, on purpose.
import { marked } from "./vendor/marked.esm.js";
// A bare `/` path stays on this origin; `//host` (and `/\host`, which browsers
// read the same way) is protocol-relative and would not, so it is refused.
const SAFE_PROTOCOL = /^(https?:|mailto:|#|\/(?![/\\]))/i;
function safeHref(href) {
if (!href) return null;
const trimmed = String(href).trim();
// Blocks javascript: and data: hrefs before they can reach the DOM.
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
}
function el(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text != null) node.textContent = text;
return node;
}
function inlineInto(parent, tokens) {
for (const t of tokens || []) {
switch (t.type) {
case "text":
// Nested inline tokens (a link inside emphasis, say) arrive here.
if (t.tokens && t.tokens.length) inlineInto(parent, t.tokens);
else parent.appendChild(document.createTextNode(t.text ?? t.raw ?? ""));
break;
case "escape":
parent.appendChild(document.createTextNode(t.text));
break;
case "strong": {
const n = el("strong");
inlineInto(n, t.tokens);
parent.appendChild(n);
break;
}
case "em": {
const n = el("em");
inlineInto(n, t.tokens);
parent.appendChild(n);
break;
}
case "del": {
const n = el("s");
inlineInto(n, t.tokens);
parent.appendChild(n);
break;
}
case "codespan":
parent.appendChild(el("code", "md-code", t.text));
break;
case "br":
parent.appendChild(document.createElement("br"));
break;
case "link": {
const href = safeHref(t.href);
if (!href) {
inlineInto(parent, t.tokens);
break;
}
const a = el("a");
a.href = href;
a.rel = "noopener noreferrer";
if (/^https?:/i.test(href)) a.target = "_blank";
if (t.title) a.title = t.title;
inlineInto(a, t.tokens);
parent.appendChild(a);
break;
}
case "image": {
const src = safeHref(t.href);
if (!src) {
parent.appendChild(document.createTextNode(t.text || ""));
break;
}
const img = el("img", "md-img");
img.src = src;
img.alt = t.text || "";
parent.appendChild(img);
break;
}
default:
// Includes `html`: rendered as literal text, never parsed.
parent.appendChild(document.createTextNode(t.raw ?? t.text ?? ""));
}
}
}
function blockInto(parent, tokens) {
for (const t of tokens || []) {
switch (t.type) {
case "space":
break;
case "heading": {
const level = Math.min(6, Math.max(2, (t.depth || 1) + 1)); // never an h1: the page owns that
const h = el("h" + level, "md-h");
inlineInto(h, t.tokens);
parent.appendChild(h);
break;
}
case "paragraph": {
const p = el("p", "md-p");
inlineInto(p, t.tokens);
parent.appendChild(p);
break;
}
case "text": {
const p = el("p", "md-p");
if (t.tokens) inlineInto(p, t.tokens);
else p.textContent = t.text || "";
parent.appendChild(p);
break;
}
case "blockquote": {
const q = el("blockquote", "md-quote");
blockInto(q, t.tokens);
parent.appendChild(q);
break;
}
case "code": {
const wrap = el("div", "md-pre-wrap");
const pre = el("pre", "md-pre");
// textContent, so a fenced block containing markup is inert.
pre.appendChild(el("code", null, t.text));
wrap.appendChild(copyButton(t.text, "md-copy"));
wrap.appendChild(pre);
parent.appendChild(wrap);
break;
}
case "hr":
parent.appendChild(el("hr", "md-hr"));
break;
case "list": {
const list = el(t.ordered ? "ol" : "ul", "md-list");
if (t.ordered && typeof t.start === "number" && t.start !== 1) list.start = t.start;
for (const item of t.items || []) {
const li = el("li", "md-li" + (item.task ? " is-task" : ""));
if (item.task) {
const box = el("span", "md-task" + (item.checked ? " is-done" : ""));
box.textContent = item.checked ? "✓" : "·";
box.setAttribute("aria-label", item.checked ? "done" : "not done");
li.appendChild(box);
}
blockInto(li, item.tokens);
list.appendChild(li);
}
parent.appendChild(list);
break;
}
case "table": {
const scroll = el("div", "md-table-wrap");
const table = el("table", "md-table");
const thead = el("thead");
const hr = el("tr");
(t.header || []).forEach((cell, i) => {
const th = el("th");
if (t.align && t.align[i]) th.style.textAlign = t.align[i];
inlineInto(th, cell.tokens);
hr.appendChild(th);
});
thead.appendChild(hr);
table.appendChild(thead);
const tbody = el("tbody");
for (const row of t.rows || []) {
const tr = el("tr");
row.forEach((cell, i) => {
const td = el("td");
if (t.align && t.align[i]) td.style.textAlign = t.align[i];
inlineInto(td, cell.tokens);
tr.appendChild(td);
});
tbody.appendChild(tr);
}
table.appendChild(tbody);
scroll.appendChild(table);
parent.appendChild(scroll);
break;
}
default: {
// Unknown or raw html block: show the source, do not interpret it.
const p = el("p", "md-p");
p.textContent = t.raw ?? t.text ?? "";
parent.appendChild(p);
}
}
}
}
/** Render markdown into a fresh element. Returns the element. */
export function md(source, className = "md") {
const host = el("div", className);
if (!source) return host;
let tokens;
try {
tokens = marked.lexer(String(source));
} catch {
host.appendChild(el("p", "md-p", String(source)));
return host;
}
blockInto(host, tokens);
return host;
}
/** Render markdown into an existing element, replacing its contents. */
export function mdInto(node, source) {
node.replaceChildren();
const rendered = md(source);
while (rendered.firstChild) node.appendChild(rendered.firstChild);
return node;
}
// The page's only clipboard action, in one place. writeText can be refused --
// a browser that has not granted the permission, a page that was not focused
// when the click landed -- and a button that silently does nothing is worse
// than one that says what to press instead.
//
// It lives here rather than in app.js because app.js imports this file and not
// the other way round, and a fenced code block needed it first.
//
// copyText() is the action itself: `button` reads "Copied" for a moment, then
// `label` again. `label` may be a function, read when the moment is up, for a
// button whose text can change in the meantime. `onRefused` is what the caller
// offers instead when the browser says no -- usually a selection to press
// Ctrl+C on.
async function copyText(text, button, label, onRefused) {
try {
await navigator.clipboard.writeText(text);
button.textContent = "Copied";
setTimeout(() => (button.textContent = typeof label === "function" ? label() : label), 1400);
} catch {
onRefused();
}
}
function selectContents(node) {
try {
const range = document.createRange();
range.selectNodeContents(node);
const sel = getSelection();
sel.removeAllRanges();
sel.addRange(range);
} catch {}
}
function copyButton(text, className, source) {
const b = el("button", className || "btn small", "Copy");
b.type = "button";
b.addEventListener("click", () =>
copyText(text, b, "Copy", () => {
// "Press Ctrl+C" on its own asks them to copy a selection that does not
// exist. Select the text for them, so the instruction is one they can
// actually follow.
const node = source || b.parentNode.querySelector("pre, code");
if (node) selectContents(node);
b.textContent = "Press Ctrl+C";
})
);
return b;
}
export { el, copyButton, copyText, selectContents };
@@ -0,0 +1,254 @@
// Plan2Code Web Console - roles, starter templates and Ask starter questions.
//
// The source of truth for the Role list in User Preferences, the starter
// templates on the first "What's the idea?" card of Pathfinder, Plan and Quick
// Task, the order each role sees them in, and the starter questions an empty
// Ask conversation offers. No DOM access at module scope and no imports: the
// page and `node --test` both import this file.
const role = (id, label) => Object.freeze({ id, label });
export const ROLES = Object.freeze([
role("engineer", "Engineer"),
role("pm", "Product lead / PM"),
role("architect", "Architect / tech lead"),
role("designer", "Designer (UX)"),
role("qa", "QA / test engineer"),
role("em", "Engineering manager"),
]);
export const ROLE_NOT_SET = "none";
export const ROLE_NOT_SET_LABEL = "Not set / none of these";
export const TEMPLATE_WORKFLOWS = Object.freeze(["pathfinder", "plan", "quick-task"]);
const ROLE_IDS = new Set(ROLES.map((r) => r.id));
// A known role id, or "none" for anything else (missing, unknown, not a string).
export function normalizeRole(value) {
return ROLE_IDS.has(value) ? value : ROLE_NOT_SET;
}
// The dashboard nudge shows until looks.json carries a role of any value:
// choosing Not set, or pressing Not now, ends it just as a real role does.
export function needsRoleNudge(looks) {
if (!looks || typeof looks !== "object") return true;
return !Object.hasOwn(looks, "role");
}
// The wording is approved (PLAN-DRAFT Appendix A); a change is a page change.
const template = (id, label, lines) => Object.freeze({ id, label, text: lines.join("\n") });
export const TEMPLATES = Object.freeze({
"engineering-spec": template("engineering-spec", "Engineering spec", [
"Engineering spec for: [the feature or change, in a sentence]",
"Who reads it: the engineers who will build and review it.",
"What it should pin down: the behaviour, the parts of the code it touches, the interfaces between them, and how we'll know it works.",
"What I already know: [constraints, links, earlier attempts]",
]),
"product-requirements": template("product-requirements", "Product requirements", [
"Product requirements for: [the feature, in a sentence]",
"Who it's for: [the users], and the product, design and engineering people deciding on it.",
"What it should pin down: the problem, who has it, what success looks like, and what waits for later.",
"What I already know: [customer asks, data, deadlines]",
]),
"design-decision": template("design-decision", "Design decision", [
"A design decision to work out: [the choice we're facing, in a sentence]",
"Who it's for: the engineers and architects who will live with it.",
"What it should pin down: the options, the trade-offs of each, the one we pick and why, and what it costs us later.",
"Constraints: [performance, compatibility, deadlines, team skills]",
]),
"test-strategy": template("test-strategy", "Test strategy", [
"Test strategy for: [the feature or area]",
"Who reads it: QA and the engineers writing the tests.",
'What it should pin down: what\'s risky, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
"What exists today: [current tests, known gaps]",
]),
"scoping-rollout": template("scoping-rollout", "Scoping & rollout", [
"Scoping and rollout for: [the feature or project]",
"Who reads it: the engineering manager, the product lead and the team.",
"What it should pin down: what's in the first release and what waits, the build order, risks to the timeline, and how it reaches users (flags, stages, who goes first).",
"Constraints: [dates, people, dependencies]",
]),
"brainstorm-notes": template("brainstorm-notes", "Brainstorm → curated notes", [
"Brainstorm to turn into curated notes: [the topic or rough idea]",
"Who reads the notes: [the team or people this goes to]",
"What I want out of it: the ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
"Starting thoughts: [anything already on your mind]",
]),
"bug-investigation": template("bug-investigation", "Bug investigation", [
"Bug to investigate: [what's going wrong, in a sentence]",
"Steps to reproduce: [1. ... 2. ...]",
"Expected: [what should happen]. Actual: [what happens instead]",
"Where and since when: [environment, version, first seen]",
]),
"small-change": template("small-change", "Small change", [
"Small change: [what to change, in a sentence]",
"Where: [the file, screen or command, if you know it]",
"Done when: [how you'll tell it worked]",
]),
"copy-tweak": template("copy-tweak", "Copy / content tweak", [
"Change the wording of: [the screen, message, email or doc]",
"Current text: [paste it]",
"New text: [paste it, or describe the tone you want]",
"Who reads it: [the people who see it]",
]),
"ui-polish": template("ui-polish", "UI polish", [
"UI polish on: [the screen or component]",
"What looks or feels off: [spacing, alignment, colour, states, small screens]",
"What good looks like: [a reference, screenshot or description]",
"Leave alone: [anything that must not move]",
]),
"visual-prototype": template("visual-prototype", "Visual prototype", [
"A throwaway visual prototype of: [the screen or component]",
"What to show: [the states or flows to click through]",
"What I want to learn: [the question it should answer]",
"Where it lives: a prototypes/ folder [or its own branch], never wired into the real code.",
]),
"add-a-test": template("add-a-test", "Add a test", [
"Add a test for: [the function, behaviour or bug]",
"Cases to cover: [the normal case, the edge cases, the bug it guards against]",
"Where tests live: [the test file or folder, if you know it]",
]),
"record-decision": template("record-decision", "Record a decision", [
"Record a decision we've already made: [the decision, in a sentence]",
"Why: [the reasons, and what we turned down]",
"What it commits us to: [the consequences]",
"Save it as an ADR in: docs/adr/ [or wherever this repo keeps them]",
]),
});
const orders = (byRole) => Object.freeze(Object.fromEntries(Object.entries(byRole).map(([r, ids]) => [r, Object.freeze(ids)])));
// One full order per role per skill. No "none" row: Not set reads Engineer's.
export const TEMPLATE_ORDERS = Object.freeze({
pathfinder: orders({
engineer: ["engineering-spec", "design-decision", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "engineering-spec", "design-decision", "test-strategy"],
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
designer: ["brainstorm-notes", "product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy"],
qa: ["test-strategy", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision", "brainstorm-notes"],
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "design-decision", "brainstorm-notes"],
}),
plan: orders({
engineer: ["engineering-spec", "bug-investigation", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "test-strategy", "design-decision", "bug-investigation"],
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "bug-investigation"],
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "bug-investigation"],
qa: ["test-strategy", "bug-investigation", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision"],
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "bug-investigation", "design-decision"],
}),
"quick-task": orders({
engineer: ["small-change", "bug-investigation", "add-a-test", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "add-a-test", "record-decision"],
architect: ["record-decision", "small-change", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "add-a-test", "record-decision"],
qa: ["add-a-test", "bug-investigation", "small-change", "ui-polish", "copy-tweak", "visual-prototype", "record-decision"],
em: ["small-change", "record-decision", "add-a-test", "bug-investigation", "copy-tweak", "ui-polish", "visual-prototype"],
}),
});
const roleRow = (role) => {
const r = normalizeRole(role);
return r === ROLE_NOT_SET ? "engineer" : r;
};
/**
* The idea card's template row for a skill: Blank first, then the skill's
* templates in the role's order. The first template carries `forYou` only for
* a chosen role, never for Not set. `[]` for a skill with no templates.
*/
export function templatesFor(workflow, role) {
if (!TEMPLATE_WORKFLOWS.includes(workflow)) return [];
const chosen = normalizeRole(role) !== ROLE_NOT_SET;
const ordered = TEMPLATE_ORDERS[workflow][roleRow(role)].map((id, i) => {
const { label, text } = TEMPLATES[id];
return { id, label, text, forYou: chosen && i === 0 };
});
return [{ id: "blank", label: "Blank", text: "" }, ...ordered];
}
// Swapping templates: an empty box, or one untouched since the last pick,
// swaps silently; anything the person typed asks first.
export function templateSwap({ selectedText, boxText, nextText } = {}) {
const box = typeof boxText === "string" ? boxText : "";
const selected = typeof selectedText === "string" ? selectedText : "";
return { text: typeof nextText === "string" ? nextText : "", confirm: box.trim() !== "" && box !== selected };
}
// Ask starter questions (PLAN-DRAFT Appendix B, approved). `lead` names the
// roles that see a starter first; `needsContext` starters wait for
// + Add context.
const starter = (id, text, lead, needsContext = false) =>
Object.freeze({ id, text, lead: Object.freeze(lead), needsContext });
export const STARTER_SETS = Object.freeze({
pathfinder: Object.freeze([
starter("pathfinder-files", "Which files or parts of the code does this decision touch?", ["engineer", "architect"], true),
starter("pathfinder-prior-art", "Has anything like this been done elsewhere in the repo?", ["engineer", "architect"]),
starter("pathfinder-decided", "What have we already decided, and what's still open?", ["pm", "em", "architect"]),
starter("pathfinder-plain", "What does this question mean, in plain words?", ["pm", "designer", "em"], true),
]),
plan: Object.freeze([
starter("plan-files", "Which existing files would this plan change?", ["engineer", "architect"]),
starter("plan-test", "How would we test this?", ["qa", "engineer"], true),
starter("plan-risks", "What are the biggest risks or unknowns in this plan?", ["architect", "em", "qa"]),
starter("plan-plain", "Explain this section as if I'm not an engineer.", ["pm", "designer", "em"], true),
]),
document: Object.freeze([
starter("document-touch", "Where does this phase touch existing code?", ["engineer"], true),
starter("document-guesses", "Which parts of this phase are still guesses?", ["architect", "engineer"], true),
starter("document-users", "What will users notice once every phase ships?", ["designer", "pm", "qa"]),
starter("document-summary", "Summarize the phases written so far in three bullets.", ["pm", "em"]),
]),
build: Object.freeze([
starter("build-last-task", "What changed in the last task, and why?", ["engineer", "em", "qa"]),
starter("build-finding", "Where exactly is this finding in the code?", ["engineer", "qa"], true),
starter("build-progress", "How far along are we, and what's next?", ["em", "pm"]),
starter("build-check", "What should I check by hand after this phase?", ["qa", "designer"]),
]),
"quick-task": Object.freeze([
starter("quick-task-files", "Which files will this touch?", ["engineer"]),
starter("quick-task-pattern", "Is there a similar pattern in the code I should follow?", ["engineer", "architect"]),
starter("quick-task-size", "Is this bigger than a quick task?", ["em", "architect"]),
starter("quick-task-try", "How do I try this out once it's done?", ["qa", "designer", "pm"]),
]),
dashboard: Object.freeze([
starter("dashboard-project", "What does this project do, in a paragraph?", ["pm", "designer", "em"]),
starter("dashboard-which-skill", "Which skill should I use for my idea?", ["pm", "designer", "em"]),
starter("dashboard-difference", "What's the difference between Pathfinder, Plan and Quick Task?", []),
starter("dashboard-spec", "Where does this spec stand?", ["pm", "em"], true),
]),
general: Object.freeze([
starter("general-step", "What is this step going to do, and what will it change?", []),
starter("general-summary", "Summarize this session so far.", ["em", "pm"]),
starter("general-left", "What's left to do after this?", ["em", "pm"]),
]),
});
// Workflows missing here (init, init-update, revise-plan, finalize, handoff,
// anything unknown) use the general set.
export const STARTER_SET_FOR = Object.freeze({
pathfinder: "pathfinder",
plan: "plan",
document: "document",
implement: "build",
"implement-review": "build",
review: "build",
"quick-task": "quick-task",
dashboard: "dashboard",
});
/**
* The starters an empty Ask conversation offers: the workflow's set, minus
* those that need context until some is attached, with the role's leads
* first and written order kept inside each group. Not set leads as Engineer.
*/
export function startersFor(workflow, role, { hasContext } = {}) {
const setId = Object.hasOwn(STARTER_SET_FOR, workflow) ? STARTER_SET_FOR[workflow] : "general";
const lead = roleRow(role);
const shown = STARTER_SETS[setId].filter((s) => hasContext || !s.needsContext);
const first = shown.filter((s) => s.lead.includes(lead));
const rest = shown.filter((s) => !s.lead.includes(lead));
return [...first, ...rest].map(({ id, text }) => ({ id, text }));
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,92 @@
// Plan2Code Web Console - the Workspace's naming and wording rules.
//
// The source of truth for what a folder may be called, the name a new folder
// gets by default, and the suggestion offered when a name is taken. Imported
// by the server (its guards), lib.mjs and the page, so they can never disagree.
// No DOM access at module scope and no imports: the page and `node --test`
// both import this file.
export const NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
export const NAME_MAX = 40;
const trimDashes = (s) => s.replace(/^-+|-+$/g, "");
/**
* The name a folder gets before anyone renames it: its last path segment,
* lowercased, with every run of other characters turned into one `-`.
*/
export function defaultName(folderPath) {
const segments = String(folderPath || "")
.split(/[\\/]/)
.filter(Boolean);
const last = segments.length ? segments[segments.length - 1] : "";
const name = trimDashes(trimDashes(last.toLowerCase().replace(/[^a-z0-9]+/g, "-")).slice(0, NAME_MAX));
return name || "folder";
}
// null when the name can be used, "bad-name" when it cannot.
export function nameProblem(name) {
if (typeof name !== "string" || !name || name.length > NAME_MAX || !NAME_PATTERN.test(name)) return "bad-name";
return null;
}
/**
* `base` when nobody has it, else the first free `base-2`, `base-3`, ...
* `base` is shortened first so the suffixed name still fits NAME_MAX.
*/
export function freeName(base, taken) {
if (!taken.has(base)) return base;
for (let n = 2; ; n++) {
const suffix = `-${n}`;
const candidate = trimDashes(base.slice(0, NAME_MAX - suffix.length)) + suffix;
if (!taken.has(candidate)) return candidate;
}
}
// How many footer label tiers there are: the page tries 0..FOOTER_TIERS-1,
// widest first, until the text fits.
export const FOOTER_TIERS = 4;
/**
* The footer's workspace label. `folders[0]` is the original folder.
* 0 plan2code + 2 folders · main
* 1 plan2code + 2 folders
* 2 plan2code +2
* 3 plan2code
*/
export function footerLabel({ folders, branch }, tier = 0) {
const list = Array.isArray(folders) ? folders : [];
const name = list.length ? list[0].name : "";
const n = Math.max(0, list.length - 1);
if (tier >= 3) return name;
let label = name;
if (n > 0) label += tier === 2 ? ` +${n}` : ` + ${n} ${n === 1 ? "folder" : "folders"}`;
if (tier === 0 && branch) label += ` · ${branch}`;
return label;
}
/**
* The reply line an agent is handed for one workspace.json change entry
* (`{ kind, name, path, description?, from? }`).
*/
export function changeLine(change) {
const { kind, name, path, description, from } = change || {};
switch (kind) {
case "added":
return `Workspace: added @${name} — ${path}` + (description ? ` (${description})` : "");
case "renamed":
return `Workspace: renamed @${from} to @${name} — ${path}`;
case "described":
return description
? `Workspace: @${name} is now described as "${description}"`
: `Workspace: @${name} description cleared`;
case "removed":
return `Workspace: removed @${name} — ${path}`;
case "missing":
return `Workspace: @${name} is missing — ${path} no longer exists`;
case "found":
return `Workspace: @${name} is back — ${path}`;
default:
return `Workspace: @${name} changed — ${path}`;
}
}
File diff suppressed because it is too large. Load diff
Loaded 100 of 523 files, more files were not shown because too many files have changed in this diff. Show more