Sync upstream v2.4.0 into v2.4.1: welcome dialog, bug/idea button with issue templates, version in Help, gear preferences and ocean default accent, plus web console screenshots, new landing page and web-console-first docs

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-02 20:51:34 -07:00
1 parent 0d7c2e140b
commit cb86034de9
288 files changed
+25222 -4767

No files matched your search

+8 -4
View File
@@ -39,6 +39,8 @@ plan2code/
│ ├── console.mjs # CLI the agent drives: open, post, wait, stop
│ └── public/ # Page assets served to the browser
├── scripts/ # Development scripts
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs puppeteer-core)
│ ├── screenshots/ # One JSON payload per staged screen, read by capture-screenshots.mjs
│ └── validate-char-count.js # Pre-commit character count validator
├── skills/ # Committed build artifact — one Agent Skill per src/ prompt
│ └── plan2code-<name>/ # SKILL.md plus references/ where present
@@ -48,6 +50,7 @@ plan2code/
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/
├── docs/ # Documentation and assets
│ └── screenshots/ # Web console screenshots, <shot>-light.webp and <shot>-dark.webp (generated)
├── specs/ # Feature specs (if any in-progress)
├── install.js # Interactive installer (Node.js)
├── package.json # Root package (husky only, private: true)
@@ -138,19 +141,20 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `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 |
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `app.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of `app.js`'s render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
| `console.md` | the 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:
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `app.js`.
- **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.
- **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 open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `app.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `app.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
- **The 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.
@@ -167,13 +171,13 @@ Key design points:
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.
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `server.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `lib.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
- **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.
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `lib.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
- **`validate()` in `lib.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
- **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.
+1 -1
View File
@@ -18,7 +18,7 @@
- **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,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.
- **Workflow file character limit:** All `src/plan2code-*.md` files (and the dashboard prompt `src/plan2code.md`) 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,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 `\|`.
@@ -16,6 +16,13 @@ npm run build:skills
# Character-count validation + skills/ drift check
npm test
# Refresh the web console screenshots in docs/screenshots/ (needs a local Chrome or Edge).
# Rerun after any change a person would see on the console page, and open every image
# before committing: right screen, both themes, no username or home path in frame.
npm i --no-save puppeteer-core # once; never added to package.json
node scripts/capture-screenshots.mjs # every screen
node scripts/capture-screenshots.mjs --only dashboard # one screen
# Plan2Code Loop
cd plan2code-loop && npm install # First time setup
cd plan2code-loop && npm run build # Build the CLI
+1 -1
View File
@@ -1 +1 @@
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
U0VOQwErJ48kORFACZSnsphnJIwkZvzfvDDm32pRub1X968+xmjPhFzBYj4CZgfvy+A4aoKW4RgsV97CEx0Xa6YqvBybBT/M7RykZpBSDWrTtgLi5op0Hxk2eI5TDer52ID4z55AgOPrOW4fT0bSv0RMdP/fh7N5Q65TG5fduMeAxlqiPyVfYldmX9OqV6xDhSPsatfWaJQhJ3/i3xfVRHP7q4ChHQiUx5DnwnkV/WEPYw1KXcMzxLBQHrn/0POxfzQwVWpji9ref8ZbG//HmOCxWNA6Z087LVHIT7gyt9TcBD+Lq2VF3FjMGoR/40agNrbXXDMgpAKJrRk88+Q5q8IPJmQXG9txDZay9+bGIqM7xpuowg6OZbsXD4r/FHUiuOEtn1uBWTBKZ71UEprzo6Ips20Xa2SBBM6+poOVOlNDVhEdem652awNlzRdqoWAYEOtmSKdbnwUlhfFhewV0nfjgB2lMs8PA/oGSjevaO+5R9JAOSU2r+y1Nnfa3fRNvzuls+1FHo4y7FOeKKHpSbWGERYLnWxD4wnfzE1FW8jtglk06lzf7mrJFCS0ApjMAj6acHg2It7YDD4yOoC7Qe/bCSouyu5Zy32bdKAwGeg1H19WsT51bkRrV5N5vpW+PVFdUsb5vdsctNDwkYlJK46FJkvv07HokzDRSeJdfWznnvxwQyjpP04b5YCzcOeRQngH9w7DmjC4bpShtSGnnXrG/DTJMqWLHztvyPwiYKngqyZ181nuRoUZzpQvYeko6SH33HVpvp39xlHJCt4s4iIqVY6g52rzVWa6YSDnMqcB/zrX2OByNanoYtZE2wiioywxakZLQ8N+0trB1rXheF9RfWzlSYYB+gBzt/3r2Y3Jff3VjdaAxgM6c/JFOaAIquOHDA/L89VV9wQVXT9cdsJT0KNVFK0OWhToTzrdVm52YBSYO4aNTX0XCLk8aevaMVh6Dcz3pINK5k9Y7leVm3vHyreUVn0MvS89DX4kMbS8RyIvSZi8TJsIhpdaTTme4A8GuwzOTNdQ04+Bxe7nmrOIZYUjwPl/UXN8y3zoYBFttlY6ucr5Uwk22TZgbpFZw4ZU5+6HZd26hgaWzy006s/lXM4J5jGNKHJd8vSyVwewHHfpqstAekyc6laaXoOd9t0a1Y1hsgl8b69w6KFuX2MQnalZ1fjlz//XvClpUAEJ9KmSUwe6kpbcVUKgd0B00HBrLdjmAws8Est6zIGkETLdPd9dtUyDeYSljhAzv4TyV9Y5bFnazZUBvXZMDPok1HLxfSK3CNbnLc3NcSgRiPCytajIF1sLuPzZwsaW4hExejHIOQZGJmC/gq4M/ikLdeDWUo7rRTybbglpJm6bN3PIx6t/A/RbDsF81OaJ6F3Wlxen+uqRsRSyv0LJ5FvAzaqP68clpifrIlB7/h6O4364ugIAveDyV8U5J6SS9JPuqS4SbFiKYi5W4E5ARF4U9TQEhLHe25lh0In7bTRWgJnadh8R6+j2voLRk33qrhueOH7i5GMbyDEG8DbBuXkHs09zpo7HuZmx+yUhmKm2yMbs53w1IsZ99Li+wJaTdvUQDxzR1IpsRDjO1U3mD9Rdri3IE/v64ciSV2lrlL3ge94n/jivBORmXmyKRZQtfnvyBJspi7xBtuvqqIwc7mcIqCLZmML5KHKEYesz6EOzGlOC5p1VW1xaxxh7wEOgXD8UthCaO0/qg4jWTWQDOKhwVolYDCw3KsRT4l4QM2PRkakBsue2ZBSj1PGmX2QjvoXLj0orv9o0WwPvCpQHh5yIwfSNhha8EJm00OPBe+hBW8ttpp2vRBBmUEcuUg+bF5ZjWsmDSiUohwqgI5RsNtw5rgPZVo3Ys8glkoi9dzzlIdp/vMUj1rX4JlfRhijTNIia3WqVhtEvycTOanHdj57YSDhRlyHARxVGmU+eANVj+8D+jJJYWu2UnhnzCsw4awkqP8jH4LRVJdqe2WKDaX361KwuvUWGcNa7dm7NhNAep+QDoRVgmkKjP1IU99xpkko+e+zcU18lnJtIZ5C2gUHm+ma17uT5/JisFuTtp9Lj5dnzcoCj2bC/5wZMmDvFoBr7C8cedeY5YmFs7lAUNEzAVweiYyQA80tf6lh58rA0X+NHKAH7kHw5BxqBSJAH1ewa/S0qZV2UrX6ASoAbahHhf0R5B+qk7yx4qXx3/wH4DKssj5OMvcRvjj1CmeVY/ErE/6UsYlhkHH5J4O3wfbo5Z1AbMD4JJ2H41KxoUn6VEA080xcXGWdOcJkfN2uVTFoVaBgxyl2ZhaZmnS94ig5Yf8TVhK2ligb0S1XezmKgqldNF68cPNad1uyP7fnbBbmW81SJWbklMkshhjCJvFt6H8l4VhsQh/wmS8nMmqDsK+d6OcHb4JoUgE1T+g03QmAY4kWFnKPKnXcanxDCGQNy/IpgMez+C3NN87pKBjcejTI63ld8xtrgORLeWTA+EBtwIUIbnDpCaR0uRo37L3azuAUyFpjksNqCK4IikJd1jmfNOz7x7uWADcRyoxlVNytHT+7SbEgNKybMDTKzByUHe7zraVii7Wh0d4cNNsLMoYut+a4riq8ivQsYMf1Mdt0Yo3CtC/AFS/+iW7s6LGYi6XGnZz2JDySxRDcqNvE4rl4QyyA5X4a8RmnDn5wx/mFUOZA7M1t6L1sfc4bcuZ0yFiV03VSzoguM9YeJIxvog889oXbH4ayuJo6NfkX3z9TJ+SQKrRqXPOPN9CuEvDB469nZtldoj0apg3LWtto08k2Y5PZghO3PWx2D370cukIYadw21CJmmDgSc44cr9RK7VnqVGhvPjlSx21sj+TjaFdWh7AqCStxt0PnCXCHKs6J4xaY8kVUG5rsq8gjn/3HnlRzeb0eAh5QF937xbXmo91g0EpGgoAM9mfheXY7EkaNXa26lJ6qXsuBCehlB7QL66ayzme7DHP1vYB4gCX0IMwUanfUIP0XKLC/SZvfmCNBuHxZZLerlVJdDlmOavmURYlMViy0HUY4m8ES/ACncMWkPsdmv/ZRo6v/q/4l+Y4zE2yEZ3DOlddHcTPNvFhFIQnIdQihrGY35fTGrILmQqlqM4QbAKiPT9oJsGqXuURyBdxQeJuJmT4V4b28mAbr0Nn+sKcfeVNd4wJ7VK4SGrdYG4KOFLmpKEI5i89OGApwxJqti1wrveyJLxF2P8XDVBA5US0vLz5WemKGDNM2NJOnvomOW30YN9CjmgM/qak9AZDZQ4x/uciOYuvPLMAzCjsMPjgUueVIcZw9eJUMIcFOwEthAeMZJ60pJT7bO34S65RvRL5co7CUzhvNlT3CFcC4VVyxKInhNt1B9IFnzI+sYZuhHW4OQnUG8atoL42J0MX39MeNEf/sAVOt1N8fC3RbylftLO9XuKGEqo+WD6755p3dC5kRy2AMZG1zMmmk8baeMSHPyM7v6lf1nXYQvFAy7IFHAg9/qTAp992IgHImsggX6ZdSQmxZpc4OhtZ14oGy+zgy7Fffi9Iidnc2O9qEBHxDiRRgkcgOs0Dg9bZWCrseaqruSKcYs/xgHt5wpLF+68RSDQ3LRau3guGQ+oQCcLKupF/4yeXFCSyd5Wd5Zcq6o/KdFfQqh4wnYsLnguDxi/qsUTxG9rUPDW94IC1w1zwImlLLqqmCYs1TRmkC7d8gRDJsRrhlK+2OAzNhRm5yL8RIBHyLJVZz69e488FQPxoHFnJG1H3sI3m3Sdt3Xq8H5xQ85UiNNQDyu3nteVzNH8Ri44x+4TVtZDrtTrwUUvW9r1eRywhGRj+pBcpxSD0VxzkMby2Z2z9cN5Ryg+SA9VW2IdFhEmQRW4ryrU2tTDlsd/EMPuoHx0sEOwyS7L/S5+ai1ZjOa3Ooi1R8Yzg97DBrVTYwSWKrNky2SRILVNiT9PYaNpreB+sWGQGk2Ji/UX13Zk2R9VSi5YBQhm5ELG4hXeHJPIU45yRg1ASi6BekyFN2GZe7QvslCzhJXZpgpxIBPVehnv6KDrk0iUu6LVI8lPaq7VbIt1vwn7xt2YS/P231EhtA5yvLFyfr1Y/Gf5NxFQhn8RSdFzTgt/pYsg5lqllS4MjeTQFziSdP5AeY3xYjmAvjqoWZ1DLAhLEO7wOMihk6rEA7+BRvSroZ3iBZp+sphk4ysi0QdTu4Jkf0L7YWkCCJksEGWCFrYFkqHSXIYKleN6bSW4K3adWo9F1V1UdoE960ghAxDMLtHPuDnKpsB3T5fgOJSxrGNUfylEgi9ya7pY/iEkhWbylCHA64N2ldWLLG0xjMw7HFUqKfLfvIKUniRWgqTue50WZYcwOqvrnvHiYxDHXPH23thAjzio/7dWuJ/j5sgSXlxhVHcZyozxIPUAw7Qsb3aUFaQqxQWxSkkkDiT1nfm3bT0IVDCr4VwYXsLqiF+TjkQlGfNqJPkjqWTut4ZA8YhSPpSUmLJcOrJPEnzCekZXmWlutT9CaFc9GEokr2HGHy6lhRg2OZRSlYcBRo3Ai6OK3nTM09O9r7zyHJR91baG/kzuK3XqXH87HXe5q+svysGL67nRb+qN+uddzPhRCkPhjT45ZeWGDX9idY+t4jMOFmP176XjMphJRPjUbCaqaN3FAGaHtM7AvFlWMvuJjaRQ7rM4hDhroCkwD5gMJ3GSzCA9FbHaPb68y8qqaVJlO+ZEHjaPluNIVcJmw19y2lFpuJXWWyc9RvFjgwVqC+XUm1M/iSUkieOnLkpgl825md9u7+fUhCVczrOrx2sjSu5t3VLG7meD7CkUa/37wbRFbX2l9kBdFOvIlBDvpuG+/ViOhsQnscux3eduWzFXT9ojWqy33ORMHzHjYJMGuCVQUckN6no1gRB3IEcAYIVcR3JhGwLOi5WMVncCBeeASRF7VfF27ib2mC9x1FvQLRDwN/9bsLoMmHajXjdiOwvaTybBQQSKy47kN3nlnIz5384VzGhdGLVPsZK4OFYXtC1vA4qBIykSWv9XQ0rltkEHLcWVbLine truncated
+78
View File
@@ -0,0 +1,78 @@
name: "🐛 Bug"
description: Something in Plan2Code or the web console is broken or behaves unexpectedly.
title: "🐛 Bug: "
labels: ["bug"]
body:
- type: textarea
id: what-happened
attributes:
label: What happened?
description: Describe the problem. Screenshots are welcome.
validations:
required: true
- type: textarea
id: expected
attributes:
label: What did you expect to happen?
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
placeholder: |
1. Run /plan2code
2. Pick ...
3. See ...
validations:
required: true
- type: dropdown
id: skill
attributes:
label: Which skill or tool?
options:
- Dashboard (/plan2code)
- Init / Init Update
- Pathfinder
- Plan / Revise Plan
- Quick Task
- Document
- Implement / Implement + Review
- Review
- Finalize
- Handoff
- Web console (page itself)
- Loop (plan2code-loop)
- Metrics
- Status line
- Installer
- Other
validations:
required: true
- type: dropdown
id: interface
attributes:
label: Where were you working?
options:
- Web console
- Terminal
- Not sure
validations:
required: true
- type: input
id: version
attributes:
label: Plan2Code version
description: Found in version.json, the installer banner, or at the bottom of the web console's Help dialog.
placeholder: "2.4.0"
- type: input
id: environment
attributes:
label: OS, Node version and agent CLI
placeholder: "Windows 11, Node 22, Claude Code"
- type: textarea
id: logs
attributes:
label: Console output or logs
description: Anything from the terminal or the browser console that helps.
render: shell
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
+29
View File
@@ -0,0 +1,29 @@
name: "💡 Idea"
description: Suggest a feature or an improvement to Plan2Code.
title: "💡 Idea: "
labels: ["enhancement"]
body:
- type: textarea
id: problem
attributes:
label: What problem or goal is this for?
description: What are you trying to do that is hard or impossible today?
validations:
required: true
- type: textarea
id: idea
attributes:
label: Your idea
description: What would you like Plan2Code to do?
validations:
required: true
- type: textarea
id: who
attributes:
label: Who would this help?
placeholder: "Product leads writing specs, engineers running the loop, ..."
- type: textarea
id: alternatives
attributes:
label: Alternatives you considered
description: Workarounds you use now, or other ways it could work.
+124 -69
View File
@@ -1,108 +1,163 @@
# Walkthrough: one feature, start to finish
A REST API for task management, from a sentence to archived specs. Every block below is a **separate
conversation** — that's the whole trick.
A REST API for task management goes from a sentence to archived specs, all on the web console.
Each session stays short, and the specs on disk carry everything from one session to the next.
← [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
## Session 1: Plan
Run `plan2code` in the project (or `/plan2code` inside your agent). The dashboard opens in your
browser with every step laid out as a card.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/dashboard-dark.webp">
<img src="../docs/screenshots/dashboard-light.webp" alt="The Plan2Code dashboard: a Set up card, then the steps in order as cards, one of them marked Suggested.">
</picture>
Pick **Plan** and describe the idea in the box: *I want to build a REST API for a task management
application.* The same page turns into the Plan session.
The questions arrive in batches of up to three, each option with its trade-off written underneath.
Answer what is there and press **Send to Plan2Code**; the next batch follows.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/question-dark.webp">
<img src="../docs/screenshots/question-light.webp" alt="A Plan question card, How tasks are paged, with three options, the first marked Suggested, each with its trade-off underneath.">
</picture>
The phase breakdown comes back as a list you can reorder and edit. Documents a skill writes on the
page open as tabs like this one, where settled parts read as decisions and anything still a guess
is marked as assumed and still open.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/doc-dark.webp">
<img src="../docs/screenshots/doc-light.webp" alt="The What we've agreed tab for the task API: a settled summary, an assumed section on paging with a dashed edge, and a dimmed draft list of what is still to work out.">
</picture>
Plan proposes a tech stack, Fastify + Postgres + Zod, and does not pick it alone: a sign-off card
asks you to approve it. Plan then designs the architecture. At 92% confidence (the gate is 90%) it
asks whether to write the draft, and with 3 assumptions written down, it writes:
```
You: /plan2code-1-plan
I want to build a REST API for a task management application.
AI: 🤔 [REQUIREMENTS ANALYSIS]
Six questions. Four of them I need answered before I can size this.
...
AI: 🤔 [TECH STACK]
Proposing Fastify + Postgres + Zod. I don't pick this alone — sign off?
You: approved
AI: 🤔 [ARCHITECTURE DESIGN]
...
AI: 🤔 [TRANSITION DECISION]
Confidence: 92% (gate is 90%). Assumptions written to the draft: 3.
→ specs/task-api/PLAN-DRAFT-20260804.md
specs/task-api/PLAN-DRAFT-20260804.md
```
Two files land: the draft, and a `PLAN-CONVERSATION-*.md` log of how you got there.
Two files land: the draft, and a `PLAN-CONVERSATION-*.md` log of how you got there. The finish
card names the next step.
> **Started foggy instead?** Run `/plan2code-0-pathfinder` first. When its map clears it writes a
> `PLAN-DRAFT` that Step 1 picks up at Phase 4, with requirements and scope already answered.
> `PLAN-DRAFT` that Plan picks up at Phase 4, with requirements and scope already answered.
---
## Session 2 — Document
## Session 2: Document
On Plan's finish card, press **Back to the dashboard** (or start a fresh console session if the
session meter says so; see Session 3 below). Pick **Document**, with `specs/task-api` selected in
the picker at the top. It reads `specs/task-api/PLAN-DRAFT-20260804.md`.
The overview and each phase file appear as tabs as they are written, so you watch the spec take
shape:
```
You: /plan2code-2-document
specs/task-api/PLAN-DRAFT-20260804.md
AI: 📝 [DOCUMENTATION]
Creating specs/task-api/overview.md
Creating specs/task-api/Phase 1.md Project setup (6 tasks)
Creating specs/task-api/Phase 2.md Data model (8 tasks)
Creating specs/task-api/Phase 3.md API endpoints (11 tasks)
Creating specs/task-api/Phase 4.md Authentication (7 tasks)
Parallel execution groups: Phase 3 and Phase 4 don't share files.
specs/task-api/overview.md
specs/task-api/phase-1.md Project setup (6 tasks)
specs/task-api/phase-2.md Data model (8 tasks)
specs/task-api/phase-3.md API endpoints (11 tasks)
specs/task-api/phase-4.md Authentication (7 tasks)
```
Parallel execution groups: Phase 3 and Phase 4 don't share files.
---
## Sessions 3…N — Implement, one phase each
## Sessions 3 to N: Implement, one phase each
```
You: /plan2code-3-implement
specs/task-api/overview.md
Look at the session meter in the top bar first. Plan and Document add 2 points each, so after
those two the meter is at 4: **Session: getting long**, in yellow. That is the cue to close this
console session and start a fresh one for the build (run `plan2code` again). This is the first of
the four rules:
AI: ⚡ [PHASE 1: Project setup]
(Phase 1 is the next unchecked phase.)
...
✓ 6/6 tasks. Checkboxes updated in Phase 1.md and overview.md.
Next: Phase 2 — Data model (8 tasks). New conversation.
```
> **1 · Keep each session short.**
> Chaining a couple of small skills on the dashboard is fine. Start a fresh console session when the session meter turns red, and always before a big planning or build step. The specs on disk carry everything between sessions.
Repeat. New conversation each time. It always finds the next open phase itself.
On the fresh dashboard, pick **Implement** for `specs/task-api`. Phase 1 (Project setup) is the next
unchecked phase, so it starts there. The page shows the build as it goes: a progress bar counting
tasks, the phase's task list ticking as each task lands on disk, and a line beside Planny saying
what it is doing now. Use the **Ask** tab for a quick question without interrupting the build.
When you reach a parallel group, it offers you the choice — open a second agent, take the other
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/build-dark.webp">
<img src="../docs/screenshots/build-light.webp" alt="A phase of a task API being built: 5 of 11 done on the progress bar, and the phase's task list with the first five ticked.">
</picture>
When all 6 of 6 tasks are ticked in `phase-1.md`, a **Completion report** tab opens with the
sign-off card: **Review the code first**, **Approve this phase**, or **I want changes**.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/signoff-dark.webp">
<img src="../docs/screenshots/signoff-light.webp" alt="The Approve this phase card, with a button to read the completion report and three choices: Review the code first, Approve this phase, and I want changes.">
</picture>
After you approve, `overview.md` marks Phase 1 done, and the finish card gives the next command:
Phase 2, Data model (8 tasks), in a new session.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/finish-dark.webp">
<img src="../docs/screenshots/finish-light.webp" alt="The finished screen after a phase sign-off: the phase is built, the next implement command with a Copy button, and a Back to the dashboard button.">
</picture>
Repeat. A fresh session 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.
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.
Pick **Implement + review** instead when review should run automatically before phase approval.
**Review** remains available on the dashboard for an independent second opinion at any other time.
---
## Final session — Finalize
## Final session: Finalize
```
You: /plan2code-4-finalize
specs/task-api/overview.md
With every phase approved, the dashboard suggests **Finalize** for `specs/task-api`. Pick it in a
fresh session. Each check lands on the page as a report tab, and anything that needs your say is
a card:
AI: 🧹 [VALIDATION]
All 32 tasks verified against the phase specs. 2 gaps found and fixed.
- **Validation.** All 32 tasks verified against the phase specs. 2 gaps found and fixed.
- **Documentation review.** README needs the new `/tasks` endpoints; AGENTS.md is current. A card
lists the proposed doc updates, and you tick the ones to make.
- **Spec cleanup.** A confirm card, then `specs/task-api/` moves to `specs--completed/task-api/`.
AI: 🧹 [DOCUMENTATION REVIEW]
README needs the new /tasks endpoints. AGENTS.md is current.
AI: 🧹 [SPEC CLEANUP]
Moved specs/task-api/ → specs--completed/task-api/
Implementation complete.
```
The finish card says the implementation is complete, and gives the commit command when doc
updates landed.
---
## If requirements move mid-build
Don't patch the code and hope the specs catch up. Run `/plan2code-1b-revise-plan` — it edits the
specs (and only the specs), so the drawing and the build stay in agreement.
Don't patch the code and hope the specs catch up. Pick **Revise the plan** on the dashboard: it
edits the specs (and only the specs), so the drawing and the build stay in agreement.
---
## Prefer the terminal?
The same journey is four commands, each in a new conversation:
1. `/plan2code-1-plan` with the idea in a sentence. Writes `specs/task-api/PLAN-DRAFT-20260804.md`.
2. `/plan2code-2-document specs/task-api/PLAN-DRAFT-20260804.md`. Writes the overview and phase files.
3. `/plan2code-3-implement specs/task-api/overview.md`, once per phase. It finds the next open phase itself.
4. `/plan2code-4-finalize specs/task-api/overview.md`. Verifies, updates docs, and archives the spec.
Add `--web` to any of them (for example `/plan2code-1-plan --web`) to open that step straight on the
web console without being asked. Every command and argument is in the README's
[Prefer the terminal?](../README.md#prefer-the-terminal) section. You can switch between terminal and
console at any point, because the files under `specs/` are the only state.
## More
- [web-console.md](web-console.md): every screen, setting and recovery path
- [../QUICK-REFERENCE.md](../QUICK-REFERENCE.md): the one-page card
+1 -1
View File
@@ -42,7 +42,7 @@ 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:
`scripts/validate-char-count.js` caps every flat `src/plan2code-*.md` at 11,500 characters (11,000 when the numbers below were measured), enforced by a husky pre-commit hook. Measured today:
```
10995 5 plan2code-0-pathfinder.md <- 5 characters of headroom
+128 -31
View File
@@ -1,8 +1,32 @@
# 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
## New here? A two-minute tour
**Launch it.** After installing, run `plan2code` in your project folder. It starts Claude Code or
Devin on the dashboard, and the page opens in your browser. In any other agent, run `/plan2code`
inside it, or add `--web` to a skill (`/plan2code-1-plan --web plan a lunch voting app`).
**What you see.**
- **The dashboard** has a card for every skill. The one it suggests next is flagged. Pick a card and
that skill starts on the same page.
- **Questions** come laid out with the trade-offs next to each option and a progress bar on top.
Nothing is sent until you press **Send**, and half-typed answers survive a closed tab.
- **Tabs** show the document taking shape, the build progress and, always last, **Ask**, where you can
put a quick question to the running agent.
- **Sign-off** asks for your approval at the end of a phase. You can run the code review first from
the same card.
**Where next.** [walkthrough.md](walkthrough.md) follows one feature from the first idea to the
last phase. The rest of this file is the reference: every card, button and rule. Prefer the terminal?
Run the same commands without `--web` and answer there; the files under `specs/` are identical.
---
The web console is the main way to use Plan2Code: a local page in your browser
where you pick a step, answer its questions, watch the documents and the build
take shape, and approve the work. Every skill runs on it, 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.
@@ -10,12 +34,34 @@ 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.
## Quick start
1. Install Plan2Code (see [Install and start](../README.md#install-and-start) in the README).
2. Run `plan2code` in your project, or `/plan2code` inside your agent. The dashboard opens in your
browser.
3. Pick a card. The same page becomes that step's session.
4. Answer on the page and press **Send to Plan2Code**.
Starting a step by its own command instead? Add `--web` (for example `/plan2code-1-plan --web`) and
it opens on the page without asking.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/dashboard-dark.webp">
<img src="../docs/screenshots/dashboard-light.webp" alt="The Plan2Code dashboard: a Set up card, then the steps in order as cards, one of them marked Suggested.">
</picture>
---
## What you get
- **Every question laid out**, with the trade-offs written next to each option
instead of scrolling past in your history.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/question-dark.webp">
<img src="../docs/screenshots/question-light.webp" alt="A Plan question card, How tasks are paged, with three options, the first marked Suggested, each with its trade-off underneath.">
</picture>
- **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.
@@ -48,12 +94,12 @@ and they were the two steps that looked like a wall of terminal text.
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
- **Light or dark, and a highlight color you pick.** The gear 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*
- **A card as wide as you want it.** The same 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
@@ -99,7 +145,7 @@ and they were the two steps that looked like a wall of terminal text.
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 two-minute *"Still working on it"* line.
- **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
@@ -113,6 +159,22 @@ and they were the two steps that looked like a wall of terminal text.
fully when the page has lost its program.
- Works offline, on your own machine only. No account, no install, no network.
An Implement phase ends on a sign-off card: read the completion report, then
review the code first, approve the phase, or ask for changes. Implement +
review has already reviewed the code, so its card has no review button.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/signoff-dark.webp">
<img src="../docs/screenshots/signoff-light.webp" alt="The Approve this phase card, with a button to read the completion report and three choices: Review the code first, Approve this phase, and I want changes.">
</picture>
The **Ask** tab is a chat beside the cards, for a quick question at any point.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/ask-dark.webp">
<img src="../docs/screenshots/ask-light.webp" alt="The Ask tab: the question Where are tasks paged? and Plan2Code's answer naming the file.">
</picture>
## Using it
The easy way in is the dashboard:
@@ -136,9 +198,11 @@ 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.
back with **Back to the dashboard**, and not after a launch. To skip it — from
the asleep screen or mid-animation — press the muted **Skip** button at the
bottom right or hit Escape; either goes straight to the dashboard, silent.
With reduced motion switched on in your system settings you get the awake
dashboard at once.
Or start any step directly, as usual:
@@ -189,14 +253,14 @@ 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
For the same reason, the web console 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**:
The first control in *User Preferences* (the gear 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
@@ -281,8 +345,9 @@ new console session starts with just the folder you started in.
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.
work this console session has done. Click it for the count, a list of each
step that added points and what it added (for example *Quick task started +1*),
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
@@ -362,7 +427,9 @@ 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:
Any note, any quick question on the Ask tab, and the fresh-idea box on
Pathfinder, Plan and Quick Task can carry files (on a card they travel with your
answer as a note attachment), 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,
@@ -438,9 +505,9 @@ send never holds up a question.
- **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.
it lists what changed, with line counts, and nothing is committed unless you
spell out a commit in your message. 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
@@ -465,6 +532,19 @@ keyboard-only navigation work.
---
## Troubleshooting
| What happened | What to do |
| --- | --- |
| You closed the tab | Open the link again. Everything is where you left it. After about two minutes with no tab open the link stops working: ask the agent to resume the session for a new one. |
| 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. If it is idle, type `continue` in the terminal and it picks your answers up. 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. |
---
## How it works
Nothing is installed. The skills ship a small zero-dependency Node server
@@ -539,17 +619,6 @@ 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
@@ -572,7 +641,9 @@ this:
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
Documents are served back only under a fixed type (`application/pdf`, or
`text/plain` for text and code) with `nosniff` (and `sandbox` on text), so
the Sent box can link them. A send may only point at
uploads inside that session's `uploads/`, images in `images` and documents
in `files`.
@@ -585,7 +656,7 @@ 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). |
| `GET /uploads/<id>.<ext>` | Serves an upload: an image as `image/jpeg` (the thumbnail after a reload), a document as `application/pdf` or `text/plain; charset=utf-8` with `nosniff` and, on text, `Content-Security-Policy: sandbox`. Only `<uuid>.<allowed ext>` names under `uploads/`; anything else is 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. |
@@ -607,6 +678,7 @@ origin.
| 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) |
| Screenshots | `node scripts/capture-screenshots.mjs` (needs `puppeteer-core` and a local Chrome or Edge) |
| 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
@@ -661,7 +733,7 @@ Two environment variables help when the start is what you are looking at:
| `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
Every `console.mjs open` 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.
@@ -670,3 +742,28 @@ 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.
### Refreshing the screenshots
The docs and the landing page show the console through the images in
`docs/screenshots/`, one light and one dark WebP per screen. Rerun the capture
after any change a person would see on the page: a new layout, a renamed
button, a different colour.
```bash
npm i --no-save puppeteer-core # once; never added to package.json
node scripts/capture-screenshots.mjs # every screen
node scripts/capture-screenshots.mjs --only dashboard # one screen
```
Each screen is staged with no agent, from the payloads in
`scripts/screenshots/` (its README names the file behind each screen), in a
throwaway sample project and console home that the script removes when it is
done. It prints each file's size and warns over 300 KB.
Open every image before you commit it: the right screen, both themes, nothing
cut off, and no username, home path or real project name anywhere on it.
## Models in User Preferences
The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude and Devin tabs) lets you add a model that came out before Plan2Code was updated; additions are kept in `~/.plan2code/models.json`, and **Reset to default** removes them. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused.
+2
View File
@@ -84,3 +84,5 @@ When you make a mistake, get corrected, or discover something about this codebas
- 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.
- After a sync merge, run `npm test` before trusting a "clean" file: when upstream and plan2code fixed the same bug, `git merge-file` keeps both copies without a conflict (a sync once left `let pattern` declared twice in `app.js`, caught only by `parse-check`).
- When extracting upstream files in Git Bash, run `git show <ref>:<path>` with `MSYS_NO_PATHCONV=1` and `C:/` style paths (never `/c/`): path conversion rewrites `origin/main:.readme/x.md` into `origin\main;.readme\x.md`, the show fails, and the merge silently runs against an empty "theirs". Check every extracted file is non-empty before merging.
+38
View File
@@ -2,6 +2,38 @@
All notable changes to Plan2Code will be documented in this file.
## v2.4.1
### ✨ Added
- **Screenshots of the web console**: seven screens (dashboard, question, living document, build, sign-off, finish, Ask tab) in light and dark, as WebP in `docs/screenshots/`. Readers see the theme that matches their system, on GitHub and on the site.
- **`scripts/capture-screenshots.mjs`**: stages each screen from the JSON payloads in `scripts/screenshots/`, in a throwaway sample project and console home, and captures it with puppeteer-core and a local Chrome or Edge. One command refreshes every image; `--only <shot>` refreshes one. `puppeteer-core` is installed with `--no-save` and never added to `package.json`.
- **New landing page**: `docs/index.html` rebuilt in the console's look, with the console above the fold.
- **Web console welcome**: the first dashboard a person sees opens a Welcome dialog with Planny waving, four tips and a **Start building** button. Closing it by any route saves `looks.welcomeSeen` in `looks.json`; Help's first tab has **Show the welcome again**.
- **Report a bug or idea from the console**: a megaphone button at the right of the top bar opens GitHub's new-issue chooser for `jparkerweb/plan2code`, with new **Bug** and **Idea** issue templates in `.github/ISSUE_TEMPLATE/` (blank issues off).
- **Version in Help**: the Help dialog's footer shows the running Plan2Code version, served by a new `GET /version` route. The skill build copies `version.json` into each skill's `references/web-console/` so the console can find it.
### 🔧 Changed
- **install.js**: the closing message beside Planny now names the dashboard first: `plan2code` from any project, or `/plan2code` in your agent when the command could not be installed. The docs link moves to the line under it.
- **web-console**: User Preferences opens from a gear button instead of the three swatches, and the default highlight color is now ocean blue instead of rust.
- **web-console**: the dashboard rail marks the suggested next step with a small dot, since the center pane's Suggested pill can scroll out of view. Send pulses only while it is the primary button.
- **web-console**: when the agent stops checking in, the status line and Help now say to type **continue** in an idle terminal so it picks your answers up.
- **web-console**: `wait` exit 10 now carries a `next` instruction (relay one line, then wait again), and `console.md` opens with the one rule that keeps the page alive: every turn ends on a `wait` call, never on text.
- **web-console**: a finished quick task offers **Back to the dashboard** as well as **Review it now**, so the finished screen is never a dead end.
- **Windows**: the folder picker (the launcher's desktop shortcut and the Workspace **Browse…** button) now opens centred and in front of other windows instead of behind the terminal.
- **Launcher**: before asking which CLI to use, `plan2code` says what it is about to do and that running `/plan2code` inside your agent works too.
### 🐛 Fixed
- **web-console**: reusing a settled question id for a different kind of question (say a multi-select turned confirm) now opens it as a new question instead of keeping the old answer.
### 📚 Documentation
- **Web console first**: README, QUICK-REFERENCE, the walkthrough and the console guide now open on the browser flow (install, run `plan2code`, pick a card) with screenshots, and keep every slash command in a "Prefer the terminal?" section. The walkthrough follows the task API through the web console, session by session, and the console guide opens with a Quick start and has Troubleshooting ahead of the internals.
- **Rule 1 is now "Keep each session short"**, worded the same in README, QUICK-REFERENCE, the walkthrough and the landing page: chain a couple of small skills on the dashboard, and start a fresh console session when the session meter turns red or before a big planning or build step.
- **Web console guide** opens with a two-minute tour; **QUICK-REFERENCE** opens with a Launch table (shell, inside an agent, straight into a skill with `--web`) and a "Terminal instead" note; the walkthrough mentions the Ask tab during a build and ends with links onward.
## v2.4.0
### ✨ Added
@@ -17,6 +49,9 @@ All notable changes to Plan2Code will be documented in this file.
- **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.
- **Curated launcher models**: the `plan2code` launcher's model menu reads `src/launcher/models.json` (copied to `~/.plan2code/bin/` and refreshed by every install) instead of asking the CLI, so Devin offers a short verified list at Low, Medium and High effort. **User Preferences → Models** (Claude and Devin tabs) adds models released after an install, kept in `~/.plan2code/models.json`, with **Reset to default**. `--model <id>` still skips the menu.
- **Quick-task build progress on the console**: an approved quick-task plan opens a **Build progress** tab that ticks each step, raises the progress bar and updates the activity line, as an Implement phase does.
- **Console extras**: sent notes and their attachments stay listed in the Sent box after a reload or in a second tab; the fresh-idea box on Pathfinder, Plan and Quick Task has **+ Attach file** (and takes a paste); clicking the session meter lists what each step added; git code blocks get a **Run it** button; the Ask tab may run one command the person spells out (a commit, a test run) and report the result; the wake-up animation has a **Skip** button.
### 🔧 Changed
@@ -26,6 +61,9 @@ All notable changes to Plan2Code will be documented in this file.
- **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.
- **Finished screens**: Review, Init, Init Update and Handoff end with **Back to the dashboard**, as Quick Task does; only a pause leaves it off.
- **Console sturdiness**: `wait` reports the server gone only after three missed health checks in a row, so a busy server is not taken for a dead one; a reused question id no longer inherits the old answer; polling stops redrawing an unchanged page and returns to the live stream (with backoff) once the server answers; `stop` gives a busy server a second, longer health check before leaving it alone; a fresh session in a linked worktree records the worktree as its folder; a text question whose `pattern` does not compile is refused at `post`.
- **scripts/validate-char-count.js**: the dashboard prompt `src/plan2code.md` is size-checked too.
## v2.3.0
+18 -4
View File
@@ -1,7 +1,21 @@
# Plan2Code Quick Reference
## Launch
The web console is the main way in: a local page where questions, documents, build progress and sign-offs live.
| How | Command | What happens |
| ------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------- |
| From your project (shell) | `plan2code` | Opens Claude Code or Devin on the dashboard (`--cli claude` / `--cli devin` to choose) |
| Inside any agent | `/plan2code` | Opens the dashboard: a card for every skill, launched on the same page |
| Straight into a skill | `/plan2code-1-plan --web` (any step) | Skips the "web console or terminal?" question and opens the page |
Pick a skill on the dashboard and the same page becomes that session. Details: [.readme/web-console.md](.readme/web-console.md) · worked example: [.readme/walkthrough.md](.readme/walkthrough.md).
## Commands
Every command below is what a dashboard card runs. Typed on its own, each one asks "web console or terminal?" first.
| Step | Command | Input | Output |
| -------- | ------------------------------- | --------------- | --------------------------------------------------------------------------------------- |
| — | /plan2code | None | Web console dashboard — a menu of every skill below, launched on the page |
@@ -18,7 +32,7 @@
| 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).
**Terminal instead:** run any command without `--web` and answer the interface question with **terminal**. Nothing is lost: same questions, same gates, same files under `specs/`. You can switch between the two mid-feature.
## File Structure
@@ -43,9 +57,9 @@ Note: `<date>` uses YYYYMMDD format (e.g., `20250204`)
## Key Rules
- Start NEW conversation for each step (and each implementation phase)
- Keep sessions short: fresh console session when the meter turns red, and before a big plan or build step
- ONE phase per conversation (but parallel phases can run in separate instances)
- Reply "approved" to complete phases
- Approve phases on the sign-off card (or reply "approved" in the terminal)
- 90% confidence required before planning completes
- Never look in `specs--completed/` (it's archived specs)
@@ -62,7 +76,7 @@ Note: `<date>` uses YYYYMMDD format (e.g., `20250204`)
When phases have no file conflicts or dependencies, they can run simultaneously:
1. Documentation Mode auto-detects parallel-eligible phases
2. Implementation Mode shows selection UI with status for each phase
2. Implementation Mode asks which phase to take (a card on the web console), with the status of each
3. Run multiple `/plan2code-3-implement` instances on different phases
4. `[/]` status shows which phases are actively being worked on
+163 -43
View File
@@ -1,22 +1,34 @@
# Plan2Code
<img src="https://raw.githubusercontent.com/jparkerweb/plan2code/main/docs/banner.png" alt="banner" data="object-fit:contain;" style="max-width:1024px;">
**A spec-driven workflow for AI coding agents.**
**A spec-driven workflow for AI coding agents. Send the plan — the build follows.**
<img src="docs/banner.jpg" alt="Plan2Code: plan and build with your AI agent, on one page. Planny, the mascot, acts out the five steps: Pathfinder, Plan, Document, Implement and Finalize." data="object-fit:contain;" style="max-width:1024px;">
An AI agent is a fine builder and a terrible client. Plan2Code stops making it both: you approve a
plan, the plan becomes a set of phase documents in your repo, and the agent builds to those documents
one phase at a time. Progress lives in files instead of chat history — so the next session, the next
agent, and the next engineer all start from the same specs.
You work through Plan2Code on a page in your browser. The dashboard lists every step as a card, and
each step's questions, progress and sign-offs arrive on that same page while your agent does the
work. What you decide still lands in your repo as plain files: an approved plan becomes phase
documents, and the agent builds to them one phase at a time, so the next session, the next agent and
the next engineer all start from the same specs.
Six commands, each posted separately. Two of them are optional.
One command opens it, every step is a card, and the terminal is always there if you prefer it.
Version 2.4.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
Version 2.4.1 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
---
## Install
## See it
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/dashboard-dark.webp">
<img src="docs/screenshots/dashboard-light.webp" alt="The Plan2Code dashboard for a project mid-build: a Set up card, then the steps in order, with the Implement card marked Suggested and reading Phase 3 of 4 is next.">
</picture>
The dashboard, in a project halfway through a build. It suggests the next step for the spec you pick.
---
## Install and start
Requires [Node.js](https://nodejs.org/) 18 or later and network access — installation runs through
the [skills CLI](https://skills.sh). Re-run any time to update.
@@ -43,14 +55,18 @@ Either route lands you on the same menu:
╚═════════════════════════════════════════════════════════╝
```
**Supported tools:** every agent supported by the skills CLI, including Claude Code · Cursor ·
GitHub Copilot · Windsurf · Codex · Continue · Codeium · Zed · Amp · OpenCode · Devin · Crush · Pi ·
Gemini CLI · Cline · Roo · Kilo · Goose · Trae · Qwen Code.
### Start
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`.
1. In any project, run `plan2code`. It starts Claude Code or Devin on the dashboard, and the
dashboard opens in your browser.
2. Pick a card.
The installer also adds a global `plan2code` command. Run it from any project and the Plan2Code
Already inside your agent? Type `/plan2code` instead.
<details>
<summary>About the plan2code command</summary>
The installer adds `plan2code` as a global command (Custom `C` → `D` adds just the 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
@@ -58,6 +74,14 @@ Claude Code or Devin CLI on your `PATH`. It starts the agent with permission pro
(`--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.
</details>
**Supported tools:** every agent supported by the skills CLI, including Claude Code · Cursor ·
GitHub Copilot · Windsurf · Codex · Continue · Codeium · Zed · Amp · OpenCode · Devin · Crush · Pi ·
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`.
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/`
@@ -78,6 +102,49 @@ npm install && npx husky
---
## A session on the page
**Answer the questions.** They arrive a few at a time, each option with its trade-off written beside
it, and a progress bar says how far along you are.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/question-dark.webp">
<img src="docs/screenshots/question-light.webp" alt="A Plan question card, How tasks are paged, with three options, the first marked Suggested, each with its trade-off underneath.">
</picture>
**Watch the build.** Tasks tick off as they land, and the line beside Planny says what is being
worked on right now.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/build-dark.webp">
<img src="docs/screenshots/build-light.webp" alt="A phase of a task API being built: 5 of 11 done on the progress bar, and the phase's task list with the first five ticked.">
</picture>
**Sign off.** Read the completion report, then approve the phase or ask for changes. In Implement,
you can also have the code reviewed first; Implement + review has already done it.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/signoff-dark.webp">
<img src="docs/screenshots/signoff-light.webp" alt="The Approve this phase card, with a button to read the completion report and three choices: Review the code first, Approve this phase, and I want changes.">
</picture>
**Ask a quick question any time.** The Ask tab is a chat beside the cards, answered at the agent's
next check-in, and it never holds up your answers.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/ask-dark.webp">
<img src="docs/screenshots/ask-light.webp" alt="The Ask tab: the question Where are tasks paged? and Plan2Code's answer naming the file.">
</picture>
There is more on the page when you need it. Notes on any question can carry screenshots and
documents. The folder label in the bottom bar opens your workspace, where you add other folders
as read-only context and point at them by `@name`. The session meter in the top bar turns from green
to red as a session grows long and suggests a fresh one. **Stop session** saves your place and gives
you the command to carry on later, and **Back to the dashboard** takes you home to pick the next
step in the same session.
---
## The workflow
```
@@ -90,39 +157,37 @@ npm install && npx husky
│decide what │ │ draw it as │ │build to the│ ╎ optional ╎ │verify, sum,│
│ to build │ │phase specs │ │ drawing │ ╎ any time ╎ │ archive │
└────────────┘ └────────────┘ └────────────┘ └╴╴╴╴╴╴╴╴╴╴╴╴┘ └────────────┘
new chat new chat new chat/phase new chat new chat
short sessions: fresh when the meter turns red, and before a big step
├◀─────────────── one feature, start to archive ──────────────────▶┤
```
Every box is its own conversation. That is not a style preference — planning context leaking into
implementation is where most agent drift starts.
Each box is a card on the dashboard. Chaining a couple of small steps in one session is fine, but
start a fresh session before a big plan or build step: planning context leaking into 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 |
| `/plan2code-init-update` | Fold what you learned this session back into `AGENTS.md` |
| `/plan2code-quick-task` | A small change that doesn't warrant the full sequence |
| `/plan2code-1b-revise-plan` | Requirements moved mid-build. Revise the specs, not the code |
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from |
The dashboard's cards, and when each one lights up for the spec you pick:
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`.
| Card | What it is for | Lights up when |
|------|----------------|----------------|
| Set up this project | Reads your project and writes AGENTS.md, the guide every later step works from. | The project has no AGENTS.md yet |
| Refresh AGENTS.md | Brings AGENTS.md and its notes up to date with what the project has learned lately. | The project has an AGENTS.md |
| Pathfinder | A foggy idea becomes a clear list of decisions, settled one question at a time. | You start fresh, or the spec is still being explored |
| Plan | Requirements, technical design and your approval: the shape of what gets built. | You start fresh, or the spec has a finished Pathfinder map or a drafted plan |
| Revise the plan | Requirements changed mid-build? Adjust the plan without starting over. | The spec is written up into phases and not fully built |
| Document | The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do. | The spec has a drafted plan |
| Implement | Builds the next phase, task by task, with a report and your sign-off at the end. | The spec has phases with tasks still to build |
| Implement + review | One phase built, then a careful review of the changes, then your sign-off. All in one run. | The spec has phases with tasks still to build |
| Finalize | Checks the work, writes the summary, files the specs away and suggests the commit message. | Every task in the spec is done |
| Quick task | Too small for the full process? A quick plan, then it just builds it. | Always |
| Review | A second opinion on the changes. Problems ranked, and you pick what gets fixed. | Always |
| Handoff | Pack this conversation into a document a fresh session can pick up cold. | Always |
---
## The four rules that do most of the work
**1 · A fresh conversation for each step, and each implementation phase.**
Step 3 gets a new chat per phase, not one chat for all of them.
**1 · Keep each session short.**
Chaining a couple of small skills on the dashboard is fine. Start a fresh console session when the session meter turns red, and always before a big planning or build step. The specs on disk carry everything between sessions.
**2 · No code until the plan hits 90% confidence.**
Step 1 will not finalize below the threshold. Under it, the agent keeps asking and keeps reading your
@@ -131,8 +196,9 @@ code — and writes every assumption down where you can argue with it.
**3 · Checkboxes are the state, not the chat.**
Progress lives in the spec files. Any agent, any session, resumes cold from them.
**4 · Reply `approved` to close a phase.**
Nothing advances on a guess about what you meant.
**4 · Approve a phase to close it.**
On the sign-off card, or by replying `approved` in the terminal. Nothing advances on a guess about
what you meant.
---
@@ -182,11 +248,14 @@ keep the two out of each other's way.
## The six steps in detail
Each one travels on its own — a fresh conversation, opened and closed, with the specs on disk as the
only thing carried between them.
Each step is its own run, and the specs on disk are the only thing carried from one to the next.
Chain a small one onto the last, or start a fresh session for a big one (rule 1).
### 0 · Pathfinder 🧭 — optional, new in 2.0
On the page: one question at a time with the options and their trade-offs, the map growing in its own
tab, and a **Write a brief** button for a printable summary.
Some ideas are too big and unclear to plan: you can feel the shape of the work but you can't write
it as requirements, so planning would just invent the answers. Pathfinder finds the *way* to the
destination; Step 1 then walks it.
@@ -218,6 +287,9 @@ sub-issues) → `PLAN-DRAFT-<date>.md`. The draft is always a local file — tha
### 1 · Plan 🤔
On the page: questions in batches of up to three, the phase breakdown as a list you can reorder and
edit, and a sign-off at each stage.
The agent works as a senior architect through six phases, stopping for you after each: requirements
analysis · system context (reading your actual codebase) · tech stack (needs your explicit sign-off) ·
architecture design · technical specification · transition decision.
@@ -228,6 +300,9 @@ It won't finalize below **90% confidence**, and every assumption it makes is wri
### 2 · Document 📝
On the page: a question only where the plan leaves something open, each phase file appearing as its
own tab as it is written, and one sign-off at the end.
The plan becomes the drawing. One `overview.md` with the phase checklist, plus one file per phase of
one-story-point tasks. Each phase is **self-contained** — an agent opening `Phase 3.md` cold needs
nothing else to build it. Unit and E2E tests are excluded unless you ask for them.
@@ -239,6 +314,9 @@ dependencies, safe to run in separate agents at once.
### 3 · Implement ⚡
On the page: a progress bar and the phase's task list ticking over as tasks land, then the completion
report and a sign-off card where you approve, ask for changes, or have the code reviewed first.
Point it at `overview.md` and it does the rest: finds the next unchecked phase, implements every task
exactly as specified, ticks tasks off as they land, then reviews its own work against the spec and
writes a completion summary.
@@ -252,6 +330,9 @@ same way, runs a focused review and the fixes you pick, and only then asks for a
### Review 🔬 — optional, any time
On the page: a few questions on scope, the findings as a report you can read in full, and a list
where you tick what gets fixed.
An independent second opinion, not a rubber stamp. It figures out its own scope (conversation
context, your instruction, or the git diff as a fallback), analyses across 11 dimensions, and ranks
findings Critical / Warning / Suggestion. Every finding cites a file and a line, or it gets dropped —
@@ -262,6 +343,9 @@ implementation step, but there's no wrong time to run it.
### 4 · Finalize 🧹
On the page: the task audit and the summary as reports, a list of the doc updates to approve, and a
confirmation before anything is archived.
Validates every task against its phase spec, writes the summary and the list of files touched, flags
the docs that drifted (`README`, `CHANGELOG`, `AGENTS.md`), then archives the whole spec folder —
`pathfinder/` included — to `specs--completed/`. That folder is the record of *why* the code looks
@@ -284,6 +368,30 @@ like this.
---
## Prefer the terminal?
Every skill also runs right in the terminal. Each one asks at the start whether you want the web
console or the terminal; add `--web` to skip the question and go straight to the web console:
`/plan2code-1-plan --web plan a REST API for tasks`.
| Command | Use it when |
|---------|-------------|
| `/plan2code` | Open the dashboard in the web console: 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 |
| `/plan2code-init-update` | Fold what you learned this session back into `AGENTS.md` |
| `/plan2code-quick-task` | A small change that doesn't warrant the full sequence |
| `/plan2code-1b-revise-plan` | Requirements moved mid-build. Revise the specs, not the code |
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from |
---
## Troubleshooting
**The skills aren't recognised.** Re-run the installer and restart your AI tool. Confirm the global
@@ -309,6 +417,18 @@ the requirements.
**Too many or too few phases.** Fix it in Step 2 — a phase should be a logical grouping of work, not
a fixed size.
**The page says it lost contact with Plan2Code.** Nothing you typed is lost, and the page reconnects
by itself. If the link has stopped working, tell the agent: it restarts the session and gives you a
new link.
**The agent runs on another machine, or over SSH.** The page is served on `127.0.0.1` of the machine
the agent runs on, so your browser can only reach it there. A forwarded port often works; otherwise
work in the terminal, which loses nothing.
**You closed the tab.** Open the link again. Everything is where you left it, including answers you
had typed but not sent. The page's program stops about two minutes after the last tab closes, so
after that, ask the agent to resume the session for a new link.
---
## Customizing
@@ -324,6 +444,7 @@ edits out through the skills CLI.
Core reference:
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off
- **[QUICK-REFERENCE.md](QUICK-REFERENCE.md)** — the one-page card: commands, inputs, outputs, decision tree
- **[.readme/walkthrough.md](.readme/walkthrough.md)** — one feature from a sentence to archived specs, session by session
- **[AGENTS.md](AGENTS.md)** — architecture and contributor guide for this repo
@@ -331,7 +452,6 @@ 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
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 127 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 584 B

After

Width:  |  Height:  |  Size: 884 B

+6 -32
View File
@@ -1,33 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Plan2Code postage stamp">
<defs>
<!-- Perforated stamp silhouette: white keeps, black bites out.
Few, deep notches so the scalloped edge still reads at 16px. -->
<mask id="perf">
<rect width="64" height="64" fill="#000"/>
<rect x="2" y="2" width="60" height="60" fill="#fff"/>
<g fill="#000">
<circle cx="2" cy="2" r="5"/><circle cx="14" cy="2" r="5"/><circle cx="26" cy="2" r="5"/>
<circle cx="38" cy="2" r="5"/><circle cx="50" cy="2" r="5"/><circle cx="62" cy="2" r="5"/>
<circle cx="2" cy="62" r="5"/><circle cx="14" cy="62" r="5"/><circle cx="26" cy="62" r="5"/>
<circle cx="38" cy="62" r="5"/><circle cx="50" cy="62" r="5"/><circle cx="62" cy="62" r="5"/>
<circle cx="2" cy="14" r="5"/><circle cx="2" cy="26" r="5"/>
<circle cx="2" cy="38" r="5"/><circle cx="2" cy="50" r="5"/>
<circle cx="62" cy="14" r="5"/><circle cx="62" cy="26" r="5"/>
<circle cx="62" cy="38" r="5"/><circle cx="62" cy="50" r="5"/>
</g>
</mask>
</defs>
<g mask="url(#perf)">
<!-- printed stamp -->
<rect x="2" y="2" width="60" height="60" fill="#D33A38"/>
<!-- the 2, set as a franking-machine numeral -->
<g fill="#FBFAF6">
<rect x="16" y="13" width="32" height="8"/>
<rect x="40" y="13" width="8" height="22"/>
<rect x="16" y="27" width="32" height="8"/>
<rect x="16" y="27" width="8" height="24"/>
<rect x="16" y="43" width="32" height="8"/>
</g>
</g>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="Plan2Code">
<rect x="6" y="2.6" width="20" height="25.4" rx="4.4" fill="#eef3fa" stroke="#3b332c" stroke-width="2.2" />
<rect x="9.6" y="27.6" width="4.8" height="2.6" rx="1.3" fill="#3b332c" />
<rect x="17.6" y="27.6" width="4.8" height="2.6" rx="1.3" fill="#3b332c" />
<path d="M16 8.8 L17.41 12.26 L21.14 12.53 L18.28 14.94 L19.17 18.57 L16 16.6 L12.83 18.57 L13.72 14.94 L10.86 12.53 L14.59 12.26 Z" fill="#2455a4" />
<path d="M12.2 20.6 Q16 24.2 19.8 20.6" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />
</svg>

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 636 B

+368 -399
View File
@@ -3,449 +3,418 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Plan2Code — Spec-Driven Workflow for AI Coding Agents</title>
<meta name="description" content="Send the plan — the build follows. You approve a plan, it becomes phase documents in your repo, and the agent builds to those documents one phase at a time.">
<title>Plan2Code: plan and build with your AI agent in your browser</title>
<meta name="description" content="Plan and build with an AI coding agent on a page in your browser. You answer the questions and approve each phase, and the specs land in your repo as plain files.">
<meta name="color-scheme" content="light dark">
<link rel="icon" href="favicon.ico" sizes="32x32">
<link rel="icon" type="image/png" sizes="32x32" href="favicon.png">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Big+Shoulders+Display:wght@500;700;800&family=Karla:wght@300;400;500;600;700&family=Caveat:wght@500&display=swap" rel="stylesheet">
<style>
:root{
--air:#E4ECF6; --air-2:#D3DEEE; --paper:#FBFAF6;
--ink:#16233D; --ink-soft:#5E6E8A;
--red:#D33A38; --blue:#2455A4; --kraft:#E5D8BE;
/* The web console's palette and type (src/web-console/public/app.css), so the
site and the product look like one thing, with the Plan2Code blue as the
accent: #2455a4 in light, and the console's Ocean highlight (palette.js),
which the screenshots use, in dark. System fonts only, like the console. */
:root {
--bg: #f6f3ee;
--panel: #ffffff;
--panel-2: #fbf9f6;
--ink: #1d1a17;
--ink-2: #5d564d;
--ink-3: #8f8779;
--rule: #e4ddd1;
--rule-2: #cfc6b6;
--accent: #2455a4;
--accent-soft: #ecf2f9;
--accent-ink: #ffffff;
--accent-line: #9ab4d3;
--ok: #2f6b45;
--focus: #1f6feb;
--code-bg: #1d1a17;
--code-ink: #f0ece5;
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
--shadow-lg: 0 2px 4px rgba(29, 26, 23, 0.06), 0 24px 60px rgba(29, 26, 23, 0.12);
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
--radius: 10px;
--width: 1120px;
--gutter: 24px;
}
*{margin:0;padding:0;box-sizing:border-box}
html{scroll-behavior:smooth}
[id]{scroll-margin-top:90px}
body{background:var(--air);color:var(--ink);font:400 16.5px/1.65 'Karla',system-ui,sans-serif;-webkit-font-smoothing:antialiased}
.bs{font-family:'Big Shoulders Display',sans-serif;font-weight:800;letter-spacing:.005em}
.hand{font-family:'Caveat',cursive}
.wrap{max-width:1140px;margin:0 auto;padding:0 34px}
a{color:inherit}
:focus-visible{outline:2px solid var(--red);outline-offset:3px}
/* ── SIGNATURE: airmail chevron border framing the page on all four sides ── */
:root{--fr:11px}
.frame-t,.frame-b,.frame-l,.frame-r{
position:fixed;z-index:60;pointer-events:none;
background:repeating-linear-gradient(-45deg,
var(--red) 0 14px, var(--paper) 14px 28px,
var(--blue) 28px 42px, var(--paper) 42px 56px);
}
.frame-t,.frame-b{left:0;right:0;height:var(--fr)}
.frame-t{top:0}
.frame-b{bottom:0}
.frame-l,.frame-r{top:0;bottom:0;width:var(--fr)}
.frame-l{left:0}
.frame-r{right:0}
body{padding:var(--fr)}
/* ── header (sticky, sits just under the top frame) ── */
.top{
background:var(--paper);border-bottom:2px solid var(--ink);
position:sticky;top:var(--fr);z-index:40;
}
.top .wrap{display:flex;align-items:center;gap:16px;padding-top:13px;padding-bottom:12px}
.brand{font-family:'Big Shoulders Display',sans-serif;font-weight:800;font-size:26px;letter-spacing:.01em;text-transform:uppercase}
.brand i{font-style:normal;color:var(--red)}
.avion{
margin-left:auto;border:1.5px solid var(--blue);color:var(--blue);
font-size:10px;letter-spacing:.22em;text-transform:uppercase;font-weight:700;padding:5px 11px;
@media (prefers-color-scheme: dark) {
:root {
--bg: #171513;
--panel: #201d1a;
--panel-2: #262220;
--ink: #f0ece5;
--ink-2: #b6afa3;
--ink-3: #8b8376;
--rule: #332e29;
--rule-2: #46403a;
--accent: #619fe5;
--accent-soft: #1a2533;
--accent-ink: #0c1117;
--accent-line: #3d5978;
--ok: #74c28f;
--focus: #6aa3ff;
--code-bg: #0f0d0c;
--code-ink: #f0ece5;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--shadow-lg: 0 2px 4px rgba(0, 0, 0, 0.45), 0 24px 60px rgba(0, 0, 0, 0.5);
}
}
/* ── hero: the envelope ── */
.hero{padding:56px 0 70px}
.env{
background:var(--paper);border:2px solid var(--ink);position:relative;
box-shadow:10px 12px 0 rgba(22,35,61,.14);padding:40px 42px 44px;
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
margin: 0;
background: var(--bg);
color: var(--ink);
font: 17px/1.6 var(--sans);
-webkit-font-smoothing: antialiased;
overflow-wrap: break-word;
}
/* cancellation waves */
.cancel{position:absolute;right:34px;top:34px;width:210px;height:110px;pointer-events:none}
.cancel .ring{fill:none;stroke:var(--red);stroke-width:2.2}
.cancel .wv{fill:none;stroke:var(--red);stroke-width:2.2;opacity:.85}
.cancel text{font-family:'Karla',sans-serif;font-weight:700;fill:var(--red);letter-spacing:.06em}
/* stamp */
.pstamp{
position:absolute;right:250px;top:34px;width:86px;height:104px;background:var(--air-2);
border:2px solid var(--ink);padding:8px;text-align:center;
}
.pstamp .in{border:1px solid rgba(22,35,61,.35);height:100%;display:flex;flex-direction:column;justify-content:center;gap:2px}
.pstamp b{font-family:'Big Shoulders Display',sans-serif;font-weight:800;font-size:26px;line-height:1;color:var(--blue)}
.pstamp span{font-size:8px;letter-spacing:.12em;text-transform:uppercase;color:var(--ink-soft);font-weight:700}
@media(max-width:900px){.cancel,.pstamp{display:none}}
img { max-width: 100%; height: auto; }
a { color: var(--accent); text-underline-offset: 3px; }
a:hover { text-decoration-thickness: 2px; }
code { font-family: var(--mono); font-size: 0.88em; }
:focus-visible { outline: 2px solid var(--focus); outline-offset: 3px; border-radius: 4px; }
h1, h2, h3 { font-family: var(--serif); font-weight: 600; line-height: 1.15; margin: 0; }
h2 { font-size: clamp(1.8rem, 4vw, 2.5rem); margin-bottom: 12px; }
h3 { font-size: 1.45rem; margin: 8px 0; }
.muted { color: var(--ink-2); }
.wrap { max-width: var(--width); margin: 0 auto; padding: 0 var(--gutter); }
.narrow { max-width: 780px; margin: 0 auto; padding: 0 var(--gutter); text-align: center; }
.skip { position: absolute; left: -9999px; top: 0; background: var(--panel); color: var(--ink); padding: 10px 16px; z-index: 10; }
.skip:focus { left: 0; }
.kick{font-size:10.5px;letter-spacing:.24em;text-transform:uppercase;color:var(--blue);font-weight:700}
h1{font-family:'Big Shoulders Display',sans-serif;font-weight:800;font-size:clamp(3rem,9vw,7rem);line-height:.86;text-transform:uppercase;margin-top:14px;max-width:13ch}
h1 em{font-style:normal;color:var(--red)}
.addr{
margin-top:32px;padding-top:26px;border-top:1.5px dashed rgba(22,35,61,.3);
display:grid;grid-template-columns:1fr 1fr;gap:36px;align-items:end;
}
.addr .to{font-size:10px;letter-spacing:.2em;text-transform:uppercase;color:var(--ink-soft);font-weight:700}
.addr p{margin-top:10px;color:var(--ink-soft);max-width:44ch}
.acts{display:flex;flex-wrap:wrap;gap:12px}
.btn{
display:inline-block;text-decoration:none;background:var(--ink);color:var(--paper);
font-family:'Big Shoulders Display',sans-serif;font-weight:700;font-size:19px;letter-spacing:.1em;
text-transform:uppercase;padding:12px 28px;transition:background .18s,transform .18s;
}
.btn:hover{background:var(--red);transform:translateY(-2px)}
.btn.-o{background:transparent;border:2px solid var(--ink);color:var(--ink);padding:10px 26px}
.btn.-o:hover{background:var(--ink);color:var(--paper)}
/* Planny, drawn as the console draws him: shell, star eye, lip, arms up. */
.planny { display: block; margin: 0 auto; width: 44px; height: 60px; overflow: visible; }
.planny .shell { fill: var(--panel); stroke: var(--ink-2); stroke-width: 1.3; }
.planny .smile, .planny .arm path { fill: none; stroke: var(--ink-2); stroke-linecap: round; }
.planny .smile { stroke-width: 0.9; }
.planny .arm path { stroke-width: 1.2; }
.planny .arm circle, .planny .foot { fill: var(--ink-2); }
.planny .eye { fill: var(--accent); }
/* ── postage meter strip ── */
.meter{background:var(--ink);color:var(--paper)}
.meter .wrap{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:0}
.meter div{padding:24px 18px;border-left:1px dashed rgba(251,250,246,.28)}
.meter div:first-child{border-left:none}
.meter b{display:block;font-family:'Big Shoulders Display',sans-serif;font-weight:800;font-size:2.4rem;line-height:1;color:#8FB6E8}
.meter span{display:block;margin-top:3px;font-size:9.5px;letter-spacing:.14em;text-transform:uppercase;opacity:.66;font-weight:700}
/* Screenshots: framed like a window, one per theme via <picture>. */
.shot { display: block; border: 1px solid var(--rule-2); border-radius: var(--radius); overflow: hidden; background: var(--panel); box-shadow: var(--shadow); }
.shot img { display: block; width: 100%; }
.shot.big { border-radius: 14px; box-shadow: var(--shadow-lg); }
/* ── dispatch (steps as airmail envelopes) ── */
.dispatch{padding:80px 0 40px}
.sect{display:flex;align-items:flex-end;gap:16px;border-bottom:2px solid var(--ink);padding-bottom:10px}
.sect h2{font-family:'Big Shoulders Display',sans-serif;font-weight:800;font-size:clamp(2rem,5vw,3.4rem);text-transform:uppercase;line-height:.95}
.sect span{margin-left:auto;font-size:10.5px;letter-spacing:.16em;text-transform:uppercase;color:var(--ink-soft);font-weight:700;padding-bottom:5px}
/* The install command and its copy button. */
.cmd { position: relative; display: inline-flex; align-items: center; gap: 12px; max-width: 100%; background: var(--code-bg); color: var(--code-ink); border-radius: var(--radius); padding: 10px 10px 10px 18px; text-align: left; }
.cmd pre { margin: 0; min-width: 0; overflow-x: auto; font: 14.5px/1.5 var(--mono); white-space: pre; }
.cmd pre span { color: var(--accent-line); user-select: none; }
.copy { flex: none; display: inline-flex; align-items: center; gap: 6px; border: 0; border-radius: 7px; background: var(--accent); color: var(--accent-ink); font: 700 13px/1 var(--sans); padding: 10px 12px; cursor: pointer; min-height: 40px; }
.copy:hover { filter: brightness(1.08); }
.copy svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.copy .tick { display: none; }
.copy.-done .clip { display: none; }
.copy.-done .tick { display: block; }
.then { margin: 12px 0 0; color: var(--ink-2); font-size: 15px; }
.letters{display:grid;grid-template-columns:repeat(auto-fit,minmax(400px,1fr));gap:22px;margin-top:30px}
.ltr{
background:var(--paper);border:2px solid var(--ink);position:relative;
padding:26px 26px 28px 40px;display:flex;flex-direction:column;
box-shadow:6px 7px 0 rgba(22,35,61,.12);transition:transform .2s,box-shadow .2s;
}
.ltr:hover{transform:translate(-3px,-3px);box-shadow:9px 10px 0 rgba(22,35,61,.16)}
/* chevron spine */
.ltr::before{
content:'';position:absolute;left:0;top:0;bottom:0;width:14px;
background:repeating-linear-gradient(-45deg,var(--red) 0 10px,var(--paper) 10px 20px,var(--blue) 20px 30px,var(--paper) 30px 40px);
border-right:1px solid var(--ink);
}
.ltr .mark{
position:absolute;right:20px;top:18px;width:56px;height:56px;border:2px solid var(--red);border-radius:50%;
display:grid;place-items:center;text-align:center;transform:rotate(-11deg);
font-size:8.5px;letter-spacing:.08em;text-transform:uppercase;color:var(--red);font-weight:700;line-height:1.25;
}
.ltr h3{font-family:'Big Shoulders Display',sans-serif;font-weight:800;font-size:1.9rem;text-transform:uppercase;line-height:1;padding-right:70px}
.ltr .flag{
display:inline-block;margin-left:9px;vertical-align:5px;font-family:'Karla',sans-serif;font-weight:700;
font-size:9px;letter-spacing:.11em;text-transform:uppercase;background:var(--blue);color:#fff;padding:3px 8px;
}
.ltr .flag.-r{background:var(--red)}
.ltr code{display:block;font-family:ui-monospace,Menlo,monospace;font-size:11.5px;color:var(--blue);margin-top:7px;font-weight:600}
.ltr p{margin-top:12px;color:var(--ink-soft);font-size:.94rem}
.ltr .pen{font-family:'Caveat',cursive;font-size:1.2rem;color:var(--red);margin-top:10px;transform:rotate(-.8deg)}
.ltr ul{list-style:none;margin-top:auto;padding-top:16px}
.ltr li{font-size:.85rem;padding:6px 0 6px 18px;position:relative;border-top:1px dotted rgba(22,35,61,.24)}
.ltr li::before{content:'✈';position:absolute;left:0;color:var(--blue);font-size:9px;top:9px}
/* Hero: centered headline, then the dashboard at full width. */
.hero { padding: 40px 0 32px; background: linear-gradient(to bottom, var(--panel), var(--bg)); }
.hero .narrow { max-width: 960px; }
.hero h1 { font-size: clamp(2.2rem, 5.6vw, 3.7rem); line-height: 1.06; margin: 12px 0 14px; }
.hero .lede { font-size: 1.2rem; color: var(--ink-2); margin: 0 auto 22px; max-width: 60ch; }
.stage { max-width: 1200px; margin: 0 auto; padding: 8px var(--gutter) 72px; }
/* ── two routes ── */
.routes{background:var(--paper);border-top:2px solid var(--ink);border-bottom:2px solid var(--ink);padding:76px 0;margin-top:56px}
.rc{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-top:28px}
.rc div{border:2px solid var(--ink);padding:26px 24px}
.rc .-a{background:rgba(211,58,56,.06)}
.rc .-b{background:rgba(36,85,164,.06)}
.rc h4{font-family:'Big Shoulders Display',sans-serif;font-weight:800;font-size:1.5rem;text-transform:uppercase}
.rc ul{list-style:none;margin-top:14px}
.rc li{padding:9px 0 9px 24px;position:relative;font-size:.95rem;border-top:1px solid rgba(22,35,61,.14);color:var(--ink-soft)}
.rc li:first-child{border-top:none}
.rc .-a li::before{content:'✕';position:absolute;left:0;color:var(--red);font-weight:700}
.rc .-b li::before{content:'✓';position:absolute;left:0;color:var(--blue);font-weight:700}
/* Sections. */
section.s { padding: 72px 0; }
section.alt { background: var(--panel); border-block: 1px solid var(--rule); }
.intro { max-width: 62ch; margin: 0; }
/* ── regulations ── */
.regs{padding:78px 0}
.rg{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:0;margin-top:26px;border-top:2px solid var(--ink);border-left:2px solid var(--ink)}
.rg div{padding:22px 20px;border-right:2px solid var(--ink);border-bottom:2px solid var(--ink);background:var(--paper)}
.rg b{font-size:10px;letter-spacing:.15em;text-transform:uppercase;color:var(--red);font-weight:700}
.rg p{margin-top:9px;font-size:.94rem;color:var(--ink-soft)}
.rg p strong{color:var(--ink);font-weight:700}
/* How a session goes: alternating screenshot and text rows. */
.row { display: grid; grid-template-columns: minmax(0, 7fr) minmax(0, 5fr); gap: 48px; align-items: center; margin-top: 56px; }
.row.flip { grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); }
.row.flip .shot { order: 2; }
.row .k { font-family: var(--serif); font-size: 3rem; line-height: 1; color: var(--accent); }
.row p { color: var(--ink-2); margin: 0; }
/* ── install ── */
.install{padding:0 0 82px}
.termwrap{position:relative;margin-top:20px}
.term{background:var(--ink);color:#D6E2F2;padding:24px 76px 24px 24px;
font-family:ui-monospace,Menlo,monospace;font-size:12.5px;line-height:2.05;overflow-x:auto}
.term .c{color:#7488A6}.term .k{color:#F0B06A}.term .p{color:#8FB6E8}
.copy{
position:absolute;top:12px;right:12px;display:grid;place-items:center;gap:0;
width:40px;height:40px;background:transparent;border:1.5px solid rgba(214,226,242,.35);
color:#8FB6E8;cursor:pointer;transition:background .18s,color .18s,border-color .18s;
/* The pipeline: a vertical line of steps, then the utilities. */
.line { list-style: none; margin: 36px 0 0; padding: 0; position: relative; }
.line::before { content: ""; position: absolute; left: 11px; top: 10px; bottom: 26px; width: 2px; background: var(--rule-2); }
.line li { position: relative; padding: 0 0 26px 48px; }
.line li::before { content: ""; position: absolute; left: 4px; top: 7px; width: 16px; height: 16px; border-radius: 50%; background: var(--panel); border: 2px solid var(--accent); }
.line li.opt::before { border-style: dashed; }
.line h3 { display: inline; font-family: var(--sans); font-size: 1.15rem; font-weight: 650; }
.chip { display: inline-block; margin-left: 8px; vertical-align: 2px; font-size: 11px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-2); border: 1px solid var(--rule-2); border-radius: 999px; padding: 2px 8px; }
.line p { margin: 4px 0 0; color: var(--ink-2); max-width: 64ch; }
.line code { color: var(--ink-2); font-size: 13px; }
.utils { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin-top: 12px; }
.util { border: 1px solid var(--rule-2); border-radius: var(--radius); background: var(--bg); padding: 16px; }
.util h3 { font-family: var(--sans); font-size: 1rem; font-weight: 650; margin: 8px 0 4px; }
.util p { margin: 0; font-size: 14.5px; color: var(--ink-2); }
.util .chip { margin-left: 0; }
/* What the page gives you: a two-column list. */
.feat { columns: 2; column-gap: 56px; margin-top: 36px; }
.feat div { break-inside: avoid; padding: 18px 0; border-top: 1px solid var(--rule); }
.feat h3 { font-size: 1.2rem; margin: 0 0 4px; }
.feat p { margin: 0; color: var(--ink-2); }
.feat-shots { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; margin-top: 40px; }
.feat-shots figure { margin: 0; }
.feat-shots figcaption { margin-top: 10px; font-size: 14.5px; color: var(--ink-2); }
/* The rules: numbered. */
ol.rules { list-style: none; padding: 0; margin: 32px 0 0; counter-reset: r; }
ol.rules li { counter-increment: r; display: grid; grid-template-columns: 3.5rem minmax(0, 1fr); gap: 16px; padding: 22px 0; border-top: 1px solid var(--rule); }
ol.rules li::before { content: counter(r); font-family: var(--serif); font-size: 2.6rem; line-height: 1; color: var(--accent); }
ol.rules h3 { font-family: var(--sans); font-size: 1.15rem; font-weight: 650; margin: 0 0 4px; }
ol.rules p { margin: 0; color: var(--ink-2); }
/* Prefer the terminal? */
.term-band { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 48px; align-items: center; }
pre.term { background: var(--code-bg); color: var(--code-ink); border-radius: var(--radius); padding: 22px; margin: 0; font: 14.5px/1.8 var(--mono); overflow-x: auto; }
/* Closing install and footer. */
.close { text-align: center; }
.close .muted { margin: 0 0 22px; }
footer { border-top: 1px solid var(--rule); padding: 26px 0 32px; color: var(--ink-2); font-size: 14.5px; }
footer .wrap { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px 22px; }
footer a { color: inherit; }
@media (max-width: 820px) {
.row, .row.flip, .term-band, .feat-shots { grid-template-columns: minmax(0, 1fr); gap: 20px; }
.row.flip .shot { order: 0; }
.row { margin-top: 44px; }
.feat { columns: 1; }
.utils { grid-template-columns: minmax(0, 1fr); }
section.s { padding: 56px 0; }
}
.copy:hover{background:#8FB6E8;color:var(--ink);border-color:#8FB6E8}
.copy svg{width:17px;height:17px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
.copy .tick{display:none}
.copy.-done{border-color:#8FB6E8;color:#8FB6E8;background:transparent}
.copy.-done .clip{display:none}
.copy.-done .tick{display:block}
.copy-flash{
position:absolute;top:20px;right:62px;font-size:9.5px;letter-spacing:.16em;
text-transform:uppercase;font-weight:700;color:#8FB6E8;opacity:0;transition:opacity .18s;pointer-events:none;
@media (max-width: 600px) {
:root { --gutter: 16px; }
body { font-size: 16px; }
.hero { padding-top: 40px; }
.cmd { display: flex; }
.cmd pre { font-size: 13px; }
ol.rules li { grid-template-columns: 2.5rem minmax(0, 1fr); }
}
.copy-flash.-on{opacity:1}
/* ── close ── */
.close{background:var(--ink);color:var(--paper);text-align:center;padding:92px 0}
.close h2{font-family:'Big Shoulders Display',sans-serif;font-weight:800;font-size:clamp(2.4rem,7vw,5.2rem);text-transform:uppercase;line-height:.9}
.close h2 em{font-style:normal;color:#8FB6E8}
.close .hand{display:block;margin-top:14px;font-size:1.5rem;color:#8FB6E8}
.close .btn{margin-top:24px;background:var(--red)}
.close .btn:hover{background:var(--paper);color:var(--ink)}
footer{background:var(--ink);color:rgba(251,250,246,.5);padding:0 0 28px;font-size:10px;letter-spacing:.15em;text-transform:uppercase;font-weight:700}
footer .wrap{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;border-top:1px dashed rgba(251,250,246,.24);padding-top:20px}
@media(max-width:700px){:root{--fr:8px}}
@media(max-width:820px){
.wrap{padding:0 20px}
.env{padding:26px 22px 28px}
.addr{grid-template-columns:1fr;gap:22px}
.rc{grid-template-columns:1fr}
.letters{grid-template-columns:1fr}
@media (prefers-reduced-motion: reduce) {
html { scroll-behavior: auto; }
* { transition: none !important; animation: none !important; }
}
@media(prefers-reduced-motion:reduce){*{transition:none!important}html{scroll-behavior:auto}}
</style>
</head>
<body>
<a class="skip" href="#main">Skip to the content</a>
<main id="main">
<div class="frame-t" aria-hidden="true"></div>
<div class="frame-b" aria-hidden="true"></div>
<div class="frame-l" aria-hidden="true"></div>
<div class="frame-r" aria-hidden="true"></div>
<header class="top">
<div class="wrap">
<span class="brand">PLAN<i>2</i>CODE</span>
<span class="avion">Par Avion &middot; Via Air Mail</span>
</div>
</header>
<section class="hero">
<div class="wrap">
<div class="env">
<div class="pstamp"><div class="in"><b>2.0</b><span>Plan2Code</span><span>Postage</span></div></div>
<svg class="cancel" viewBox="0 0 210 110" aria-hidden="true">
<circle class="ring" cx="52" cy="55" r="42"/>
<text x="52" y="46" text-anchor="middle" font-size="10">SHIPPED</text>
<text x="52" y="62" text-anchor="middle" font-size="13" font-weight="700">2026</text>
<text x="52" y="76" text-anchor="middle" font-size="8">NO REWORK</text>
<path class="wv" d="M98,36 C118,28 138,44 158,36 C178,28 194,40 208,34"/>
<path class="wv" d="M98,50 C118,42 138,58 158,50 C178,42 194,54 208,48"/>
<path class="wv" d="M98,64 C118,56 138,72 158,64 C178,56 194,68 208,62"/>
<path class="wv" d="M98,78 C118,70 138,86 158,78 C178,70 194,82 208,76"/>
</svg>
<p class="kick">Spec-driven workflow for AI coding agents</p>
<h1>Send the plan.<br>The build <em>follows</em>.</h1>
<div class="addr">
<div>
<p class="to">Addressed to</p>
<p>Anyone who has watched an AI agent confidently build the wrong thing. You approve a plan, it becomes phase documents in your repo, and the agent works to those documents one phase at a time.</p>
</div>
<div class="acts">
<a class="btn" href="#installation">Install Plan2Code</a>
<a class="btn -o" href="#dispatch">Read the letters</a>
</div>
</div>
<section class="hero" aria-labelledby="hero-title">
<div class="narrow">
<svg class="planny" viewBox="0 0 22 30" aria-hidden="true" focusable="false">
<rect class="foot" x="5.7" y="27.1" width="3.6" height="1.7" rx="0.85"/>
<rect class="foot" x="12.7" y="27.1" width="3.6" height="1.7" rx="0.85"/>
<rect class="shell" x="3" y="7" width="16" height="20" rx="3.2"/>
<path class="eye" d="M11 10.95 L11.79 12.91 L13.9 13.06 L12.28 14.42 L12.79 16.47 L11 15.35 L9.21 16.47 L9.72 14.42 L8.1 13.06 L10.21 12.91 Z"/>
<path class="smile" d="M8.3 18.4 Q11 21 13.7 18.4"/>
<g class="arm"><path d="M3 16.5 L1.1 13.7"/><circle cx="1.1" cy="13.7" r="0.85"/></g>
<g class="arm"><path d="M19 16.5 L20.9 13.7"/><circle cx="20.9" cy="13.7" r="0.85"/></g>
</svg>
<h1 id="hero-title">Plan and build with your AI agent, on one page.</h1>
<p class="lede">Plan2Code asks the questions, drafts the plan and builds it one phase at a time. You answer and approve in your browser, and the specs land in your repo.</p>
<div class="cmd">
<pre id="install-cmd"><span aria-hidden="true">$ </span>npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git</pre>
<button class="copy" type="button" aria-label="Copy the install command">
<svg class="clip" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="11" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
<svg class="tick" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 12.5 9.5 18 20 6.5"/></svg>
<span class="label">Copy</span>
</button>
</div>
<p class="then">then run <code>plan2code</code> in any project.</p>
</div>
</section>
<div class="meter">
<div class="wrap">
<div><b>90%</b><span>Confidence gate</span></div>
<div><b>11</b><span>Review dimensions</span></div>
<div><b>1</b><span>Chat per phase</span></div>
<div><b>0</b><span>Context pollution</span></div>
</div>
<div class="stage">
<picture class="shot big">
<source media="(prefers-color-scheme: dark)" srcset="screenshots/dashboard-dark.webp">
<img src="screenshots/dashboard-light.webp" width="2560" height="1600" alt="The Plan2Code dashboard for a task API that is half built: a Set up card, then the steps in order, with the Implement card marked Suggested and reading Phase 3 of 4 is next.">
</picture>
</div>
<section class="dispatch wrap" id="dispatch">
<div class="sect"><h2>Six written letters</h2><span>Two optional</span></div>
<div class="letters">
<article class="ltr">
<span class="mark">Opt<br>00</span>
<h3>Pathfinder<span class="flag">New in 2.0</span></h3>
<code>/plan2code-0-pathfinder</code>
<p>For an idea that arrives too foggy to plan. It charts the idea as a map of decision questions and clears them one at a time until nothing is left to decide.</p>
<p class="pen">it never answers its own questions — that's the point</p>
<ul>
<li>One decision per file, cleared one at a time</li>
<li>Ask for a brief — plain-English minutes, any time</li>
<li>Research questions fan out to parallel agents</li>
<li>Clears at ≥18/25 on four confidence dimensions</li>
<li>Hands a hot plan draft to Step 1</li>
</ul>
</article>
<article class="ltr">
<span class="mark">Req<br>01</span>
<h3>Plan</h3>
<code>/plan2code-1-plan</code>
<p>A real back-and-forth about what gets built. Requirements pulled apart, your codebase actually read, the stack confirmed rather than assumed.</p>
<ul>
<li>Functional and non-functional requirements</li>
<li>Integration points read from real source</li>
<li>Tech stack confirmed by explicit approval</li>
<li>Will not finalize below 90% confidence</li>
</ul>
</article>
<article class="ltr">
<span class="mark">Req<br>02</span>
<h3>Document</h3>
<code>/plan2code-2-document</code>
<p>The plan stops being a conversation and becomes files — an overview plus one self-contained phase document per phase, cut into one-story-point tasks.</p>
<ul>
<li>overview.md and Phase 1…N.md land in your repo</li>
<li>One-point tasks with real checkboxes</li>
<li>Parallel groups marked for concurrent agents</li>
<li>Each phase readable with no prior context</li>
</ul>
</article>
<article class="ltr">
<span class="mark">Req<br>03</span>
<h3>Implement</h3>
<code>/plan2code-3-implement</code>
<p>Build to the drawing, one phase per conversation. Planning context bleeding into implementation is where most agent drift starts.</p>
<p class="pen">reply “approved” — nothing advances on a guess</p>
<ul>
<li>Fresh conversation for every phase</li>
<li>Specs followed exactly as documented</li>
<li>Self-review against the spec before close</li>
<li>[/] claims prevent parallel-agent collisions</li>
</ul>
</article>
<article class="ltr">
<span class="mark">Opt<br>✳</span>
<h3>Review<span class="flag -r">Second opinion</span></h3>
<code>/plan2code-review</code>
<p>An independent senior engineer with fresh eyes and no attachment to the code that just shipped. It reads every changed file completely and reports only what it can prove — file, line, and a concrete fix.</p>
<ul>
<li>Scope adapts: files, branch diff, or subsystem</li>
<li>All 11 dimensions reported, clean ones justified</li>
<li>Ranked Critical / Warning / Suggestion</li>
<li>Read-only until you reply H, A, or S 1,3,5</li>
</ul>
</article>
<article class="ltr">
<span class="mark">Req<br>04</span>
<h3>Finalize</h3>
<code>/plan2code-4-finalize</code>
<p>Close it out. Every task audited against the spec it came from, a summary of what was built, docs checked for drift, and the folder filed away.</p>
<ul>
<li>Audit for tasks quietly left open</li>
<li>Summary of what was built and changed</li>
<li>README and other docs reconciled</li>
<li>Specs archived to specs--completed/</li>
</ul>
</article>
</div>
</section>
<section class="routes">
<section class="s" id="session" aria-labelledby="session-title">
<div class="wrap">
<div class="sect"><h2>Two routes</h2><span>Same destination</span></div>
<div class="rc">
<div class="-a">
<h4>Sent without an address</h4>
<ul>
<li>Coding starts, requirements arrive later</li>
<li>Design problems surface mid-build</li>
<li>Constant backtracking and rework</li>
<li>Context bloated with abandoned attempts</li>
<li>No way to prove requirements were met</li>
<li>Tokens burned on trial and error</li>
</ul>
<h2 id="session-title">How a session goes</h2>
<p class="intro muted">One page, from the first card to the sign-off. Your agent does the work in the terminal; you do your part here.</p>
<div class="row">
<picture class="shot">
<source media="(prefers-color-scheme: dark)" srcset="screenshots/question-dark.webp">
<img src="screenshots/question-light.webp" width="2560" height="1600" loading="lazy" alt="A Plan question card, How tasks are paged, with three options, the first marked Suggested, each with its trade-off underneath.">
</picture>
<div>
<span class="k" aria-hidden="true">1</span>
<h3>Pick a card, answer on the page</h3>
<p>Pick a step on the dashboard and it starts right there. Questions arrive a few at a time, each option with its trade-off written under it.</p>
</div>
<div class="-b">
<h4>Sent with a plan attached</h4>
<ul>
<li>The plan is approved before any code</li>
<li>Problems caught while they are still cheap</li>
<li>Implementation follows the drawing</li>
<li>Clean context, one phase at a time</li>
<li>Checkboxes prove what is done</li>
<li>Tokens spent building the agreed thing</li>
</ul>
</div>
<div class="row flip">
<picture class="shot">
<source media="(prefers-color-scheme: dark)" srcset="screenshots/build-dark.webp">
<img src="screenshots/build-light.webp" width="2560" height="1600" loading="lazy" alt="A phase of a task API being built: 5 of 11 done on the progress bar, and the phase's task list with the first five ticked.">
</picture>
<div>
<span class="k" aria-hidden="true">2</span>
<h3>Watch it build</h3>
<p>Tasks tick off as they land, and the line beside Planny says what is being worked on right now.</p>
</div>
</div>
<div class="row">
<picture class="shot">
<source media="(prefers-color-scheme: dark)" srcset="screenshots/signoff-dark.webp">
<img src="screenshots/signoff-light.webp" width="2560" height="1600" loading="lazy" alt="The Approve this phase card, with a button to read the completion report and three choices: Review the code first, Approve this phase, and I want changes.">
</picture>
<div>
<span class="k" aria-hidden="true">3</span>
<h3>Sign off</h3>
<p>Read the completion report, then approve the phase or ask for changes. In Implement, you can also have the code reviewed first.</p>
</div>
</div>
</div>
</section>
<section class="regs wrap">
<div class="sect"><h2>Postal regulations</h2><span>Four · non-negotiable</span></div>
<div class="rg">
<div><b>Reg 01</b><p>A <strong>fresh conversation</strong> for each step, and each implementation phase.</p></div>
<div><b>Reg 02</b><p>No code until the plan hits <strong>90% confidence</strong>. The gate does not negotiate.</p></div>
<div><b>Reg 03</b><p><strong>Checkboxes are the state</strong>, not the chat. Any session resumes cold.</p></div>
<div><b>Reg 04</b><p>Reply <strong>approved</strong> to close a phase. Nothing advances on a guess.</p></div>
</div>
</section>
<section class="install wrap" id="installation">
<div class="sect"><h2>Installation</h2><span>Node 18+ · network required · re-run to update</span></div>
<div class="termwrap">
<pre class="term" id="install-cmd"><span class="p">$</span> npx <span class="k">--allow-git=all</span> git+https://github.com/jparkerweb/plan2code.git</pre>
<span class="copy-flash" id="copy-flash" aria-hidden="true">Copied</span>
<button class="copy" id="copy-btn" type="button" aria-label="Copy install command to clipboard" title="Copy install command">
<svg class="clip" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="11" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
<svg class="tick" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 12.5 9.5 18 20 6.5"/></svg>
</button>
</div>
</section>
<section class="close">
<section class="s alt" id="pipeline" aria-labelledby="pipeline-title">
<div class="wrap">
<h2>Post it once.<br><em>Then go outside.</em></h2>
<span class="hand">free, MIT, twenty seconds to install</span>
<br><a class="btn" href="https://github.com/jparkerweb/plan2code">Plan2Code Git Repo</a>
<h2 id="pipeline-title">The pipeline</h2>
<p class="intro muted">Every step is a card on the dashboard. Each one writes files the next one reads, so any session can pick up cold.</p>
<ol class="line">
<li class="opt"><h3>Pathfinder</h3><span class="chip">Step 0 · optional</span><p>A foggy idea becomes a clear list of decisions, settled one question at a time. <code>/plan2code-0-pathfinder</code></p></li>
<li><h3>Plan</h3><span class="chip">Step 1</span><p>Requirements, technical design and your approval: the shape of what gets built. <code>/plan2code-1-plan</code></p></li>
<li><h3>Document</h3><span class="chip">Step 2</span><p>The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do. <code>/plan2code-2-document</code></p></li>
<li><h3>Implement</h3><span class="chip">Step 3 · once per phase</span><p>Builds the next phase, task by task, with a report and your sign-off at the end. <strong>Implement + review</strong> adds a careful review of the changes before the sign-off. <code>/plan2code-3-implement</code></p></li>
<li><h3>Finalize</h3><span class="chip">Step 4</span><p>Checks the work, writes the summary, files the specs away and suggests the commit message. <code>/plan2code-4-finalize</code></p></li>
</ol>
<div class="utils">
<div class="util"><span class="chip">Any time</span><h3>Quick task</h3><p>Too small for the full process? A quick plan, then it just builds it.</p></div>
<div class="util"><span class="chip">Any time</span><h3>Review</h3><p>A second opinion on the changes. Problems ranked, and you pick what gets fixed.</p></div>
<div class="util"><span class="chip">Any time</span><h3>Handoff</h3><p>Pack this conversation into a document a fresh session can pick up cold.</p></div>
</div>
</div>
</section>
<footer><div class="wrap"><span>Plan2Code v2.0.0</span><span>MIT</span><span>plan2code.jparkerweb.com</span></div></footer>
<section class="s" id="features" aria-labelledby="features-title">
<div class="wrap">
<h2 id="features-title">What the page gives you</h2>
<p class="intro muted">The same workflow as the terminal, with more room to think.</p>
<div class="feat">
<div><h3>Trade-offs in plain view</h3><p>Questions arrive a few at a time, each option with its trade-off written under it, so you choose rather than guess.</p></div>
<div><h3>Review before you approve</h3><p>Review the code first, on the sign-off card, reviews exactly the files the phase changed. You tick which findings get fixed, then approve.</p></div>
<div><h3>The Ask tab</h3><p>A chat beside the cards for anything you want to know. It is answered at the agent's next check-in and never holds up your answers.</p></div>
<div><h3>Attachments on notes</h3><p>Paste a screenshot or attach a document to a note on any question, and show instead of describe.</p></div>
<div><h3>Workspace folders</h3><p>Add a shared library or a design folder as read-only context, and point at it by its <code>@name</code>.</p></div>
<div><h3>Session meter</h3><p>A ring in the top bar turns from green to red as a session grows long, and suggests when a fresh one would serve you better.</p></div>
<div><h3>Runs on your machine</h3><p>A small program Plan2Code starts for you serves the page on <code>127.0.0.1</code>. No account, no dependencies, and nothing leaves your computer.</p></div>
</div>
<div class="feat-shots">
<figure>
<picture class="shot">
<source media="(prefers-color-scheme: dark)" srcset="screenshots/ask-dark.webp">
<img src="screenshots/ask-light.webp" width="2560" height="1600" loading="lazy" alt="The Ask tab: the question Where are tasks paged? and Plan2Code's answer naming the file.">
</picture>
<figcaption>The Ask tab, answered between tasks.</figcaption>
</figure>
<figure>
<picture class="shot">
<source media="(prefers-color-scheme: dark)" srcset="screenshots/finish-dark.webp">
<img src="screenshots/finish-light.webp" width="2560" height="1600" loading="lazy" alt="The finished screen after a phase: what happened, the next command with a Copy button, and a Back to the dashboard button.">
</picture>
<figcaption>Every ending says what to run next.</figcaption>
</figure>
</div>
</div>
</section>
<section class="s alt" id="rules" aria-labelledby="rules-title">
<div class="wrap">
<h2 id="rules-title">The rules</h2>
<p class="intro muted">Four rules do most of the work.</p>
<ol class="rules">
<li><div><h3>Keep each session short.</h3><p>Chaining a couple of small skills on the dashboard is fine. Start a fresh console session when the session meter turns red, and always before a big planning or build step. The specs on disk carry everything between sessions.</p></div></li>
<li><div><h3>No code until the plan hits 90% confidence.</h3><p>Step 1 will not finalize below the threshold. Under it, the agent keeps asking and keeps reading your code, and writes every assumption down where you can argue with it.</p></div></li>
<li><div><h3>Checkboxes are the state, not the chat.</h3><p>Progress lives in the spec files. Any agent, any session, resumes cold from them.</p></div></li>
<li><div><h3>Approve a phase to close it.</h3><p>On the sign-off card, or by replying <code>approved</code> in the terminal. Nothing advances on a guess about what you meant.</p></div></li>
</ol>
</div>
</section>
<section class="s" id="terminal" aria-labelledby="terminal-title">
<div class="wrap term-band">
<div>
<h2 id="terminal-title">Prefer the terminal?</h2>
<p class="muted">Every skill also runs right in the terminal. Each one asks at the start whether you want the page or the terminal; add <code>--web</code> to skip the question and go straight to the page.</p>
<p><a href="https://github.com/jparkerweb/plan2code#prefer-the-terminal">See every command in the README</a></p>
</div>
<pre class="term">/plan2code
/plan2code-1-plan --web plan a REST API for tasks</pre>
</div>
</section>
<section class="s alt close" id="install" aria-labelledby="install-title">
<div class="narrow">
<h2 id="install-title">Install</h2>
<p class="muted">Needs Node.js 18 or later. Run it again any time to update.</p>
<div class="cmd">
<pre><span aria-hidden="true">$ </span>npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git</pre>
<button class="copy" type="button" aria-label="Copy the install command">
<svg class="clip" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="11" height="12" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
<svg class="tick" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 12.5 9.5 18 20 6.5"/></svg>
<span class="label">Copy</span>
</button>
</div>
<p class="then">then run <code>plan2code</code> in any project.</p>
</div>
</section>
</main>
<footer>
<div class="wrap">
<a href="https://github.com/jparkerweb/plan2code">Plan2Code on GitHub</a>
<span>MIT license</span>
<span>Version 2.4.1</span>
</div>
</footer>
<script>
(function(){
(function () {
var CMD = 'npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git';
var btn = document.getElementById('copy-btn');
var flash = document.getElementById('copy-flash');
var timer;
function done(){
btn.classList.add('-done');
flash.classList.add('-on');
clearTimeout(timer);
timer = setTimeout(function(){
btn.classList.remove('-done');
flash.classList.remove('-on');
}, 1800);
}
function fallback(){
var ta = document.createElement('textarea');
ta.value = CMD;
ta.setAttribute('readonly','');
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
try { document.execCommand('copy'); done(); } catch(e) {}
document.body.removeChild(ta);
}
btn.addEventListener('click', function(){
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(CMD).then(done, fallback);
} else {
fallback();
function wire(btn) {
var label = btn.querySelector('.label');
var timer;
function done() {
btn.classList.add('-done');
label.textContent = 'Copied';
clearTimeout(timer);
timer = setTimeout(function () {
btn.classList.remove('-done');
label.textContent = 'Copy';
}, 1800);
}
});
function fallback() {
var ta = document.createElement('textarea');
ta.value = CMD;
ta.setAttribute('readonly', '');
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
try { document.execCommand('copy'); done(); } catch (e) {}
document.body.removeChild(ta);
}
btn.addEventListener('click', function () {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(CMD).then(done, fallback);
} else {
fallback();
}
});
}
var buttons = document.querySelectorAll('.copy');
for (var i = 0; i < buttons.length; i++) wire(buttons[i]);
})();
</script>
</body>
Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

+60 -17
View File
@@ -549,6 +549,12 @@ function computeExpectedSkills() {
for (const reference of prompt.additionalReferences || []) {
const absSource = path.join(SRC_DIR, reference.source);
if (reference.source === 'web-console') {
expected.set(
`${SKILLS_DIR_NAME}/${skillName}/references/${reference.target}/version.json`,
fs.readFileSync(path.join(__dirname, 'version.json'))
);
}
try {
if (fs.statSync(absSource).isDirectory()) {
for (const relPath of listFilesRecursive(absSource)) {
@@ -884,14 +890,14 @@ async function install() {
return 1;
}
// Point at the dashboard first: the `plan2code` command when it installed, the skill otherwise.
const dashboardWhere = launcherFailed ? 'Open the dashboard in your agent:' : 'Open the dashboard from any project:';
const dashboardCommand = launcherFailed ? '/plan2code' : LAUNCHER_COMMAND;
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.BRIGHT}◡${COLORS.GREEN} │${COLORS.RESET} ${COLORS.BRIGHT}https://github.com/jparkerweb/plan2code${COLORS.RESET}`);
console.log(`${COLORS.GREEN} ╰┬─┬╯${COLORS.RESET}`);
console.log(`${COLORS.GREEN} ╲│ ${COLORS.CYAN}★${COLORS.GREEN} │╱${COLORS.RESET} ${COLORS.BRIGHT}${dashboardWhere}${COLORS.RESET}`);
console.log(`${COLORS.GREEN} │ ${COLORS.BRIGHT}◡${COLORS.GREEN} │${COLORS.RESET} ${COLORS.BRIGHT}${COLORS.CYAN}${dashboardCommand}${COLORS.RESET}`);
console.log(`${COLORS.GREEN} ╰┬─┬╯${COLORS.RESET} ${COLORS.DIM}Docs:${COLORS.RESET} ${COLORS.BRIGHT}https://github.com/jparkerweb/plan2code${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('');
@@ -2131,6 +2137,8 @@ function uninstallPlan2CodeBot() {
const LAUNCHER_COMMAND = 'plan2code';
const LAUNCHER_MARKER = 'plan2code-launcher';
const LAUNCHER_SRC = path.join(__dirname, 'src', 'launcher', 'plan2code.js');
const MODELS_SRC = path.join(__dirname, 'src', 'launcher', 'models.json');
const MODELS_DEST = path.join(os.homedir(), '.plan2code', 'bin', 'models.json');
const LAUNCHER_DEST = path.join(os.homedir(), '.plan2code', 'bin', 'plan2code.js');
const LAUNCHER_STATE = path.join(os.homedir(), '.plan2code', 'launcher.json');
const LAUNCHER_PICK_FOLDER_FLAG = '--pick-folder';
@@ -2180,28 +2188,60 @@ function getLauncherBinCandidates() {
}
/**
* Shims written into the bin directory — the same trio npm creates for a global bin on
* 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.
* Each runs the Node that ran the installer (`nodePath`, an absolute path) rather than `node`
* from PATH, because a desktop entry starts without the shell profile that puts an nvm Node
* on PATH, and `nvm use` can swap that Node later. If the path is gone (Node was upgraded or
* removed), the shim falls back to `node` on PATH, as npm's own shims do.
*/
function getLauncherShims(binDir) {
function getLauncherShims(binDir, nodePath = process.execPath) {
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 shQuote = (value) => `'${value.replace(/'/g, "'\\''")}'`;
const psQuote = (value) => `'${value.replace(/'/g, "''")}'`;
const cmdEscape = (value) => value.replace(/%/g, '%%');
const posixNode = shQuote(nodePath.replace(/\\/g, '/'));
const posixDest = shQuote(LAUNCHER_DEST.replace(/\\/g, '/'));
const shims = [
{
file: base,
content: `#!/bin/sh\n# ${LAUNCHER_MARKER}\nNODE="${posixNode}"\n[ -x "$NODE" ] || NODE=node\nexec "$NODE" "${posixDest}" "$@"\n`,
content: [
'#!/bin/sh',
`# ${LAUNCHER_MARKER}`,
`NODE=${posixNode}`,
`if [ -x "$NODE" ]; then exec "$NODE" ${posixDest} "$@"; else exec node ${posixDest} "$@"; fi`,
'',
].join('\n'),
},
];
if (process.platform === 'win32') {
const cmdNode = cmdEscape(nodePath);
const cmdDest = cmdEscape(LAUNCHER_DEST);
shims.push(
{ file: `${base}.cmd`, content: `@echo off\r\nrem ${LAUNCHER_MARKER}\r\nnode "${LAUNCHER_DEST}" %*\r\n` },
{
file: `${base}.cmd`,
content: [
'@echo off',
`rem ${LAUNCHER_MARKER}`,
`if not exist "${cmdNode}" goto p2c_path_node`,
`"${cmdNode}" "${cmdDest}" %*`,
'exit /b %ERRORLEVEL%',
':p2c_path_node',
`node "${cmdDest}" %*`,
'',
].join('\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`,
content: [
'#!/usr/bin/env pwsh',
`# ${LAUNCHER_MARKER}`,
`$node = ${psQuote(nodePath)}`,
"if (-not (Test-Path -LiteralPath $node -PathType Leaf)) { $node = 'node' }",
`& $node ${psQuote(LAUNCHER_DEST)} $args`,
'exit $LASTEXITCODE',
'',
].join('\r\n'),
}
);
}
@@ -2397,6 +2437,9 @@ async function installLauncher({ quiet = false } = {}) {
try {
fs.mkdirSync(path.dirname(LAUNCHER_DEST), { recursive: true });
fs.copyFileSync(LAUNCHER_SRC, LAUNCHER_DEST);
// The curated model menu is the authors' source of truth, so it is overwritten on every install.
// Models the user added in User Preferences live in ~/.plan2code/models.json and are untouched.
fs.copyFileSync(MODELS_SRC, MODELS_DEST);
if (process.platform !== 'win32') fs.chmodSync(LAUNCHER_DEST, 0o755);
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Installed: ${LAUNCHER_DEST}`);
} catch (error) {
@@ -2467,7 +2510,7 @@ function uninstallLauncher() {
}
const shortcut = getShortcutFile();
if (isOurShortcut(shortcut)) remove(shortcut);
for (const file of [LAUNCHER_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE]) {
for (const file of [LAUNCHER_DEST, MODELS_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE]) {
if (fs.existsSync(file)) remove(file);
}
try {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "plan2code",
"version": "2.4.0",
"version": "2.4.1",
"private": true,
"bin": {
"plan2code-install": "./install.js"
+368
View File
@@ -0,0 +1,368 @@
#!/usr/bin/env node
// Screenshots of the web console for the docs. Dev-only: lives in scripts/ so
// it never ships inside a skill.
//
// node scripts/capture-screenshots.mjs [--only <shot>] [--browser <path>]
// [--out <dir>]
//
// Every shot is staged with no agent: a throwaway sample project called
// `task-api`, a throwaway console home (PLAN2CODE_CONSOLE_HOME), then
// `console.mjs open` and `post` with the payloads in scripts/screenshots/.
// Each screen is saved light and dark, at 1280x800 and twice the pixel
// density, as `<out>/<shot>-light.webp` and `<out>/<shot>-dark.webp`.
// The shots use the console's Ocean highlight rather than its default orange:
// it is the console's nearest to the Plan2Code blue the site and README use.
//
// Shots: dashboard, question, doc, build, signoff, finish, ask.
//
// Needs puppeteer-core (`npm i --no-save puppeteer-core`, never added to
// package.json) and a local Chrome or Edge. Writes nothing outside its temp
// folders and --out.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
const PAYLOADS = path.join(ROOT, "scripts", "screenshots");
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 OUT = path.resolve(args.out || path.join(ROOT, "docs", "screenshots"));
const QUALITY = 85;
const WARN_KB = 300;
const THEMES = ["light", "dark"];
// Which workflow each shot opens under, which payloads it posts in order,
// which tab it is captured on (by the tab's label; none means the first tab),
// and where to scroll first: `scrollTo` is put at the top of the view and
// `mustShow` has to end up wholly inside it (none means the top).
const SHOTS = {
// The suggested card sits below the fold at 1280x800, and it is the point of
// the shot. Starting at the "Hide unavailable" switch keeps the spec picker's
// cut out of frame and the card in it.
dashboard: {
workflow: "dashboard",
posts: ["dashboard"],
scrollTo: ".dash-toggle",
mustShow: ".dash-card:has(.pill.suggested)",
},
question: { workflow: "plan", posts: ["question"] },
doc: { workflow: "plan", posts: ["doc"], tab: "What we've agreed" },
build: { workflow: "implement", posts: ["build"], tab: "Phase 3 tasks" },
signoff: { workflow: "implement", posts: ["signoff"] },
finish: { workflow: "implement", posts: ["signoff", "finish"] },
ask: { workflow: "plan", posts: ["question"], ask: "Where are tasks paged?" },
};
// On Windows the temp dir sits under the user's profile, and the page can
// show the project's path, so the sample project goes at the drive root
// instead. Elsewhere the temp dir carries no username. Each run makes its own
// folder there (p2c-shots-XXXXXX), so it never deletes anything it did not
// create and two runs never share one.
const SCRATCH_ROOT = process.platform === "win32" ? path.parse(os.tmpdir()).root : os.tmpdir();
let SCRATCH = null;
let HOME = null;
let ENV = null;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function fail(message) {
console.error(message);
process.exit(1);
}
function findBrowser() {
if (typeof args.browser === "string") return fs.existsSync(args.browser) ? args.browser : null;
const candidates = [
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
"/usr/bin/google-chrome",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
];
return candidates.find((p) => fs.existsSync(p)) || null;
}
function phaseFile(n, name, tasks, done) {
const lines = tasks.map((t, i) => `- [${done ? "x" : " "}] **Task ${n}.${i + 1}:** ${t}`).join("\n");
return `# Phase ${n}: ${name}\n\n**Status:** ${done ? "Complete" : "Not Started"}\n\n## Tasks\n\n${lines}\n`;
}
// A neutral project the console scans as mid-build: Phases 1 and 2 done,
// Phases 3 and 4 still to do.
function makeSampleProject() {
const project = path.join(SCRATCH, "task-api");
const spec = path.join(project, "specs", "task-api");
fs.mkdirSync(spec, { recursive: true });
fs.writeFileSync(
path.join(project, "AGENTS.md"),
"# AGENTS.md\n\nA REST API for a team's tasks, on Fastify, Postgres and Zod.\n\n## Development Commands\n\n- `npm start` runs the API\n- `npm test` runs the tests\n"
);
fs.writeFileSync(
path.join(spec, "overview.md"),
[
"# Task API",
"",
"**Status:** In Progress",
"",
"## Summary",
"",
"A REST API for a team's tasks: create, list, update and delete them, with filters by status and assignee and cursor paging.",
"",
"## Phase Checklist",
"",
"- [x] Phase 1: Project setup ([phase-1.md](./phase-1.md))",
"- [x] Phase 2: Data model ([phase-2.md](./phase-2.md))",
"- [ ] Phase 3: API endpoints ([phase-3.md](./phase-3.md))",
"- [ ] Phase 4: Authentication ([phase-4.md](./phase-4.md))",
"",
].join("\n")
);
// The file the Ask shot's answer points at.
fs.mkdirSync(path.join(project, "src", "tasks"), { recursive: true });
fs.writeFileSync(
path.join(project, "src", "tasks", "paginate.js"),
[
"// Cursor paging for GET /tasks: up to 50 tasks a page, oldest first.",
"export function paginate(tasks, cursor, limit = 50) {",
" const start = cursor ? tasks.findIndex((t) => t.id === cursor) + 1 : 0;",
" const page = tasks.slice(start, start + limit);",
" return { tasks: page, nextCursor: page.length === limit ? page[page.length - 1].id : null };",
"}",
"",
].join("\n")
);
fs.writeFileSync(path.join(spec, "phase-1.md"), phaseFile(1, "Project setup", ["Scaffold the Fastify app", "Add the Postgres connection", "Add the test runner"], true));
fs.writeFileSync(
path.join(spec, "phase-2.md"),
phaseFile(2, "Data model", ["Add the tasks table and its migration", "Add the task model", "Add status and assignee indexes", "Seed sample tasks"], true)
);
fs.writeFileSync(
path.join(spec, "phase-3.md"),
phaseFile(3, "API endpoints", ["Add GET /tasks with cursor paging", "Add POST /tasks", "Add PATCH /tasks/:id", "Add DELETE /tasks/:id"], false)
);
fs.writeFileSync(
path.join(spec, "phase-4.md"),
phaseFile(4, "Authentication", ["Add API keys", "Require a key on every route", "Scope tasks to the key's team"], false)
);
return project;
}
function cli(cwd, ...cliArgs) {
const r = spawnSync(process.execPath, [CONSOLE_CLI, ...cliArgs], { cwd, env: ENV, encoding: "utf8" });
const line = (r.stdout || "").trim().split("\n").pop() || "";
let out = null;
try {
out = JSON.parse(line);
} catch {}
return { code: r.status, out, err: r.stderr };
}
function post(project, sid, name) {
const r = cli(project, "post", "--session", sid, "--file", path.join(PAYLOADS, name + ".json"));
if (r.code !== 0) throw new Error(`post ${name}.json failed (${r.code}): ${r.err.trim()}`);
}
// Opens a session for the shot and posts its payloads. Returns { sid, url }.
function stage(project, shot) {
const spec = SHOTS[shot];
const r = cli(project, "open", "--workflow", spec.workflow, "--no-open");
if (r.code !== 0 || !r.out || !r.out.url) throw new Error(`open failed (${r.code}): ${r.err.trim()}`);
for (const name of spec.posts) post(project, r.out.sid, name);
return { sid: r.out.sid, url: r.out.url };
}
// Waits for the page to draw real state, then lets the animations finish
// (the dashboard's wake-up is the longest).
async function settle(page) {
await page.waitForNetworkIdle({ idleTime: 500, timeout: 15000 }).catch(() => {});
await page.waitForSelector(".dash-card, .card, .handoff, .ask-pane, .doc", { timeout: 15000 }).catch(() => {});
await sleep(3500);
}
async function openTab(page, label) {
await page.evaluate((text) => {
const tab = [...document.querySelectorAll("#views .view-tab")].find((b) => b.firstChild && b.firstChild.textContent.trim() === text);
if (tab) tab.click();
}, label);
await sleep(600);
}
async function scrollTo(page, { scrollTo: top, mustShow }) {
const problem = await page.evaluate(
(topSel, showSel) => {
const node = document.querySelector(topSel);
if (!node) return `nothing matched ${topSel}, captured from the top`;
node.scrollIntoView({ block: "start", behavior: "instant" });
if (!showSel) return null;
const show = document.querySelector(showSel);
if (!show) return `nothing matched ${showSel}`;
const r = show.getBoundingClientRect();
return r.top >= 0 && r.bottom <= window.innerHeight ? null : `${showSel} is not wholly in view`;
},
top,
mustShow || null
);
if (problem) console.log(` warning: ${problem}`);
await sleep(300);
}
async function shoot(page, name) {
const written = [];
for (const theme of THEMES) {
await page.emulateMediaFeatures([{ name: "prefers-color-scheme", value: theme }]);
// The theme is applied at load, so reload rather than trust a live switch.
await page.reload({ waitUntil: "domcontentloaded" });
await settle(page);
if (page.__tab) await openTab(page, page.__tab);
if (page.__scroll && page.__scroll.scrollTo) await scrollTo(page, page.__scroll);
const file = path.join(OUT, `${name}-${theme}.webp`);
await page.screenshot({ type: "webp", quality: QUALITY, path: file });
const kb = Math.round(fs.statSync(file).size / 1024);
console.log(`${path.basename(file)} ${kb} KB`);
if (kb > WARN_KB) console.log(` warning: ${path.basename(file)} is over ${WARN_KB} KB`);
written.push(file);
}
return written;
}
// Opens the page for a staged session and saves both themes.
async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
const ctx = await browser.createBrowserContext();
try {
const page = await ctx.newPage();
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
await page.goto(url, { waitUntil: "domcontentloaded" });
await settle(page);
page.__tab = tab || null;
page.__scroll = { scrollTo: top, mustShow };
return await shoot(page, name);
} finally {
await ctx.close();
}
}
// The Ask shot: a question typed and sent on the page, collected with `chat`
// the way an agent would, and answered with a posted reply.
async function captureAsk(browser, project, sid, url, question) {
const ctx = await browser.createBrowserContext();
try {
const page = await ctx.newPage();
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
await page.goto(url, { waitUntil: "domcontentloaded" });
await settle(page);
await openTab(page, "Ask");
await page.waitForSelector("#ask-input:not([disabled])", { timeout: 10000 });
await page.type("#ask-input", question);
await page.evaluate(() => {
const send = [...document.querySelectorAll(".ask-composer button")].find((b) => b.textContent.trim() === "Send");
if (send) send.click();
});
let entry = null;
for (let i = 0; i < 40 && !entry; i++) {
const r = cli(project, "chat", "--session", sid);
if (r.code === 0 && r.out && r.out.chat) entry = r.out.chat.find((c) => c.kind === "message");
if (!entry) await sleep(250);
}
if (!entry) throw new Error("the Ask question never reached the console");
const reply = path.join(HOME, "ask-reply.json");
fs.writeFileSync(
reply,
JSON.stringify({
chat: {
replies: [
{
id: "r" + entry.seq,
re: entry.seq,
conversation: entry.conversation,
md: "Paging is in `src/tasks/paginate.js`. It reads the `cursor` query parameter, returns up to 50 tasks and a `nextCursor`, and `GET /tasks` calls it on every request.",
},
],
},
agent: { status: "waiting" },
})
);
const r = cli(project, "post", "--session", sid, "--file", reply);
if (r.code !== 0) throw new Error(`posting the Ask reply failed (${r.code}): ${r.err.trim()}`);
await sleep(1000);
page.__tab = "Ask";
return await shoot(page, "ask");
} finally {
await ctx.close();
}
}
async function main() {
const names = args.only ? [args.only] : Object.keys(SHOTS);
for (const n of names) if (!SHOTS[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(SHOTS).join(", ")}`);
let puppeteer;
try {
puppeteer = (await import("puppeteer-core")).default;
} catch {
fail("puppeteer-core is not installed. Run: npm i --no-save puppeteer-core");
}
const browserPath = findBrowser();
if (!browserPath) fail("No Chrome or Edge found. Pass one with --browser <path>.");
SCRATCH = fs.mkdtempSync(path.join(SCRATCH_ROOT, "p2c-shots-"));
HOME = path.join(SCRATCH, "console-home");
ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
fs.mkdirSync(HOME, { recursive: true });
fs.mkdirSync(OUT, { recursive: true });
let browser = null;
let project = null;
try {
project = makeSampleProject();
// A saved role keeps the dashboard's "pick your role" banner out of shot,
// and the Ocean highlight is the console's nearest to the Plan2Code blue
// the landing page uses.
fs.writeFileSync(path.join(HOME, "looks.json"), JSON.stringify({ looks: { role: "engineer", accent: "ocean" } }));
browser = await puppeteer.launch({
executablePath: browserPath,
headless: true,
args: ["--no-first-run", "--no-default-browser-check", "--mute-audio"],
});
for (const name of names) {
const { sid, url } = stage(project, name);
try {
if (SHOTS[name].ask) await captureAsk(browser, project, sid, url, SHOTS[name].ask);
else await capture(browser, url, name, SHOTS[name]);
} finally {
cli(project, "stop", "--session", sid);
}
}
} finally {
if (browser) await browser.close();
if (project) cli(project, "stop", "--all");
removeScratch();
}
}
// `stop` signals the server and returns without waiting for it to exit, and
// on Windows a server still closing holds its log open. Retry the delete, and
// never let a failed cleanup replace the run's own result or error.
function removeScratch() {
try {
fs.rmSync(SCRATCH, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
} catch (e) {
console.log(`warning: could not remove ${SCRATCH} (${e.code || e.message}); delete it by hand`);
}
}
main().catch((e) => {
console.error(e && e.message ? e.message : e);
process.exit(1);
});
+18
View File
@@ -0,0 +1,18 @@
# Screenshot payloads
Each JSON file here stages one web console screen for the docs, with no agent
involved. `node scripts/capture-screenshots.mjs` opens a console session in a
throwaway sample project, posts these files, and saves the screens as light
and dark WebP images in `docs/screenshots/`.
| File | Stages |
| --- | --- |
| `dashboard.json` | The dashboard menu, suggesting the next build phase |
| `question.json` | A Plan session with three questions open (also the base of the Ask shot) |
| `doc.json` | A living document with settled, assumed and draft sections, and its review card |
| `build.json` | A phase being built: the progress bar, the task list and the current task |
| `signoff.json` | The completion report and the sign-off card |
| `finish.json` | The finished screen after sign-off (posted after `signoff.json`) |
Refresh every image with `node scripts/capture-screenshots.mjs`, or one with
`--only <shot>`.
+40
View File
@@ -0,0 +1,40 @@
{
"workflow": "implement",
"title": "task-api: Phase 3",
"headline": {
"stage": "Phase 3: API endpoints",
"cleared": 5,
"total": 11
},
"docs": [
{
"id": "phase",
"title": "Phase 3 tasks",
"version": 6,
"blocks": [
{
"id": "tasks",
"state": "settled",
"md": "- [x] **Task 3.1:** Register the /tasks routes plugin\n- [x] **Task 3.2:** Add GET /tasks with cursor paging\n- [x] **Task 3.3:** Add GET /tasks/:id\n- [x] **Task 3.4:** Add POST /tasks with a Zod schema\n- [x] **Task 3.5:** Add PATCH /tasks/:id for status and fields\n- [ ] **Task 3.6:** Add DELETE /tasks/:id as a soft delete\n- [ ] **Task 3.7:** Filter GET /tasks by status and assignee\n- [ ] **Task 3.8:** Return one error shape for 400, 404 and 409\n- [ ] **Task 3.9:** Document the endpoints in openapi.yaml\n- [ ] **Task 3.10:** Write tests for paging, filters and validation\n- [ ] **Task 3.11:** Run the test suite and record the results"
}
]
},
{
"id": "phasefile",
"title": "phase-3.md",
"version": 6,
"blocks": [
{
"id": "body",
"state": "settled",
"md": "# Phase 3: API endpoints\n\n**Status:** In Progress\n**Estimated Tasks:** 11\n\n## Overview\n\nThe /tasks endpoints: list with paging and filters, read, create, update and soft delete, with one error shape for every failure.\n\n## Prerequisites\n\n- Phase 2 complete (the tasks table and model exist) VERIFIED\n- Postgres runs locally VERIFIED\n\n## Tasks\n\n- [x] **Task 3.1:** Register the /tasks routes plugin\n- [x] **Task 3.2:** Add GET /tasks with cursor paging\n- [x] **Task 3.3:** Add GET /tasks/:id\n- [x] **Task 3.4:** Add POST /tasks with a Zod schema\n- [x] **Task 3.5:** Add PATCH /tasks/:id for status and fields\n- [ ] **Task 3.6:** Add DELETE /tasks/:id as a soft delete\n- [ ] **Task 3.7:** Filter GET /tasks by status and assignee\n- [ ] **Task 3.8:** Return one error shape for 400, 404 and 409\n- [ ] **Task 3.9:** Document the endpoints in openapi.yaml\n- [ ] **Task 3.10:** Write tests for paging, filters and validation\n- [ ] **Task 3.11:** Run the test suite and record the results\n\n## Acceptance Criteria\n\n- Every endpoint validates its input and answers errors in one shape\n- Paging stays stable while tasks are added and removed\n"
}
]
}
],
"agent": {
"status": "working",
"activity": "Task 6 of 11: deleting a task",
"quietMinutes": 15
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"menu": {
"note": "task-api is built up to Phase 2 of 4. Phase 3 is next.",
"recommend": "plan2code-3-implement",
"details": {
"plan2code-3-implement": "Phase 3 of 4 is next"
}
},
"agent": {
"status": "waiting"
}
}
+63
View File
@@ -0,0 +1,63 @@
{
"workflow": "plan",
"title": "Task API",
"headline": {
"stage": "Step 3 of 7: What we've agreed",
"cleared": 4,
"total": 7,
"confidence": "Most of it is settled. Paging is assumed for now."
},
"docs": [
{
"id": "map",
"title": "What we've agreed",
"version": 2,
"note": "Added paging",
"blocks": [
{
"id": "b1",
"state": "settled",
"md": "## Where we're headed\n\nA REST API for a team's tasks: create, list, update and delete them, with filters by status and assignee. Built on Fastify, Postgres and Zod."
},
{
"id": "b2",
"state": "assumed",
"md": "### Paging\n\nAssuming cursor paging, 50 tasks per page. Still open: the web app may want page numbers."
},
{
"id": "b3",
"state": "draft",
"md": "### Still to work out\n\n- How clients sign in\n- Whether a deleted task can be restored"
}
]
}
],
"items": [
{
"id": "agree",
"kind": "review",
"title": "Check the plan so far",
"doc": "map",
"body": "Read what we've agreed, then approve it or say what to change. Paging is marked as assumed.",
"verdicts": [
{
"id": "approve",
"label": "Looks right"
},
{
"id": "changes",
"label": "I want changes"
}
],
"token": {
"approve": "yes",
"changes": "needs changes"
},
"nothingYet": "Nothing is written to disk until you approve.",
"fallbackText": "Does what we've agreed look right? Reply yes, or describe what to change."
}
],
"agent": {
"status": "waiting"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"items": [
{
"id": "signoff",
"status": "answered",
"answer": {
"verdict": "approve"
}
}
],
"finish": {
"headline": "Phase 3 is built",
"body": "11 of 11 tasks, all on disk. Phase 4 (authentication) is next.",
"command": "/plan2code-3-implement specs/task-api/overview.md",
"doc": "report",
"dashboard": true
},
"agent": {
"status": "waiting"
}
}
+117
View File
@@ -0,0 +1,117 @@
{
"workflow": "plan",
"title": "Task API",
"headline": {
"stage": "Step 1 of 7: What we're building",
"cleared": 1,
"total": 7,
"confidence": "A clear idea so far. Who calls the API and how it signs in are still open."
},
"topics": [
{
"id": "t1",
"title": "What we're building",
"status": "current"
}
],
"items": [
{
"id": "q2",
"topic": "t1",
"kind": "choice",
"title": "How tasks are paged",
"body": "A team can have thousands of tasks. How should the list endpoint hand them back?",
"options": [
{
"k": "A",
"text": "Cursor paging",
"detail": "Stable while tasks are added and removed. No jumping to page 7.",
"recommended": true
},
{
"k": "B",
"text": "Page numbers",
"detail": "Familiar and easy to link to, but rows shift when tasks change mid-scroll."
},
{
"k": "C",
"text": "Everything at once",
"detail": "Simplest to build; slow and heavy once a team has a few thousand tasks."
}
],
"token": {
"A": "a",
"B": "b",
"C": "c"
},
"fallbackText": "How tasks are paged: a) cursor paging b) page numbers c) everything at once. My guess: a."
},
{
"id": "q3",
"topic": "t1",
"kind": "multi",
"title": "Day one endpoints",
"body": "Which of these should be there on the first day? Anything left unticked waits for a later version.",
"options": [
{
"k": "1",
"text": "List and read tasks",
"detail": "GET /tasks and GET /tasks/:id, with filters by status and assignee."
},
{
"k": "2",
"text": "Create and update tasks",
"detail": "POST /tasks and PATCH /tasks/:id, validated."
},
{
"k": "3",
"text": "Delete tasks",
"detail": "A soft delete, so a task can come back."
},
{
"k": "4",
"text": "Comments on a task",
"detail": "A thread under each task. Doubles the data model."
}
],
"presets": [
{
"label": "The essentials",
"ks": [
"1",
"2"
]
},
{
"label": "Everything",
"ks": [
"1",
"2",
"3",
"4"
]
}
],
"token": {
"1": "1",
"2": "2",
"3": "3",
"4": "4"
},
"fallbackText": "Day one endpoints (pick any): 1) list and read 2) create and update 3) delete 4) comments on a task."
},
{
"id": "q4",
"topic": "t1",
"kind": "text",
"title": "Who calls it",
"body": "Which apps will call this API, and roughly how many people use them?",
"placeholder": "For example: our web app and a mobile app, about 2,000 people across 40 teams.",
"token": {},
"fallbackText": "Who calls it: which apps will call this API, and roughly how many people use them?"
}
],
"agent": {
"status": "waiting"
}
}
+88
View File
@@ -0,0 +1,88 @@
{
"workflow": "implement",
"title": "task-api: Phase 3",
"headline": {
"stage": "Phase 3: API endpoints",
"cleared": 11,
"total": 11
},
"docs": [
{
"id": "phase",
"title": "Phase 3 tasks",
"version": 12,
"blocks": [
{
"id": "tasks",
"state": "settled",
"md": "- [x] **Task 3.1:** Register the /tasks routes plugin\n- [x] **Task 3.2:** Add GET /tasks with cursor paging\n- [x] **Task 3.3:** Add GET /tasks/:id\n- [x] **Task 3.4:** Add POST /tasks with a Zod schema\n- [x] **Task 3.5:** Add PATCH /tasks/:id for status and fields\n- [x] **Task 3.6:** Add DELETE /tasks/:id as a soft delete\n- [x] **Task 3.7:** Filter GET /tasks by status and assignee\n- [x] **Task 3.8:** Return one error shape for 400, 404 and 409\n- [x] **Task 3.9:** Document the endpoints in openapi.yaml\n- [x] **Task 3.10:** Write tests for paging, filters and validation\n- [x] **Task 3.11:** Run the test suite and record the results"
}
]
},
{
"id": "report",
"title": "Completion report",
"version": 1,
"blocks": [
{
"id": "summary",
"state": "settled",
"md": "## Summary\n\nThe /tasks endpoints work end to end. Clients can list tasks with cursor paging and filters, read one, create, update and soft delete, and every failure comes back in the same error shape.\n\n**Tasks:** 11 of 11 done, none blocked."
},
{
"id": "tests",
"state": "settled",
"md": "## Tests\n\n| Suite | Passed | Failed |\n| --- | --- | --- |\n| tasks | 31 | 0 |\n| paging | 8 | 0 |"
},
{
"id": "files",
"state": "settled",
"md": "## Files\n\n**Created:** `src/tasks/routes.js`, `src/tasks/schema.js`, `src/tasks/paginate.js`, `test/tasks.test.js`\n\n**Modified:** `src/app.js`, `openapi.yaml`"
},
{
"id": "verify",
"state": "settled",
"md": "## How to check it\n\n1. Run `npm test`: 39 passing.\n2. Create two tasks, then call `GET /tasks?limit=1`: one task and a `nextCursor`.\n3. `PATCH /tasks/:id` with an unknown status answers 400 in the shared error shape."
}
]
}
],
"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
}
}
+24
View File
@@ -11,8 +11,10 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
const require = createRequire(import.meta.url);
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const LAUNCHER = path.join(ROOT, "src", "launcher", "plan2code.js");
const IS_WINDOWS = process.platform === "win32";
@@ -126,6 +128,28 @@ test("launcher: an unknown --cli exits 2, a missing CLI 127, and nothing is star
assert.equal(box.argsOf("claude"), null);
});
test("launcher: mergeModels keeps the shipped list first and drops user duplicates", () => {
const { mergeModels, modelEntries } = require(LAUNCHER);
const shipped = [{ id: "a", label: "A" }, { id: "b", label: "B" }];
const user = [{ id: "b", label: "B old" }, { id: "c", label: "C" }, { id: "c", label: "C again" }];
assert.deepEqual(mergeModels(shipped, user), [...shipped, { id: "c", label: "C" }]);
assert.deepEqual(mergeModels(shipped, []), shipped);
// A missing or corrupt user file yields no additions rather than an error.
assert.deepEqual(modelEntries(null, "devin"), []);
assert.deepEqual(modelEntries({ devin: "nope" }, "devin"), []);
assert.deepEqual(modelEntries({ devin: [{ id: 1 }, null, { id: "ok", label: "Ok" }] }, "devin"), [{ id: "ok", label: "Ok" }]);
});
test("launcher: the shipped models.json is curated Devin at low/medium/high only", () => {
const shipped = JSON.parse(fs.readFileSync(path.join(path.dirname(LAUNCHER), "models.json"), "utf8"));
assert.ok(shipped.claude.length > 0);
assert.ok(shipped.devin.length > 0 && shipped.devin.length <= 30);
for (const { id, label } of shipped.devin) {
assert.ok(id && label);
assert.doesNotMatch(id, /(xhigh|max|fast|priority)$/);
}
});
test("launcher: with neither CLI installed it exits 127 naming both", (t) => {
const box = sandbox([]);
t.after(box.cleanup);
+515 -17
View File
@@ -75,6 +75,7 @@ import {
STOP_REPLY,
sentAnswer,
submittedAwaiting,
noteAwaiting,
suggestionFrom,
turnGate,
verdictLabel,
@@ -136,6 +137,7 @@ import {
} from "../src/web-console/public/workspace.js";
import {
levelFor,
breakdownFrom,
meterView,
pointsFrom,
RED_AT,
@@ -146,6 +148,7 @@ import {
} from "../src/web-console/public/meter.js";
import { applyMention, matchNames, mentionAt } from "../src/web-console/public/mentions.js";
import { FAVICON_BODY, FAVICON_COLORS, faviconState, faviconSvg } from "../src/web-console/public/favicon.js";
import { runHint } from "../src/web-console/public/render.js";
import { pickerCommand, pickFolder, WINDOWS_PICKER_SOURCE, WORKSPACE_PICKER_PROMPT } from "../src/web-console/picker.mjs";
import {
appendLedger,
@@ -153,6 +156,7 @@ import {
bindLoopback,
chatReplyLines,
checkDocument,
cwdHash,
handOff,
initialWorkspace,
parseArgs,
@@ -170,6 +174,7 @@ import {
SPEC_STATES,
staleScratch,
staleSessions,
STATE_LOCK_FILE,
sweepUploads,
terminalLine,
UPLOAD_MAX_AGE_MS,
@@ -182,7 +187,12 @@ const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-test-"));
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
const MODELS_DIR = path.join(HOME, "plan2code");
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_NO_BROWSER: "1" };
// The session cookie is named for the server's port: browsers ignore the port
// when they scope a cookie, so one shared name let each session's server
// overwrite the one before it.
function cli(args, { expectFail = false, env, cwd = ROOT } = {}) {
const res = spawnSync(process.execPath, [CONSOLE_CLI, ...args], {
@@ -1228,10 +1238,36 @@ test("a document that is the wrong type, lies about its type, or is too large is
assert.equal((await uploadDoc("a.md", MD, { origin: "http://evil.example.com" })).status, 403);
});
test("a document is never served back, and deleting it removes its file", async () => {
test("a document is served back inline under a fixed type, and deleting it removes its file", async () => {
const { id, path: file } = (await uploadDoc("spec.pdf", PDF)).json;
const url = `/uploads/${id}.pdf`;
assert.equal((await raw("GET", url)).status, 404);
const pdf = await raw("GET", url);
assert.equal(pdf.status, 200);
assert.equal(pdf.headers["content-type"], "application/pdf");
assert.equal(pdf.headers["x-content-type-options"], "nosniff");
assert.equal(pdf.headers["content-security-policy"], undefined, "a sandboxed PDF cannot open in the viewer");
assert.deepEqual(pdf.body, PDF);
for (const [name, buf, type] of [
["page.html", Buffer.from("<script>fetch('/submit')</script>"), "text/plain; charset=utf-8"],
["logo.svg", MD, null],
["notes.md", MD, "text/plain; charset=utf-8"],
]) {
const up = await uploadDoc(name, buf);
if (!type) {
assert.equal(up.status, 415, "an svg is not an allowed document");
continue;
}
const text = await raw("GET", `/uploads/${up.json.id}.${name.split(".").pop()}`);
assert.equal(text.status, 200, name);
assert.equal(text.headers["content-type"], type, "text and code are never served as html");
assert.equal(text.headers["content-security-policy"], "sandbox");
assert.deepEqual(text.body, buf);
assert.equal((await raw("DELETE", `/uploads/${up.json.id}.${name.split(".").pop()}`)).status, 204);
}
assert.equal((await raw("GET", url, undefined, { cookie: "" })).status, 403);
for (const p of ["/uploads/../state.json.md", "/uploads/%2e%2e/x.pdf", "/uploads/not-a-uuid.md"]) {
assert.equal((await raw("GET", p)).status, 404, p);
}
for (const p of ["/uploads/../state.json.md", "/uploads/%2e%2e/x.pdf", "/uploads/not-a-uuid.md"]) {
assert.equal((await raw("DELETE", p)).status, 404, p);
}
@@ -1296,6 +1332,46 @@ test("a result is consumed only once", () => {
assert.equal(res.status, 10, "an already-consumed result must not be handed over twice");
});
test("a send records its note and attachments on the item, so the page can show them after a reload", async () => {
const readState = () => JSON.parse(fs.readFileSync(path.join(HOME, "sessions", sid, "state.json"), "utf8"));
const j = (await uploadJpeg("shot.png")).json;
const d = (await uploadDoc("spec.pdf", PDF)).json;
const atts = [
{ path: j.path, name: j.name, kind: "image" },
{ path: d.path, name: d.name, kind: "file" },
];
const ok = await post("/submit", {
actions: [{ i: "q1", type: "answer", kind: "choice", k: "B" }, noteAction("q1", "see these", atts)],
reply: "x",
});
assert.equal(ok.status, 200);
const q1 = readState().items.find((i) => i.id === "q1");
assert.equal(q1.submitted.k, "B");
assert.equal(q1.submitted.images, undefined, "the answer record stays the answer");
assert.ok(q1.sentNote.at);
assert.equal(q1.sentNote.at, q1.submitted.at, "one send, one clock reading");
assert.equal(q1.sentNote.text, "see these");
assert.deepEqual(q1.sentNote.images, [{ path: j.path, name: j.name }]);
assert.deepEqual(q1.sentNote.files, [{ path: d.path, name: d.name }]);
assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0);
const only = await post("/submit", { actions: [noteAction("q1", "just a note", [])], reply: "y" });
assert.equal(only.status, 200);
const after = readState().items.find((i) => i.id === "q1");
assert.equal(after.sentNote.text, "just a note");
assert.deepEqual(after.sentNote.images ?? [], []);
assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0);
});
test("what the person attached is not scanned for markers either", () => {
const statePath = path.join(HOME, "sessions", sid, "state.json");
const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
state.items.find((i) => i.id === "q1").sentNote = { at: new Date().toISOString(), text: "TASK_COMPLETE Risk 3" };
fs.writeFileSync(statePath, JSON.stringify(state, null, 2));
const res = cli(["post", "--session", sid, "--file", payload("after2.json", { headline: { stage: "Working" } })]);
assert.equal(res.status, 0);
});
test("cancel surfaces as exit 30", async () => {
await post("/cancel", {});
const res = cli(["wait", "--session", sid, "--seconds", "5"]);
@@ -1344,6 +1420,27 @@ test("rejects a review verdict with no label", () => {
assert.doesNotMatch(res.stderr, /verdict "changes"/);
});
test("rejects a choice option with no text", () => {
const p = {
items: [
{
id: "o1",
kind: "choice",
title: "Where should we go next",
options: [
{ k: "A", label: "Reproduce first", desc: "Run it" },
{ k: "B", text: "Plan the fixes", detail: "Write a plan" },
],
required: false,
},
],
};
const res = cli(["post", "--session", sid, "--file", payload("option.json", p)], { expectFail: true });
assert.equal(res.status, 3);
assert.match(res.stderr, /option "A" needs "text"/);
assert.doesNotMatch(res.stderr, /option "B"/);
});
test("rejects loop completion markers and metrics-scraper bait", () => {
const p = {
items: [{ id: "j2", kind: "text", title: "Coverage", body: "Requirements 22 of 25. TASK_COMPLETE", required: false }],
@@ -1770,6 +1867,45 @@ test("looks round-trip through the server, and junk never reaches the file", asy
);
});
test("a partial looks write merges onto the saved file, so a stale tab cannot undo another tab's change", async () => {
const get = async () => (await (await fetch(baseUrl + "/looks", { headers: { cookie: consoleCookie(baseUrl, token) } })).json()).looks;
assert.equal((await post("/looks", { set: { sound: false } })).status, 200);
assert.deepEqual(await get(), { theme: "dark", accent: "cobalt", sound: false });
assert.equal((await post("/looks", { set: { accent: "sky" } })).status, 200);
assert.deepEqual(await get(), { theme: "dark", accent: "sky", sound: false }, "keys this write did not name stay put");
assert.equal((await post("/looks", { set: { deep: { nested: true } } })).status, 400);
assert.deepEqual(await get(), { theme: "dark", accent: "sky", sound: false });
assert.equal((await post("/looks", { looks: { theme: "dark", accent: "cobalt" } })).status, 200);
});
test("the tab title carries the session's short id, so tabs from different agents can be told apart", async () => {
const html = await (await fetch(baseUrl + "/", { headers: { cookie: consoleCookie(baseUrl, token) } })).text();
assert.match(html, new RegExp(`<title>[^<]* · #${sid.slice(-6)} · Plan2Code</title>`));
});
test("models: the user's additions round-trip, XHigh and Max are refused, and the shipped list is read-only", async () => {
fs.mkdirSync(path.join(MODELS_DIR, "bin"), { recursive: true });
fs.writeFileSync(path.join(MODELS_DIR, "bin", "models.json"), JSON.stringify({ claude: [{ id: "opus", label: "Opus" }], devin: [{ id: "adaptive", label: "Adaptive" }] }));
const get = async () => (await fetch(baseUrl + "/models", { headers: { cookie: consoleCookie(baseUrl, token) } })).json();
assert.deepEqual((await get()).shipped.devin, [{ id: "adaptive", label: "Adaptive" }]);
assert.deepEqual((await get()).user, { claude: [], devin: [] });
const saved = await post("/models", { models: { devin: [{ id: " new-model-medium ", label: "" }, { id: "new-model-medium" }, { id: "" }] } });
assert.equal(saved.status, 200);
assert.deepEqual((await get()).user, { claude: [], devin: [{ id: "new-model-medium", label: "new-model-medium" }] });
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(MODELS_DIR, "models.json"), "utf8")).devin.length, 1, "the launcher reads this file");
for (const id of ["some-model-xhigh", "some-model-MAX", "bad id!"]) {
assert.equal((await post("/models", { models: { devin: [{ id }] } })).status, 400, id);
}
assert.equal((await post("/models", { nope: true })).status, 400);
assert.equal((await get()).user.devin.length, 1, "a refused write must not touch what is saved");
assert.equal((await post("/models", { models: {} })).status, 200, "reset to default");
assert.deepEqual((await get()).user, { claude: [], devin: [] });
});
test("stop leaves a process it cannot identify as ours alone", () => {
// A handle file can outlive a reboot in the system temp dir and its pid can
// be reused. Killing on the strength of a number alone can hit anything.
@@ -2051,6 +2187,18 @@ test("a send the agent never settled is still a send in flight", () => {
assert.equal(submittedAwaiting({ submitted: sub, thread: [{ who: "agent", text: "No time on me." }] }), null);
});
test("a note the agent has not answered yet is still on its way", () => {
const note = { at: "2026-09-23T03:00:00Z", text: "look at this" };
assert.equal(noteAwaiting({}), null);
assert.equal(noteAwaiting(null), null);
assert.equal(noteAwaiting({ sentNote: "nope" }), null);
assert.equal(noteAwaiting({ sentNote: note }), note);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "Earlier.", at: "2026-09-23T02:00:00Z" }] }), note);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "Seen.", at: "2026-09-23T03:01:00Z" }] }), null);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "user", text: "look at this", at: "2026-09-23T03:00:00Z" }] }), null);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "No clock." }] }), null);
});
// --- the session's ending ------------------------------------------------
//
// Everything else the page shows is a pause. `finish` is the one signal that
@@ -2943,26 +3091,26 @@ test("open without --title names the session after the project folder", () => {
cli(["stop", "--session", res.json.sid]);
});
// A saved dark theme and accent used to flash the default light rust for as
// A saved dark theme and accent used to flash the default light accent for as
// long as it took the script to fetch /looks. The server paints them now.
test("saved looks are painted by the server before any script runs", async () => {
const looksFile = path.join(HOME, "looks.json");
const before = fs.existsSync(looksFile) ? fs.readFileSync(looksFile) : null;
fs.writeFileSync(
looksFile,
JSON.stringify({ looks: { theme: "dark", accent: "ocean", sound: true, width: "wide" } })
JSON.stringify({ looks: { theme: "dark", accent: "violet", sound: true, width: "wide" } })
);
try {
const res = cli(["open", "--workflow", "plan", "--no-open"]);
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
const cookie = consoleCookie(m[1], m[2]);
const html = await (await fetch(m[1] + "/", { headers: { cookie } })).text();
assert.match(html, /<html lang="en" data-theme="dark" data-looks-accent="ocean" data-width="wide">/);
assert.match(html, /<html lang="en" data-theme="dark" data-looks-accent="violet" data-width="wide">/);
const css = await (await fetch(m[1] + "/app.css", { headers: { cookie } })).text();
assert.ok(css.includes(`:root[data-looks-accent="ocean"][data-theme="dark"]{--accent:${ACCENTS.ocean.dark[0]}`));
assert.ok(css.includes(`:root[data-looks-accent="violet"][data-theme="dark"]{--accent:${ACCENTS.violet.dark[0]}`));
assert.ok(!css.includes(`data-looks-accent="${DEFAULT_ACCENT}"`), "the default needs no rule");
const boot = JSON.parse(html.match(/id="boot">([\s\S]*?)<\/script>/)[1]);
assert.equal(boot.looks.accent, "ocean");
assert.equal(boot.looks.accent, "violet");
cli(["stop", "--session", res.json.sid]);
} finally {
if (before) fs.writeFileSync(looksFile, before);
@@ -3373,6 +3521,7 @@ test("post and wait hand back the terminal line; the collected result on disk do
const waiting = cli(["wait", "--session", res.json.sid, "--seconds", "5"]);
assert.equal(waiting.status, 10);
assert.equal(waiting.json.message, "Waiting on your answer in the web console");
assert.match(waiting.json.next, /run this same wait command again/);
assert.equal(waiting.json.terminalLine, terminalLine(res.json.url));
const sent = await fetch(`${s.base}/submit`, {
@@ -3396,6 +3545,21 @@ test("post and wait hand back the terminal line; the collected result on disk do
}
});
test("building.md gives a quick-task build its own Build progress tab", () => {
const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "building.md"), "utf8");
const section = md.slice(md.indexOf("## Quick task (`quick-task`)"));
assert.ok(section.includes('"title": "Build progress"'));
assert.match(section, /post after every step/i);
});
test("building.md has the finished quick task offer Back to the dashboard as well as the review", () => {
const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "building.md"), "utf8");
const section = md.slice(md.indexOf("## Quick task (`quick-task`)"));
const bullet = section.slice(section.indexOf("**The finish after the build:**"), section.indexOf("**Escalated / aborted:**"));
assert.ok(bullet.includes('"dashboard": true'));
assert.ok(bullet.includes("Review it now"));
});
/* ------------------------------------------- quick question: the contract */
// Every outcome `wait` had before the chat channel existed, pinned by exit
@@ -3411,7 +3575,7 @@ const pinKeys = (obj, expected, what) =>
`${what}: top-level keys changed`
);
const RESULT_KEYS = ["type", "at", "sid", "rev", "actions", "reply", "consumedAt", "terminalLine"];
const WAITING_KEYS = ["status", "sid", "elapsed", "answered", "total", "staged", "url", "message", "terminalLine"];
const WAITING_KEYS = ["status", "sid", "elapsed", "answered", "total", "staged", "url", "message", "next", "terminalLine"];
function openSession(extra = {}) {
const res = cli(["open", "--file", payload(`pin-${Date.now()}.json`, { ...BASE, ...extra }), "--no-open"]);
@@ -3756,15 +3920,14 @@ test("typed text never starts a reply line of its own, so it cannot pass for a d
}
});
test("a finished session refuses a question as offline", async () => {
test("a finished session whose agent is still listening still takes a question", async () => {
const s = openSession();
try {
postPatch(s, { finish: { headline: "The map is written" } });
await until(async () => (await chatFrame(s)).offline);
await until(async () => !(await chatFrame(s)).offline);
const res = await ask(s, "Anyone there?");
assert.equal(res.status, 409);
assert.equal(res.body.error, "offline");
assert.equal((await s.send("/chat", { reset: true, conversation: 1 })).status, 409);
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.equal(res.body.ok, true);
} finally {
cli(["stop", "--session", s.sid]);
}
@@ -4064,8 +4227,9 @@ test("unreadDot and shouldChime: one chime per new reply, never while on Ask, ne
test("chatOffline: finished, paused, a stale working agent (with quietMinutes), an adrift waiting agent, a live one", () => {
const now = 10 * 60 * 60 * 1000;
const ago = (ms) => ({ agentLastSeenMs: now - ms, now });
assert.equal(chatOffline({ finish: { headline: "Done" }, agent: { status: "waiting" }, ...ago(0) }), true);
assert.equal(chatOffline({ finish: { headline: "Paused — saved" }, agent: { status: "working" }, ...ago(0) }), true);
assert.equal(chatOffline({ finish: { headline: "Done" }, agent: { status: "waiting" }, ...ago(0) }), false, "a live agent through the finish wait is online");
assert.equal(chatOffline({ finish: { headline: "Done" }, agent: { status: "waiting" }, ...ago(3 * 60 * 1000 + 1000) }), true, "offline once it goes quiet");
assert.equal(chatOffline({ finish: { headline: "Paused — saved" }, agent: { status: "working" }, ...ago(STALE_MS + 1000) }), true);
assert.equal(chatOffline({ agent: { status: "working" }, ...ago(STALE_MS + 1000) }), true);
assert.equal(chatOffline({ agent: { status: "working" }, ...ago(STALE_MS - 1000) }), false);
assert.equal(chatOffline({ agent: { status: "working", quietMinutes: 20 }, ...ago(15 * 60 * 1000) }), false, "a long task is not offline");
@@ -4420,9 +4584,27 @@ test("meter: levels, ring, fold and tooltip wording", () => {
fraction: 0.25,
words: "Session: fresh",
tooltip: "This session is fresh (2 points).",
items: [{ label: "Document started", points: 2 }],
});
});
test("meter: the breakdown lists each scoring entry once and sums to the total", () => {
const entries = [
{ kind: "launch", id: "L1", workflow: "dashboard" },
{ kind: "launch", id: "L2", workflow: "quick-task" },
{ kind: "run", id: "L2:phase-2", event: "implement-phase" },
{ kind: "run", id: "L2:phase-2", event: "implement-phase" },
{ kind: "run", id: "L2:handoff", event: "handoff" },
{ kind: "folder-issue", id: "L2:api", name: "api", reason: "denied" },
];
assert.deepEqual(breakdownFrom(entries), [
{ label: "Quick task started", points: 1 },
{ label: "Implement phase built: phase-2", points: 2 },
]);
assert.equal(pointsFrom(entries), breakdownFrom(entries).reduce((n, r) => n + r.points, 0));
assert.deepEqual(breakdownFrom(null), []);
});
test("workspace: default names, name rules and the free-name suggestion", () => {
assert.equal(defaultName("C:\\git\\My Repo_v2"), "my-repo-v2");
assert.equal(defaultName("/home/sam/api/"), "api");
@@ -4531,6 +4713,7 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
"meter-fill",
"meter-words",
"meter-pop",
"meter-list",
"meter-help",
]) {
assert.ok(html.includes(`id="${id}"`), `index.html must carry #${id}`);
@@ -5010,6 +5193,274 @@ test("meter: a folder issue shows in the frame's workspace.issues until the next
}
});
/* ------------------------------------------- review fixes: two writers, one page */
// Browsers scope a cookie by host and ignore the port. With one shared name,
// the second session's link overwrote the first session's token, and the
// first tab got nothing but 403s from then on.
test("two sessions keep their own cookies: each server reads only the one named for its port", async () => {
const a = openSession();
const b = openSession();
try {
for (const s of [a, b]) {
const token = s.url.match(/\/s\/([^/]+)\//)[1];
const res = await fetch(s.url, { redirect: "manual" });
assert.ok(res.headers.get("set-cookie").startsWith(`${consoleCookie(s.base, token)};`));
}
// What a browser holding both sends to either server.
const both = `${a.cookie}; ${b.cookie}`;
for (const s of [a, b]) {
assert.equal((await fetch(`${s.base}/state`, { headers: { cookie: both, connection: "close" } })).status, 200);
}
// The old shared name is no longer a key to anything.
const aToken = a.url.match(/\/s\/([^/]+)\//)[1];
const shared = await fetch(`${a.base}/state`, { headers: { cookie: `p2c_console=${aToken}`, connection: "close" } });
assert.equal(shared.status, 403);
// Another session's cookie opens nothing here either.
const crossed = b.cookie.replace(/^p2c_console_\d+/, `p2c_console_${new URL(a.base).port}`);
assert.equal((await fetch(`${a.base}/state`, { headers: { cookie: crossed, connection: "close" } })).status, 403);
} finally {
cli(["stop", "--session", a.sid]);
cli(["stop", "--session", b.sid]);
}
});
// state.json has two writers, `post` and the server's /submit. Both are held
// at the lock here until each has read nothing yet, then let go together:
// whichever writes second must be building on the first one's write.
test("a post and a submit that overlap both survive: the state lock serialises them", async () => {
const s = openSession();
try {
const lock = path.join(s.session, STATE_LOCK_FILE);
fs.writeFileSync(lock, String(process.pid));
const patchFile = payload(`overlap-${Date.now()}.json`, {
items: [{ id: "q2", kind: "text", title: "Team name", required: false }],
agent: { status: "waiting", activity: "Asking about the team" },
});
const posting = new Promise((resolve) => {
const child = spawn(process.execPath, [CONSOLE_CLI, "post", "--session", s.sid, "--file", patchFile], { env: ENV, cwd: ROOT });
let err = "";
child.stderr.on("data", (c) => (err += c));
child.on("exit", (code) => resolve({ code, err }));
});
const submitting = s.send("/submit", EXPORT_A);
await sleep(400);
assert.ok(fs.existsSync(lock), "nobody broke a live, young lock");
fs.rmSync(lock);
const [posted, submitted] = await Promise.all([posting, submitting]);
assert.equal(posted.code, 0, posted.err);
assert.equal(submitted.status, 200);
const state = readState(s.session);
const q1 = state.items.find((i) => i.id === "q1");
assert.ok(state.items.some((i) => i.id === "q2"), "the post's new question is kept");
assert.equal(state.agent.activity, "Asking about the team");
assert.equal(q1.submitted && q1.submitted.k, "A", "the send's record is kept");
assert.equal(state.phase, "submitted");
assert.equal(fs.existsSync(lock), false, "and the lock is let go");
assert.equal(cli(["wait", "--session", s.sid, "--seconds", "5"]).status, 0);
} finally {
cli(["stop", "--session", s.sid]);
}
});
test("a lock left by a writer that died is broken rather than waited on for good", () => {
const s = openSession();
try {
const lock = path.join(s.session, STATE_LOCK_FILE);
// A pid no process has: the holder is gone.
fs.writeFileSync(lock, "999999999");
const res = postPatch(s, { agent: { status: "working" } });
assert.equal(res.status, 0, res.stderr);
assert.equal(readState(s.session).agent.status, "working");
assert.equal(fs.existsSync(lock), false);
} finally {
cli(["stop", "--session", s.sid]);
}
});
// A young handle and a live pid are what a server that died a minute ago
// leaves behind for any process to inherit. Only /health is proof.
test("stop never kills a live process that does not answer /health as ours", () => {
const bystander = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
const sidForged = "20000101-000000-beef01";
// Under the test home, as the CLI sees it: this process has no override of
// its own, and lib.mjs would name the real runtime dir.
const dir = path.join(HOME, "runtime", cwdHash(repoRoots(ROOT).project));
fs.mkdirSync(dir, { recursive: true });
const forged = path.join(dir, `${sidForged}.json`);
try {
fs.writeFileSync(
forged,
JSON.stringify({ v: 1, sid: sidForged, pid: bystander.pid, port: 1, url: "http://127.0.0.1:1/", startedAt: new Date().toISOString() })
);
const res = cli(["stop", "--session", sidForged]);
assert.equal(res.json.stopped, 0);
assert.equal(res.json.skippedStaleHandles, 1);
assert.equal(fs.existsSync(forged), false, "the handle goes");
assert.doesNotThrow(() => process.kill(bystander.pid, 0), "the process stays");
} finally {
bystander.kill();
fs.rmSync(forged, { force: true });
}
});
// A fresh `open` starts the server before it writes the state. The server used
// to seed workspace.json at boot from the folder holding .git, which for a
// linked worktree is the main checkout.
test("open from a linked worktree seeds the workspace with the worktree, not the main checkout", () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-wt-"));
const repo = path.join(base, "repo");
const wt = path.join(base, "wt");
fs.mkdirSync(repo);
const git = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
git(repo, "init", "-q");
git(repo, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "x");
git(repo, "worktree", "add", "-q", wt);
const { worktree, project } = repoRoots(wt);
assert.notEqual(worktree, project);
let sidOpened = null;
try {
const res = cliIn(wt, ["open", "--workflow", "plan", "--no-open"]);
sidOpened = res.json.sid;
assert.deepEqual(res.json.workspace.folders.map((f) => f.path), [worktree]);
const onDisk = JSON.parse(fs.readFileSync(path.join(res.json.session, WORKSPACE_FILE), "utf8"));
assert.deepEqual(onDisk.folders.map((f) => f.path), [worktree], "workspace.json names the worktree");
} finally {
if (sidOpened) cliIn(wt, ["stop", "--session", sidOpened]);
fs.rmSync(base, { recursive: true, force: true });
}
});
/* ------------------------------------------- review fixes: the CLI's edges */
test("validate refuses a text pattern that does not compile, and post exits 3 on it", () => {
const item = (pattern) => ({ items: [{ id: "t1", kind: "text", title: "Ticket number", pattern }] });
assert.deepEqual(validate(item("^[A-Z]+-\\d+$")), []);
assert.match(validate(item("([")).join("\n"), /"pattern" is not a valid JavaScript regular expression/);
assert.match(validate(item(7)).join("\n"), /"pattern" must be a string/);
const s = openSession();
try {
const before = fs.readFileSync(path.join(s.session, "state.json"), "utf8");
const bad = postPatch(s, { items: [{ id: "t1", kind: "text", title: "Ticket number", pattern: "([", required: false }] }, { expectFail: true });
assert.equal(bad.status, 3);
assert.match(bad.stderr, /pattern/);
assert.equal(fs.readFileSync(path.join(s.session, "state.json"), "utf8"), before, "nothing was written");
} finally {
cli(["stop", "--session", s.sid]);
}
});
test("a flag that needs a value and has none is bad usage, exit 2, never a crash", () => {
for (const argv of [
["open", "--resume"],
["open", "--session", "--no-open"],
["wait", "--session"],
["post", "--session", sid, "--file"],
["keep", "--session", sid, "--upload", "x", "--name", "--spec", "specs/x"],
["status", "--session"],
["stop", "--session"],
]) {
const res = cli(argv, { expectFail: true });
assert.equal(res.status, 2, argv.join(" "));
assert.match(res.stderr, /needs a value/, argv.join(" "));
assert.doesNotMatch(res.stderr, /TypeError|at .*\.mjs/, argv.join(" "));
}
});
test("wait reads --seconds 6s as six seconds, not as nothing", () => {
const s = openSession();
try {
const t0 = Date.now();
const res = cli(["wait", "--session", s.sid, "--seconds", "6s"]);
assert.equal(res.status, 10);
assert.ok(Date.now() - t0 >= 5000, "the slice ran its length");
} finally {
cli(["stop", "--session", s.sid]);
}
});
test("only open leaves the console-dir pointer; status, help and a bad command do not", () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pointer-"));
const env = { PLAN2CODE_CONSOLE_HOME: home, PLAN2CODE_MODELS_DIR: path.join(home, "plan2code") };
const pointer = path.join(home, "console-dir");
try {
cli(["status"], { env });
cli(["help"], { env });
const usage = cli(["nope"], { env, expectFail: true });
assert.match(usage.stderr, /keep/, "the usage line names every command");
assert.equal(fs.existsSync(pointer), false);
const opened = cli(["open", "--no-open"], { env });
assert.equal(fs.readFileSync(pointer, "utf8").trim(), path.join(ROOT, "src", "web-console"));
cli(["stop", "--session", opened.json.sid], { env });
} finally {
fs.rmSync(home, { recursive: true, force: true });
}
});
/* ------------------------------------------- review fixes: the Origin guard */
// Every route that changes something refuses a foreign Origin before it reads
// a byte of the body. /workspace/browse is the one that could open a native
// dialog; the echo stands in for it, so a guard that failed would answer 200
// here rather than put a picker on the screen.
test("every state-changing route refuses a foreign Origin, and nothing changes", async () => {
const picked = tempFolder();
const s = consoleSession(["--workflow", "plan", "--file", payload(`origin-${Date.now()}.json`, BASE)], {
env: { PLAN2CODE_PICKER_ECHO: picked },
});
const files = ["state.json", "result.json", "draft.json", WORKSPACE_FILE, "chat.ndjson"];
const snapshot = () =>
Object.fromEntries(
[...files.map((f) => path.join(s.session, f)), path.join(HOME, "looks.json")].map((f) => [
f,
fs.existsSync(f) ? fs.readFileSync(f, "utf8") : null,
])
);
const routes = [
["POST", "/submit", EXPORT_A],
["POST", "/cancel", {}],
["POST", "/chat", { text: "Why CSV?", conversation: 1 }],
["POST", "/chat/decision", { re: "r1", decision: "approve", conversation: 1 }],
["POST", "/draft", { staged: { q1: { k: "B" } } }],
["POST", "/looks", { looks: { theme: "light" } }],
["POST", "/models", { models: { devin: [{ id: "x" }] } }],
["POST", "/workspace/add", { path: picked }],
["POST", "/workspace/edit", { id: "f0", name: "renamed" }],
["POST", "/workspace/remove", { id: "f0" }],
["POST", "/workspace/browse", {}],
["POST", "/bye", {}],
["POST", "/upload", null],
["DELETE", "/uploads/00000000-0000-0000-0000-000000000000.jpg", null],
];
try {
await s.get("/workspace");
const before = snapshot();
for (const [method, route, body] of routes) {
const res = await fetch(`${s.base}${route}`, {
method,
headers: { "content-type": "application/json", cookie: s.cookie, origin: "http://evil.example.com", connection: "close" },
body: body === null ? undefined : JSON.stringify(body),
});
assert.equal(res.status, 403, `${method} ${route}`);
}
assert.deepEqual(snapshot(), before, "no file moved");
// And the same requests from the page's own origin do get through, so the
// 403s above are the guard and not something else.
const own = await fetch(`${s.base}/workspace/browse`, {
method: "POST",
headers: { "content-type": "application/json", cookie: s.cookie, origin: s.base, connection: "close" },
body: "{}",
});
assert.equal(own.status, 200);
assert.deepEqual(await own.json(), { path: picked });
} finally {
cli(["stop", "--session", s.sid]);
fs.rmSync(picked, { recursive: true, force: true });
}
});
test.after(() => {
try {
execFileSync(process.execPath, [CONSOLE_CLI, "stop", "--all"], { env: ENV, cwd: ROOT });
@@ -5158,7 +5609,7 @@ test("validate rejects an item pattern that is not a valid regular expression",
for (const bad of ["([a-z", "*oops", 42]) {
const problems = validate({ items: [item(bad)] });
assert.equal(problems.length, 1, JSON.stringify(bad));
assert.match(problems[0], /item "slug" "pattern" must be a string holding a valid JavaScript regular expression/);
assert.match(problems[0], /item "slug" "pattern" (must be a string holding a JavaScript regular expression|is not a valid JavaScript regular expression)/);
}
});
@@ -5167,3 +5618,50 @@ test("the usage line names every command", () => {
assert.equal(res.status, 2);
assert.match(res.stderr, /<open\|post\|wait\|chat\|keep\|status\|stop\|help>/);
});
test("runHint: git blocks get Run it, command words get the hint, the rest nothing", () => {
assert.equal(runHint("git add -A && git commit -m \"x\""), "run");
assert.equal(runHint("\n\ngit status\n"), "run");
assert.equal(runHint("git"), "run");
assert.equal(runHint("node install.js --build-skills"), "hint");
assert.equal(runHint("docker compose up"), "hint");
assert.equal(runHint("#!/bin/bash\necho hi"), "hint");
assert.equal(runHint("pws run.ps1"), null);
assert.equal(runHint("/plan2code-3-implement specs/x/overview.md"), null);
assert.equal(runHint("/plan2code"), null);
assert.equal(runHint('{"a": 1}'), null);
assert.equal(runHint("some prose, not a command"), null);
assert.equal(runHint(""), null);
assert.equal(runHint(null), null);
// The first non-empty line decides: a git line after a blank one runs.
assert.equal(runHint(" \ngit commit -m \"x\"\n"), "run");
});
test("a reused item id does not inherit the previous answer's submitted record", async () => {
const { applyPatch } = await import("../src/web-console/lib.mjs");
const before = { items: [{ id: "q7", kind: "choice", title: "A", body: "old", status: "open", submitted: { at: "t", text: "old answer" } }] };
const reworded = applyPatch(before, { items: [{ id: "q7", kind: "choice", title: "B", body: "new", status: "open" }] });
assert.equal(reworded.items[0].submitted, undefined);
assert.equal(reworded.items[0].status, "open");
// Settling or threading the same question keeps the record.
assert.ok(applyPatch(before, { items: [{ id: "q7", status: "answered", answer: { k: "A" } }] }).items[0].submitted);
// A settled question with a typo fixed stays settled.
const settled = { items: [{ id: "q7", kind: "choice", title: "A", body: "old", status: "answered", answer: { k: "A" }, submitted: { at: "t", k: "A" } }] };
const edited = applyPatch(settled, { items: [{ id: "q7", body: "old, fixed" }] }).items[0];
assert.deepEqual([edited.status, edited.answer, !!edited.submitted], ["answered", { k: "A" }, true]);
assert.ok(applyPatch(before, { items: [{ id: "q7", thread: [{ who: "agent", text: "hi" }] }] }).items[0].submitted);
// A settled id reused for a different kind of question opens as a new one, even with no status in the patch.
const swapped = applyPatch(settled, { items: [{ id: "q7", kind: "confirm", title: "C", body: "new" }] }).items[0];
assert.deepEqual([swapped.status, swapped.answer, swapped.submitted], ["open", undefined, undefined]);
});
test("unansweredChat lists delivered Quick questions that still have no reply", async () => {
const { unansweredChat, appendChat, writeCursor } = await import("../src/web-console/lib.mjs");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-chat-"));
appendChat(dir, { kind: "reset", conversation: 1, workflow: "dashboard", reason: "start" });
appendChat(dir, { kind: "message", conversation: 1, text: "run it" });
assert.deepEqual(unansweredChat(dir, {}), [], "not handed over yet, so not owed");
writeCursor(dir, 2);
assert.deepEqual(unansweredChat(dir, {}), [2]);
assert.deepEqual(unansweredChat(dir, { chat: { replies: [{ id: "r2", re: 2, conversation: 1, md: "done" }] } }), []);
});
@@ -273,7 +273,7 @@ for whichever comes first:
| 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. |
| `wait` exit `20` | The server is gone, not necessarily the tab. Resume it (`open --resume <sid> --no-open --workflow <yours>`) and keep waiting. |
| 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:
@@ -406,15 +406,38 @@ post carries `"run": { "event": "implement-review-phase", "id": "phase-N" }`.
("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.
`"answer": { "verdict": "yes" }`) in the post that starts the build, and
open a **Build progress** tab in that same post, the way an Implement phase
gets its tasks tab. The plan's steps are the task list and `total` is their
number:
```jsonc
{
"stopWarning": "",
"items": [{ "id": "<the Build this plan? item's id>", "status": "answered", "answer": { "verdict": "yes" } }],
"headline": { "stage": "Building", "cleared": 0, "total": 4 },
"docs": [{ "id": "tasks", "title": "Build progress", "version": 1, "blocks": [
{ "id": "tasks", "state": "settled", "md": "- [ ] Step one\n- [ ] Step two\n- [ ] Step three\n- [ ] Step four" }
]}],
"agent": { "status": "working", "activity": "Step 1 of 4: step one", "quietMinutes": 10 }
}
```
Then post after every step, exactly as "While you build": bump the doc's
`version` and repost the whole list with that step ticked, raise
`headline.cleared`, and set `agent.activity` to the next step ("Step 2 of 4:
step two"). Never go silent for the whole build: a quick task with many steps
is the case this tab is for. Check for a Quick question between steps, and do
not call `wait` until the build is done.
- **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.
sign-off card to put it on — and `"dashboard": true`, so the finished screen
also offers **Back to the dashboard**. Both are required: a finish without
`dashboard` leaves the person on a dead end. Keep waiting for whichever
button is pressed, 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"`.
@@ -27,6 +27,12 @@ workflow still applies: the same questions, the same order, the same gates, the
same cap of three questions at a time, the same recap before anything is recorded.
You are not allowed to answer your own questions just because a form makes it easy.
> **The one rule that keeps the page alive: while the session is open, every
> turn ends on a `wait` call, never on text.** `wait` exit `10` means "nobody
> has answered yet", not "done": relay one line and run `wait` again in the
> same turn, as many times as it takes. A turn that ends without a `wait`
> running strands the person's next click. Details: The wait loop, below.
---
## Deciding whether to use it
@@ -172,7 +178,19 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
Do not poll faster than this. Do not spin on `status`. Exit 10 is not a finished
turn: never emit a final response or stop after an arbitrary number of slices;
relay one line and immediately call `wait` again. Do not give up: people step
away from a session and come back.
away from a session and come back. The same holds after a `finish`: keep
waiting (resuming the server on exit `20`) until the dashboard or done press
or about ten minutes with nothing, because the Ask tab stays live and its
messages only arrive through `wait`. Ending your turn earlier strands them.
**The turn never ends on a wait.** While a console session is open, including
after a finish that offers a button (Back to the dashboard, Review it now), the
last thing in every turn you take is a `wait` call, never a line of text. The
line you relay after exit `10` goes in the same turn as the next `wait`, so
write it and call `wait` straight after. A turn that ends with the session open
and no `wait` running is a bug the person feels at once: their button press
sits unread until they ask why. If you catch yourself about to write a closing
summary while the page is still open, call `wait` first.
**Collect promptly.** A question someone has sent is locked on the page for as
long as you are mid-turn on it: they can read, move around and answer the other
@@ -453,6 +471,14 @@ messages, `offline` when no agent is connected or the session has finished,
### Answering
**Every message gets a reply, always.** The Ask tab is the person talking to
you, and the page shows "working on the answer" until a reply lands. Never
leave one unanswered, whatever it asks and whatever mid-task you are in. When
a message asks you to do something, do it if you can, then say what happened; if
you will not, the reply says so and why. `post` and `wait` print
`unansweredChat` with a `warning` for every message handed over and not yet
replied to: treat that as a stop-and-reply.
1. Handle any card answers first, under the workflow's own rules.
2. Write the chat replies, in inbox order.
3. Send **one** `post` with the card updates and `chat: { replies: [...] }`.
@@ -510,8 +536,9 @@ enforces it, so never tell someone to keep asking past it.
proposal is a new reply.
- Hard limits: never touch the running skill's own files under
`specs/<idea>/` (`post` rejects a proposal that names them); run no commands
beyond read-only lookups; never commit; refuse a request outside these and
say why.
beyond read-only lookups, except one the person plainly asks you to run in
their message (a commit they spell out, a test run): run it, then report the
result in the reply; refuse anything else and say why, in the reply.
- Edits happen only at check-ins, never mid-task in a build.
```jsonc
@@ -715,8 +742,10 @@ review run from a build's review button stays in the build's session, under
its workflow: `building.md` → The review, mid-session. On completion the finish's `command` is the suggested
commit when fixes landed — filled in, in the AGENTS.md format, with
`"where": "When you are happy with it, commit it from your terminal:"` —
otherwise leave `command` out. A stop mid-review loses nothing on disk, so its
finish is the bare `/plan2code-review`.
otherwise leave `command` out. The completion finish carries `"dashboard": true`
so the finished screen offers **Back to the dashboard**; keep waiting for the
press. A stop mid-review loses nothing on disk, so its finish is the bare
`/plan2code-review` (a pause, so no dashboard button).
### Handoff (`handoff`)
@@ -892,6 +921,8 @@ Session meter) and `folderIssue` (Workspace → When a folder cannot be read).
### Every item
**Give every new question a new `id`.** An id names one question for the whole session. The server drops a stale `submitted` record if you reword a question under an old id, but never rely on it: a fresh id is the only unambiguous way to ask something new.
```jsonc
{
"id": "q7",
@@ -1141,7 +1172,7 @@ usual slices for up to about ten minutes:
| --- | --- |
| An action `{ "i": "__dashboard", "type": "dashboard" }` | `open --resume <sid> --no-open --workflow dashboard` (the resume re-runs the project scan), then ONE post with `"finish": null`, the `menu` payload and `"agent": { "status": "waiting" }`. Then read the dashboard skill (`~/.agents/skills/plan2code/SKILL.md`) and carry on as the dashboard from its "The menu" section, in this same conversation. The same action can also arrive before any finish, from the top bar's triangle: see Stop requests → "Back to the dashboard, mid-workflow". |
| An action `__review` or `__done` | As `building.md` says (quick task only). |
| `wait` exit `20` | They closed the tab. Do not resume: the session is over. |
| `wait` exit `20` | The server is gone, not necessarily the tab. `open --resume <sid> --no-open --workflow <yours>`, then keep waiting: their Ask messages and the dashboard button still need you. Give up only when the resume itself fails. |
| Nothing after about ten minutes | `stop` the server. The page swaps the button for the `/plan2code` command. |
### 2. Stop the server
@@ -54,6 +54,7 @@ import {
nowIso,
parseArgs,
pendingChatCount,
unansweredChat,
pendingWorkspaceChanges,
pidAlive,
print,
@@ -77,6 +78,7 @@ import {
sweepUploads,
switchWorkflow,
terminalLine,
updateState,
UPLOAD_MAX_AGE_MS,
validate,
validateChat,
@@ -88,6 +90,10 @@ import {
import { RUN_EVENTS } from "./public/meter.js";
import { changeLine } from "./public/workspace.js";
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
// still be one of our servers, so its pid gets no second look.
const MAX_SERVER_LIFE_MS = 4 * 60 * 60 * 1000;
const argv = process.argv.slice(2);
const cmd = argv[0];
const args = parseArgs(argv.slice(1));
@@ -102,8 +108,24 @@ function trace(what) {
/* ----------------------------------------------------------------- open */
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written by `open` alone, which starts every session: a
// `wait` or a `post` every few seconds need not rewrite it each time.
function leavePointer() {
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
}
async function cmdOpen() {
trace("open: start");
leavePointer();
const { project, worktree, branch } = repoRoots();
reapHandles(project);
trace("open: project found");
@@ -113,6 +135,11 @@ async function cmdOpen() {
let state;
// A new skill run for the meter: a fresh open, or a resume into another workflow.
let launched = true;
// Everything `open` does to a stored state, as a step it can take twice:
// once now, on the read below, so a bad payload is refused before anything
// starts, and again on a fresh read under the state lock when it writes, so
// a send the person made in between is kept rather than written over.
let reshape = (s) => s;
if (sid) {
sid = path.basename(sid);
@@ -120,27 +147,6 @@ async function cmdOpen() {
if (!fs.existsSync(dir)) die(`no session "${sid}" to resume`, 1);
state = readJson(path.join(dir, "state.json"));
if (!state) die(`session "${sid}" has no state`, 1);
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (state.finish && /^\s*paused\b/i.test(String(state.finish.headline || ""))) {
delete state.finish;
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
state.items = (state.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(state.items.map((i) => i.topic));
state.topics = (state.topics || []).filter((t) => liveTopics.has(t.id));
}
// A resume can also be a hand-off: the dashboard launches another skill
// into its own session, and the first thing that skill needs is for the
// page to stop being a dashboard. Letting the flags restate these fields
@@ -148,26 +154,51 @@ async function cmdOpen() {
// rather than a resume plus a whole extra post.
const switching = args.workflow && args.workflow !== state.workflow;
launched = Boolean(switching);
if (switching && (args.workflow === "dashboard" || state.workflow === "dashboard")) {
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. A skill run inline from another (a
// quick task's review) never passes the dashboard, so it keeps the page.
state = switchWorkflow(state, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
fs.rmSync(path.join(dir, "draft.json"), { force: true });
} else if (switching) state.workflow = args.workflow;
if (args.title) state.title = args.title;
if (args.spec) state.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete state.wake;
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. A skill run inline from another (a
// quick task's review) never passes the dashboard, so it keeps the page.
const hop = switching && (args.workflow === "dashboard" || state.workflow === "dashboard");
if (hop) fs.rmSync(path.join(dir, "draft.json"), { force: true });
reshape = (s) => {
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (s.finish && /^\s*paused\b/i.test(String(s.finish.headline || ""))) {
delete s.finish;
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
s.items = (s.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(s.items.map((i) => i.topic));
s.topics = (s.topics || []).filter((t) => liveTopics.has(t.id));
}
if (hop) {
s = switchWorkflow(s, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
} else if (switching) s.workflow = args.workflow;
if (args.title) s.title = args.title;
if (args.spec) s.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete s.wake;
return s;
};
} else {
sid = newSessionId();
// Named, not made: the folder is created once --file has passed, so a
@@ -185,22 +216,36 @@ async function cmdOpen() {
// Only a freshly opened dashboard plays Planny's wake-up.
if (args.workflow === "dashboard") state.wake = true;
}
// On every open, so a resume from another worktree refreshes both.
state.worktree = worktree;
state.branch = branch;
// A first payload's meter and folder reports, as `post` takes them: checked
// now, before anything is written, and appended once the launch is.
let openRun;
let openIssue;
let patch = null;
if (args.file) {
const patch = readJson(path.resolve(args.file));
patch = readJson(path.resolve(args.file));
if (!patch) die(`could not read --file ${args.file} as JSON`, 2);
({ run: openRun, folderIssue: openIssue } = patch);
delete patch.run;
delete patch.folderIssue;
}
const base = reshape;
const settle = (s) => {
s = base(s);
// On every open, so a resume from another worktree refreshes both.
s.worktree = worktree;
s.branch = branch;
return s;
};
reshape = (s) => (patch ? applyPatch(settle(s), patch) : settle(s));
state = settle(state);
if (patch) {
ledgerFromPost(dir, openRun, openIssue, state.workflow);
state = applyPatch(state, patch);
try {
state = applyPatch(state, patch);
} catch (e) {
die(e.message, 3);
}
const problems = validate(state);
if (problems.length) return failValidation(problems);
}
@@ -209,13 +254,15 @@ async function cmdOpen() {
// A fresh session needs a fresh server, and a server is a whole Node boot:
// the slowest thing `open` does, bar the browser. Start both now, before
// the scan and the state write, so their start-up runs alongside them
// instead of after. Neither can reach a page before the server is up, and
// the state is on disk long before that; the server reads it per request,
// never at boot.
// instead of after. The server does look at the state as it boots, and on
// a fresh session finds none yet: it takes the worktree from its command
// line, not from the state, and picks the state up on its first request or
// poll tick. No page can reach it before it is listening, and the state is
// on disk long before a browser gets there.
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null;
const reusable = existing && pidAlive(existing.pid) ? healthOk(existing) : Promise.resolve(false);
let boot = null;
if (!existing) boot = await startServer(project, sid, dir);
if (!existing) boot = await startServer(project, worktree, sid, dir);
// The dashboard's spec picker reads its inventory straight off the session
// state, so the scan belongs to `open` rather than to the agent: filesystem
@@ -223,23 +270,43 @@ async function cmdOpen() {
// never something a model has to remember to fetch. Rooted at the worktree's
// own top level: `project` is the common-dir key so linked worktrees share
// sessions, but each shows the specs on its own disk.
if (state.workflow === "dashboard") state.scan = scanProject(worktree);
const scan = state.workflow === "dashboard" ? scanProject(worktree) : null;
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
const carried = Boolean(waiting && !waiting.consumedAt);
// Under the state lock, which a send on the page takes too: the result and
// the state are read fresh here and the state is rebuilt from that read, so
// nothing the person sent since the read above is lost or stamped over.
let carried = false;
let written;
try {
written = updateState(dir, (fresh) => {
const next = fresh ? reshape(fresh) : state;
if (scan) next.scan = scan;
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) state.phase = "collecting";
writeJsonAtomic(path.join(dir, "state.json"), state);
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
carried = Boolean(waiting && !waiting.consumedAt);
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) next.phase = "collecting";
return next;
});
} catch (e) {
written = { error: e.message };
}
if (!written || written.error) {
// A server just started for this state would only serve a page that never starts.
if (boot) boot.kill();
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
@@ -288,14 +355,14 @@ async function cmdOpen() {
// A handle whose pid is alive but is not ours (the pid was reused) leaves
// this for last: nothing could be started until that was known.
let started = boot || (await startServer(project, sid, dir));
let started = boot || (await startServer(project, worktree, sid, dir));
let handle = await awaitHandle(started);
if (!handle && started.handoff) {
// The handover went wrong somewhere (a platform that will not pass the
// socket, a server that died taking it). Once more the old way, where
// the server binds its own port: slower, and certain.
started.kill();
started = await startServer(project, sid, dir, { handoff: false });
started = await startServer(project, worktree, sid, dir, { handoff: false });
handle = await awaitHandle(started);
}
if (!handle) {
@@ -372,7 +439,7 @@ function isFolder(p) {
* boot: a process's first listen() blocks for ~50ms on Windows while the
* socket stack loads, which is time the server spends booting anyway.
*/
async function startServer(project, sid, dir, { handoff = true } = {}) {
async function startServer(project, worktree, sid, dir, { handoff = true } = {}) {
const token = newToken();
const handlePath = handleFile(project, sid);
ensureDir(path.dirname(handlePath));
@@ -389,6 +456,9 @@ async function startServer(project, sid, dir, { handoff = true } = {}) {
`--session=${dir}`,
`--token=${token}`,
`--project=${project}`,
// The checkout the session runs in, which the state does not hold yet
// on a fresh open. See WORKTREE in server.mjs.
`--worktree=${worktree}`,
...(handoff ? ["--handoff"] : []),
...(args["idle-ms"] ? [`--idle-ms=${args["idle-ms"]}`] : []),
],
@@ -487,20 +557,37 @@ function cmdPost() {
delete patch.folderIssue;
const ledgerLines = ledgerFromPost(dir, run, folderIssue, before.workflow);
let next;
// The patch is applied to a fresh read under the state lock, never to the
// read above: a send the person made in between is in the file, and a write
// built on the older read would take it away. Nothing in here may exit, so
// the lock is always let go; a refusal is carried out and reported after.
let refused = null;
let problems = [];
let written;
try {
next = applyPatch(before, patch);
written = updateState(dir, (fresh) => {
if (!fresh) {
refused = ["that session has no state", 1];
return null;
}
let next;
try {
next = applyPatch(fresh, patch);
} catch (e) {
refused = [e.message, 3];
return null;
}
problems = validate(next);
if (!problems.length && patch.chat) problems = validateChat(next, readChat(dir));
return problems.length ? null : next;
});
} catch (e) {
die(e.message, 3);
die(e.message, 1);
}
const problems = validate(next);
if (refused) die(...refused);
if (problems.length) return failValidation(problems);
if (patch.chat) {
const chatProblems = validateChat(next, readChat(dir));
if (chatProblems.length) return failValidation(chatProblems);
}
const next = written.state;
writeJsonAtomic(statePath, next);
for (const line of ledgerLines) appendLedger(dir, line);
appendEvent(dir, { type: "post", items: (patch.items || []).length });
@@ -512,6 +599,7 @@ function cmdPost() {
items: next.items.length,
open,
phase: next.phase,
...unansweredNote(dir, next),
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
});
}
@@ -554,13 +642,15 @@ function ledgerFromPost(dir, run, issue, workflow) {
async function cmdWait() {
const dir = mustSession();
// A --seconds that is not a number would make the deadline NaN, and the
// slice would end at once with exit 10: a busy loop, not a wait.
// "240s" reads as 240. A --seconds with no number in it at all would make
// the deadline NaN, and the slice would end at once with exit 10: a busy
// loop, not a wait. So that is refused rather than guessed at.
const given = args.seconds;
if (given !== undefined && (typeof given !== "string" || !given.trim() || !Number.isFinite(Number(given)))) {
const asked = typeof given === "string" ? Number.parseFloat(given) : NaN;
if (given !== undefined && !Number.isFinite(asked)) {
die(`--seconds must be a number, got "${args.seconds}"`, 2);
}
const seconds = Math.max(5, Number(args.seconds || 240));
const seconds = Math.max(5, given === undefined ? 240 : asked);
const sid = path.basename(dir);
const project = projectRoot();
const resultPath = path.join(dir, "result.json");
@@ -580,6 +670,11 @@ async function cmdWait() {
// was a full read and parse every 400ms, which put up to 0.4s between the
// person pressing Send and the agent starting on it, on every single send.
let healthAt = 0;
// A busy server (right after a post, say) can miss one health check without
// being gone. Only a missing handle or dead pid is proof at once; a server
// that merely does not answer must fail three checks in a row, each with a
// longer look, before the slice ends with exit 20.
let healthMisses = 0;
// Null, not the current stamp: a result written between the check above and
// this line would otherwise read as already seen and wait out the slice.
let seen = null;
@@ -605,11 +700,17 @@ async function cmdWait() {
if (Date.now() - healthAt > 5000) {
healthAt = Date.now();
const handle = listHandles(project).find((h) => h.sid === sid);
if (!handle || !pidAlive(handle.pid) || !(await healthOk(handle))) {
if (!handle || !pidAlive(handle.pid)) {
print(serverGone(sid));
process.exitCode = 20;
return;
}
if (await healthOk(handle, 4000)) healthMisses = 0;
else if (++healthMisses >= 3) {
print(serverGone(sid));
process.exitCode = 20;
return;
} else healthAt = Date.now() - 3000; // look again in about 2s, not 5s
}
sleepSync(50);
}
@@ -630,7 +731,9 @@ async function cmdWait() {
staged,
url: handle ? handle.url : "",
message: "Waiting on your answer in the web console",
next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.",
pendingChat: 0,
...unansweredNote(dir, state),
// A workspace change alone never ends a slice: it rides on the next send.
pendingWorkspace: pendingWorkspaceChanges(dir).length,
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
@@ -638,11 +741,19 @@ async function cmdWait() {
process.exitCode = 10;
}
// Quick questions already handed over with no reply yet. Always empty when all are answered.
function unansweredNote(dir, state) {
const seqs = unansweredChat(dir, state);
return seqs.length
? { unansweredChat: seqs, warning: "Quick questions " + seqs.join(", ") + " have no reply yet and the page still shows them as pending. Reply to each now (chat.replies, re = seq): do what was asked when you can, or say why you will not." }
: {};
}
function serverGone(sid) {
return {
status: "server-gone",
sid,
message: "The console server is not running. Start it again with `open --resume` and give the person the new link.",
message: "The console server is not running. Start it again with `open --resume <sid> --no-open`, then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
};
}
@@ -943,10 +1054,13 @@ async function cmdStop() {
// reboot in the system temp directory, and PIDs get reused; without this
// check `stop --all` can kill an unrelated program that happens to have
// inherited the number. /health returning our own sid is the only proof:
// a young handle with a live pid is not, since the server may have died
// minutes ago and its number gone straight to something else. A server
// too wedged to answer /health still meets its own idle deadline.
if (!(await healthOk(h))) {
// a live pid and a young handle are not, since a server that died a
// minute ago leaves exactly that behind for any process to inherit. A
// busy server gets a second, longer look, and still has to answer as
// ours; one that does not is left alone, and only its handle goes.
const young = Date.now() - Date.parse(h.startedAt || 0) < MAX_SERVER_LIFE_MS;
const ours = (await healthOk(h)) || (young && pidAlive(h.pid) && (await healthOk(h, 5000)));
if (!ours) {
skipped++;
try {
fs.rmSync(h.handlePath, { force: true });
@@ -1074,18 +1188,6 @@ const COMMANDS = {
help: cmdHelp,
};
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written on every invocation, help and errors included.
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
// Say which Node is too old, rather than dying later inside a health check with
// "fetch is not defined". Whatever agent is driving this has to be able to read
// the failure, tell the person in one line, and carry on in the terminal.
@@ -1105,4 +1207,12 @@ if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
process.exit(2);
}
// A flag given with no value parses as `true`, and a boolean handed on as a
// path or a name crashes somewhere deep (path.basename(true) throws). Every
// flag that takes a value is checked once, here, and refused as bad usage.
const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "upload", "name", "from", "seconds", "limit", "idle-ms"];
for (const flag of VALUE_FLAGS) {
if (flag in args && typeof args[flag] !== "string") die(`--${flag} needs a value`, 2);
}
await COMMANDS[cmd]();
@@ -39,6 +39,13 @@ export const SESSIONS_DIR = path.join(HOME_DIR, "sessions");
// state: a browser ties localStorage to the origin, and the origin carries the
// ephemeral port, so the file under this dir is the only copy of a preference
// that survives the next session's new port.
// Model menus for the `plan2code` launcher. The shipped list (bin/models.json) is the
// authors' and is overwritten by every install; the user's additions (models.json) are
// theirs. The launcher reads both. PLAN2CODE_MODELS_DIR moves them, for tests.
const PLAN2CODE_DIR = process.env.PLAN2CODE_MODELS_DIR || path.join(os.homedir(), ".plan2code");
export const SHIPPED_MODELS_FILE = path.join(PLAN2CODE_DIR, "bin", "models.json");
export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
@@ -141,6 +148,91 @@ export function appendEvent(dir, event) {
return line;
}
/* ----------------------------------------------------- the state lock */
// state.json has two writers in two processes: console.mjs (`open` and `post`,
// the agent's side) and the server (`/submit` stamps the phase and records
// what was sent on each item). Each writer reads the file, changes it and
// writes it back, so two of them overlapping lose whichever wrote first. Every
// read-modify-write of state.json therefore runs under this lock, a file
// created with O_EXCL beside it. The sections it guards are a read, a merge
// and a write, milliseconds long, so a lock older than LOCK_STALE_MS, or one
// whose holder has died, is a crash left behind and is broken. The wait runs
// past the stale age, so a writer always gets in eventually.
export const STATE_LOCK_FILE = "state.json.lock";
const LOCK_STALE_MS = 5000;
const LOCK_WAIT_MS = 7000;
function lockStale(lock) {
try {
const st = fs.statSync(lock);
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) return true;
const pid = Number.parseInt(fs.readFileSync(lock, "utf8"), 10);
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && !pidAlive(pid);
} catch (err) {
// Gone between the failed create and this look: free, so try again.
return err.code === "ENOENT";
}
}
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn) {
const lock = path.join(dir, STATE_LOCK_FILE);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
try {
fd = fs.openSync(lock, "wx");
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
} catch {}
continue;
}
sleepSync(Math.min(5 * (attempt + 1), 50));
}
}
try {
try {
fs.writeSync(fd, String(process.pid));
} finally {
fs.closeSync(fd);
}
return fn();
} finally {
try {
fs.rmSync(lock, { force: true });
} catch {}
}
}
// The one way to change state.json: under the lock, read it fresh, hand it to
// fn (null when there is no state yet, with the raw text beside it), and write
// back whatever fn returns. A null return writes nothing. Returns the written
// state and its text, or null.
export function updateState(dir, fn) {
const file = path.join(dir, "state.json");
return withStateLock(dir, () => {
let text = null;
try {
text = fs.readFileSync(file, "utf8");
} catch {}
let state = null;
try {
state = text === null ? null : JSON.parse(text);
} catch {}
const next = fn(state, text);
if (!next) return null;
return { state: next, text: writeJsonAtomic(file, next) };
});
}
export function sleepSync(ms) {
// Node built-ins only, and this runs in short one-shot CLI commands.
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
@@ -827,6 +919,41 @@ const ITEM_DEFAULTS = {
thread: [],
};
// The question a card asks. If a patch rewrites any of these on a known id, it
// is a new question wearing an old id.
const QUESTION_FIELDS = ["kind", "title", "body", "options", "steps", "rows", "summary", "doc", "verdicts"];
/**
* Merge item patches by id, and keep a reused id from inheriting the person's
* old answer. `submitted` is the server's record of what they sent to the
* PREVIOUS question. When a patch changes what an item asks and doesn't itself
* settle it, that record (and any stale `answer`) is dropped, so the page shows
* the new question as open instead of "Sent, waiting for Plan2Code" forever.
*/
function dropStaleSubmissions(currentItems, before, patchList) {
const merged = mergeKeyed(currentItems, patchList, "id", ITEM_DEFAULTS, "items");
for (const entry of patchList) {
const prev = (before || []).find((x) => x.id === entry.id);
if (!prev || (prev.submitted === undefined && prev.answer === undefined)) continue;
const rewritten = QUESTION_FIELDS.some(
(f) => f in entry && JSON.stringify(entry[f]) !== JSON.stringify(prev[f]),
);
const settles = entry.status === "answered" || entry.status === "skipped" || "answer" in entry;
// A settled question edited in place (a typo in its body) stays settled; only an
// explicit reopen turns it into a new question.
const wasSettled = prev.status === "answered" || prev.status === "skipped";
// A different kind is never a typo fix: a multi turned confirm is another question.
const kindChanged = "kind" in entry && entry.kind !== prev.kind;
const reopens = entry.status === "open" || entry.status === "reopened" || kindChanged;
if (!rewritten || settles || (wasSettled && !reopens)) continue;
const item = merged.find((x) => x.id === entry.id);
if (wasSettled && !("status" in entry)) item.status = "open";
if (!("submitted" in entry)) delete item.submitted;
delete item.answer;
}
return merged;
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -868,7 +995,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = mergeKeyed(next.items, v, "id", ITEM_DEFAULTS, "items");
next.items = dropStaleSubmissions(next.items, state.items, v);
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1033,6 +1160,17 @@ export function validate(state) {
if ((item.kind === "choice" || item.kind === "multi") && !Array.isArray(item.options)) {
problems.push(`item "${item.id}" is a ${item.kind} and needs "options"`);
}
if ((item.kind === "choice" || item.kind === "multi") && Array.isArray(item.options)) {
for (const o of item.options) {
if (!o || typeof o.k !== "string" || !o.k.trim()) {
problems.push(`item "${item.id}" has an option with no "k" (its key, like "A")`);
} else if (typeof o.text !== "string" || !o.text.trim()) {
problems.push(
`item "${item.id}" option "${o.k}" needs "text" (the label) and optionally "detail". Options use "text"/"detail", not "label"/"desc".`
);
}
}
}
if (item.verdicts != null) {
if (!Array.isArray(item.verdicts) || !item.verdicts.length) {
problems.push(`item "${item.id}" "verdicts" must be a non-empty array of { id, label }`);
@@ -1051,16 +1189,18 @@ export function validate(state) {
if (item.templates != null && (item.kind !== "text" || item.templates !== "idea")) {
problems.push(`item "${item.id}" has "templates": only a text item can carry it, and its only value is "idea".`);
}
// The page compiles this to check the answer. One that will not compile
// is dropped there, so the check the agent asked for would silently not run.
// The page compiles it as the person types, and a pattern that does not
// compile throws there, on every keystroke, with nothing on screen to say why.
if (item.pattern != null) {
let compiles = typeof item.pattern === "string";
try {
if (compiles) new RegExp(item.pattern);
} catch {
compiles = false;
if (typeof item.pattern !== "string") {
problems.push(`item "${item.id}" "pattern" must be a string holding a JavaScript regular expression`);
} else {
try {
new RegExp(item.pattern);
} catch (e) {
problems.push(`item "${item.id}" "pattern" is not a valid JavaScript regular expression: ${e.message}`);
}
}
if (!compiles) problems.push(`item "${item.id}" "pattern" must be a string holding a valid JavaScript regular expression`);
}
const recs = (item.options || []).filter((o) => o.recommended);
if (recs.length > 1) problems.push(`item "${item.id}" marks ${recs.length} options recommended; at most one`);
@@ -1148,7 +1288,7 @@ export function validate(state) {
// server's record of an answer someone pressed Send on; if their own words
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
// would be rejected and the session would wedge with no way out.
const authored = state.items.map(({ submitted, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -1203,6 +1343,8 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
// chat.ndjson the server. One JSON line per entry: message / decision / reset.
// chat-cursor.json console.mjs. The last seq the agent was handed.
// state.json console.mjs `post`. The agent's replies, under chat.replies.
// (state.json as a whole has a second writer, the server's
// /submit, so every change to it goes through updateState().)
//
// The Workspace and the session meter follow the same rule, in files that
// switchWorkflow() never touches, so they carry across dashboard hops:
@@ -1351,6 +1493,19 @@ export function deliverableChat(entries) {
return entries.some((e) => e.kind !== "reset") ? entries : [];
}
// Things the person said that were handed over but never answered. The page keeps
// showing "working on the answer" for each until a reply lands, so the agent is
// told on every post and every wait slice until it has replied (a refusal is a reply).
export function unansweredChat(dir, state) {
const { conversation } = currentConversation(readChat(dir, 0));
const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re));
const cursor = readCursor(dir);
return readChat(dir, 0)
.filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation)
.filter((e) => e.seq <= cursor && !replied.has(e.seq))
.map((e) => e.seq);
}
// How many things the person said are still waiting to be collected.
export function pendingChatCount(dir, state) {
return collectChat(dir, state).filter((e) => e.kind !== "reset").length;
@@ -25,6 +25,7 @@ export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace"
export const WINDOWS_PICKER_SOURCE = `
using System;
using System.Runtime.InteropServices;
using System.Threading;
public static class Plan2CodeFolderPicker {
[ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
@@ -62,12 +63,40 @@ public static class Plan2CodeFolderPicker {
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
private static extern void SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid iid, out IShellItem item);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string className, string title);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int w, int h, uint flags);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int index);
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);
private static void Raise(string title) {
for (int i = 0; i < 100; i++) {
IntPtr hwnd = FindWindow(null, title);
if (hwnd != IntPtr.Zero) {
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
int h = Math.Min(750, GetSystemMetrics(1) - 80);
int x = (GetSystemMetrics(0) - w) / 2 + 40;
int y = (GetSystemMetrics(1) - h) / 2 + 40;
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
SetForegroundWindow(hwnd);
return;
}
Thread.Sleep(50);
}
}
public static string Pick(IntPtr owner, string title, string start) {
IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
try {
@@ -83,6 +112,9 @@ public static class Plan2CodeFolderPicker {
dialog.SetFolder(folder);
} catch (Exception) {}
}
Thread raiser = new Thread(delegate() { Raise(title); });
raiser.IsBackground = true;
raiser.Start();
int hr = dialog.Show(owner);
if (hr == ERROR_CANCELLED) return null;
Marshal.ThrowExceptionForHR(hr);
@@ -69,6 +69,22 @@ export function submittedAwaiting(item) {
return replied ? null : s;
}
/**
* The note (and its attachments) the person last sent on an item, while the
* agent has yet to say anything after it. The server records it as `sentNote`
* on every send, so the page can show it in the Notes pane and in the Sent
* box instead of letting it vanish into a send that shows no sign of arriving.
* Any thread message from the send onwards, or none with a clock to compare,
* means it has been picked up.
*/
export function noteAwaiting(item) {
const n = item && item.sentNote;
if (!n || typeof n !== "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -11,10 +11,10 @@
--ink-3: #8f8779;
--rule: #e4ddd1;
--rule-2: #cfc6b6;
--accent: #ae4f2b;
--accent-soft: #fbeee7;
--accent: #206cc3;
--accent-soft: #ecf2f9;
--accent-ink: #ffffff;
--accent-line: #dd9b7e;
--accent-line: #9ab4d3;
--ok: #2f6b45;
--ok-soft: #e4f0e8;
--stage: #9a6a12;
@@ -49,10 +49,10 @@
--ink-3: #8b8376;
--rule: #332e29;
--rule-2: #46403a;
--accent: #e8825a;
--accent-soft: #34211a;
--accent-ink: #1a120e;
--accent-line: #8a4f36;
--accent: #619fe5;
--accent-soft: #1a2533;
--accent-ink: #0c1117;
--accent-line: #3d5978;
--ok: #74c28f;
--ok-soft: #1c2d22;
--stage: #e0ab4c;
@@ -73,10 +73,10 @@
--ink-3: #8b8376;
--rule: #332e29;
--rule-2: #46403a;
--accent: #e8825a;
--accent-soft: #34211a;
--accent-ink: #1a120e;
--accent-line: #8a4f36;
--accent: #619fe5;
--accent-soft: #1a2533;
--accent-ink: #0c1117;
--accent-line: #3d5978;
--ok: #74c28f;
--ok-soft: #1c2d22;
--stage: #e0ab4c;
@@ -241,6 +241,19 @@ body {
}
.meter-pop[hidden] { display: none; }
.meter-tip { margin: 0 0 6px; font-size: 13px; color: var(--ink-2); }
.meter-list {
list-style: none; margin: 0 0 8px; padding: 6px 0 0;
border-top: 1px solid var(--rule);
max-height: 40vh; overflow-y: auto;
font-size: 12px; color: var(--ink-2);
}
.meter-list[hidden] { display: none; }
.meter-list li { display: flex; justify-content: space-between; gap: 16px; padding: 2px 0; }
.meter-fresh { margin: 0 0 8px; padding-top: 6px; border-top: 1px solid var(--rule); }
.meter-fresh[hidden] { display: none; }
.meter-fresh-text { margin: 0 0 6px; font-size: 12px; color: var(--ink-2); }
.meter-fresh-row .handoff-code { flex-basis: 180px; font-size: 12px; padding: 6px 10px; }
.meter-item-points { flex: none; font-weight: 600; color: var(--ink); font-variant-numeric: tabular-nums; }
.badge {
font-size: 11px;
@@ -652,6 +665,16 @@ h1 {
}
.wake.dormant .wake-hint { opacity: 1; }
/* Skip: muted, bottom right, so it never competes with the animation. */
.wake-skip {
position: absolute; right: 14px; bottom: 14px;
padding: 4px 12px; border: 1px solid var(--ink-3); border-radius: 4px;
background: transparent; color: var(--ink-3);
font: inherit; font-size: 0.8rem; letter-spacing: 0.08em; text-transform: uppercase;
cursor: pointer; opacity: 0.7;
}
.wake-skip:hover, .wake-skip:focus-visible { opacity: 1; color: var(--ink); border-color: var(--ink); }
/* 0.0 s, powered down: the resting state every beat starts from. Arms hang
slack against his sides, the star is shut and the smile not yet drawn. */
.wake-bot { filter: grayscale(1); opacity: 0.55; }
@@ -1132,6 +1155,20 @@ h1 {
.rail-mark { flex: none; width: 15px; text-align: center; font-size: 12px; color: var(--ink-3); margin-top: 1px; }
.rail-mark.done { color: var(--ok); }
.rail-mark.staged { color: var(--stage); font-weight: 700; }
/* Echoes the center pane's "Suggested" pill, which can scroll out of view;
the dot keeps the call-out visible while just scanning the rail. The
title grows to push the dot flush with the row's right edge. */
.rail-item > span:not(.rail-mark):not(.rail-suggested-dot) { flex: 1 1 auto; }
.rail-suggested-dot {
flex: none;
width: 7px;
height: 7px;
border-radius: 50%;
margin-top: 5px;
background: var(--accent);
}
.rail-item.is-suggested:not([aria-current="true"]) { color: var(--ink); }
.rail-mark.open { color: var(--accent); }
/* The session's own page, above the topic groups. It names the state it is
@@ -1618,7 +1655,7 @@ input[type="text"].invalid { border-color: var(--warn); }
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
}
#btn-send:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
.btn.ghost:hover { background: var(--panel-2); color: var(--ink); }
.btn.danger { border-color: var(--warn); color: var(--warn); }
@@ -1734,6 +1771,7 @@ input[type="text"].invalid { border-color: var(--warn); }
}
.attach-row { display: flex; align-items: center; margin: -4px 0 6px -13px; }
.attach-row.is-under { margin: 6px 0 4px -13px; }
.attach-tray { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }
.attach-thumb {
position: relative;
@@ -1784,6 +1822,10 @@ input[type="text"].invalid { border-color: var(--warn); }
font-size: 12.5px; font-weight: 600; color: var(--ink);
}
.attach-chip-size { color: var(--ink-2); font-size: 11.5px; }
.attach-link { color: inherit; text-decoration: none; border-radius: 8px; }
.attach-link:hover .attach-thumb, .attach-link:focus-visible .attach-thumb { border-color: var(--accent); }
.attach-link:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.msg.pending { border-style: dashed; border-color: var(--stage); background: transparent; }
.ask-row .attach-chip { padding-right: 10px; }
.footer-held { margin-top: 3px; color: var(--ink-2); font-size: 12.5px; }
@@ -1863,6 +1905,23 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
transition: opacity 0.12s;
}
.md-pre-wrap:hover .md-copy, .md-copy:focus { opacity: 1; }
/* Run it, on git blocks: Copy's twin, tucked under it so the wider
"Press Ctrl+C" fallback label can never collide. */
.md-run {
position: absolute; top: 34px; right: 8px;
font: 600 11.5px var(--sans);
background: var(--panel); color: var(--ink-2);
border: 1px solid var(--rule-2); border-radius: 6px;
padding: 4px 9px; cursor: pointer; opacity: 0;
transition: opacity 0.12s;
}
.md-pre-wrap:hover .md-run, .md-run:focus { opacity: 1; }
/* The muted nudge on other command-looking blocks, a caption under the block. */
.md-run-hint {
margin: -6px 2px 0;
font: 11px var(--sans); color: var(--ink-3);
opacity: 0.8;
}
.md-hr { border: 0; border-top: 1px solid var(--rule); margin: 20px 0; }
.md-table-wrap { overflow-x: auto; margin: 0 0 13px; }
.md-table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
@@ -1996,9 +2055,15 @@ kbd {
.icon-btn:hover .ab-mark, .icon-btn:hover .ab-dot { stroke: var(--accent); fill: none; }
.icon-btn:hover .ab-dot { fill: var(--accent); }
.icon-btn .sw-a { fill: var(--accent); }
.icon-btn .sw-b { fill: var(--ok); }
.icon-btn .sw-c { fill: var(--stage); }
a.icon-btn { box-sizing: border-box; text-decoration: none; }
.icon-btn .mg-body { fill: none; stroke: var(--ink-3); stroke-width: 1.4; stroke-linejoin: round; }
.icon-btn .mg-line { fill: none; stroke: var(--ink-2); stroke-width: 1.4; stroke-linecap: round; stroke-linejoin: round; }
.icon-btn:hover .mg-body, .icon-btn:hover .mg-line { stroke: var(--accent); }
.icon-btn .gr-teeth { fill: none; stroke: var(--ink-3); stroke-width: 2.2; }
.icon-btn .gr-ring { fill: none; stroke: var(--ink-3); stroke-width: 1.6; }
.icon-btn .gr-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
.icon-btn:hover .gr-teeth, .icon-btn:hover .gr-ring, .icon-btn:hover .gr-hub { stroke: var(--accent); }
/* ------------------------------------------------------------ swatches */
@@ -2132,7 +2197,8 @@ kbd {
flex-direction: column;
}
.modal.help[open] { display: flex; }
.modal.help .modal-actions { flex: none; margin-top: 16px; }
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
.help-layout {
display: grid;
@@ -2288,6 +2354,111 @@ kbd {
}
.modal::backdrop { background: rgba(0, 0, 0, 0.45); }
.modal h2 { font: 600 21px/1.25 var(--serif); margin: 0 0 10px; }
/* The Welcome: a dark poster with Planny, four columns, one button. */
.modal.welcome {
width: min(840px, calc(100vw - 32px));
max-width: none;
padding: 0;
overflow: hidden;
}
.modal.welcome[open] { display: flex; flex-direction: column; max-height: calc(100vh - 96px); }
.welcome-poster {
position: relative;
flex: none;
overflow: hidden;
padding: 52px 48px 40px;
text-align: center;
color: #fff;
background:
radial-gradient(circle at 50% 125%, color-mix(in srgb, var(--accent) 85%, #fff) 0, transparent 58%),
linear-gradient(180deg, #16181d, color-mix(in srgb, var(--accent) 50%, #16181d));
}
.welcome-sky i { position: absolute; width: 3px; height: 3px; border-radius: 50%; background: #fff; opacity: 0.55; }
.welcome-sky i:nth-child(1) { top: 18%; left: 11%; }
.welcome-sky i:nth-child(2) { top: 34%; left: 84%; }
.welcome-sky i:nth-child(3) { top: 12%; left: 66%; }
.welcome-sky i:nth-child(4) { top: 56%; left: 20%; }
.welcome-sky i:nth-child(5) { top: 62%; left: 91%; }
.welcome-sky i:nth-child(6) { top: 26%; left: 32%; width: 2px; height: 2px; }
.welcome-bot { display: flex; justify-content: center; }
/* The dock's own Planny, larger and in light ink for the dark poster. */
.welcome-bot .planny { width: 70px; height: 96px; }
.welcome-bot .planny .shell,
.welcome-bot .planny .smile,
.welcome-bot .planny .arm path { stroke: #f0ece5; }
.welcome-bot .planny .shell { fill: #1e2127; }
.welcome-bot .planny .arm circle,
.welcome-bot .planny .foot { fill: #f0ece5; }
.welcome-kicker {
margin: 20px 0 6px;
font-size: 12px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: rgba(255, 255, 255, 0.75);
}
.modal.welcome h2 { font: 600 38px/1.15 var(--serif); margin: 0 0 12px; color: #fff; }
.welcome-lead { margin: 0 auto; max-width: 52ch; font-size: 15px; line-height: 1.55; color: rgba(255, 255, 255, 0.85); }
.welcome-cols {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
min-height: 0;
overflow-y: auto;
padding: 34px 36px 8px;
text-align: center;
}
.welcome-col h3 { font: 600 15px/1.3 var(--sans); margin: 12px 0 4px; color: var(--ink); }
.welcome-col p { margin: 0; font-size: 13px; line-height: 1.5; color: var(--ink-2); }
.welcome-col strong { color: var(--ink); }
.welcome-col code {
font: 600 12px var(--mono);
padding: 1px 6px;
border-radius: 5px;
background: var(--accent-soft);
color: var(--accent);
}
.welcome-col kbd {
font: 600 11.5px var(--mono);
padding: 0 6px;
border-radius: 5px;
border: 1px solid var(--rule-2);
border-bottom-width: 2px;
background: var(--panel-2);
color: var(--ink);
}
.welcome-dot { display: inline-grid; place-items: center; width: 50px; height: 50px; border-radius: 50%; }
.welcome-dot svg {
width: 22px;
height: 22px;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.welcome-dot.is-accent { background: var(--accent-soft); color: var(--accent); }
.welcome-dot.is-stage { background: var(--stage-soft); color: var(--stage); }
.welcome-dot.is-plain { background: var(--panel-2); color: var(--ink-2); border: 1px solid var(--rule); }
.welcome-dot.is-ok { background: var(--ok-soft); color: var(--ok); }
.welcome-dot.is-bare { background: none; color: var(--ok); }
.welcome-dot.is-bare svg { width: 30px; height: 30px; }
.modal.welcome .modal-actions { flex: none; justify-content: center; margin: 0; padding: 24px 36px 36px; }
.modal.welcome .modal-actions .btn { padding: 12px 40px; font-size: 15px; border-radius: 999px; }
@media (max-width: 720px) {
.welcome-poster { padding: 36px 24px 28px; }
.modal.welcome h2 { font-size: 28px; }
.welcome-cols { grid-template-columns: 1fr 1fr; padding: 24px 20px 8px; }
}
.help-link {
background: none;
border: 0;
padding: 0;
font: inherit;
color: var(--accent);
text-decoration: underline;
cursor: pointer;
}
.help-link:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 2px; }
.modal-blurb { margin: 0 0 18px; color: var(--ink-2); font-size: 13.5px; }
.modal-ranges { border: 0; margin: 0; padding: 0; display: grid; gap: 8px; }
@@ -3190,3 +3361,24 @@ kbd {
.help-mood-bot, .help-mood-bot *, .help-mood-bot.is-work .eye { animation: none !important; }
#btn-send { animation: none; }
}
/* User Preferences: the launcher's model menu. */
.models-tabs { display: flex; gap: 6px; }
.models-tabs .btn[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
.models-note { font-size: 0.9em; opacity: 0.85; }
.models-note p, .models-note ul { margin: 0 0 6px; }
.models-note ul { padding-left: 18px; }
.models-list { display: grid; gap: 4px; max-height: 160px; overflow: auto; }
.models-list:empty { display: none; }
.models-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 6px; align-items: center; }
.models-row.locked { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); font-size: 0.88em; opacity: 0.75; }
.models-row input { min-width: 0; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* A word the person has to type, bold and in their highlight color so it
does not get lost in the status sentence. */
.agent-key {
color: var(--accent);
font-weight: 700;
}
@@ -10,7 +10,7 @@
// this, that reversibility is the whole point.
import { md, el, copyButton, selectContents } from "./render.js";
import { ACCENTS, DEFAULT_CARD_WIDTH, SOUND_EVENTS, cardWidth, soundKey, soundPrefs } from "./palette.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, SOUND_EVENTS, cardWidth, soundKey, soundPrefs } from "./palette.js";
import { activityLabel, workingLine } from "./labels.js";
import { playWake } from "./boot.js";
import {
@@ -64,6 +64,7 @@ import {
STOP_REPLY,
sentAnswer,
submittedAwaiting,
noteAwaiting,
suggestionFrom,
THUMB_EDGE,
turnGate,
@@ -128,7 +129,7 @@ const LOOKS_KEY = "p2c-console:looks";
// The per-event sound switches (SOUND_EVENTS) live in palette.js too.
const DEFAULT_LOOKS = {
theme: "system",
accent: "rust",
accent: DEFAULT_ACCENT,
sound: true,
...soundPrefs(null),
width: DEFAULT_CARD_WIDTH,
@@ -136,6 +137,8 @@ const DEFAULT_LOOKS = {
};
let looks = { ...DEFAULT_LOOKS };
let syncedLooks = null;
let looksReady = false;
function adoptLooks(saved) {
looks = { ...DEFAULT_LOOKS, ...saved };
@@ -178,25 +181,47 @@ async function syncLooks() {
}
if (saved && saved.looks && typeof saved.looks === "object") {
adoptLooks(saved.looks);
syncedLooks = { ...looks };
try {
localStorage.setItem(LOOKS_KEY, JSON.stringify(looks));
} catch {}
applyLooks();
renderSwatches();
} else if (localStorage.getItem(LOOKS_KEY)) {
pushLooks();
} else {
// Blocked storage throws on read, and that must not stop the page loading.
let held = false;
try {
held = Boolean(localStorage.getItem(LOOKS_KEY));
} catch {}
if (held) pushLooks();
}
looksReady = true;
// Not inline: with the server's copy in the page this runs before `S` exists.
setTimeout(maybeWelcome, 0);
}
// Fire-and-forget mirror. A failed POST costs nothing the next session would
// notice on this port; the localStorage copy still covers the reload case.
function pushLooks() {
try {
// Only what this tab changed since it last synced, so a tab with stale
// settings never overwrites another tab's change to a different key.
const set = {};
for (const [k, v] of Object.entries(looks)) if (!syncedLooks || syncedLooks[k] !== v) set[k] = v;
const before = syncedLooks;
const partial = Boolean(before);
if (partial && !Object.keys(set).length) return;
syncedLooks = { ...looks };
const body = partial ? { set } : { looks };
// A write that did not land must be sent again with the next change.
const undo = () => (syncedLooks = before);
fetch("/looks", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ looks }),
}).catch(() => {});
body: JSON.stringify(body),
})
.then((res) => res.ok || undo())
.catch(undo);
} catch {}
}
@@ -380,6 +405,24 @@ for (const evt of ["pointerdown", "keydown"]) {
});
}
// Run it, on a fenced git block (render.js): stage the block as the Ask
// draft and open the chat. The person still presses Send, so nothing runs
// on a stray click — the same fill-the-box pattern as the Ask starters.
document.addEventListener("click", (e) => {
const run = e.target.closest(".md-run");
if (!run) return;
const code = run.closest(".md-pre-wrap")?.querySelector("code");
if (!code || !code.textContent.trim()) return;
local.chat.draft = `run:\n${code.textContent}`;
view = "ask";
save();
render();
const ta = $("ask-input");
if (!ta) return;
ta.focus();
ta.setSelectionRange(ta.value.length, ta.value.length);
});
// The stars for Planny's flight, made once. Each gets its place and pace as
// custom properties set through the CSSOM: the CSP forbids style attributes
// in markup, and the stylesheet cannot roll dice. They sit still, invisible,
@@ -795,13 +838,16 @@ async function loadState() {
const res = await fetch("/state", { cache: "no-store" });
if (!res.ok) throw new Error(String(res.status));
const body = await res.json();
adopt(body);
// The server answers again: back to the stream, once the wait is up.
if (!es && pollTimer && Date.now() >= esRetryAt) {
clearInterval(pollTimer);
pollTimer = null;
connect();
// The same rev is the same state: adopting it again would redraw the page
// every few seconds while polling for nothing. Still proof of life, though.
if (S && typeof body.rev === "number" && body.rev === rev) {
lastContact = Date.now();
agentLastSeen = body.agentLastSeen || agentLastSeen;
markGone();
} else {
adopt(body);
}
retryStream();
} catch {
markGone();
}
@@ -1158,6 +1204,11 @@ function connect() {
esErrors = 0;
esRetryMs = ES_RETRY_MIN_MS;
lastContact = Date.now();
// Back on the stream: polling was only ever the stand-in.
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
};
es.onerror = () => {
esErrors++;
@@ -1179,6 +1230,18 @@ function startPolling() {
pollTimer = setInterval(loadState, 3000);
}
// While polling, every answer from the server is a cue to try the stream
// again, so polling lasts only as long as the outage did. Polling carries on
// while an attempt is open, so startPolling() never runs for a failed one; the
// wait is pushed back here instead, or a dead stream would be retried on every
// poll. One attempt at a time, since `es` is set while it is trying.
function retryStream() {
if (!pollTimer || es || Date.now() < esRetryAt) return;
esRetryAt = Date.now() + esRetryMs;
esRetryMs = Math.min(esRetryMs * 2, ES_RETRY_MAX_MS);
connect();
}
setInterval(() => {
fetch("/ping", { method: "POST" })
.then((r) => (r.ok ? r.json() : null))
@@ -1186,6 +1249,7 @@ setInterval(() => {
if (!body) return;
lastContact = Date.now();
agentLastSeen = body.agentLastSeen || agentLastSeen;
retryStream();
// A rev we have not seen means a state frame went missing -- a dropped
// SSE reconnect, a tab asleep in a background window. Ask for it rather
// than waiting for the next change to come along.
@@ -1442,6 +1506,31 @@ function renderMeter() {
$("meter-words").textContent = meterFrame.words;
pill.title = meterFrame.tooltip;
$("meter-tip").textContent = meterFrame.tooltip;
// What the points are made of: one row per piece of work that scored.
const list = $("meter-list");
const rows = Array.isArray(meterFrame.items) ? meterFrame.items : [];
list.hidden = !rows.length;
list.replaceChildren(
...rows.map((row) => {
const li = el("li");
li.appendChild(el("span", "meter-item-label", row.label));
li.appendChild(el("span", "meter-item-points", "+" + row.points));
return li;
})
);
// Once the session is past fresh, say how to start a new one.
const fresh = $("meter-fresh");
fresh.hidden = meterFrame.level === "green";
if (fresh.hidden || fresh.dataset.built) return;
fresh.dataset.built = "1";
const text = handoffText({ command: DASHBOARD_COMMAND });
const code = el("code", "handoff-code", text);
const row = el("div", "handoff-command meter-fresh-row");
row.append(code, copyButton(text, "btn small ghost handoff-copy", code));
fresh.append(
textWithCode("p", "meter-fresh-text", `To start a new session, run \`${DASHBOARD_COMMAND}\` in a new conversation:`),
row
);
}
function toggleMeterPop(open) {
@@ -1469,7 +1558,7 @@ function renderChrome() {
renderMeter();
$("title").textContent = S.title || "Session";
$("badge").textContent = workflowLabel(S.workflow);
document.title = (S.title || "Session") + " · Plan2Code";
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
const h = S.headline || {};
// On a finished session an open item is frozen: the send on it counts as
@@ -1529,7 +1618,18 @@ function renderStatus() {
moodVar = Math.floor(Math.random() * MOOD_VARIANTS[mood]);
}
bot.setAttribute("class", `planny is-${mood} v${moodVar}`);
if (text.textContent !== line) text.textContent = line;
if (text.dataset.line !== line) {
text.dataset.line = line;
text.replaceChildren(
...line.split(/\*\*(.+?)\*\*/).map((part, i) => {
if (i % 2 === 0) return document.createTextNode(part);
const key = document.createElement("strong");
key.className = "agent-key";
key.textContent = part;
return key;
})
);
}
tick.textContent = count || "";
$("agent-spin").hidden = !spin;
$("dock").classList.toggle("is-flying", Boolean(spin));
@@ -1584,7 +1684,7 @@ function renderStatus() {
if (agentStale()) {
return say(
"work",
"Plan2Code has not checked in for a few minutes. Your answers are saved. Have a look at your terminal (it may be happily working away, or waiting for your permission approval)."
"Still working on it. Longer tasks can go a few minutes between updates. Your answers are saved. If it stays quiet for a long while, check your terminal (it may be waiting on a permission approval)."
);
}
// Same clock as agentStale(), so the soft line at 30 s hands over to the
@@ -1602,8 +1702,8 @@ function renderStatus() {
return say(
"adrift",
stranded()
? "Plan2Code is not running. Your answers are saved and waiting for it. The terminal may be waiting for your permission approval."
: "Plan2Code is not running right now. Anything you answer here is saved. The terminal may be waiting for your permission approval."
? "Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval."
: "Plan2Code is not running right now. Anything you answer here is saved. If the terminal is idle, type **continue** there to wake it; it may also be waiting for your permission approval."
);
}
@@ -1740,7 +1840,7 @@ function renderViews() {
for (const t of tabs) {
const b = el("button", "view-tab", t.label);
b.type = "button";
b.setAttribute("aria-current", String(view === t.id));
b.setAttribute("aria-current", String(view === t.id || (t.id === "questions" && view === "end")));
if (t.count) {
const c = el("span", "tab-count", String(t.count));
b.appendChild(c);
@@ -1756,7 +1856,7 @@ function renderViews() {
chatDot = false;
save();
}
view = t.id;
view = t.id === "questions" && finish() ? "end" : t.id;
// The cached text paints at once; the fresh read repaints if the file
// changed on disk since.
render();
@@ -1821,16 +1921,20 @@ function renderSidebar() {
// session outline usually lives. The card that is mid-launch gets the
// half-filled mark the page uses for "sent, on its way".
if (isDashboard() && !fin) {
const menu = (S && S.menu) || {};
for (const g of CATALOG_GROUPS) {
const box = el("div", "rail-group");
const head = el("p", "rail-title");
head.appendChild(el("span", null, g.title));
box.appendChild(head);
for (const e of SKILL_CATALOG.filter((x) => x.group === g.id)) {
const av = cardAvailability(e, scan(), selSpec());
const av = cardPresentation(e, scan(), selSpec(), menu);
// Unavailable for the selected spec fades hard; the brief greying
// while a launch is in flight or the server is away does not.
const b = el("button", "rail-item" + (av.on ? "" : " is-unavailable"));
const b = el(
"button",
"rail-item" + (av.on ? "" : " is-unavailable") + (av.recommended ? " is-suggested" : "")
);
b.type = "button";
b.disabled = Boolean(local.launching) || gone || pendingResult || !av.on;
if (!av.on && av.reason) b.title = av.reason;
@@ -1845,6 +1949,13 @@ function renderSidebar() {
mark.title = isGoing ? "starting" : isPicked ? "picked" : "pick to start";
b.appendChild(mark);
b.appendChild(el("span", null, e.title));
// The center pane's own "Suggested" pill scrolls out of view, so the
// rail repeats the call-out here as a small dot next to the title.
if (av.recommended) {
const dot = el("span", "rail-suggested-dot", "");
dot.title = "Suggested next step";
b.appendChild(dot);
}
// Same as a card click: the pick goes to the confirm pane, never
// straight to a launch. From the Overview tab too, so the pane shows.
b.addEventListener("click", () => {
@@ -2465,6 +2576,34 @@ function renderDashboard(main) {
if (note) revealNote(note, wake.typed);
}
main.appendChild(wrap);
// Deferred: this runs inside render(), and the dialog is not part of it.
queueMicrotask(maybeWelcome);
}
/* ------------------------------------------------------------- welcome */
// The first dashboard a person ever sees gets a Welcome dialog. Closing it by
// any route (button, Esc, backdrop) saves looks.welcomeSeen, which rides in
// looks.json like every other preference. Waits out the wake-up animation and
// never lands on top of another open dialog.
function maybeWelcome() {
if (!looksReady || looks.welcomeSeen === true || !S || !isDashboard() || finish() || wake) return;
if (document.querySelector("dialog[open]")) return;
openWelcome();
}
function openWelcome() {
if ($("help-modal").open) $("help-modal").close();
const slot = $("welcome-bot");
if (!slot.firstElementChild) {
const bot = $("planny").cloneNode(true);
bot.removeAttribute("id");
bot.setAttribute("class", "planny is-point v1");
slot.appendChild(bot);
}
const dlg = $("welcome-modal");
if (!dlg.open) dlg.showModal();
$("welcome-done").focus();
}
/* ------------------------------------------------------------- wake-up */
@@ -2505,10 +2644,12 @@ function maybeWake() {
playWake({
stage,
bot: stage.querySelector(".wake-bot"),
skipEl: stage.querySelector(".wake-skip"),
target: $("planny"),
stir: stirWake,
onStart: () => sound("bootup"),
onGlide: wakeGlide,
onSkip: skipWakeSounds,
signal: wake.abort.signal,
}).then(({ skipped }) => {
stopSnore();
@@ -2541,6 +2682,14 @@ function stopSnore() {
snore = null;
}
// The Skip button: silence anything the intro already queued or started. The
// promise's .then does the snore and the bootup fade; this only clears cues
// still waiting to play.
function skipWakeSounds() {
soundQueued = null;
soundHeld = null;
}
// The glide: the menu rises in and the note starts typing. On a skip the run
// is already ending and its promise settles everything, so nothing here.
function wakeGlide({ instant }) {
@@ -2575,7 +2724,10 @@ function typeNote() {
// Done once the entrance has played and the note is all there. Nothing to
// redraw: what is on screen already is the finished dashboard.
function settleWake() {
if (wake && wake.entered && wake.typed == null) wake = null;
if (wake && wake.entered && wake.typed == null) {
wake = null;
maybeWelcome();
}
}
function finishWake() {
@@ -3206,6 +3358,34 @@ function inFlightFor(item) {
return sub ? { value: sub, summary: "" } : null;
}
// A sent note's attachments as links: an image opens full size, a document
// opens in its own tab. The page serves both by the upload's own file name.
function sentAttachments(note) {
const entries = [
...(note.images || []).map((e) => ({ ...e, kind: "image" })),
...(note.files || []).map((e) => ({ ...e, kind: "file" })),
];
if (!entries.length) return null;
const tray = el("div", "attach-tray");
for (const e of entries) {
const a = el("a", "attach-link");
a.href = uploadUrl(e);
a.target = "_blank";
a.rel = "noopener";
a.title = e.name || "attachment";
if (e.kind === "image") {
const fig = el("figure", "attach-thumb is-ready");
const pic = el("img");
pic.src = a.href;
pic.alt = e.name || "image";
fig.appendChild(pic);
a.appendChild(fig);
} else a.appendChild(docChip({ name: e.name || "file" }, "ready"));
tray.appendChild(a);
}
return tray;
}
function renderCard(item) {
const staged = local.staged[item.id];
const flight = inFlightFor(item);
@@ -3357,6 +3537,13 @@ function renderInFlight(card, item, flight) {
box.appendChild(ul);
}
if (text) box.appendChild(el("blockquote", "answered-text", text));
const note = noteAwaiting(item);
const sub = submittedAwaiting(item);
if (note && sub && note.at === sub.at) {
if (note.text) box.appendChild(el("blockquote", "answered-text", note.text));
const tray = sentAttachments(note);
if (tray) box.appendChild(tray);
}
// Say which of the two it actually is. Once the agent has collected the send,
// "waiting to be picked up" is no longer true, and a status line that lies is
@@ -3660,6 +3847,19 @@ function stageQuiet(id, value) {
save();
}
// The next answer for a click, carrying over the words typed on the card. Note
// boxes stage quietly, without a render, so the `staged` a builder closed over
// at render time can be missing everything typed since: read the live answer
// when the click lands instead. A click that clears the pick while text is
// still in the box keeps the text as a note on its own (`bare`), the same shape
// the note box stages when nothing is picked.
function withNote(item, value, bare = { type: "answer", kind: item.kind }) {
const cur = local.staged[item.id];
const text = cur && cur.text;
if (!text) return value;
return value ? { ...value, text } : { ...bare, text };
}
// Unique per question and option, and the same on every render.
const optionId = (item, o, i) => `pick-${item.id}-${o.k || i}`;
@@ -3724,12 +3924,18 @@ function buildMulti(card, item, staged) {
box.checked = on;
box.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
box.addEventListener("change", () => {
const next = new Set(chosen);
const cur = local.staged[item.id];
const next = new Set((cur && cur.ks) || []);
if (box.checked) next.add(o.k);
else next.delete(o.k);
// Unticking the last box keeps what is written in "Anything else".
stage(
item.id,
next.size ? { type: "answer", kind: "multi", ks: [...next], text: staged && staged.text } : null
withNote(item, next.size ? { type: "answer", kind: "multi", ks: [...next] } : null, {
type: "answer",
kind: "multi",
ks: [],
})
);
});
@@ -3772,7 +3978,14 @@ function renderPresets(card, item, staged) {
b.type = "button";
b.setAttribute("aria-pressed", String(on));
b.addEventListener("click", () =>
stage(item.id, on ? null : { type: "answer", kind: "multi", ks: [...p.ks], text: staged && staged.text })
stage(
item.id,
withNote(item, on ? null : { type: "answer", kind: "multi", ks: [...p.ks] }, {
type: "answer",
kind: "multi",
ks: [],
})
)
);
row.appendChild(b);
}
@@ -3858,6 +4071,20 @@ function buildText(card, item, staged) {
wrap.appendChild(templateRow(item, input, templatesFor(S.workflow, looks.role), check));
}
wrap.appendChild(input);
// Fresh-idea boxes take files as context, the same ones the note pane holds.
if (!single && TEMPLATE_WORKFLOWS.includes(S.workflow)) {
input.addEventListener("paste", (e) => {
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
if (!files.length) return;
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
attachFiles(item.id, files);
});
const under = attachRow(item.id, "Add files to this answer");
under.classList.add("is-under");
wrap.appendChild(under);
const attached = noteImages(item.id);
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
}
if (item.help) wrap.appendChild(el("p", "help", item.help));
wrap.appendChild(err);
card.appendChild(wrap);
@@ -3946,7 +4173,9 @@ function buildConfirm(card, item, staged) {
const on = staged && staged.yes === yes;
const b = el("button", "btn" + (on ? " primary" : "") + (danger && !on ? " danger" : ""), label);
b.type = "button";
b.addEventListener("click", () => stage(item.id, on ? null : { type: "answer", kind: "confirm", yes }));
b.addEventListener("click", () =>
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "confirm", yes }))
);
return b;
};
row.appendChild(mk(yesLabel, true, item.danger));
@@ -4031,7 +4260,7 @@ function buildReview(card, item, staged) {
const b = el("button", "btn" + (on ? " primary" : "") + (v.danger && !on ? " danger" : ""), verdictText(v));
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, on ? null : { type: "answer", kind: "review", verdict: v.id, text: staged && staged.text })
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }))
);
row.appendChild(b);
}
@@ -4044,6 +4273,15 @@ function buildReview(card, item, staged) {
function buildChecklist(card, item, staged) {
const doneSet = new Set((staged && staged.done) || []);
// Built from the live answer, so a note typed since the render rides along.
// Nothing ticked, no state and no note is no answer at all: stage nothing
// rather than an empty one that would still count as ready to send.
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
const list = el("ol", "steps");
(item.steps || []).forEach((step, i) => {
const li = el("li", "step");
@@ -4052,10 +4290,11 @@ function buildChecklist(card, item, staged) {
box.id = `step-${item.id}-${i}`;
box.checked = doneSet.has(i);
box.addEventListener("change", () => {
const next = new Set(doneSet);
const cur = local.staged[item.id];
const next = new Set((cur && cur.done) || []);
if (box.checked) next.add(i);
else next.delete(i);
stage(item.id, { ...(staged || { type: "answer", kind: "checklist" }), done: [...next] });
commitList({ done: [...next] });
});
const label = el("label");
label.htmlFor = box.id;
@@ -4079,14 +4318,7 @@ function buildChecklist(card, item, staged) {
const on = staged && staged.state === s.id;
const b = el("button", "btn" + (on ? " primary" : ""), s.label);
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, {
...(staged || { type: "answer", kind: "checklist" }),
type: "answer",
kind: "checklist",
state: on ? null : s.id,
})
);
b.addEventListener("click", () => commitList({ state: on ? null : s.id }));
row.appendChild(b);
}
card.appendChild(row);
@@ -4142,7 +4374,7 @@ function buildList(card, item, staged) {
const ul = el("ul", "rows");
let dragIndex = null;
const commit = (next) => stage(item.id, { type: "answer", kind: "list", rows: next });
const commit = (next) => stage(item.id, withNote(item, { type: "answer", kind: "list", rows: next }));
rows.forEach((row, i) => {
const li = el("li", "row-item");
@@ -4245,7 +4477,8 @@ function buildList(card, item, staged) {
if (staged) {
const reset = el("button", "linky", "Put it back how it was");
reset.type = "button";
reset.addEventListener("click", () => stage(item.id, null));
// Puts the rows back; a note typed below stays.
reset.addEventListener("click", () => stage(item.id, withNote(item, null)));
row.appendChild(reset);
}
card.appendChild(row);
@@ -4267,8 +4500,14 @@ function commentField(card, item, labelText, required) {
ta.addEventListener("input", () => {
setDraft(id, ta.value);
const cur = local.staged[item.id];
if (cur) stageQuiet(item.id, { ...cur, text: ta.value.trim() || undefined });
else if (ta.value.trim())
if (cur) {
const next = { ...cur, text: ta.value.trim() || undefined };
// Emptying the box of a note-only answer leaves nothing to send, so it
// unstages rather than counting as ready.
const empty = (v) => v == null || v === "" || (Array.isArray(v) && !v.length);
const bare = Object.keys(next).every((k) => k === "type" || k === "kind" || empty(next[k]));
stageQuiet(item.id, bare ? null : next);
} else if (ta.value.trim())
stageQuiet(item.id, { type: "answer", kind: item.kind, text: ta.value.trim() });
stagedChanged();
});
@@ -4424,8 +4663,8 @@ function askState() {
// frame for the moment after a 409 stale, before the new frame lands.
const askConversation = () => local.chat.conversation ?? askFrame().conversation;
// An upload's server path is `<session>/uploads/<uuid>.jpg`; the page serves
// it at /uploads/<uuid>.jpg.
// An upload's server path is `<session>/uploads/<uuid>.<ext>`; the page serves
// it at /uploads/<uuid>.<ext>.
const uploadUrl = (img) => img.url || "/uploads/" + String(img.path || "").split(/[\\/]/).pop();
function renderAsk(main) {
@@ -4983,7 +5222,7 @@ function renderAside() {
aside.appendChild(el("h2", null, "Notes on this"));
const thread = item.thread || [];
if (!thread.length) {
if (!thread.length && !(isOpen(item) && !finish() && noteAwaiting(item))) {
aside.appendChild(
el(
"p",
@@ -5004,6 +5243,21 @@ function renderAside() {
aside.appendChild(box);
}
// A note that has been sent but not yet picked up: shown at once, so the
// send is seen to have gone, and gone when the agent replies.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
if (waiting) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
box.appendChild(who);
if (waiting.text) box.appendChild(md(waiting.text, "md"));
const tray = sentAttachments(waiting);
if (tray) box.appendChild(tray);
aside.appendChild(box);
}
// A finished session has nobody left for a note to reach, so the box would
// be a place to type words that go nowhere.
if (!isOpen(item) || finish()) {
@@ -5018,24 +5272,7 @@ function renderAside() {
wrap.appendChild(label);
const attached = noteImages(item.id);
const addRow = el("div", "attach-row");
const addBtn = el("button", "btn small ghost", "+ Attach file");
addBtn.type = "button";
addBtn.setAttribute("aria-label", "Add files to this note");
addBtn.disabled = attached.length >= MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
addBtn.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(item.id, picker.files);
picker.value = "";
});
addRow.appendChild(addBtn);
addRow.appendChild(picker);
wrap.appendChild(addRow);
wrap.appendChild(attachRow(item.id, "Add files to this note"));
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
@@ -5079,8 +5316,8 @@ function pageIcon() {
return svg;
}
// A document in a tray: never an <img>, since documents are never served
// back. Icon, extension badge, name and size, and nothing to click but ×.
// A document in a tray: never an <img>, since a document is not a picture.
// Icon, extension badge, name and size; a sent one is wrapped in a link.
function docChip(entry, status) {
const ext = docExt(entry.name) || "";
const fig = el("figure", `attach-thumb attach-chip is-${status}`);
@@ -5096,6 +5333,29 @@ function docChip(entry, status) {
return fig;
}
// The + Attach file control and its hidden picker, for a note's box or a
// card's own. Files go to the item's note attachments either way.
function attachRow(itemId, ariaLabel) {
const row = el("div", "attach-row");
const btn = el("button", "btn small ghost", "+ Attach file");
btn.type = "button";
btn.setAttribute("aria-label", ariaLabel);
btn.disabled = noteImages(itemId).length >= MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
btn.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(itemId, picker.files);
picker.value = "";
});
row.appendChild(btn);
row.appendChild(picker);
return row;
}
function attachTray(itemId, attached) {
const tray = el("div", "attach-tray");
for (const img of attached) {
@@ -5220,8 +5480,8 @@ function setNoteImages(itemId, list) {
else delete local.images[itemId];
}
// Where an attachment is deleted from. Documents are never served back, so
// they have no `url`; their route is built from the path, as uploadUrl does.
// Where an attachment is deleted from. Documents have no `url`, so their
// route is built from the path, as uploadUrl does.
const deleteUrl = (entry) => entry.url || "/uploads/" + String(entry.path || "").split(/[\\/]/).pop();
// The files in a paste worth attaching: images and allowed documents. A paste
@@ -6461,7 +6721,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.md-table th, .md-table td { border: 1px solid #e4ddd1; padding: 8px 11px; text-align: left; }
.md-table th { background: #fbf9f6; font-weight: 600; }
.md-img { max-width: 100%; border-radius: 8px; }
.md a { color: #ae4f2b; }
.md a { color: #206cc3; }
@media print {
body { background: #fff; }
main { padding: 0; min-height: 0; }
@@ -6585,7 +6845,7 @@ function renderAbout() {
} else if (agentAdrift()) {
line.classList.add("is-bad");
line.textContent =
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there.";
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type continue there to wake it.";
} else {
line.classList.add("is-good");
line.textContent = "Right now: both halves are talking to each other.";
@@ -6594,6 +6854,18 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
try {
const res = await fetch("/version", { cache: "no-store" });
const { version } = res.ok ? await res.json() : {};
el.textContent = version ? "Plan2Code v" + version : "";
el.hidden = !version;
} catch {
el.hidden = true;
}
}
const HELP_MOODS = [
["point", "Your turn"],
["work", "Working"],
@@ -6683,6 +6955,7 @@ function openHelp() {
});
selectHelpTab(id);
renderAbout();
renderHelpVersion();
$("help-modal").showModal();
$("help-tab-" + id).focus();
}
@@ -6729,6 +7002,19 @@ function lightDismiss(dlg) {
lightDismiss($("looks-modal"));
lightDismiss($("help-modal"));
lightDismiss($("workspace-modal"));
lightDismiss($("welcome-modal"));
$("welcome-done").addEventListener("click", () => $("welcome-modal").close());
$("welcome-modal").addEventListener("close", () => {
if (looks.welcomeSeen !== true) {
looks.welcomeSeen = true;
saveLooks();
}
$("btn-about").focus();
});
$("help-panels").addEventListener("click", (e) => {
if (e.target.closest && e.target.closest('[data-action="welcome"]')) openWelcome();
});
$("btn-about").addEventListener("click", () => {
openHelp();
@@ -6757,6 +7043,8 @@ $("help-modal").addEventListener("keydown", (e) => {
$("btn-looks").addEventListener("click", () => {
renderSwatches();
setModelsStatus("", false);
loadModelsData();
$("looks-modal").showModal();
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
@@ -6764,7 +7052,7 @@ $("looks-modal").addEventListener("close", () => {
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET };
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
saveLooks();
render();
});
@@ -6812,6 +7100,101 @@ for (const box of document.querySelectorAll("input[data-sound]")) {
});
}
// Models: the launcher's menu. The built-in list ships with every install and is read-only
// here; what the person adds is saved to the server, which the launcher reads on its next run.
let modelsData = null;
let modelsTab = "claude";
function setModelsStatus(text, isError) {
const status = $("models-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function renderModels() {
for (const cli of ["claude", "devin"]) {
$("models-tab-" + cli).setAttribute("aria-pressed", String(cli === modelsTab));
}
const shipped = $("models-shipped");
const user = $("models-user");
shipped.replaceChildren();
user.replaceChildren();
if (!modelsData) {
setModelsStatus("Models could not be loaded.", true);
return;
}
for (const m of modelsData.shipped[modelsTab] || []) {
const row = el("div", "models-row locked");
row.append(el("span", null, m.id), el("span", null, m.label || ""));
shipped.appendChild(row);
}
const mine = modelsData.user[modelsTab];
mine.forEach((m, i) => {
const row = el("div", "models-row");
const id = el("input");
id.value = m.id;
id.placeholder = "Model id";
id.setAttribute("aria-label", "Model id");
const label = el("input");
label.value = m.label;
label.placeholder = "Name shown in the menu";
label.setAttribute("aria-label", "Name shown in the menu");
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
id.addEventListener("change", () => { m.id = id.value.trim(); saveModels(); });
label.addEventListener("change", () => { m.label = label.value.trim(); saveModels(); });
remove.addEventListener("click", () => {
mine.splice(i, 1);
saveModels();
renderModels();
});
row.append(id, label, remove);
user.appendChild(row);
});
}
async function saveModels() {
try {
const res = await fetch("/models", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ models: modelsData.user }),
});
const body = await res.json();
if (!res.ok) return setModelsStatus(body.error || "Could not save.", true);
setModelsStatus("Saved. Restart plan2code to use it.", false);
} catch {
setModelsStatus("Could not save.", true);
}
}
async function loadModelsData() {
try {
const res = await fetch("/models");
if (res.ok) modelsData = await res.json();
} catch {}
renderModels();
}
for (const cli of ["claude", "devin"]) {
$("models-tab-" + cli).addEventListener("click", () => {
modelsTab = cli;
renderModels();
});
}
$("models-add").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user[modelsTab].push({ id: "", label: "" });
renderModels();
$("models-user").querySelector(".models-row:last-child input")?.focus();
});
$("models-reset").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user = { claude: [], devin: [] };
saveModels();
renderModels();
});
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
@@ -24,10 +24,13 @@ export const DONE_AT_MS = 5000;
// 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 }) {
// out to the end with its sound; only `skipEl` (the muted Skip button, or the
// Escape key, for anyone without a mouse) and `signal` aborting (the page
// leaving the dashboard, dormant or mid-run) cut it short, as a skip.
// `onSkip` is the page's cue to silence the intro sounds
// once a skip lands. Under reduced motion nothing is shown and it resolves at
// once.
export function playWake({ stage, bot, target, skipEl, stir, onStart, onGlide, onSkip, signal }) {
return new Promise((resolve) => {
if (matchMedia("(prefers-reduced-motion: reduce)").matches || signal?.aborted) {
resolve({ skipped: false });
@@ -41,8 +44,18 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
if (e.target === bot && e.propertyName === "transform") end(false);
};
const skip = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through.
// The Skip button's events must reach it: the document handlers below run
// in the capture phase, ahead of the button's own click.
const hitsSkip = (e) => Boolean(skipEl && e.target instanceof Node && skipEl.contains(e.target));
const onSkipClick = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through;
// Escape skips, so the run can be left by keyboard too.
const swallow = (e) => {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
if (e.ctrlKey || e.metaKey || e.altKey) return;
e.preventDefault();
e.stopPropagation();
@@ -79,6 +92,8 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
document.removeEventListener("keydown", swallow, true);
bot.removeEventListener("transitionend", onGlideEnd);
signal?.removeEventListener("abort", skip);
skipEl?.removeEventListener("click", onSkipClick);
if (skipped) onSkip?.();
stage.hidden = true;
stage.classList.remove("dormant", "stirring", "booting", "gliding");
bot.style.removeProperty("--wake-glide");
@@ -89,6 +104,11 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
// 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) {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
e.preventDefault();
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
@@ -110,6 +130,7 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
document.addEventListener("pointerdown", start, true);
document.addEventListener("keydown", start, true);
skipEl?.addEventListener("click", onSkipClick);
signal?.addEventListener("abort", skip);
stage.hidden = false;
stage.classList.add("dormant");
@@ -211,13 +211,15 @@ export function shouldChime(prevDot, nextDot) {
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).
* Whether nobody is there to answer a chat message. A finished session's agent
* is often still listening through its last wait (the review and dashboard
* buttons on the hand-off card live as long as it does), so finish alone does
* not end the chat — going quiet does. Offline once the agent has been silent
* longer than the page would tolerate before calling it stuck (working) or
* adrift (anything else), which is also the only signal left once the server
* is gone.
*/
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);
@@ -57,6 +57,7 @@
</g>
</svg>
<p class="wake-hint">Click to wake Planny</p>
<button class="wake-skip" type="button">Skip</button>
</div>
<header class="topbar">
@@ -94,6 +95,8 @@
</button>
<div class="meter-pop" id="meter-pop" role="dialog" aria-label="Session meter" hidden>
<p class="meter-tip" id="meter-tip"></p>
<ul class="meter-list" id="meter-list" aria-label="What the points are made of" hidden></ul>
<div class="meter-fresh" id="meter-fresh" hidden></div>
<button type="button" class="linky" id="meter-help">What is this?</button>
</div>
</span>
@@ -128,13 +131,28 @@
title="Colors, theme and sound"
aria-label="Colors, theme and sound"
>
<!-- Three swatches, so the button says what it opens without a word. -->
<!-- A gear: ring, hub and eight teeth. -->
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<circle cx="5" cy="5.5" r="3.1" class="sw-a" />
<circle cx="11" cy="5.5" r="3.1" class="sw-b" />
<circle cx="8" cy="11" r="3.1" class="sw-c" />
<path class="gr-teeth" d="M12 8h2.6M8 12v2.6M4 8H1.4M8 4V1.4M10.83 10.83l1.84 1.84M5.17 10.83l-1.84 1.84M5.17 5.17L3.33 3.33M10.83 5.17l1.84-1.84" />
<circle cx="8" cy="8" r="4.2" class="gr-ring" />
<circle cx="8" cy="8" r="1.6" class="gr-hub" />
</svg>
</button>
<a
class="icon-btn"
id="btn-feedback"
href="https://github.com/jparkerweb/plan2code/issues/new/choose"
target="_blank"
rel="noopener noreferrer"
title="Report a bug or suggest an idea"
aria-label="Report a bug or suggest an idea (opens GitHub in a new tab)"
>
<!-- A megaphone: horn, handle and two sound waves. -->
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<path class="mg-body" d="M1.8 6.2h2.8L10.4 3v10L4.6 9.8H1.8z" />
<path class="mg-line" d="M4.6 9.8l.9 3.4h1.6l-.6-2.7M12.4 6.1a2.6 2.6 0 0 1 0 3.8M13.8 4.5a5 5 0 0 1 0 7" />
</svg>
</a>
</div>
<div class="topbar-row second">
<div class="row-left">
@@ -595,6 +613,9 @@
written and approving things, instead of typing it all into the
terminal.
</p>
<p>
New here? <button type="button" class="help-link" data-action="welcome">Show the welcome again</button>
</p>
<figure class="help-figure" data-figure="about">
<svg class="help-diagram" viewBox="0 0 560 160" role="img" aria-labelledby="hd-about-title hd-about-desc">
<title id="hd-about-title">You, this page, its program and Plan2Code, all on your machine</title>
@@ -680,7 +701,7 @@
A simplified outline of this page with six numbered areas, in the
same order as the sections below: 1, the top bar, with the title on
the left, the progress bar in the middle, the question mark and
swatch buttons on the right, and Stop session under the title;
gear buttons on the right, and Stop session under the title;
2, Planny and the outline down the left; 3, the view tabs, on the
top bar's second row at the right; 4, the question card in the
middle with Previous and Next under it; 5, the notes panel on the
@@ -738,10 +759,14 @@
"4 of 9 done" while something is being built.
</li>
<li>
The <strong>?</strong> button opens this Help, and the swatch button
The <strong>?</strong> button opens this Help, and the gear button
beside it opens <strong>User Preferences</strong>: your role first,
then your colors, theme, card width and sounds.
</li>
<li>
The <strong>megaphone</strong> button at the far right opens GitHub in a
new tab, where you can report a bug or suggest an idea.
</li>
<li>
<strong>Stop session</strong> ends the session and saves your place.
See "Stopping and finishing".
@@ -1339,7 +1364,8 @@
<p>
Each step you run here adds points: a plan or a set of documents
weighs more than a single answered question, and a built phase more
still. Click the ring to see the count. It is a rule of thumb, not a
still. Click the ring to see the count and a list of each step that added
points, with what it added. It is a rule of thumb, not a
reading of Plan2Code's real memory: long sessions tend to make it
miss things, and the ring is there to remind you.
</p>
@@ -1675,7 +1701,8 @@
</p>
<p>
If it stays quiet a couple of minutes longer, the line changes to
"Plan2Code has not checked in for a few minutes", with Planny still
"Still working on it. Longer tasks can go a few minutes between
updates", with Planny still
in his working pose. It may be busy, or still waiting on you in the
terminal; the terminal is where to look. A build that said a task may
take longer gets that long before the line changes.
@@ -1721,7 +1748,7 @@
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
Everything on the page works from the keyboard, and the swatch button
Everything on the page works from the keyboard, and the gear button
lets you make it look and sound the way you like.
</p>
<h4>Keyboard shortcuts</h4>
@@ -1761,7 +1788,7 @@
</p>
<h4>Your preferences</h4>
<p>
The swatch button at the top, beside <strong>?</strong>, opens
The gear button at the top, beside <strong>?</strong>, opens
<strong>User Preferences</strong>:
</p>
<ul>
@@ -1786,7 +1813,7 @@
</li>
<li>
<strong>Highlight color</strong>: one of
<span data-fact="accentCount">32</span>, rust to begin with. It marks
<span data-fact="accentCount">32</span>, ocean blue to begin with. It marks
what is yours to do, and Planny's star uses it while he works.
</li>
<li>
@@ -1936,6 +1963,29 @@
</div>
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
</fieldset>
<fieldset class="modal-ranges looks-models">
<legend>Models</legend>
<div class="models-tabs" role="group" aria-label="Which agent">
<button type="button" class="btn small ghost" id="models-tab-claude" aria-pressed="true">Claude</button>
<button type="button" class="btn small ghost" id="models-tab-devin" aria-pressed="false">Devin</button>
</div>
<div class="models-note">
<p><strong>You usually don't need to change this.</strong> Plan2Code ships an up-to-date model list with every release. Add a model here only when a new one comes out before Plan2Code has been updated.</p>
<ul>
<li>Restart <code>plan2code</code> to see a change in its model menu.</li>
<li>At any time, run <code>plan2code --model &lt;id&gt;</code>, or pick your model inside your agent before running a skill.</li>
<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>
<li>Devin models are limited to Low, Medium and High effort.</li>
</ul>
</div>
<div class="models-list" id="models-shipped" aria-label="Built-in models"></div>
<div class="models-list" id="models-user" aria-label="Models you added"></div>
<div class="models-actions">
<button type="button" class="btn small" id="models-add">Add a model</button>
<button type="button" class="btn small ghost" id="models-reset">Reset to default</button>
<span class="help" id="models-status" role="status"></span>
</div>
</fieldset>
<div class="modal-actions">
<button type="button" class="btn ghost" id="looks-reset">Back to default</button>
<button type="button" class="btn primary" id="looks-done">Done</button>
@@ -1994,10 +2044,61 @@
<div id="help-panels" class="help-panels"></div>
</div>
<div class="modal-actions">
<span class="help-version" id="help-version" hidden></span>
<button type="button" class="btn primary" id="help-done">Close</button>
</div>
</dialog>
<!-- Shown once, on the first dashboard a person sees. Closing it by any
route saves looks.welcomeSeen; Help's first tab reopens it. -->
<dialog class="modal welcome" id="welcome-modal" aria-labelledby="welcome-title">
<div class="welcome-poster">
<div class="welcome-sky" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i></div>
<!-- Planny is cloned in from #planny by app.js, so he is always the
same robot as the one in the dock. -->
<div class="welcome-bot" id="welcome-bot" aria-hidden="true"></div>
<p class="welcome-kicker">Plan2Code Web Console</p>
<h2 id="welcome-title">Ideas in. Working code out.</h2>
<p class="welcome-lead">
Answer questions, read what gets written and approve each step here,
instead of in the terminal. It runs on this machine only.
</p>
</div>
<div class="welcome-cols">
<div class="welcome-col">
<span class="welcome-dot is-accent">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3.5" y="9" width="12" height="9" rx="1.6" transform="rotate(-12 9.5 13.5)" /><rect x="8.5" y="6" width="12" height="9" rx="1.6" /></svg>
</span>
<h3>Pick a card</h3>
<p>Start with <strong>Suggested</strong>. Pathfinder for a foggy idea, Quick Task for something small.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-stage">
<svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><circle cx="10" cy="10" r="7" opacity="0.35" /><circle cx="10" cy="10" r="7" pathLength="100" stroke-dasharray="50 100" stroke-dashoffset="25" transform="rotate(-90 10 10)" /></svg>
</span>
<h3>Refresh at half way</h3>
<p>Once the session meter passes half, finish the step and start a new conversation.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-bare">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3.5" y="5" width="17" height="14" rx="2" /><path d="M7.5 10l3 2-3 2M12.5 14.5h4" /></svg>
</span>
<h3>Come back</h3>
<p><code>/plan2code</code> in your agent, or <code>plan2code</code> in any folder.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-plain">
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M12 8h2.6M8 12v2.6M4 8H1.4M8 4V1.4M10.83 10.83l1.84 1.84M5.17 10.83l-1.84 1.84M5.17 5.17L3.33 3.33M10.83 5.17l1.84-1.84" /><circle cx="8" cy="8" r="4.2" /><circle cx="8" cy="8" r="1.6" /></svg>
</span>
<h3>Get help</h3>
<p><kbd>?</kbd> opens Help. The gear holds your role, theme and sounds.</p>
</div>
</div>
<div class="modal-actions">
<button type="button" class="btn primary" id="welcome-done">Start building</button>
</div>
</dialog>
<dialog class="modal" id="stop-modal" aria-labelledby="stop-title">
<h2 id="stop-title">Stop this session?</h2>
<p class="modal-blurb" id="stop-blurb"></p>
@@ -35,23 +35,68 @@ export const RUN_EVENTS = new Set(Object.keys(WEIGHTS));
const weightOf = (key) => (Object.prototype.hasOwnProperty.call(WEIGHTS, key) ? WEIGHTS[key] : 0);
// What each scoring event is called in the meter's list of contributions.
const LAUNCH_LABELS = Object.freeze({
plan: "Plan started",
"revise-plan": "Revise plan started",
document: "Document started",
review: "Review started",
"quick-task": "Quick task started",
init: "Init started",
"init-update": "Init update started",
finalize: "Finalize started",
});
const RUN_LABELS = Object.freeze({
"pathfinder-chart": "Pathfinder map written",
"pathfinder-question": "Pathfinder question settled",
plan: "Plan drafted",
"revise-plan": "Plan revised",
document: "Spec documented",
"implement-phase": "Implement phase built",
"implement-review-phase": "Implement + Review phase built",
review: "Code review run",
"quick-task": "Quick task built",
init: "Init run",
"init-update": "Init update run",
finalize: "Finalize run",
handoff: "Handoff written",
});
// The unit a run names, from its ledger id ("L3:phase-2" -> "phase-2").
const unitOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(id.indexOf(":") + 1) : "");
/**
* The session's points, folded from ledger entries in order. An id seen
* before is skipped, so a repeated `post` never counts twice.
* What the count is made of: one { label, points } per ledger entry that
* scored, in order. An id seen before is skipped, so a repeated `post` never
* counts twice. Entries that weigh nothing are left out.
*/
export function pointsFrom(entries) {
export function breakdownFrom(entries) {
const seen = new Set();
let points = 0;
const rows = [];
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);
let points = 0;
let label = "";
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
points = weightOf(entry.workflow);
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
} else if (entry.kind === "run") {
points = weightOf(entry.event);
const unit = unitOf(entry.id);
label = (RUN_LABELS[entry.event] || entry.event) + (unit ? `: ${unit}` : "");
}
if (points > 0) rows.push({ label, points });
}
return points;
return rows;
}
/** The session's points, folded from ledger entries in order. */
export function pointsFrom(entries) {
return breakdownFrom(entries).reduce((sum, row) => sum + row.points, 0);
}
export const YELLOW_AT = 4;
@@ -94,5 +139,12 @@ export const RED_BANNER =
export function meterView(entries) {
const points = pointsFrom(entries);
const level = levelFor(points);
return { points, level, fraction: ringFraction(points), words: WORDS[level], tooltip: tooltipFor(points) };
return {
points,
level,
fraction: ringFraction(points),
words: WORDS[level],
tooltip: tooltipFor(points),
items: breakdownFrom(entries),
};
}
@@ -187,7 +187,7 @@ export const ACCENTS = {
},
};
export const DEFAULT_ACCENT = "rust";
export const DEFAULT_ACCENT = "ocean";
// 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
@@ -23,7 +23,8 @@ 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.
// Blocks javascript: and data: hrefs before they can reach the DOM, and a
// protocol-relative `//host` (or `/\host`), which leaves the page for another site.
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
}
@@ -103,6 +104,26 @@ function inlineInto(parent, tokens) {
}
}
// What a fenced code block offers beside Copy, from its first non-empty line:
// `'run'` gets a Run it button (git commands — the one kind a person keeps
// copying into Ask by hand), `'hint'` a muted note that pasting it into Ask
// may get the agent to run it, and `null` nothing extra. A leading `/` is a
// skill command for a new conversation, never a terminal command, so it gets
// neither.
const COMMAND_WORDS =
/^(git|node|npm|npx|pnpm|yarn|bun|deno|python3?|pip3?|brew|curl|wget|docker|kubectl|terraform|make|cmake|cargo|go|java|mvn|gradle|gh|aws|az|gcloud|jq|ssh|scp|rsync|chmod|chown|mkdir|cp|mv|rm|ls|cd|cat|echo|export|source|bash|sh|zsh|fish|pwsh|powershell|cmd|systemctl|service|apt|apt-get|dnf|yum|pacman|tar|unzip|zip)\b/i;
export function runHint(text) {
const firstLine = (text || "")
.split("\n")
.map((line) => line.trim())
.find((line) => line.length > 0);
if (!firstLine || firstLine.startsWith("/")) return null;
if (/^git(\s|$)/.test(firstLine)) return "run";
if (firstLine.startsWith("#!")) return "hint";
return COMMAND_WORDS.test(firstLine) ? "hint" : null;
}
function blockInto(parent, tokens) {
for (const t of tokens || []) {
switch (t.type) {
@@ -140,7 +161,16 @@ function blockInto(parent, tokens) {
// textContent, so a fenced block containing markup is inert.
pre.appendChild(el("code", null, t.text));
wrap.appendChild(copyButton(t.text, "md-copy"));
const hint = runHint(t.text);
if (hint === "run") {
const run = el("button", "md-run", "Run it");
run.type = "button";
wrap.appendChild(run);
}
wrap.appendChild(pre);
if (hint === "hint") {
wrap.appendChild(el("p", "md-run-hint", "The agent may be able to run this — paste it into the Ask tab"));
}
parent.appendChild(wrap);
break;
}
@@ -21,8 +21,11 @@ import {
CHAT_CURSOR_FILE,
CHAT_FILE,
LEDGER_FILE,
HERE,
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
@@ -44,6 +47,7 @@ import {
readWorkspace,
remoteWarning,
typedCount,
withStateLock,
writeJsonAtomic,
writeWorkspace,
} from "./lib.mjs";
@@ -84,6 +88,12 @@ if (typeof args.token !== "string" || !args.token) {
}
const TOKEN = args.token;
const PROJECT = args.project || process.cwd();
// The checkout this session runs in, from `open`. PROJECT is the folder that
// holds .git, which for a linked worktree is the MAIN checkout: the wrong
// folder to seed the workspace with or resolve a typed path against. A fresh
// `open` starts this server before it writes the state, so until the state is
// there this is the only place the worktree can come from.
const WORKTREE = typeof args.worktree === "string" ? args.worktree : "";
const IDLE_MS = Number(args["idle-ms"] || 30 * 60 * 1000);
const MAX_LIFE_MS = Number(args["max-life-ms"] || 4 * 60 * 60 * 1000);
@@ -96,12 +106,12 @@ const CURSOR_PATH = path.join(DIR, CHAT_CURSOR_FILE);
// Images and documents attached to notes and quick questions. Only ever named
// by the server (a UUID, plus `jpg` or an extension from DOC_TYPES), and only
// ever resolved inside this directory: the client's file name is a label.
// Only images are served back; a document is written, read by the agent from
// disk, and deleted, never handed to a browser.
// Images are served back as JPEG. A document is served under a fixed type
// (PDF, or text/plain for everything else, sandboxed and never sniffed), so
// the page can link it without ever letting a browser run it.
const UPLOADS_DIR = path.join(DIR, "uploads");
const UPLOAD_EXTS = ["jpg", ...Object.keys(DOC_TYPES)];
const EXT_ALT = UPLOAD_EXTS.join("|");
const UPLOAD_ROUTE = /^\/uploads\/([0-9a-f-]{36})\.jpg$/;
const UPLOAD_ANY_ROUTE = new RegExp(`^/uploads/([0-9a-f-]{36})\\.(${EXT_ALT})$`);
const UPLOAD_NAME = new RegExp(`^[0-9a-f-]{36}\\.(${EXT_ALT})$`);
@@ -216,7 +226,7 @@ const SERVABLE = new Set([
// live in it). A stat says whether anything moved; refreshing through
// checkState also means a request that sees a new state first still counts
// it as a new revision and tells every other tab. Callers must not mutate
// what this returns -- /submit clones before it edits.
// what this returns -- /submit edits a fresh read of its own, under the lock.
function readState() {
checkState();
return stateNow;
@@ -302,6 +312,10 @@ const foldPath = (p) => (FOLD_CASE ? p.toLowerCase() : p);
let workspaceSeen = { stamp: null, ws: null };
// The folder the session runs in: the state's own once it is written, else
// the one `open` passed on the command line. Null while neither is known.
const sessionWorktree = () => stateNow?.worktree || WORKTREE || null;
// The session's workspace, created with just the original folder when absent.
function workspaceNow() {
const stamp = fileStamp(WORKSPACE_PATH);
@@ -311,10 +325,15 @@ function workspaceNow() {
workspaceSeen = { stamp, ws };
return ws;
}
const fresh = initialWorkspace(stateNow?.worktree || PROJECT);
const root = sessionWorktree();
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
// Nor saved while the session's folder is unknown: PROJECT is only a guess
// (the main checkout, for a linked worktree), and the file, once written,
// is what every later read trusts.
if (!root) return fresh;
try {
saveWorkspace(fresh);
} catch {}
@@ -405,7 +424,7 @@ function nextFolderId(ws) {
function addFolder(ws, body) {
const raw = typeof body.path === "string" ? body.path.trim().replace(/^(["'])(.*)\1$/, "$2").trim() : "";
const input = raw.replace(/^~(?=$|[\\/])/, () => os.homedir());
const resolved = raw ? path.resolve(stateNow?.worktree || PROJECT, input) : "";
const resolved = raw ? path.resolve(sessionWorktree() || PROJECT, input) : "";
if (!resolved || !isFolder(resolved)) return [400, { reason: "not-a-folder" }];
const same = ws.folders.find((f) => foldPath(path.resolve(f.path)) === foldPath(resolved));
if (same) return [400, { reason: "duplicate", name: same.name }];
@@ -455,7 +474,7 @@ function removeFolder(ws, body) {
// Where the picker opens: beside the last folder added, else the original.
function pickerStart(ws) {
const added = ws.folders.filter((f) => !f.original);
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || PROJECT;
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || sessionWorktree() || PROJECT;
}
// One picker at a time. Spawned, never spawnSync: the dialog can sit open for
@@ -464,6 +483,8 @@ function pickerStart(ws) {
let pickerBusy = false;
function bootWorkspace() {
// Nothing to check yet: the first read once the state is written makes it.
if (!sessionWorktree() && !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
const remote = remoteWarning().remote || "";
if ((ws.remote || "") !== remote) {
@@ -541,9 +562,14 @@ function recordSubmitted(state, actions) {
if (!Array.isArray(state.items)) return;
const at = nowIso();
for (const action of actions) {
if (!action || typeof action !== "object" || action.type === "comment") continue;
if (!action || typeof action !== "object") continue;
const item = state.items.find((i) => i && i.id === action.i);
if (!item) continue;
if (action.type === "comment") {
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
continue;
}
const { i, type, ...rest } = action;
// JSON.parse makes "__proto__" an own property, and it would then be
// written back into state.json and re-read forever.
@@ -577,12 +603,13 @@ function timingSafeEq(a, b) {
return crypto.timingSafeEqual(ab, bb);
}
// Named per port. Cookies ignore the port, so every console on 127.0.0.1 shares
// one jar: under a single name, opening a second session overwrote the first
// one's cookie and locked its tab out.
function cookieName(port = PORT) {
return `p2c_console_${port}`;
}
// One cookie per port. Browsers scope cookies by host and ignore the port, so
// with one shared name every session on 127.0.0.1 wrote over the one before
// it, and the first session's tab went on sending the second one's token and
// got nothing but 403s. The port is what makes a session's origin its own, and
// a resumed server on a new port is reached again only through its /s/ link,
// which sets the cookie under the new name.
const cookieName = () => `p2c_console_${PORT}`;
function cookieToken(req) {
const raw = req.headers.cookie || "";
@@ -623,6 +650,47 @@ function touch() {
lastContact = Date.now();
}
const MODEL_CLIS = ["claude", "devin"];
const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/;
// Devin's XHigh and Max efforts are never offered, curated or added.
const MODEL_EFFORT_BLOCKED = /-(xhigh|max)$/i;
/**
* The user's added models: { claude: [{id,label}], devin: [...] }. Returns { models } or
* { error }. Blank rows are dropped; ids are trimmed and made unique per CLI; a label
* defaults to the id. Nothing else in the body survives.
*/
function cleanModels(input) {
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "models must be an object" };
const models = {};
for (const cli of MODEL_CLIS) {
const list = input[cli] == null ? [] : input[cli];
if (!Array.isArray(list) || list.length > 50) return { error: `${cli} must be a list of at most 50 models` };
const seen = new Set();
models[cli] = [];
for (const row of list) {
const id = String((row && row.id) ?? "").trim();
if (!id) continue;
if (!MODEL_ID.test(id)) return { error: `"${id}" is not a valid model id` };
if (MODEL_EFFORT_BLOCKED.test(id)) return { error: `"${id}": only Low, Medium and High efforts are allowed` };
if (seen.has(id)) continue;
seen.add(id);
const label = String((row && row.label) ?? "").trim().slice(0, 80) || id;
models[cli].push({ id, label });
}
}
return { models };
}
function shippedModels() {
const file = readJson(SHIPPED_MODELS_FILE, null) || {};
const out = {};
for (const cli of MODEL_CLIS) {
out[cli] = (Array.isArray(file[cli]) ? file[cli] : []).filter((m) => m && typeof m.id === "string");
}
return out;
}
/**
* Whittle a POSTed settings object down to what a settings file may hold.
* The page only sends { theme, accent } today, but the file is shared and
@@ -668,8 +736,8 @@ function asset(rel) {
// The saved highlight color, painted from the very first frame. The page's
// script owns the colors once it runs (applyLooks clears the attribute these
// hang off), but until then the only way to avoid flashing the default rust
// at someone who picked ocean is a stylesheet rule the server can switch on
// hang off), but until then the only way to avoid flashing the default ocean
// at someone who picked violet is a stylesheet rule the server can switch on
// with an attribute: the CSP forbids inline styles, and the colors live in
// palette.js, so they are generated from there rather than copied into CSS.
function accentCss() {
@@ -742,7 +810,10 @@ function renderIndex() {
// `$'` in the inserted text as patterns, and titles and state are free text.
return indexTemplate
.replace('<html lang="en">', () => `<html lang="en"${htmlAttrs}>`)
.replace("<title>Plan2Code Console</title>", () => `<title>${escHtml(title)} · Plan2Code</title>`)
.replace(
"<title>Plan2Code Console</title>",
() => `<title>${escHtml(title)} · #${escHtml(String(SID).slice(-6))} · Plan2Code</title>`
)
.replace('<h1 id="title">Plan2Code Console</h1>', () => `<h1 id="title">${escHtml(title)}</h1>`)
.replace(
'<span class="badge" id="badge">Pathfinder</span>',
@@ -821,7 +892,7 @@ const server = http.createServer((req, res) => {
302,
baseHeaders({
location: "/",
"set-cookie": `${cookieName(port)}=${TOKEN}; HttpOnly; SameSite=Strict; Path=/`,
"set-cookie": `${cookieName()}=${TOKEN}; HttpOnly; SameSite=Strict; Path=/`,
})
);
return res.end();
@@ -887,6 +958,14 @@ const server = http.createServer((req, res) => {
return;
}
if (pathname === "/version" && req.method === "GET") {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const version = readJson(file, {}).version;
if (typeof version === "string" && version) return json(res, 200, { version });
}
return json(res, 404, { error: "no version" });
}
if (pathname === "/state" && req.method === "GET") {
const state = readState();
if (!state) return json(res, 404, { error: "no state" });
@@ -957,7 +1036,10 @@ const server = http.createServer((req, res) => {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, 400, { error: "body must be JSON" });
const looks = cleanLooks(body && body.looks);
// `set` carries only the keys one tab changed, merged onto what is on
// disk, so a tab holding stale settings cannot undo another tab's change.
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
const looks = set ? { ...(readJson(LOOKS_FILE, null)?.looks || {}), ...set } : cleanLooks(body && body.looks);
if (!looks) return json(res, 400, { error: "looks must be an object of simple settings" });
try {
ensureDir(path.dirname(LOOKS_FILE));
@@ -969,6 +1051,29 @@ const server = http.createServer((req, res) => {
});
}
// The launcher's model menu: what ships (read-only here) and what the user added.
if (pathname === "/models" && req.method === "GET") {
const saved = readJson(USER_MODELS_FILE, null) || {};
const { models } = cleanModels(saved);
return json(res, 200, { shipped: shippedModels(), user: models || { claude: [], devin: [] } });
}
if (pathname === "/models" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, 400, { error: "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
try {
ensureDir(path.dirname(USER_MODELS_FILE));
writeJsonAtomic(USER_MODELS_FILE, models);
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, { ok: true, user: models });
});
}
if (pathname === "/upload" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
const contentType = String(req.headers["content-type"] || "");
@@ -1008,8 +1113,8 @@ const server = http.createServer((req, res) => {
}
// A document: the extension comes from the allow-list via its name, and
// the bytes have to agree with it. No `url` comes back, because a
// document is never served.
// the bytes have to agree with it. No `url` comes back: the page builds
// the link from the path, as it does for the delete route.
if (contentType.startsWith("application/octet-stream")) {
// The extension comes from the whole name: the label is cut at 200
// characters, and a long name would lose it there.
@@ -1033,11 +1138,11 @@ const server = http.createServer((req, res) => {
// Matched on the raw request line as well as the parsed path: URL parsing
// folds `..` segments away, and nothing that needed folding is an upload.
// GET serves images only; DELETE takes documents too.
// GET and DELETE take images and documents alike.
if (pathname.startsWith("/uploads/") || req.url.startsWith("/uploads/")) {
if (req.method === "GET") {
const m = UPLOAD_ROUTE.exec(req.url);
const file = m && m[0] === pathname ? uploadPath(m[1]) : null;
const m = UPLOAD_ANY_ROUTE.exec(req.url);
const file = m && m[0] === pathname ? uploadPath(m[1], m[2]) : null;
if (!file) return json(res, 404, { error: "not found" });
let buf;
try {
@@ -1045,7 +1150,15 @@ const server = http.createServer((req, res) => {
} catch {
return json(res, 404, { error: "not found" });
}
return send(res, 200, buf, "image/jpeg", { "cache-control": "private, max-age=86400" });
const ext = m[2];
if (ext === "jpg") return send(res, 200, buf, "image/jpeg", { "cache-control": "private, max-age=86400" });
const pdf = DOC_TYPES[ext].kind === "pdf";
// A sandboxed PDF cannot load the browser's viewer, and one needs no
// sandbox: text is the only thing a browser might otherwise run.
return send(res, 200, buf, pdf ? "application/pdf" : "text/plain; charset=utf-8", {
...(pdf ? {} : { "content-security-policy": "sandbox" }),
"cache-control": "private, max-age=86400",
});
}
if (req.method === "DELETE") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
@@ -1079,16 +1192,6 @@ const server = http.createServer((req, res) => {
if (badAttachments) {
return json(res, 400, { error: "a comment carries at most 5 attachments, each uploaded to this session" });
}
// One send is one agent turn. Writing over a result the agent has not
// collected yet destroys everything in it, and the loss is silent: two
// tabs, or one impatient second press, and an approval disappears.
if (pendingResult()) {
return json(res, 409, {
error: "pending",
message:
"Your last answers have not been picked up yet. Nothing is lost, they are still on their way.",
});
}
const result = {
type: "submit",
at: nowIso(),
@@ -1097,26 +1200,68 @@ const server = http.createServer((req, res) => {
actions: body.actions,
reply: body.reply || "",
};
// The result and the state change together, under the state lock: a
// `post` or an `open` landing in the middle of a send would otherwise
// write back a state read before it, and the send's record would go, or
// this write would carry an older state over the agent's new one.
let refused = null;
let written = null;
let agentWrote = false;
try {
// Atomic: the waiter polls this file and will land mid-write eventually.
writeJsonAtomic(RESULT_FILE, result);
written = withStateLock(DIR, () => {
// One send is one agent turn. Writing over a result the agent has not
// collected yet destroys everything in it, and the loss is silent: two
// tabs, or one impatient second press, and an approval disappears.
if (pendingResult()) {
refused = "pending";
return null;
}
try {
// Atomic: the waiter polls this file and will land mid-write eventually.
writeJsonAtomic(RESULT_FILE, result);
} catch (e) {
refused = String(e.message);
return null;
}
try {
// Read fresh from disk, never from the cache: an agent write the
// watcher has not reached yet is in the file and must be kept.
const text = fs.readFileSync(STATE_FILE, "utf8");
const state = JSON.parse(text);
agentWrote = text !== lastStateText;
state.phase = "submitted";
recordSubmitted(state, body.actions);
return { state, text: writeJsonAtomic(STATE_FILE, state) };
} catch {
// The answers are safe in result.json; the stamp is only a courtesy.
return null;
}
});
} catch (e) {
return json(res, 500, { error: String(e.message) });
refused = String(e.message);
}
if (refused === "pending") {
return json(res, 409, {
error: "pending",
message:
"Your last answers have not been picked up yet. Nothing is lost, they are still on their way.",
});
}
if (refused) return json(res, 500, { error: refused });
appendEvent(DIR, { type: "submit", rev, count: body.actions.length });
const current = readState();
if (current) {
// A copy: the cached state is what every other reader is handed.
const state = structuredClone(current);
state.phase = "submitted";
recordSubmitted(state, body.actions);
try {
// Account for our own write here rather than letting the watcher find
// it: the watcher reads a changed state.json as proof the AGENT is
// alive, and this write is not that.
adoptStateText(writeJsonAtomic(STATE_FILE, state), state);
rev++;
} catch {}
if (written) {
// Account for our own write here rather than letting the watcher find
// it: the watcher reads a changed state.json as proof the AGENT is
// alive, and this write is not that. An agent write it swept up on the
// way is, and is handled as the watcher would have handled it.
adoptStateText(written.text, written.state);
rev++;
if (agentWrote) {
agentSeenAt = Date.now();
try {
ensureConversation(written.state);
} catch {}
}
}
// Name the items that went. A page with OTHER answers staged should drop
// only what was sent, and a brief request is a submit carrying no answers
@@ -1282,15 +1427,21 @@ const server = http.createServer((req, res) => {
if (pathname === "/cancel" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
if (pendingResult()) return json(res, 409, { error: "pending", message: "A send is still on its way." });
const result = { type: "cancel", at: nowIso(), sid: SID, rev, actions: [], reply: "" };
// As /submit: a cancel that never reached disk must not tell the page it
// did, or the page stands down while the agent waits on forever.
// Under the state lock like a send, so `open` clearing a collected result
// can never take this one with it. As /submit: a cancel that never reached
// disk must not tell the page it did, or the page stands down while the
// agent waits on forever.
let pending = false;
try {
writeJsonAtomic(RESULT_FILE, result);
withStateLock(DIR, () => {
pending = pendingResult();
if (!pending) writeJsonAtomic(RESULT_FILE, result);
});
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
if (pending) return json(res, 409, { error: "pending", message: "A send is still on its way." });
appendEvent(DIR, { type: "cancel", rev });
broadcast("cancelled", { rev });
return json(res, 200, { ok: true });
@@ -1319,6 +1470,8 @@ const server = http.createServer((req, res) => {
// Treat a departure as "shorten the deadline", never as "exit now": the user
// may simply be reloading.
if (pathname === "/bye") {
// It moves the shutdown deadline, so only the page itself may send it.
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
if (clients.size === 0) lastContact = Date.now() - (IDLE_MS - 2 * 60 * 1000);
return json(res, 200, { ok: true });
}
@@ -1382,7 +1535,9 @@ function readRaw(req, limit, cb) {
/* ------------------------------------------------------- state watching */
// The agent writes state.json through `console.mjs post`. Watch the DIRECTORY,
// The agent writes state.json through `console.mjs post`, and the server only
// through /submit; both under the state lock (updateState() in lib.mjs), so
// neither can write back a state read before the other's. Watch the DIRECTORY,
// not the file: on Windows a watch on a file breaks the moment that file is
// replaced by rename, which is exactly what an atomic write does.
let watchTimer = null;
@@ -1490,7 +1645,9 @@ setInterval(() => {
// the server deciding to stop. Do not "optimise" this away.
setInterval(() => {
const idle = Date.now() - lastContact;
if (idle > IDLE_MS) {
// Answers nobody has collected yet keep the server up (bounded by MAX_LIFE_MS):
// exiting would strand the tab and the send it holds.
if (idle > IDLE_MS && !resultFlags().pending) {
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle });
process.exit(0);
}
@@ -0,0 +1,22 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-02",
"mode": "utility"
}
@@ -273,7 +273,7 @@ for whichever comes first:
| 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. |
| `wait` exit `20` | The server is gone, not necessarily the tab. Resume it (`open --resume <sid> --no-open --workflow <yours>`) and keep waiting. |
| 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:
@@ -406,15 +406,38 @@ post carries `"run": { "event": "implement-review-phase", "id": "phase-N" }`.
("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.
`"answer": { "verdict": "yes" }`) in the post that starts the build, and
open a **Build progress** tab in that same post, the way an Implement phase
gets its tasks tab. The plan's steps are the task list and `total` is their
number:
```jsonc
{
"stopWarning": "",
"items": [{ "id": "<the Build this plan? item's id>", "status": "answered", "answer": { "verdict": "yes" } }],
"headline": { "stage": "Building", "cleared": 0, "total": 4 },
"docs": [{ "id": "tasks", "title": "Build progress", "version": 1, "blocks": [
{ "id": "tasks", "state": "settled", "md": "- [ ] Step one\n- [ ] Step two\n- [ ] Step three\n- [ ] Step four" }
]}],
"agent": { "status": "working", "activity": "Step 1 of 4: step one", "quietMinutes": 10 }
}
```
Then post after every step, exactly as "While you build": bump the doc's
`version` and repost the whole list with that step ticked, raise
`headline.cleared`, and set `agent.activity` to the next step ("Step 2 of 4:
step two"). Never go silent for the whole build: a quick task with many steps
is the case this tab is for. Check for a Quick question between steps, and do
not call `wait` until the build is done.
- **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.
sign-off card to put it on — and `"dashboard": true`, so the finished screen
also offers **Back to the dashboard**. Both are required: a finish without
`dashboard` leaves the person on a dead end. Keep waiting for whichever
button is pressed, 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"`.
@@ -27,6 +27,12 @@ workflow still applies: the same questions, the same order, the same gates, the
same cap of three questions at a time, the same recap before anything is recorded.
You are not allowed to answer your own questions just because a form makes it easy.
> **The one rule that keeps the page alive: while the session is open, every
> turn ends on a `wait` call, never on text.** `wait` exit `10` means "nobody
> has answered yet", not "done": relay one line and run `wait` again in the
> same turn, as many times as it takes. A turn that ends without a `wait`
> running strands the person's next click. Details: The wait loop, below.
---
## Deciding whether to use it
@@ -172,7 +178,19 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
Do not poll faster than this. Do not spin on `status`. Exit 10 is not a finished
turn: never emit a final response or stop after an arbitrary number of slices;
relay one line and immediately call `wait` again. Do not give up: people step
away from a session and come back.
away from a session and come back. The same holds after a `finish`: keep
waiting (resuming the server on exit `20`) until the dashboard or done press
or about ten minutes with nothing, because the Ask tab stays live and its
messages only arrive through `wait`. Ending your turn earlier strands them.
**The turn never ends on a wait.** While a console session is open, including
after a finish that offers a button (Back to the dashboard, Review it now), the
last thing in every turn you take is a `wait` call, never a line of text. The
line you relay after exit `10` goes in the same turn as the next `wait`, so
write it and call `wait` straight after. A turn that ends with the session open
and no `wait` running is a bug the person feels at once: their button press
sits unread until they ask why. If you catch yourself about to write a closing
summary while the page is still open, call `wait` first.
**Collect promptly.** A question someone has sent is locked on the page for as
long as you are mid-turn on it: they can read, move around and answer the other
@@ -453,6 +471,14 @@ messages, `offline` when no agent is connected or the session has finished,
### Answering
**Every message gets a reply, always.** The Ask tab is the person talking to
you, and the page shows "working on the answer" until a reply lands. Never
leave one unanswered, whatever it asks and whatever mid-task you are in. When
a message asks you to do something, do it if you can, then say what happened; if
you will not, the reply says so and why. `post` and `wait` print
`unansweredChat` with a `warning` for every message handed over and not yet
replied to: treat that as a stop-and-reply.
1. Handle any card answers first, under the workflow's own rules.
2. Write the chat replies, in inbox order.
3. Send **one** `post` with the card updates and `chat: { replies: [...] }`.
@@ -510,8 +536,9 @@ enforces it, so never tell someone to keep asking past it.
proposal is a new reply.
- Hard limits: never touch the running skill's own files under
`specs/<idea>/` (`post` rejects a proposal that names them); run no commands
beyond read-only lookups; never commit; refuse a request outside these and
say why.
beyond read-only lookups, except one the person plainly asks you to run in
their message (a commit they spell out, a test run): run it, then report the
result in the reply; refuse anything else and say why, in the reply.
- Edits happen only at check-ins, never mid-task in a build.
```jsonc
@@ -715,8 +742,10 @@ review run from a build's review button stays in the build's session, under
its workflow: `building.md` → The review, mid-session. On completion the finish's `command` is the suggested
commit when fixes landed — filled in, in the AGENTS.md format, with
`"where": "When you are happy with it, commit it from your terminal:"` —
otherwise leave `command` out. A stop mid-review loses nothing on disk, so its
finish is the bare `/plan2code-review`.
otherwise leave `command` out. The completion finish carries `"dashboard": true`
so the finished screen offers **Back to the dashboard**; keep waiting for the
press. A stop mid-review loses nothing on disk, so its finish is the bare
`/plan2code-review` (a pause, so no dashboard button).
### Handoff (`handoff`)
@@ -892,6 +921,8 @@ Session meter) and `folderIssue` (Workspace → When a folder cannot be read).
### Every item
**Give every new question a new `id`.** An id names one question for the whole session. The server drops a stale `submitted` record if you reword a question under an old id, but never rely on it: a fresh id is the only unambiguous way to ask something new.
```jsonc
{
"id": "q7",
@@ -1141,7 +1172,7 @@ usual slices for up to about ten minutes:
| --- | --- |
| An action `{ "i": "__dashboard", "type": "dashboard" }` | `open --resume <sid> --no-open --workflow dashboard` (the resume re-runs the project scan), then ONE post with `"finish": null`, the `menu` payload and `"agent": { "status": "waiting" }`. Then read the dashboard skill (`~/.agents/skills/plan2code/SKILL.md`) and carry on as the dashboard from its "The menu" section, in this same conversation. The same action can also arrive before any finish, from the top bar's triangle: see Stop requests → "Back to the dashboard, mid-workflow". |
| An action `__review` or `__done` | As `building.md` says (quick task only). |
| `wait` exit `20` | They closed the tab. Do not resume: the session is over. |
| `wait` exit `20` | The server is gone, not necessarily the tab. `open --resume <sid> --no-open --workflow <yours>`, then keep waiting: their Ask messages and the dashboard button still need you. Give up only when the resume itself fails. |
| Nothing after about ten minutes | `stop` the server. The page swaps the button for the `/plan2code` command. |
### 2. Stop the server
@@ -54,6 +54,7 @@ import {
nowIso,
parseArgs,
pendingChatCount,
unansweredChat,
pendingWorkspaceChanges,
pidAlive,
print,
@@ -77,6 +78,7 @@ import {
sweepUploads,
switchWorkflow,
terminalLine,
updateState,
UPLOAD_MAX_AGE_MS,
validate,
validateChat,
@@ -88,6 +90,10 @@ import {
import { RUN_EVENTS } from "./public/meter.js";
import { changeLine } from "./public/workspace.js";
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
// still be one of our servers, so its pid gets no second look.
const MAX_SERVER_LIFE_MS = 4 * 60 * 60 * 1000;
const argv = process.argv.slice(2);
const cmd = argv[0];
const args = parseArgs(argv.slice(1));
@@ -102,8 +108,24 @@ function trace(what) {
/* ----------------------------------------------------------------- open */
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written by `open` alone, which starts every session: a
// `wait` or a `post` every few seconds need not rewrite it each time.
function leavePointer() {
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
}
async function cmdOpen() {
trace("open: start");
leavePointer();
const { project, worktree, branch } = repoRoots();
reapHandles(project);
trace("open: project found");
@@ -113,6 +135,11 @@ async function cmdOpen() {
let state;
// A new skill run for the meter: a fresh open, or a resume into another workflow.
let launched = true;
// Everything `open` does to a stored state, as a step it can take twice:
// once now, on the read below, so a bad payload is refused before anything
// starts, and again on a fresh read under the state lock when it writes, so
// a send the person made in between is kept rather than written over.
let reshape = (s) => s;
if (sid) {
sid = path.basename(sid);
@@ -120,27 +147,6 @@ async function cmdOpen() {
if (!fs.existsSync(dir)) die(`no session "${sid}" to resume`, 1);
state = readJson(path.join(dir, "state.json"));
if (!state) die(`session "${sid}" has no state`, 1);
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (state.finish && /^\s*paused\b/i.test(String(state.finish.headline || ""))) {
delete state.finish;
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
state.items = (state.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(state.items.map((i) => i.topic));
state.topics = (state.topics || []).filter((t) => liveTopics.has(t.id));
}
// A resume can also be a hand-off: the dashboard launches another skill
// into its own session, and the first thing that skill needs is for the
// page to stop being a dashboard. Letting the flags restate these fields
@@ -148,26 +154,51 @@ async function cmdOpen() {
// rather than a resume plus a whole extra post.
const switching = args.workflow && args.workflow !== state.workflow;
launched = Boolean(switching);
if (switching && (args.workflow === "dashboard" || state.workflow === "dashboard")) {
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. A skill run inline from another (a
// quick task's review) never passes the dashboard, so it keeps the page.
state = switchWorkflow(state, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
fs.rmSync(path.join(dir, "draft.json"), { force: true });
} else if (switching) state.workflow = args.workflow;
if (args.title) state.title = args.title;
if (args.spec) state.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete state.wake;
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. A skill run inline from another (a
// quick task's review) never passes the dashboard, so it keeps the page.
const hop = switching && (args.workflow === "dashboard" || state.workflow === "dashboard");
if (hop) fs.rmSync(path.join(dir, "draft.json"), { force: true });
reshape = (s) => {
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (s.finish && /^\s*paused\b/i.test(String(s.finish.headline || ""))) {
delete s.finish;
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
s.items = (s.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(s.items.map((i) => i.topic));
s.topics = (s.topics || []).filter((t) => liveTopics.has(t.id));
}
if (hop) {
s = switchWorkflow(s, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
} else if (switching) s.workflow = args.workflow;
if (args.title) s.title = args.title;
if (args.spec) s.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete s.wake;
return s;
};
} else {
sid = newSessionId();
// Named, not made: the folder is created once --file has passed, so a
@@ -185,22 +216,36 @@ async function cmdOpen() {
// Only a freshly opened dashboard plays Planny's wake-up.
if (args.workflow === "dashboard") state.wake = true;
}
// On every open, so a resume from another worktree refreshes both.
state.worktree = worktree;
state.branch = branch;
// A first payload's meter and folder reports, as `post` takes them: checked
// now, before anything is written, and appended once the launch is.
let openRun;
let openIssue;
let patch = null;
if (args.file) {
const patch = readJson(path.resolve(args.file));
patch = readJson(path.resolve(args.file));
if (!patch) die(`could not read --file ${args.file} as JSON`, 2);
({ run: openRun, folderIssue: openIssue } = patch);
delete patch.run;
delete patch.folderIssue;
}
const base = reshape;
const settle = (s) => {
s = base(s);
// On every open, so a resume from another worktree refreshes both.
s.worktree = worktree;
s.branch = branch;
return s;
};
reshape = (s) => (patch ? applyPatch(settle(s), patch) : settle(s));
state = settle(state);
if (patch) {
ledgerFromPost(dir, openRun, openIssue, state.workflow);
state = applyPatch(state, patch);
try {
state = applyPatch(state, patch);
} catch (e) {
die(e.message, 3);
}
const problems = validate(state);
if (problems.length) return failValidation(problems);
}
@@ -209,13 +254,15 @@ async function cmdOpen() {
// A fresh session needs a fresh server, and a server is a whole Node boot:
// the slowest thing `open` does, bar the browser. Start both now, before
// the scan and the state write, so their start-up runs alongside them
// instead of after. Neither can reach a page before the server is up, and
// the state is on disk long before that; the server reads it per request,
// never at boot.
// instead of after. The server does look at the state as it boots, and on
// a fresh session finds none yet: it takes the worktree from its command
// line, not from the state, and picks the state up on its first request or
// poll tick. No page can reach it before it is listening, and the state is
// on disk long before a browser gets there.
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null;
const reusable = existing && pidAlive(existing.pid) ? healthOk(existing) : Promise.resolve(false);
let boot = null;
if (!existing) boot = await startServer(project, sid, dir);
if (!existing) boot = await startServer(project, worktree, sid, dir);
// The dashboard's spec picker reads its inventory straight off the session
// state, so the scan belongs to `open` rather than to the agent: filesystem
@@ -223,23 +270,43 @@ async function cmdOpen() {
// never something a model has to remember to fetch. Rooted at the worktree's
// own top level: `project` is the common-dir key so linked worktrees share
// sessions, but each shows the specs on its own disk.
if (state.workflow === "dashboard") state.scan = scanProject(worktree);
const scan = state.workflow === "dashboard" ? scanProject(worktree) : null;
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
const carried = Boolean(waiting && !waiting.consumedAt);
// Under the state lock, which a send on the page takes too: the result and
// the state are read fresh here and the state is rebuilt from that read, so
// nothing the person sent since the read above is lost or stamped over.
let carried = false;
let written;
try {
written = updateState(dir, (fresh) => {
const next = fresh ? reshape(fresh) : state;
if (scan) next.scan = scan;
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) state.phase = "collecting";
writeJsonAtomic(path.join(dir, "state.json"), state);
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
carried = Boolean(waiting && !waiting.consumedAt);
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) next.phase = "collecting";
return next;
});
} catch (e) {
written = { error: e.message };
}
if (!written || written.error) {
// A server just started for this state would only serve a page that never starts.
if (boot) boot.kill();
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
@@ -288,14 +355,14 @@ async function cmdOpen() {
// A handle whose pid is alive but is not ours (the pid was reused) leaves
// this for last: nothing could be started until that was known.
let started = boot || (await startServer(project, sid, dir));
let started = boot || (await startServer(project, worktree, sid, dir));
let handle = await awaitHandle(started);
if (!handle && started.handoff) {
// The handover went wrong somewhere (a platform that will not pass the
// socket, a server that died taking it). Once more the old way, where
// the server binds its own port: slower, and certain.
started.kill();
started = await startServer(project, sid, dir, { handoff: false });
started = await startServer(project, worktree, sid, dir, { handoff: false });
handle = await awaitHandle(started);
}
if (!handle) {
@@ -372,7 +439,7 @@ function isFolder(p) {
* boot: a process's first listen() blocks for ~50ms on Windows while the
* socket stack loads, which is time the server spends booting anyway.
*/
async function startServer(project, sid, dir, { handoff = true } = {}) {
async function startServer(project, worktree, sid, dir, { handoff = true } = {}) {
const token = newToken();
const handlePath = handleFile(project, sid);
ensureDir(path.dirname(handlePath));
@@ -389,6 +456,9 @@ async function startServer(project, sid, dir, { handoff = true } = {}) {
`--session=${dir}`,
`--token=${token}`,
`--project=${project}`,
// The checkout the session runs in, which the state does not hold yet
// on a fresh open. See WORKTREE in server.mjs.
`--worktree=${worktree}`,
...(handoff ? ["--handoff"] : []),
...(args["idle-ms"] ? [`--idle-ms=${args["idle-ms"]}`] : []),
],
@@ -487,20 +557,37 @@ function cmdPost() {
delete patch.folderIssue;
const ledgerLines = ledgerFromPost(dir, run, folderIssue, before.workflow);
let next;
// The patch is applied to a fresh read under the state lock, never to the
// read above: a send the person made in between is in the file, and a write
// built on the older read would take it away. Nothing in here may exit, so
// the lock is always let go; a refusal is carried out and reported after.
let refused = null;
let problems = [];
let written;
try {
next = applyPatch(before, patch);
written = updateState(dir, (fresh) => {
if (!fresh) {
refused = ["that session has no state", 1];
return null;
}
let next;
try {
next = applyPatch(fresh, patch);
} catch (e) {
refused = [e.message, 3];
return null;
}
problems = validate(next);
if (!problems.length && patch.chat) problems = validateChat(next, readChat(dir));
return problems.length ? null : next;
});
} catch (e) {
die(e.message, 3);
die(e.message, 1);
}
const problems = validate(next);
if (refused) die(...refused);
if (problems.length) return failValidation(problems);
if (patch.chat) {
const chatProblems = validateChat(next, readChat(dir));
if (chatProblems.length) return failValidation(chatProblems);
}
const next = written.state;
writeJsonAtomic(statePath, next);
for (const line of ledgerLines) appendLedger(dir, line);
appendEvent(dir, { type: "post", items: (patch.items || []).length });
@@ -512,6 +599,7 @@ function cmdPost() {
items: next.items.length,
open,
phase: next.phase,
...unansweredNote(dir, next),
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
});
}
@@ -554,13 +642,15 @@ function ledgerFromPost(dir, run, issue, workflow) {
async function cmdWait() {
const dir = mustSession();
// A --seconds that is not a number would make the deadline NaN, and the
// slice would end at once with exit 10: a busy loop, not a wait.
// "240s" reads as 240. A --seconds with no number in it at all would make
// the deadline NaN, and the slice would end at once with exit 10: a busy
// loop, not a wait. So that is refused rather than guessed at.
const given = args.seconds;
if (given !== undefined && (typeof given !== "string" || !given.trim() || !Number.isFinite(Number(given)))) {
const asked = typeof given === "string" ? Number.parseFloat(given) : NaN;
if (given !== undefined && !Number.isFinite(asked)) {
die(`--seconds must be a number, got "${args.seconds}"`, 2);
}
const seconds = Math.max(5, Number(args.seconds || 240));
const seconds = Math.max(5, given === undefined ? 240 : asked);
const sid = path.basename(dir);
const project = projectRoot();
const resultPath = path.join(dir, "result.json");
@@ -580,6 +670,11 @@ async function cmdWait() {
// was a full read and parse every 400ms, which put up to 0.4s between the
// person pressing Send and the agent starting on it, on every single send.
let healthAt = 0;
// A busy server (right after a post, say) can miss one health check without
// being gone. Only a missing handle or dead pid is proof at once; a server
// that merely does not answer must fail three checks in a row, each with a
// longer look, before the slice ends with exit 20.
let healthMisses = 0;
// Null, not the current stamp: a result written between the check above and
// this line would otherwise read as already seen and wait out the slice.
let seen = null;
@@ -605,11 +700,17 @@ async function cmdWait() {
if (Date.now() - healthAt > 5000) {
healthAt = Date.now();
const handle = listHandles(project).find((h) => h.sid === sid);
if (!handle || !pidAlive(handle.pid) || !(await healthOk(handle))) {
if (!handle || !pidAlive(handle.pid)) {
print(serverGone(sid));
process.exitCode = 20;
return;
}
if (await healthOk(handle, 4000)) healthMisses = 0;
else if (++healthMisses >= 3) {
print(serverGone(sid));
process.exitCode = 20;
return;
} else healthAt = Date.now() - 3000; // look again in about 2s, not 5s
}
sleepSync(50);
}
@@ -630,7 +731,9 @@ async function cmdWait() {
staged,
url: handle ? handle.url : "",
message: "Waiting on your answer in the web console",
next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.",
pendingChat: 0,
...unansweredNote(dir, state),
// A workspace change alone never ends a slice: it rides on the next send.
pendingWorkspace: pendingWorkspaceChanges(dir).length,
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
@@ -638,11 +741,19 @@ async function cmdWait() {
process.exitCode = 10;
}
// Quick questions already handed over with no reply yet. Always empty when all are answered.
function unansweredNote(dir, state) {
const seqs = unansweredChat(dir, state);
return seqs.length
? { unansweredChat: seqs, warning: "Quick questions " + seqs.join(", ") + " have no reply yet and the page still shows them as pending. Reply to each now (chat.replies, re = seq): do what was asked when you can, or say why you will not." }
: {};
}
function serverGone(sid) {
return {
status: "server-gone",
sid,
message: "The console server is not running. Start it again with `open --resume` and give the person the new link.",
message: "The console server is not running. Start it again with `open --resume <sid> --no-open`, then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
};
}
@@ -943,10 +1054,13 @@ async function cmdStop() {
// reboot in the system temp directory, and PIDs get reused; without this
// check `stop --all` can kill an unrelated program that happens to have
// inherited the number. /health returning our own sid is the only proof:
// a young handle with a live pid is not, since the server may have died
// minutes ago and its number gone straight to something else. A server
// too wedged to answer /health still meets its own idle deadline.
if (!(await healthOk(h))) {
// a live pid and a young handle are not, since a server that died a
// minute ago leaves exactly that behind for any process to inherit. A
// busy server gets a second, longer look, and still has to answer as
// ours; one that does not is left alone, and only its handle goes.
const young = Date.now() - Date.parse(h.startedAt || 0) < MAX_SERVER_LIFE_MS;
const ours = (await healthOk(h)) || (young && pidAlive(h.pid) && (await healthOk(h, 5000)));
if (!ours) {
skipped++;
try {
fs.rmSync(h.handlePath, { force: true });
@@ -1074,18 +1188,6 @@ const COMMANDS = {
help: cmdHelp,
};
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written on every invocation, help and errors included.
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
// Say which Node is too old, rather than dying later inside a health check with
// "fetch is not defined". Whatever agent is driving this has to be able to read
// the failure, tell the person in one line, and carry on in the terminal.
@@ -1105,4 +1207,12 @@ if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
process.exit(2);
}
// A flag given with no value parses as `true`, and a boolean handed on as a
// path or a name crashes somewhere deep (path.basename(true) throws). Every
// flag that takes a value is checked once, here, and refused as bad usage.
const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "upload", "name", "from", "seconds", "limit", "idle-ms"];
for (const flag of VALUE_FLAGS) {
if (flag in args && typeof args[flag] !== "string") die(`--${flag} needs a value`, 2);
}
await COMMANDS[cmd]();
@@ -39,6 +39,13 @@ export const SESSIONS_DIR = path.join(HOME_DIR, "sessions");
// state: a browser ties localStorage to the origin, and the origin carries the
// ephemeral port, so the file under this dir is the only copy of a preference
// that survives the next session's new port.
// Model menus for the `plan2code` launcher. The shipped list (bin/models.json) is the
// authors' and is overwritten by every install; the user's additions (models.json) are
// theirs. The launcher reads both. PLAN2CODE_MODELS_DIR moves them, for tests.
const PLAN2CODE_DIR = process.env.PLAN2CODE_MODELS_DIR || path.join(os.homedir(), ".plan2code");
export const SHIPPED_MODELS_FILE = path.join(PLAN2CODE_DIR, "bin", "models.json");
export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
@@ -141,6 +148,91 @@ export function appendEvent(dir, event) {
return line;
}
/* ----------------------------------------------------- the state lock */
// state.json has two writers in two processes: console.mjs (`open` and `post`,
// the agent's side) and the server (`/submit` stamps the phase and records
// what was sent on each item). Each writer reads the file, changes it and
// writes it back, so two of them overlapping lose whichever wrote first. Every
// read-modify-write of state.json therefore runs under this lock, a file
// created with O_EXCL beside it. The sections it guards are a read, a merge
// and a write, milliseconds long, so a lock older than LOCK_STALE_MS, or one
// whose holder has died, is a crash left behind and is broken. The wait runs
// past the stale age, so a writer always gets in eventually.
export const STATE_LOCK_FILE = "state.json.lock";
const LOCK_STALE_MS = 5000;
const LOCK_WAIT_MS = 7000;
function lockStale(lock) {
try {
const st = fs.statSync(lock);
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) return true;
const pid = Number.parseInt(fs.readFileSync(lock, "utf8"), 10);
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && !pidAlive(pid);
} catch (err) {
// Gone between the failed create and this look: free, so try again.
return err.code === "ENOENT";
}
}
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn) {
const lock = path.join(dir, STATE_LOCK_FILE);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
try {
fd = fs.openSync(lock, "wx");
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
} catch {}
continue;
}
sleepSync(Math.min(5 * (attempt + 1), 50));
}
}
try {
try {
fs.writeSync(fd, String(process.pid));
} finally {
fs.closeSync(fd);
}
return fn();
} finally {
try {
fs.rmSync(lock, { force: true });
} catch {}
}
}
// The one way to change state.json: under the lock, read it fresh, hand it to
// fn (null when there is no state yet, with the raw text beside it), and write
// back whatever fn returns. A null return writes nothing. Returns the written
// state and its text, or null.
export function updateState(dir, fn) {
const file = path.join(dir, "state.json");
return withStateLock(dir, () => {
let text = null;
try {
text = fs.readFileSync(file, "utf8");
} catch {}
let state = null;
try {
state = text === null ? null : JSON.parse(text);
} catch {}
const next = fn(state, text);
if (!next) return null;
return { state: next, text: writeJsonAtomic(file, next) };
});
}
export function sleepSync(ms) {
// Node built-ins only, and this runs in short one-shot CLI commands.
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
@@ -827,6 +919,41 @@ const ITEM_DEFAULTS = {
thread: [],
};
// The question a card asks. If a patch rewrites any of these on a known id, it
// is a new question wearing an old id.
const QUESTION_FIELDS = ["kind", "title", "body", "options", "steps", "rows", "summary", "doc", "verdicts"];
/**
* Merge item patches by id, and keep a reused id from inheriting the person's
* old answer. `submitted` is the server's record of what they sent to the
* PREVIOUS question. When a patch changes what an item asks and doesn't itself
* settle it, that record (and any stale `answer`) is dropped, so the page shows
* the new question as open instead of "Sent, waiting for Plan2Code" forever.
*/
function dropStaleSubmissions(currentItems, before, patchList) {
const merged = mergeKeyed(currentItems, patchList, "id", ITEM_DEFAULTS, "items");
for (const entry of patchList) {
const prev = (before || []).find((x) => x.id === entry.id);
if (!prev || (prev.submitted === undefined && prev.answer === undefined)) continue;
const rewritten = QUESTION_FIELDS.some(
(f) => f in entry && JSON.stringify(entry[f]) !== JSON.stringify(prev[f]),
);
const settles = entry.status === "answered" || entry.status === "skipped" || "answer" in entry;
// A settled question edited in place (a typo in its body) stays settled; only an
// explicit reopen turns it into a new question.
const wasSettled = prev.status === "answered" || prev.status === "skipped";
// A different kind is never a typo fix: a multi turned confirm is another question.
const kindChanged = "kind" in entry && entry.kind !== prev.kind;
const reopens = entry.status === "open" || entry.status === "reopened" || kindChanged;
if (!rewritten || settles || (wasSettled && !reopens)) continue;
const item = merged.find((x) => x.id === entry.id);
if (wasSettled && !("status" in entry)) item.status = "open";
if (!("submitted" in entry)) delete item.submitted;
delete item.answer;
}
return merged;
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -868,7 +995,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = mergeKeyed(next.items, v, "id", ITEM_DEFAULTS, "items");
next.items = dropStaleSubmissions(next.items, state.items, v);
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1033,6 +1160,17 @@ export function validate(state) {
if ((item.kind === "choice" || item.kind === "multi") && !Array.isArray(item.options)) {
problems.push(`item "${item.id}" is a ${item.kind} and needs "options"`);
}
if ((item.kind === "choice" || item.kind === "multi") && Array.isArray(item.options)) {
for (const o of item.options) {
if (!o || typeof o.k !== "string" || !o.k.trim()) {
problems.push(`item "${item.id}" has an option with no "k" (its key, like "A")`);
} else if (typeof o.text !== "string" || !o.text.trim()) {
problems.push(
`item "${item.id}" option "${o.k}" needs "text" (the label) and optionally "detail". Options use "text"/"detail", not "label"/"desc".`
);
}
}
}
if (item.verdicts != null) {
if (!Array.isArray(item.verdicts) || !item.verdicts.length) {
problems.push(`item "${item.id}" "verdicts" must be a non-empty array of { id, label }`);
@@ -1051,16 +1189,18 @@ export function validate(state) {
if (item.templates != null && (item.kind !== "text" || item.templates !== "idea")) {
problems.push(`item "${item.id}" has "templates": only a text item can carry it, and its only value is "idea".`);
}
// The page compiles this to check the answer. One that will not compile
// is dropped there, so the check the agent asked for would silently not run.
// The page compiles it as the person types, and a pattern that does not
// compile throws there, on every keystroke, with nothing on screen to say why.
if (item.pattern != null) {
let compiles = typeof item.pattern === "string";
try {
if (compiles) new RegExp(item.pattern);
} catch {
compiles = false;
if (typeof item.pattern !== "string") {
problems.push(`item "${item.id}" "pattern" must be a string holding a JavaScript regular expression`);
} else {
try {
new RegExp(item.pattern);
} catch (e) {
problems.push(`item "${item.id}" "pattern" is not a valid JavaScript regular expression: ${e.message}`);
}
}
if (!compiles) problems.push(`item "${item.id}" "pattern" must be a string holding a valid JavaScript regular expression`);
}
const recs = (item.options || []).filter((o) => o.recommended);
if (recs.length > 1) problems.push(`item "${item.id}" marks ${recs.length} options recommended; at most one`);
@@ -1148,7 +1288,7 @@ export function validate(state) {
// server's record of an answer someone pressed Send on; if their own words
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
// would be rejected and the session would wedge with no way out.
const authored = state.items.map(({ submitted, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -1203,6 +1343,8 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
// chat.ndjson the server. One JSON line per entry: message / decision / reset.
// chat-cursor.json console.mjs. The last seq the agent was handed.
// state.json console.mjs `post`. The agent's replies, under chat.replies.
// (state.json as a whole has a second writer, the server's
// /submit, so every change to it goes through updateState().)
//
// The Workspace and the session meter follow the same rule, in files that
// switchWorkflow() never touches, so they carry across dashboard hops:
@@ -1351,6 +1493,19 @@ export function deliverableChat(entries) {
return entries.some((e) => e.kind !== "reset") ? entries : [];
}
// Things the person said that were handed over but never answered. The page keeps
// showing "working on the answer" for each until a reply lands, so the agent is
// told on every post and every wait slice until it has replied (a refusal is a reply).
export function unansweredChat(dir, state) {
const { conversation } = currentConversation(readChat(dir, 0));
const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re));
const cursor = readCursor(dir);
return readChat(dir, 0)
.filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation)
.filter((e) => e.seq <= cursor && !replied.has(e.seq))
.map((e) => e.seq);
}
// How many things the person said are still waiting to be collected.
export function pendingChatCount(dir, state) {
return collectChat(dir, state).filter((e) => e.kind !== "reset").length;
@@ -25,6 +25,7 @@ export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace"
export const WINDOWS_PICKER_SOURCE = `
using System;
using System.Runtime.InteropServices;
using System.Threading;
public static class Plan2CodeFolderPicker {
[ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
@@ -62,12 +63,40 @@ public static class Plan2CodeFolderPicker {
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
private static extern void SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid iid, out IShellItem item);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string className, string title);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int w, int h, uint flags);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int index);
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);
private static void Raise(string title) {
for (int i = 0; i < 100; i++) {
IntPtr hwnd = FindWindow(null, title);
if (hwnd != IntPtr.Zero) {
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
int h = Math.Min(750, GetSystemMetrics(1) - 80);
int x = (GetSystemMetrics(0) - w) / 2 + 40;
int y = (GetSystemMetrics(1) - h) / 2 + 40;
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
SetForegroundWindow(hwnd);
return;
}
Thread.Sleep(50);
}
}
public static string Pick(IntPtr owner, string title, string start) {
IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
try {
@@ -83,6 +112,9 @@ public static class Plan2CodeFolderPicker {
dialog.SetFolder(folder);
} catch (Exception) {}
}
Thread raiser = new Thread(delegate() { Raise(title); });
raiser.IsBackground = true;
raiser.Start();
int hr = dialog.Show(owner);
if (hr == ERROR_CANCELLED) return null;
Marshal.ThrowExceptionForHR(hr);
@@ -69,6 +69,22 @@ export function submittedAwaiting(item) {
return replied ? null : s;
}
/**
* The note (and its attachments) the person last sent on an item, while the
* agent has yet to say anything after it. The server records it as `sentNote`
* on every send, so the page can show it in the Notes pane and in the Sent
* box instead of letting it vanish into a send that shows no sign of arriving.
* Any thread message from the send onwards, or none with a clock to compare,
* means it has been picked up.
*/
export function noteAwaiting(item) {
const n = item && item.sentNote;
if (!n || typeof n !== "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -11,10 +11,10 @@
--ink-3: #8f8779;
--rule: #e4ddd1;
--rule-2: #cfc6b6;
--accent: #ae4f2b;
--accent-soft: #fbeee7;
--accent: #206cc3;
--accent-soft: #ecf2f9;
--accent-ink: #ffffff;
--accent-line: #dd9b7e;
--accent-line: #9ab4d3;
--ok: #2f6b45;
--ok-soft: #e4f0e8;
--stage: #9a6a12;
@@ -49,10 +49,10 @@
--ink-3: #8b8376;
--rule: #332e29;
--rule-2: #46403a;
--accent: #e8825a;
--accent-soft: #34211a;
--accent-ink: #1a120e;
--accent-line: #8a4f36;
--accent: #619fe5;
--accent-soft: #1a2533;
--accent-ink: #0c1117;
--accent-line: #3d5978;
--ok: #74c28f;
--ok-soft: #1c2d22;
--stage: #e0ab4c;
@@ -73,10 +73,10 @@
--ink-3: #8b8376;
--rule: #332e29;
--rule-2: #46403a;
--accent: #e8825a;
--accent-soft: #34211a;
--accent-ink: #1a120e;
--accent-line: #8a4f36;
--accent: #619fe5;
--accent-soft: #1a2533;
--accent-ink: #0c1117;
--accent-line: #3d5978;
--ok: #74c28f;
--ok-soft: #1c2d22;
--stage: #e0ab4c;
@@ -241,6 +241,19 @@ body {
}
.meter-pop[hidden] { display: none; }
.meter-tip { margin: 0 0 6px; font-size: 13px; color: var(--ink-2); }
.meter-list {
list-style: none; margin: 0 0 8px; padding: 6px 0 0;
border-top: 1px solid var(--rule);
max-height: 40vh; overflow-y: auto;
font-size: 12px; color: var(--ink-2);
}
.meter-list[hidden] { display: none; }
.meter-list li { display: flex; justify-content: space-between; gap: 16px; padding: 2px 0; }
.meter-fresh { margin: 0 0 8px; padding-top: 6px; border-top: 1px solid var(--rule); }
.meter-fresh[hidden] { display: none; }
.meter-fresh-text { margin: 0 0 6px; font-size: 12px; color: var(--ink-2); }
.meter-fresh-row .handoff-code { flex-basis: 180px; font-size: 12px; padding: 6px 10px; }
.meter-item-points { flex: none; font-weight: 600; color: var(--ink); font-variant-numeric: tabular-nums; }
.badge {
font-size: 11px;
@@ -652,6 +665,16 @@ h1 {
}
.wake.dormant .wake-hint { opacity: 1; }
/* Skip: muted, bottom right, so it never competes with the animation. */
.wake-skip {
position: absolute; right: 14px; bottom: 14px;
padding: 4px 12px; border: 1px solid var(--ink-3); border-radius: 4px;
background: transparent; color: var(--ink-3);
font: inherit; font-size: 0.8rem; letter-spacing: 0.08em; text-transform: uppercase;
cursor: pointer; opacity: 0.7;
}
.wake-skip:hover, .wake-skip:focus-visible { opacity: 1; color: var(--ink); border-color: var(--ink); }
/* 0.0 s, powered down: the resting state every beat starts from. Arms hang
slack against his sides, the star is shut and the smile not yet drawn. */
.wake-bot { filter: grayscale(1); opacity: 0.55; }
@@ -1132,6 +1155,20 @@ h1 {
.rail-mark { flex: none; width: 15px; text-align: center; font-size: 12px; color: var(--ink-3); margin-top: 1px; }
.rail-mark.done { color: var(--ok); }
.rail-mark.staged { color: var(--stage); font-weight: 700; }
/* Echoes the center pane's "Suggested" pill, which can scroll out of view;
the dot keeps the call-out visible while just scanning the rail. The
title grows to push the dot flush with the row's right edge. */
.rail-item > span:not(.rail-mark):not(.rail-suggested-dot) { flex: 1 1 auto; }
.rail-suggested-dot {
flex: none;
width: 7px;
height: 7px;
border-radius: 50%;
margin-top: 5px;
background: var(--accent);
}
.rail-item.is-suggested:not([aria-current="true"]) { color: var(--ink); }
.rail-mark.open { color: var(--accent); }
/* The session's own page, above the topic groups. It names the state it is
@@ -1618,7 +1655,7 @@ input[type="text"].invalid { border-color: var(--warn); }
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
}
#btn-send:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
.btn.ghost:hover { background: var(--panel-2); color: var(--ink); }
.btn.danger { border-color: var(--warn); color: var(--warn); }
@@ -1734,6 +1771,7 @@ input[type="text"].invalid { border-color: var(--warn); }
}
.attach-row { display: flex; align-items: center; margin: -4px 0 6px -13px; }
.attach-row.is-under { margin: 6px 0 4px -13px; }
.attach-tray { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }
.attach-thumb {
position: relative;
@@ -1784,6 +1822,10 @@ input[type="text"].invalid { border-color: var(--warn); }
font-size: 12.5px; font-weight: 600; color: var(--ink);
}
.attach-chip-size { color: var(--ink-2); font-size: 11.5px; }
.attach-link { color: inherit; text-decoration: none; border-radius: 8px; }
.attach-link:hover .attach-thumb, .attach-link:focus-visible .attach-thumb { border-color: var(--accent); }
.attach-link:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.msg.pending { border-style: dashed; border-color: var(--stage); background: transparent; }
.ask-row .attach-chip { padding-right: 10px; }
.footer-held { margin-top: 3px; color: var(--ink-2); font-size: 12.5px; }
@@ -1863,6 +1905,23 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
transition: opacity 0.12s;
}
.md-pre-wrap:hover .md-copy, .md-copy:focus { opacity: 1; }
/* Run it, on git blocks: Copy's twin, tucked under it so the wider
"Press Ctrl+C" fallback label can never collide. */
.md-run {
position: absolute; top: 34px; right: 8px;
font: 600 11.5px var(--sans);
background: var(--panel); color: var(--ink-2);
border: 1px solid var(--rule-2); border-radius: 6px;
padding: 4px 9px; cursor: pointer; opacity: 0;
transition: opacity 0.12s;
}
.md-pre-wrap:hover .md-run, .md-run:focus { opacity: 1; }
/* The muted nudge on other command-looking blocks, a caption under the block. */
.md-run-hint {
margin: -6px 2px 0;
font: 11px var(--sans); color: var(--ink-3);
opacity: 0.8;
}
.md-hr { border: 0; border-top: 1px solid var(--rule); margin: 20px 0; }
.md-table-wrap { overflow-x: auto; margin: 0 0 13px; }
.md-table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
@@ -1996,9 +2055,15 @@ kbd {
.icon-btn:hover .ab-mark, .icon-btn:hover .ab-dot { stroke: var(--accent); fill: none; }
.icon-btn:hover .ab-dot { fill: var(--accent); }
.icon-btn .sw-a { fill: var(--accent); }
.icon-btn .sw-b { fill: var(--ok); }
.icon-btn .sw-c { fill: var(--stage); }
a.icon-btn { box-sizing: border-box; text-decoration: none; }
.icon-btn .mg-body { fill: none; stroke: var(--ink-3); stroke-width: 1.4; stroke-linejoin: round; }
.icon-btn .mg-line { fill: none; stroke: var(--ink-2); stroke-width: 1.4; stroke-linecap: round; stroke-linejoin: round; }
.icon-btn:hover .mg-body, .icon-btn:hover .mg-line { stroke: var(--accent); }
.icon-btn .gr-teeth { fill: none; stroke: var(--ink-3); stroke-width: 2.2; }
.icon-btn .gr-ring { fill: none; stroke: var(--ink-3); stroke-width: 1.6; }
.icon-btn .gr-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
.icon-btn:hover .gr-teeth, .icon-btn:hover .gr-ring, .icon-btn:hover .gr-hub { stroke: var(--accent); }
/* ------------------------------------------------------------ swatches */
@@ -2132,7 +2197,8 @@ kbd {
flex-direction: column;
}
.modal.help[open] { display: flex; }
.modal.help .modal-actions { flex: none; margin-top: 16px; }
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
.help-layout {
display: grid;
@@ -2288,6 +2354,111 @@ kbd {
}
.modal::backdrop { background: rgba(0, 0, 0, 0.45); }
.modal h2 { font: 600 21px/1.25 var(--serif); margin: 0 0 10px; }
/* The Welcome: a dark poster with Planny, four columns, one button. */
.modal.welcome {
width: min(840px, calc(100vw - 32px));
max-width: none;
padding: 0;
overflow: hidden;
}
.modal.welcome[open] { display: flex; flex-direction: column; max-height: calc(100vh - 96px); }
.welcome-poster {
position: relative;
flex: none;
overflow: hidden;
padding: 52px 48px 40px;
text-align: center;
color: #fff;
background:
radial-gradient(circle at 50% 125%, color-mix(in srgb, var(--accent) 85%, #fff) 0, transparent 58%),
linear-gradient(180deg, #16181d, color-mix(in srgb, var(--accent) 50%, #16181d));
}
.welcome-sky i { position: absolute; width: 3px; height: 3px; border-radius: 50%; background: #fff; opacity: 0.55; }
.welcome-sky i:nth-child(1) { top: 18%; left: 11%; }
.welcome-sky i:nth-child(2) { top: 34%; left: 84%; }
.welcome-sky i:nth-child(3) { top: 12%; left: 66%; }
.welcome-sky i:nth-child(4) { top: 56%; left: 20%; }
.welcome-sky i:nth-child(5) { top: 62%; left: 91%; }
.welcome-sky i:nth-child(6) { top: 26%; left: 32%; width: 2px; height: 2px; }
.welcome-bot { display: flex; justify-content: center; }
/* The dock's own Planny, larger and in light ink for the dark poster. */
.welcome-bot .planny { width: 70px; height: 96px; }
.welcome-bot .planny .shell,
.welcome-bot .planny .smile,
.welcome-bot .planny .arm path { stroke: #f0ece5; }
.welcome-bot .planny .shell { fill: #1e2127; }
.welcome-bot .planny .arm circle,
.welcome-bot .planny .foot { fill: #f0ece5; }
.welcome-kicker {
margin: 20px 0 6px;
font-size: 12px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: rgba(255, 255, 255, 0.75);
}
.modal.welcome h2 { font: 600 38px/1.15 var(--serif); margin: 0 0 12px; color: #fff; }
.welcome-lead { margin: 0 auto; max-width: 52ch; font-size: 15px; line-height: 1.55; color: rgba(255, 255, 255, 0.85); }
.welcome-cols {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
min-height: 0;
overflow-y: auto;
padding: 34px 36px 8px;
text-align: center;
}
.welcome-col h3 { font: 600 15px/1.3 var(--sans); margin: 12px 0 4px; color: var(--ink); }
.welcome-col p { margin: 0; font-size: 13px; line-height: 1.5; color: var(--ink-2); }
.welcome-col strong { color: var(--ink); }
.welcome-col code {
font: 600 12px var(--mono);
padding: 1px 6px;
border-radius: 5px;
background: var(--accent-soft);
color: var(--accent);
}
.welcome-col kbd {
font: 600 11.5px var(--mono);
padding: 0 6px;
border-radius: 5px;
border: 1px solid var(--rule-2);
border-bottom-width: 2px;
background: var(--panel-2);
color: var(--ink);
}
.welcome-dot { display: inline-grid; place-items: center; width: 50px; height: 50px; border-radius: 50%; }
.welcome-dot svg {
width: 22px;
height: 22px;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.welcome-dot.is-accent { background: var(--accent-soft); color: var(--accent); }
.welcome-dot.is-stage { background: var(--stage-soft); color: var(--stage); }
.welcome-dot.is-plain { background: var(--panel-2); color: var(--ink-2); border: 1px solid var(--rule); }
.welcome-dot.is-ok { background: var(--ok-soft); color: var(--ok); }
.welcome-dot.is-bare { background: none; color: var(--ok); }
.welcome-dot.is-bare svg { width: 30px; height: 30px; }
.modal.welcome .modal-actions { flex: none; justify-content: center; margin: 0; padding: 24px 36px 36px; }
.modal.welcome .modal-actions .btn { padding: 12px 40px; font-size: 15px; border-radius: 999px; }
@media (max-width: 720px) {
.welcome-poster { padding: 36px 24px 28px; }
.modal.welcome h2 { font-size: 28px; }
.welcome-cols { grid-template-columns: 1fr 1fr; padding: 24px 20px 8px; }
}
.help-link {
background: none;
border: 0;
padding: 0;
font: inherit;
color: var(--accent);
text-decoration: underline;
cursor: pointer;
}
.help-link:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 2px; }
.modal-blurb { margin: 0 0 18px; color: var(--ink-2); font-size: 13.5px; }
.modal-ranges { border: 0; margin: 0; padding: 0; display: grid; gap: 8px; }
@@ -3190,3 +3361,24 @@ kbd {
.help-mood-bot, .help-mood-bot *, .help-mood-bot.is-work .eye { animation: none !important; }
#btn-send { animation: none; }
}
/* User Preferences: the launcher's model menu. */
.models-tabs { display: flex; gap: 6px; }
.models-tabs .btn[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
.models-note { font-size: 0.9em; opacity: 0.85; }
.models-note p, .models-note ul { margin: 0 0 6px; }
.models-note ul { padding-left: 18px; }
.models-list { display: grid; gap: 4px; max-height: 160px; overflow: auto; }
.models-list:empty { display: none; }
.models-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 6px; align-items: center; }
.models-row.locked { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); font-size: 0.88em; opacity: 0.75; }
.models-row input { min-width: 0; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* A word the person has to type, bold and in their highlight color so it
does not get lost in the status sentence. */
.agent-key {
color: var(--accent);
font-weight: 700;
}
@@ -10,7 +10,7 @@
// this, that reversibility is the whole point.
import { md, el, copyButton, selectContents } from "./render.js";
import { ACCENTS, DEFAULT_CARD_WIDTH, SOUND_EVENTS, cardWidth, soundKey, soundPrefs } from "./palette.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, SOUND_EVENTS, cardWidth, soundKey, soundPrefs } from "./palette.js";
import { activityLabel, workingLine } from "./labels.js";
import { playWake } from "./boot.js";
import {
@@ -64,6 +64,7 @@ import {
STOP_REPLY,
sentAnswer,
submittedAwaiting,
noteAwaiting,
suggestionFrom,
THUMB_EDGE,
turnGate,
@@ -128,7 +129,7 @@ const LOOKS_KEY = "p2c-console:looks";
// The per-event sound switches (SOUND_EVENTS) live in palette.js too.
const DEFAULT_LOOKS = {
theme: "system",
accent: "rust",
accent: DEFAULT_ACCENT,
sound: true,
...soundPrefs(null),
width: DEFAULT_CARD_WIDTH,
@@ -136,6 +137,8 @@ const DEFAULT_LOOKS = {
};
let looks = { ...DEFAULT_LOOKS };
let syncedLooks = null;
let looksReady = false;
function adoptLooks(saved) {
looks = { ...DEFAULT_LOOKS, ...saved };
@@ -178,25 +181,47 @@ async function syncLooks() {
}
if (saved && saved.looks && typeof saved.looks === "object") {
adoptLooks(saved.looks);
syncedLooks = { ...looks };
try {
localStorage.setItem(LOOKS_KEY, JSON.stringify(looks));
} catch {}
applyLooks();
renderSwatches();
} else if (localStorage.getItem(LOOKS_KEY)) {
pushLooks();
} else {
// Blocked storage throws on read, and that must not stop the page loading.
let held = false;
try {
held = Boolean(localStorage.getItem(LOOKS_KEY));
} catch {}
if (held) pushLooks();
}
looksReady = true;
// Not inline: with the server's copy in the page this runs before `S` exists.
setTimeout(maybeWelcome, 0);
}
// Fire-and-forget mirror. A failed POST costs nothing the next session would
// notice on this port; the localStorage copy still covers the reload case.
function pushLooks() {
try {
// Only what this tab changed since it last synced, so a tab with stale
// settings never overwrites another tab's change to a different key.
const set = {};
for (const [k, v] of Object.entries(looks)) if (!syncedLooks || syncedLooks[k] !== v) set[k] = v;
const before = syncedLooks;
const partial = Boolean(before);
if (partial && !Object.keys(set).length) return;
syncedLooks = { ...looks };
const body = partial ? { set } : { looks };
// A write that did not land must be sent again with the next change.
const undo = () => (syncedLooks = before);
fetch("/looks", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ looks }),
}).catch(() => {});
body: JSON.stringify(body),
})
.then((res) => res.ok || undo())
.catch(undo);
} catch {}
}
@@ -380,6 +405,24 @@ for (const evt of ["pointerdown", "keydown"]) {
});
}
// Run it, on a fenced git block (render.js): stage the block as the Ask
// draft and open the chat. The person still presses Send, so nothing runs
// on a stray click — the same fill-the-box pattern as the Ask starters.
document.addEventListener("click", (e) => {
const run = e.target.closest(".md-run");
if (!run) return;
const code = run.closest(".md-pre-wrap")?.querySelector("code");
if (!code || !code.textContent.trim()) return;
local.chat.draft = `run:\n${code.textContent}`;
view = "ask";
save();
render();
const ta = $("ask-input");
if (!ta) return;
ta.focus();
ta.setSelectionRange(ta.value.length, ta.value.length);
});
// The stars for Planny's flight, made once. Each gets its place and pace as
// custom properties set through the CSSOM: the CSP forbids style attributes
// in markup, and the stylesheet cannot roll dice. They sit still, invisible,
@@ -795,13 +838,16 @@ async function loadState() {
const res = await fetch("/state", { cache: "no-store" });
if (!res.ok) throw new Error(String(res.status));
const body = await res.json();
adopt(body);
// The server answers again: back to the stream, once the wait is up.
if (!es && pollTimer && Date.now() >= esRetryAt) {
clearInterval(pollTimer);
pollTimer = null;
connect();
// The same rev is the same state: adopting it again would redraw the page
// every few seconds while polling for nothing. Still proof of life, though.
if (S && typeof body.rev === "number" && body.rev === rev) {
lastContact = Date.now();
agentLastSeen = body.agentLastSeen || agentLastSeen;
markGone();
} else {
adopt(body);
}
retryStream();
} catch {
markGone();
}
@@ -1158,6 +1204,11 @@ function connect() {
esErrors = 0;
esRetryMs = ES_RETRY_MIN_MS;
lastContact = Date.now();
// Back on the stream: polling was only ever the stand-in.
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
};
es.onerror = () => {
esErrors++;
@@ -1179,6 +1230,18 @@ function startPolling() {
pollTimer = setInterval(loadState, 3000);
}
// While polling, every answer from the server is a cue to try the stream
// again, so polling lasts only as long as the outage did. Polling carries on
// while an attempt is open, so startPolling() never runs for a failed one; the
// wait is pushed back here instead, or a dead stream would be retried on every
// poll. One attempt at a time, since `es` is set while it is trying.
function retryStream() {
if (!pollTimer || es || Date.now() < esRetryAt) return;
esRetryAt = Date.now() + esRetryMs;
esRetryMs = Math.min(esRetryMs * 2, ES_RETRY_MAX_MS);
connect();
}
setInterval(() => {
fetch("/ping", { method: "POST" })
.then((r) => (r.ok ? r.json() : null))
@@ -1186,6 +1249,7 @@ setInterval(() => {
if (!body) return;
lastContact = Date.now();
agentLastSeen = body.agentLastSeen || agentLastSeen;
retryStream();
// A rev we have not seen means a state frame went missing -- a dropped
// SSE reconnect, a tab asleep in a background window. Ask for it rather
// than waiting for the next change to come along.
@@ -1442,6 +1506,31 @@ function renderMeter() {
$("meter-words").textContent = meterFrame.words;
pill.title = meterFrame.tooltip;
$("meter-tip").textContent = meterFrame.tooltip;
// What the points are made of: one row per piece of work that scored.
const list = $("meter-list");
const rows = Array.isArray(meterFrame.items) ? meterFrame.items : [];
list.hidden = !rows.length;
list.replaceChildren(
...rows.map((row) => {
const li = el("li");
li.appendChild(el("span", "meter-item-label", row.label));
li.appendChild(el("span", "meter-item-points", "+" + row.points));
return li;
})
);
// Once the session is past fresh, say how to start a new one.
const fresh = $("meter-fresh");
fresh.hidden = meterFrame.level === "green";
if (fresh.hidden || fresh.dataset.built) return;
fresh.dataset.built = "1";
const text = handoffText({ command: DASHBOARD_COMMAND });
const code = el("code", "handoff-code", text);
const row = el("div", "handoff-command meter-fresh-row");
row.append(code, copyButton(text, "btn small ghost handoff-copy", code));
fresh.append(
textWithCode("p", "meter-fresh-text", `To start a new session, run \`${DASHBOARD_COMMAND}\` in a new conversation:`),
row
);
}
function toggleMeterPop(open) {
@@ -1469,7 +1558,7 @@ function renderChrome() {
renderMeter();
$("title").textContent = S.title || "Session";
$("badge").textContent = workflowLabel(S.workflow);
document.title = (S.title || "Session") + " · Plan2Code";
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
const h = S.headline || {};
// On a finished session an open item is frozen: the send on it counts as
@@ -1529,7 +1618,18 @@ function renderStatus() {
moodVar = Math.floor(Math.random() * MOOD_VARIANTS[mood]);
}
bot.setAttribute("class", `planny is-${mood} v${moodVar}`);
if (text.textContent !== line) text.textContent = line;
if (text.dataset.line !== line) {
text.dataset.line = line;
text.replaceChildren(
...line.split(/\*\*(.+?)\*\*/).map((part, i) => {
if (i % 2 === 0) return document.createTextNode(part);
const key = document.createElement("strong");
key.className = "agent-key";
key.textContent = part;
return key;
})
);
}
tick.textContent = count || "";
$("agent-spin").hidden = !spin;
$("dock").classList.toggle("is-flying", Boolean(spin));
@@ -1584,7 +1684,7 @@ function renderStatus() {
if (agentStale()) {
return say(
"work",
"Plan2Code has not checked in for a few minutes. Your answers are saved. Have a look at your terminal (it may be happily working away, or waiting for your permission approval)."
"Still working on it. Longer tasks can go a few minutes between updates. Your answers are saved. If it stays quiet for a long while, check your terminal (it may be waiting on a permission approval)."
);
}
// Same clock as agentStale(), so the soft line at 30 s hands over to the
@@ -1602,8 +1702,8 @@ function renderStatus() {
return say(
"adrift",
stranded()
? "Plan2Code is not running. Your answers are saved and waiting for it. The terminal may be waiting for your permission approval."
: "Plan2Code is not running right now. Anything you answer here is saved. The terminal may be waiting for your permission approval."
? "Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval."
: "Plan2Code is not running right now. Anything you answer here is saved. If the terminal is idle, type **continue** there to wake it; it may also be waiting for your permission approval."
);
}
@@ -1740,7 +1840,7 @@ function renderViews() {
for (const t of tabs) {
const b = el("button", "view-tab", t.label);
b.type = "button";
b.setAttribute("aria-current", String(view === t.id));
b.setAttribute("aria-current", String(view === t.id || (t.id === "questions" && view === "end")));
if (t.count) {
const c = el("span", "tab-count", String(t.count));
b.appendChild(c);
@@ -1756,7 +1856,7 @@ function renderViews() {
chatDot = false;
save();
}
view = t.id;
view = t.id === "questions" && finish() ? "end" : t.id;
// The cached text paints at once; the fresh read repaints if the file
// changed on disk since.
render();
@@ -1821,16 +1921,20 @@ function renderSidebar() {
// session outline usually lives. The card that is mid-launch gets the
// half-filled mark the page uses for "sent, on its way".
if (isDashboard() && !fin) {
const menu = (S && S.menu) || {};
for (const g of CATALOG_GROUPS) {
const box = el("div", "rail-group");
const head = el("p", "rail-title");
head.appendChild(el("span", null, g.title));
box.appendChild(head);
for (const e of SKILL_CATALOG.filter((x) => x.group === g.id)) {
const av = cardAvailability(e, scan(), selSpec());
const av = cardPresentation(e, scan(), selSpec(), menu);
// Unavailable for the selected spec fades hard; the brief greying
// while a launch is in flight or the server is away does not.
const b = el("button", "rail-item" + (av.on ? "" : " is-unavailable"));
const b = el(
"button",
"rail-item" + (av.on ? "" : " is-unavailable") + (av.recommended ? " is-suggested" : "")
);
b.type = "button";
b.disabled = Boolean(local.launching) || gone || pendingResult || !av.on;
if (!av.on && av.reason) b.title = av.reason;
@@ -1845,6 +1949,13 @@ function renderSidebar() {
mark.title = isGoing ? "starting" : isPicked ? "picked" : "pick to start";
b.appendChild(mark);
b.appendChild(el("span", null, e.title));
// The center pane's own "Suggested" pill scrolls out of view, so the
// rail repeats the call-out here as a small dot next to the title.
if (av.recommended) {
const dot = el("span", "rail-suggested-dot", "");
dot.title = "Suggested next step";
b.appendChild(dot);
}
// Same as a card click: the pick goes to the confirm pane, never
// straight to a launch. From the Overview tab too, so the pane shows.
b.addEventListener("click", () => {
@@ -2465,6 +2576,34 @@ function renderDashboard(main) {
if (note) revealNote(note, wake.typed);
}
main.appendChild(wrap);
// Deferred: this runs inside render(), and the dialog is not part of it.
queueMicrotask(maybeWelcome);
}
/* ------------------------------------------------------------- welcome */
// The first dashboard a person ever sees gets a Welcome dialog. Closing it by
// any route (button, Esc, backdrop) saves looks.welcomeSeen, which rides in
// looks.json like every other preference. Waits out the wake-up animation and
// never lands on top of another open dialog.
function maybeWelcome() {
if (!looksReady || looks.welcomeSeen === true || !S || !isDashboard() || finish() || wake) return;
if (document.querySelector("dialog[open]")) return;
openWelcome();
}
function openWelcome() {
if ($("help-modal").open) $("help-modal").close();
const slot = $("welcome-bot");
if (!slot.firstElementChild) {
const bot = $("planny").cloneNode(true);
bot.removeAttribute("id");
bot.setAttribute("class", "planny is-point v1");
slot.appendChild(bot);
}
const dlg = $("welcome-modal");
if (!dlg.open) dlg.showModal();
$("welcome-done").focus();
}
/* ------------------------------------------------------------- wake-up */
@@ -2505,10 +2644,12 @@ function maybeWake() {
playWake({
stage,
bot: stage.querySelector(".wake-bot"),
skipEl: stage.querySelector(".wake-skip"),
target: $("planny"),
stir: stirWake,
onStart: () => sound("bootup"),
onGlide: wakeGlide,
onSkip: skipWakeSounds,
signal: wake.abort.signal,
}).then(({ skipped }) => {
stopSnore();
@@ -2541,6 +2682,14 @@ function stopSnore() {
snore = null;
}
// The Skip button: silence anything the intro already queued or started. The
// promise's .then does the snore and the bootup fade; this only clears cues
// still waiting to play.
function skipWakeSounds() {
soundQueued = null;
soundHeld = null;
}
// The glide: the menu rises in and the note starts typing. On a skip the run
// is already ending and its promise settles everything, so nothing here.
function wakeGlide({ instant }) {
@@ -2575,7 +2724,10 @@ function typeNote() {
// Done once the entrance has played and the note is all there. Nothing to
// redraw: what is on screen already is the finished dashboard.
function settleWake() {
if (wake && wake.entered && wake.typed == null) wake = null;
if (wake && wake.entered && wake.typed == null) {
wake = null;
maybeWelcome();
}
}
function finishWake() {
@@ -3206,6 +3358,34 @@ function inFlightFor(item) {
return sub ? { value: sub, summary: "" } : null;
}
// A sent note's attachments as links: an image opens full size, a document
// opens in its own tab. The page serves both by the upload's own file name.
function sentAttachments(note) {
const entries = [
...(note.images || []).map((e) => ({ ...e, kind: "image" })),
...(note.files || []).map((e) => ({ ...e, kind: "file" })),
];
if (!entries.length) return null;
const tray = el("div", "attach-tray");
for (const e of entries) {
const a = el("a", "attach-link");
a.href = uploadUrl(e);
a.target = "_blank";
a.rel = "noopener";
a.title = e.name || "attachment";
if (e.kind === "image") {
const fig = el("figure", "attach-thumb is-ready");
const pic = el("img");
pic.src = a.href;
pic.alt = e.name || "image";
fig.appendChild(pic);
a.appendChild(fig);
} else a.appendChild(docChip({ name: e.name || "file" }, "ready"));
tray.appendChild(a);
}
return tray;
}
function renderCard(item) {
const staged = local.staged[item.id];
const flight = inFlightFor(item);
@@ -3357,6 +3537,13 @@ function renderInFlight(card, item, flight) {
box.appendChild(ul);
}
if (text) box.appendChild(el("blockquote", "answered-text", text));
const note = noteAwaiting(item);
const sub = submittedAwaiting(item);
if (note && sub && note.at === sub.at) {
if (note.text) box.appendChild(el("blockquote", "answered-text", note.text));
const tray = sentAttachments(note);
if (tray) box.appendChild(tray);
}
// Say which of the two it actually is. Once the agent has collected the send,
// "waiting to be picked up" is no longer true, and a status line that lies is
@@ -3660,6 +3847,19 @@ function stageQuiet(id, value) {
save();
}
// The next answer for a click, carrying over the words typed on the card. Note
// boxes stage quietly, without a render, so the `staged` a builder closed over
// at render time can be missing everything typed since: read the live answer
// when the click lands instead. A click that clears the pick while text is
// still in the box keeps the text as a note on its own (`bare`), the same shape
// the note box stages when nothing is picked.
function withNote(item, value, bare = { type: "answer", kind: item.kind }) {
const cur = local.staged[item.id];
const text = cur && cur.text;
if (!text) return value;
return value ? { ...value, text } : { ...bare, text };
}
// Unique per question and option, and the same on every render.
const optionId = (item, o, i) => `pick-${item.id}-${o.k || i}`;
@@ -3724,12 +3924,18 @@ function buildMulti(card, item, staged) {
box.checked = on;
box.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
box.addEventListener("change", () => {
const next = new Set(chosen);
const cur = local.staged[item.id];
const next = new Set((cur && cur.ks) || []);
if (box.checked) next.add(o.k);
else next.delete(o.k);
// Unticking the last box keeps what is written in "Anything else".
stage(
item.id,
next.size ? { type: "answer", kind: "multi", ks: [...next], text: staged && staged.text } : null
withNote(item, next.size ? { type: "answer", kind: "multi", ks: [...next] } : null, {
type: "answer",
kind: "multi",
ks: [],
})
);
});
@@ -3772,7 +3978,14 @@ function renderPresets(card, item, staged) {
b.type = "button";
b.setAttribute("aria-pressed", String(on));
b.addEventListener("click", () =>
stage(item.id, on ? null : { type: "answer", kind: "multi", ks: [...p.ks], text: staged && staged.text })
stage(
item.id,
withNote(item, on ? null : { type: "answer", kind: "multi", ks: [...p.ks] }, {
type: "answer",
kind: "multi",
ks: [],
})
)
);
row.appendChild(b);
}
@@ -3858,6 +4071,20 @@ function buildText(card, item, staged) {
wrap.appendChild(templateRow(item, input, templatesFor(S.workflow, looks.role), check));
}
wrap.appendChild(input);
// Fresh-idea boxes take files as context, the same ones the note pane holds.
if (!single && TEMPLATE_WORKFLOWS.includes(S.workflow)) {
input.addEventListener("paste", (e) => {
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
if (!files.length) return;
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
attachFiles(item.id, files);
});
const under = attachRow(item.id, "Add files to this answer");
under.classList.add("is-under");
wrap.appendChild(under);
const attached = noteImages(item.id);
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
}
if (item.help) wrap.appendChild(el("p", "help", item.help));
wrap.appendChild(err);
card.appendChild(wrap);
@@ -3946,7 +4173,9 @@ function buildConfirm(card, item, staged) {
const on = staged && staged.yes === yes;
const b = el("button", "btn" + (on ? " primary" : "") + (danger && !on ? " danger" : ""), label);
b.type = "button";
b.addEventListener("click", () => stage(item.id, on ? null : { type: "answer", kind: "confirm", yes }));
b.addEventListener("click", () =>
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "confirm", yes }))
);
return b;
};
row.appendChild(mk(yesLabel, true, item.danger));
@@ -4031,7 +4260,7 @@ function buildReview(card, item, staged) {
const b = el("button", "btn" + (on ? " primary" : "") + (v.danger && !on ? " danger" : ""), verdictText(v));
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, on ? null : { type: "answer", kind: "review", verdict: v.id, text: staged && staged.text })
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }))
);
row.appendChild(b);
}
@@ -4044,6 +4273,15 @@ function buildReview(card, item, staged) {
function buildChecklist(card, item, staged) {
const doneSet = new Set((staged && staged.done) || []);
// Built from the live answer, so a note typed since the render rides along.
// Nothing ticked, no state and no note is no answer at all: stage nothing
// rather than an empty one that would still count as ready to send.
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
const list = el("ol", "steps");
(item.steps || []).forEach((step, i) => {
const li = el("li", "step");
@@ -4052,10 +4290,11 @@ function buildChecklist(card, item, staged) {
box.id = `step-${item.id}-${i}`;
box.checked = doneSet.has(i);
box.addEventListener("change", () => {
const next = new Set(doneSet);
const cur = local.staged[item.id];
const next = new Set((cur && cur.done) || []);
if (box.checked) next.add(i);
else next.delete(i);
stage(item.id, { ...(staged || { type: "answer", kind: "checklist" }), done: [...next] });
commitList({ done: [...next] });
});
const label = el("label");
label.htmlFor = box.id;
@@ -4079,14 +4318,7 @@ function buildChecklist(card, item, staged) {
const on = staged && staged.state === s.id;
const b = el("button", "btn" + (on ? " primary" : ""), s.label);
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, {
...(staged || { type: "answer", kind: "checklist" }),
type: "answer",
kind: "checklist",
state: on ? null : s.id,
})
);
b.addEventListener("click", () => commitList({ state: on ? null : s.id }));
row.appendChild(b);
}
card.appendChild(row);
@@ -4142,7 +4374,7 @@ function buildList(card, item, staged) {
const ul = el("ul", "rows");
let dragIndex = null;
const commit = (next) => stage(item.id, { type: "answer", kind: "list", rows: next });
const commit = (next) => stage(item.id, withNote(item, { type: "answer", kind: "list", rows: next }));
rows.forEach((row, i) => {
const li = el("li", "row-item");
@@ -4245,7 +4477,8 @@ function buildList(card, item, staged) {
if (staged) {
const reset = el("button", "linky", "Put it back how it was");
reset.type = "button";
reset.addEventListener("click", () => stage(item.id, null));
// Puts the rows back; a note typed below stays.
reset.addEventListener("click", () => stage(item.id, withNote(item, null)));
row.appendChild(reset);
}
card.appendChild(row);
@@ -4267,8 +4500,14 @@ function commentField(card, item, labelText, required) {
ta.addEventListener("input", () => {
setDraft(id, ta.value);
const cur = local.staged[item.id];
if (cur) stageQuiet(item.id, { ...cur, text: ta.value.trim() || undefined });
else if (ta.value.trim())
if (cur) {
const next = { ...cur, text: ta.value.trim() || undefined };
// Emptying the box of a note-only answer leaves nothing to send, so it
// unstages rather than counting as ready.
const empty = (v) => v == null || v === "" || (Array.isArray(v) && !v.length);
const bare = Object.keys(next).every((k) => k === "type" || k === "kind" || empty(next[k]));
stageQuiet(item.id, bare ? null : next);
} else if (ta.value.trim())
stageQuiet(item.id, { type: "answer", kind: item.kind, text: ta.value.trim() });
stagedChanged();
});
@@ -4424,8 +4663,8 @@ function askState() {
// frame for the moment after a 409 stale, before the new frame lands.
const askConversation = () => local.chat.conversation ?? askFrame().conversation;
// An upload's server path is `<session>/uploads/<uuid>.jpg`; the page serves
// it at /uploads/<uuid>.jpg.
// An upload's server path is `<session>/uploads/<uuid>.<ext>`; the page serves
// it at /uploads/<uuid>.<ext>.
const uploadUrl = (img) => img.url || "/uploads/" + String(img.path || "").split(/[\\/]/).pop();
function renderAsk(main) {
@@ -4983,7 +5222,7 @@ function renderAside() {
aside.appendChild(el("h2", null, "Notes on this"));
const thread = item.thread || [];
if (!thread.length) {
if (!thread.length && !(isOpen(item) && !finish() && noteAwaiting(item))) {
aside.appendChild(
el(
"p",
@@ -5004,6 +5243,21 @@ function renderAside() {
aside.appendChild(box);
}
// A note that has been sent but not yet picked up: shown at once, so the
// send is seen to have gone, and gone when the agent replies.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
if (waiting) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
box.appendChild(who);
if (waiting.text) box.appendChild(md(waiting.text, "md"));
const tray = sentAttachments(waiting);
if (tray) box.appendChild(tray);
aside.appendChild(box);
}
// A finished session has nobody left for a note to reach, so the box would
// be a place to type words that go nowhere.
if (!isOpen(item) || finish()) {
@@ -5018,24 +5272,7 @@ function renderAside() {
wrap.appendChild(label);
const attached = noteImages(item.id);
const addRow = el("div", "attach-row");
const addBtn = el("button", "btn small ghost", "+ Attach file");
addBtn.type = "button";
addBtn.setAttribute("aria-label", "Add files to this note");
addBtn.disabled = attached.length >= MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
addBtn.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(item.id, picker.files);
picker.value = "";
});
addRow.appendChild(addBtn);
addRow.appendChild(picker);
wrap.appendChild(addRow);
wrap.appendChild(attachRow(item.id, "Add files to this note"));
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
@@ -5079,8 +5316,8 @@ function pageIcon() {
return svg;
}
// A document in a tray: never an <img>, since documents are never served
// back. Icon, extension badge, name and size, and nothing to click but ×.
// A document in a tray: never an <img>, since a document is not a picture.
// Icon, extension badge, name and size; a sent one is wrapped in a link.
function docChip(entry, status) {
const ext = docExt(entry.name) || "";
const fig = el("figure", `attach-thumb attach-chip is-${status}`);
@@ -5096,6 +5333,29 @@ function docChip(entry, status) {
return fig;
}
// The + Attach file control and its hidden picker, for a note's box or a
// card's own. Files go to the item's note attachments either way.
function attachRow(itemId, ariaLabel) {
const row = el("div", "attach-row");
const btn = el("button", "btn small ghost", "+ Attach file");
btn.type = "button";
btn.setAttribute("aria-label", ariaLabel);
btn.disabled = noteImages(itemId).length >= MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
btn.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(itemId, picker.files);
picker.value = "";
});
row.appendChild(btn);
row.appendChild(picker);
return row;
}
function attachTray(itemId, attached) {
const tray = el("div", "attach-tray");
for (const img of attached) {
@@ -5220,8 +5480,8 @@ function setNoteImages(itemId, list) {
else delete local.images[itemId];
}
// Where an attachment is deleted from. Documents are never served back, so
// they have no `url`; their route is built from the path, as uploadUrl does.
// Where an attachment is deleted from. Documents have no `url`, so their
// route is built from the path, as uploadUrl does.
const deleteUrl = (entry) => entry.url || "/uploads/" + String(entry.path || "").split(/[\\/]/).pop();
// The files in a paste worth attaching: images and allowed documents. A paste
@@ -6461,7 +6721,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.md-table th, .md-table td { border: 1px solid #e4ddd1; padding: 8px 11px; text-align: left; }
.md-table th { background: #fbf9f6; font-weight: 600; }
.md-img { max-width: 100%; border-radius: 8px; }
.md a { color: #ae4f2b; }
.md a { color: #206cc3; }
@media print {
body { background: #fff; }
main { padding: 0; min-height: 0; }
@@ -6585,7 +6845,7 @@ function renderAbout() {
} else if (agentAdrift()) {
line.classList.add("is-bad");
line.textContent =
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there.";
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type continue there to wake it.";
} else {
line.classList.add("is-good");
line.textContent = "Right now: both halves are talking to each other.";
@@ -6594,6 +6854,18 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
try {
const res = await fetch("/version", { cache: "no-store" });
const { version } = res.ok ? await res.json() : {};
el.textContent = version ? "Plan2Code v" + version : "";
el.hidden = !version;
} catch {
el.hidden = true;
}
}
const HELP_MOODS = [
["point", "Your turn"],
["work", "Working"],
@@ -6683,6 +6955,7 @@ function openHelp() {
});
selectHelpTab(id);
renderAbout();
renderHelpVersion();
$("help-modal").showModal();
$("help-tab-" + id).focus();
}
@@ -6729,6 +7002,19 @@ function lightDismiss(dlg) {
lightDismiss($("looks-modal"));
lightDismiss($("help-modal"));
lightDismiss($("workspace-modal"));
lightDismiss($("welcome-modal"));
$("welcome-done").addEventListener("click", () => $("welcome-modal").close());
$("welcome-modal").addEventListener("close", () => {
if (looks.welcomeSeen !== true) {
looks.welcomeSeen = true;
saveLooks();
}
$("btn-about").focus();
});
$("help-panels").addEventListener("click", (e) => {
if (e.target.closest && e.target.closest('[data-action="welcome"]')) openWelcome();
});
$("btn-about").addEventListener("click", () => {
openHelp();
@@ -6757,6 +7043,8 @@ $("help-modal").addEventListener("keydown", (e) => {
$("btn-looks").addEventListener("click", () => {
renderSwatches();
setModelsStatus("", false);
loadModelsData();
$("looks-modal").showModal();
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
@@ -6764,7 +7052,7 @@ $("looks-modal").addEventListener("close", () => {
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET };
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
saveLooks();
render();
});
@@ -6812,6 +7100,101 @@ for (const box of document.querySelectorAll("input[data-sound]")) {
});
}
// Models: the launcher's menu. The built-in list ships with every install and is read-only
// here; what the person adds is saved to the server, which the launcher reads on its next run.
let modelsData = null;
let modelsTab = "claude";
function setModelsStatus(text, isError) {
const status = $("models-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function renderModels() {
for (const cli of ["claude", "devin"]) {
$("models-tab-" + cli).setAttribute("aria-pressed", String(cli === modelsTab));
}
const shipped = $("models-shipped");
const user = $("models-user");
shipped.replaceChildren();
user.replaceChildren();
if (!modelsData) {
setModelsStatus("Models could not be loaded.", true);
return;
}
for (const m of modelsData.shipped[modelsTab] || []) {
const row = el("div", "models-row locked");
row.append(el("span", null, m.id), el("span", null, m.label || ""));
shipped.appendChild(row);
}
const mine = modelsData.user[modelsTab];
mine.forEach((m, i) => {
const row = el("div", "models-row");
const id = el("input");
id.value = m.id;
id.placeholder = "Model id";
id.setAttribute("aria-label", "Model id");
const label = el("input");
label.value = m.label;
label.placeholder = "Name shown in the menu";
label.setAttribute("aria-label", "Name shown in the menu");
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
id.addEventListener("change", () => { m.id = id.value.trim(); saveModels(); });
label.addEventListener("change", () => { m.label = label.value.trim(); saveModels(); });
remove.addEventListener("click", () => {
mine.splice(i, 1);
saveModels();
renderModels();
});
row.append(id, label, remove);
user.appendChild(row);
});
}
async function saveModels() {
try {
const res = await fetch("/models", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ models: modelsData.user }),
});
const body = await res.json();
if (!res.ok) return setModelsStatus(body.error || "Could not save.", true);
setModelsStatus("Saved. Restart plan2code to use it.", false);
} catch {
setModelsStatus("Could not save.", true);
}
}
async function loadModelsData() {
try {
const res = await fetch("/models");
if (res.ok) modelsData = await res.json();
} catch {}
renderModels();
}
for (const cli of ["claude", "devin"]) {
$("models-tab-" + cli).addEventListener("click", () => {
modelsTab = cli;
renderModels();
});
}
$("models-add").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user[modelsTab].push({ id: "", label: "" });
renderModels();
$("models-user").querySelector(".models-row:last-child input")?.focus();
});
$("models-reset").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user = { claude: [], devin: [] };
saveModels();
renderModels();
});
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
@@ -24,10 +24,13 @@ export const DONE_AT_MS = 5000;
// 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 }) {
// out to the end with its sound; only `skipEl` (the muted Skip button, or the
// Escape key, for anyone without a mouse) and `signal` aborting (the page
// leaving the dashboard, dormant or mid-run) cut it short, as a skip.
// `onSkip` is the page's cue to silence the intro sounds
// once a skip lands. Under reduced motion nothing is shown and it resolves at
// once.
export function playWake({ stage, bot, target, skipEl, stir, onStart, onGlide, onSkip, signal }) {
return new Promise((resolve) => {
if (matchMedia("(prefers-reduced-motion: reduce)").matches || signal?.aborted) {
resolve({ skipped: false });
@@ -41,8 +44,18 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
if (e.target === bot && e.propertyName === "transform") end(false);
};
const skip = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through.
// The Skip button's events must reach it: the document handlers below run
// in the capture phase, ahead of the button's own click.
const hitsSkip = (e) => Boolean(skipEl && e.target instanceof Node && skipEl.contains(e.target));
const onSkipClick = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through;
// Escape skips, so the run can be left by keyboard too.
const swallow = (e) => {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
if (e.ctrlKey || e.metaKey || e.altKey) return;
e.preventDefault();
e.stopPropagation();
@@ -79,6 +92,8 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
document.removeEventListener("keydown", swallow, true);
bot.removeEventListener("transitionend", onGlideEnd);
signal?.removeEventListener("abort", skip);
skipEl?.removeEventListener("click", onSkipClick);
if (skipped) onSkip?.();
stage.hidden = true;
stage.classList.remove("dormant", "stirring", "booting", "gliding");
bot.style.removeProperty("--wake-glide");
@@ -89,6 +104,11 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
// 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) {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
e.preventDefault();
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
@@ -110,6 +130,7 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
document.addEventListener("pointerdown", start, true);
document.addEventListener("keydown", start, true);
skipEl?.addEventListener("click", onSkipClick);
signal?.addEventListener("abort", skip);
stage.hidden = false;
stage.classList.add("dormant");
@@ -211,13 +211,15 @@ export function shouldChime(prevDot, nextDot) {
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).
* Whether nobody is there to answer a chat message. A finished session's agent
* is often still listening through its last wait (the review and dashboard
* buttons on the hand-off card live as long as it does), so finish alone does
* not end the chat — going quiet does. Offline once the agent has been silent
* longer than the page would tolerate before calling it stuck (working) or
* adrift (anything else), which is also the only signal left once the server
* is gone.
*/
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);
@@ -57,6 +57,7 @@
</g>
</svg>
<p class="wake-hint">Click to wake Planny</p>
<button class="wake-skip" type="button">Skip</button>
</div>
<header class="topbar">
@@ -94,6 +95,8 @@
</button>
<div class="meter-pop" id="meter-pop" role="dialog" aria-label="Session meter" hidden>
<p class="meter-tip" id="meter-tip"></p>
<ul class="meter-list" id="meter-list" aria-label="What the points are made of" hidden></ul>
<div class="meter-fresh" id="meter-fresh" hidden></div>
<button type="button" class="linky" id="meter-help">What is this?</button>
</div>
</span>
@@ -128,13 +131,28 @@
title="Colors, theme and sound"
aria-label="Colors, theme and sound"
>
<!-- Three swatches, so the button says what it opens without a word. -->
<!-- A gear: ring, hub and eight teeth. -->
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<circle cx="5" cy="5.5" r="3.1" class="sw-a" />
<circle cx="11" cy="5.5" r="3.1" class="sw-b" />
<circle cx="8" cy="11" r="3.1" class="sw-c" />
<path class="gr-teeth" d="M12 8h2.6M8 12v2.6M4 8H1.4M8 4V1.4M10.83 10.83l1.84 1.84M5.17 10.83l-1.84 1.84M5.17 5.17L3.33 3.33M10.83 5.17l1.84-1.84" />
<circle cx="8" cy="8" r="4.2" class="gr-ring" />
<circle cx="8" cy="8" r="1.6" class="gr-hub" />
</svg>
</button>
<a
class="icon-btn"
id="btn-feedback"
href="https://github.com/jparkerweb/plan2code/issues/new/choose"
target="_blank"
rel="noopener noreferrer"
title="Report a bug or suggest an idea"
aria-label="Report a bug or suggest an idea (opens GitHub in a new tab)"
>
<!-- A megaphone: horn, handle and two sound waves. -->
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<path class="mg-body" d="M1.8 6.2h2.8L10.4 3v10L4.6 9.8H1.8z" />
<path class="mg-line" d="M4.6 9.8l.9 3.4h1.6l-.6-2.7M12.4 6.1a2.6 2.6 0 0 1 0 3.8M13.8 4.5a5 5 0 0 1 0 7" />
</svg>
</a>
</div>
<div class="topbar-row second">
<div class="row-left">
@@ -595,6 +613,9 @@
written and approving things, instead of typing it all into the
terminal.
</p>
<p>
New here? <button type="button" class="help-link" data-action="welcome">Show the welcome again</button>
</p>
<figure class="help-figure" data-figure="about">
<svg class="help-diagram" viewBox="0 0 560 160" role="img" aria-labelledby="hd-about-title hd-about-desc">
<title id="hd-about-title">You, this page, its program and Plan2Code, all on your machine</title>
@@ -680,7 +701,7 @@
A simplified outline of this page with six numbered areas, in the
same order as the sections below: 1, the top bar, with the title on
the left, the progress bar in the middle, the question mark and
swatch buttons on the right, and Stop session under the title;
gear buttons on the right, and Stop session under the title;
2, Planny and the outline down the left; 3, the view tabs, on the
top bar's second row at the right; 4, the question card in the
middle with Previous and Next under it; 5, the notes panel on the
@@ -738,10 +759,14 @@
"4 of 9 done" while something is being built.
</li>
<li>
The <strong>?</strong> button opens this Help, and the swatch button
The <strong>?</strong> button opens this Help, and the gear button
beside it opens <strong>User Preferences</strong>: your role first,
then your colors, theme, card width and sounds.
</li>
<li>
The <strong>megaphone</strong> button at the far right opens GitHub in a
new tab, where you can report a bug or suggest an idea.
</li>
<li>
<strong>Stop session</strong> ends the session and saves your place.
See "Stopping and finishing".
@@ -1339,7 +1364,8 @@
<p>
Each step you run here adds points: a plan or a set of documents
weighs more than a single answered question, and a built phase more
still. Click the ring to see the count. It is a rule of thumb, not a
still. Click the ring to see the count and a list of each step that added
points, with what it added. It is a rule of thumb, not a
reading of Plan2Code's real memory: long sessions tend to make it
miss things, and the ring is there to remind you.
</p>
@@ -1675,7 +1701,8 @@
</p>
<p>
If it stays quiet a couple of minutes longer, the line changes to
"Plan2Code has not checked in for a few minutes", with Planny still
"Still working on it. Longer tasks can go a few minutes between
updates", with Planny still
in his working pose. It may be busy, or still waiting on you in the
terminal; the terminal is where to look. A build that said a task may
take longer gets that long before the line changes.
@@ -1721,7 +1748,7 @@
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
Everything on the page works from the keyboard, and the swatch button
Everything on the page works from the keyboard, and the gear button
lets you make it look and sound the way you like.
</p>
<h4>Keyboard shortcuts</h4>
@@ -1761,7 +1788,7 @@
</p>
<h4>Your preferences</h4>
<p>
The swatch button at the top, beside <strong>?</strong>, opens
The gear button at the top, beside <strong>?</strong>, opens
<strong>User Preferences</strong>:
</p>
<ul>
@@ -1786,7 +1813,7 @@
</li>
<li>
<strong>Highlight color</strong>: one of
<span data-fact="accentCount">32</span>, rust to begin with. It marks
<span data-fact="accentCount">32</span>, ocean blue to begin with. It marks
what is yours to do, and Planny's star uses it while he works.
</li>
<li>
@@ -1936,6 +1963,29 @@
</div>
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
</fieldset>
<fieldset class="modal-ranges looks-models">
<legend>Models</legend>
<div class="models-tabs" role="group" aria-label="Which agent">
<button type="button" class="btn small ghost" id="models-tab-claude" aria-pressed="true">Claude</button>
<button type="button" class="btn small ghost" id="models-tab-devin" aria-pressed="false">Devin</button>
</div>
<div class="models-note">
<p><strong>You usually don't need to change this.</strong> Plan2Code ships an up-to-date model list with every release. Add a model here only when a new one comes out before Plan2Code has been updated.</p>
<ul>
<li>Restart <code>plan2code</code> to see a change in its model menu.</li>
<li>At any time, run <code>plan2code --model &lt;id&gt;</code>, or pick your model inside your agent before running a skill.</li>
<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>
<li>Devin models are limited to Low, Medium and High effort.</li>
</ul>
</div>
<div class="models-list" id="models-shipped" aria-label="Built-in models"></div>
<div class="models-list" id="models-user" aria-label="Models you added"></div>
<div class="models-actions">
<button type="button" class="btn small" id="models-add">Add a model</button>
<button type="button" class="btn small ghost" id="models-reset">Reset to default</button>
<span class="help" id="models-status" role="status"></span>
</div>
</fieldset>
<div class="modal-actions">
<button type="button" class="btn ghost" id="looks-reset">Back to default</button>
<button type="button" class="btn primary" id="looks-done">Done</button>
@@ -1994,10 +2044,61 @@
<div id="help-panels" class="help-panels"></div>
</div>
<div class="modal-actions">
<span class="help-version" id="help-version" hidden></span>
<button type="button" class="btn primary" id="help-done">Close</button>
</div>
</dialog>
<!-- Shown once, on the first dashboard a person sees. Closing it by any
route saves looks.welcomeSeen; Help's first tab reopens it. -->
<dialog class="modal welcome" id="welcome-modal" aria-labelledby="welcome-title">
<div class="welcome-poster">
<div class="welcome-sky" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i></div>
<!-- Planny is cloned in from #planny by app.js, so he is always the
same robot as the one in the dock. -->
<div class="welcome-bot" id="welcome-bot" aria-hidden="true"></div>
<p class="welcome-kicker">Plan2Code Web Console</p>
<h2 id="welcome-title">Ideas in. Working code out.</h2>
<p class="welcome-lead">
Answer questions, read what gets written and approve each step here,
instead of in the terminal. It runs on this machine only.
</p>
</div>
<div class="welcome-cols">
<div class="welcome-col">
<span class="welcome-dot is-accent">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3.5" y="9" width="12" height="9" rx="1.6" transform="rotate(-12 9.5 13.5)" /><rect x="8.5" y="6" width="12" height="9" rx="1.6" /></svg>
</span>
<h3>Pick a card</h3>
<p>Start with <strong>Suggested</strong>. Pathfinder for a foggy idea, Quick Task for something small.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-stage">
<svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><circle cx="10" cy="10" r="7" opacity="0.35" /><circle cx="10" cy="10" r="7" pathLength="100" stroke-dasharray="50 100" stroke-dashoffset="25" transform="rotate(-90 10 10)" /></svg>
</span>
<h3>Refresh at half way</h3>
<p>Once the session meter passes half, finish the step and start a new conversation.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-bare">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3.5" y="5" width="17" height="14" rx="2" /><path d="M7.5 10l3 2-3 2M12.5 14.5h4" /></svg>
</span>
<h3>Come back</h3>
<p><code>/plan2code</code> in your agent, or <code>plan2code</code> in any folder.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-plain">
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M12 8h2.6M8 12v2.6M4 8H1.4M8 4V1.4M10.83 10.83l1.84 1.84M5.17 10.83l-1.84 1.84M5.17 5.17L3.33 3.33M10.83 5.17l1.84-1.84" /><circle cx="8" cy="8" r="4.2" /><circle cx="8" cy="8" r="1.6" /></svg>
</span>
<h3>Get help</h3>
<p><kbd>?</kbd> opens Help. The gear holds your role, theme and sounds.</p>
</div>
</div>
<div class="modal-actions">
<button type="button" class="btn primary" id="welcome-done">Start building</button>
</div>
</dialog>
<dialog class="modal" id="stop-modal" aria-labelledby="stop-title">
<h2 id="stop-title">Stop this session?</h2>
<p class="modal-blurb" id="stop-blurb"></p>
@@ -35,23 +35,68 @@ export const RUN_EVENTS = new Set(Object.keys(WEIGHTS));
const weightOf = (key) => (Object.prototype.hasOwnProperty.call(WEIGHTS, key) ? WEIGHTS[key] : 0);
// What each scoring event is called in the meter's list of contributions.
const LAUNCH_LABELS = Object.freeze({
plan: "Plan started",
"revise-plan": "Revise plan started",
document: "Document started",
review: "Review started",
"quick-task": "Quick task started",
init: "Init started",
"init-update": "Init update started",
finalize: "Finalize started",
});
const RUN_LABELS = Object.freeze({
"pathfinder-chart": "Pathfinder map written",
"pathfinder-question": "Pathfinder question settled",
plan: "Plan drafted",
"revise-plan": "Plan revised",
document: "Spec documented",
"implement-phase": "Implement phase built",
"implement-review-phase": "Implement + Review phase built",
review: "Code review run",
"quick-task": "Quick task built",
init: "Init run",
"init-update": "Init update run",
finalize: "Finalize run",
handoff: "Handoff written",
});
// The unit a run names, from its ledger id ("L3:phase-2" -> "phase-2").
const unitOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(id.indexOf(":") + 1) : "");
/**
* The session's points, folded from ledger entries in order. An id seen
* before is skipped, so a repeated `post` never counts twice.
* What the count is made of: one { label, points } per ledger entry that
* scored, in order. An id seen before is skipped, so a repeated `post` never
* counts twice. Entries that weigh nothing are left out.
*/
export function pointsFrom(entries) {
export function breakdownFrom(entries) {
const seen = new Set();
let points = 0;
const rows = [];
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);
let points = 0;
let label = "";
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
points = weightOf(entry.workflow);
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
} else if (entry.kind === "run") {
points = weightOf(entry.event);
const unit = unitOf(entry.id);
label = (RUN_LABELS[entry.event] || entry.event) + (unit ? `: ${unit}` : "");
}
if (points > 0) rows.push({ label, points });
}
return points;
return rows;
}
/** The session's points, folded from ledger entries in order. */
export function pointsFrom(entries) {
return breakdownFrom(entries).reduce((sum, row) => sum + row.points, 0);
}
export const YELLOW_AT = 4;
@@ -94,5 +139,12 @@ export const RED_BANNER =
export function meterView(entries) {
const points = pointsFrom(entries);
const level = levelFor(points);
return { points, level, fraction: ringFraction(points), words: WORDS[level], tooltip: tooltipFor(points) };
return {
points,
level,
fraction: ringFraction(points),
words: WORDS[level],
tooltip: tooltipFor(points),
items: breakdownFrom(entries),
};
}
@@ -187,7 +187,7 @@ export const ACCENTS = {
},
};
export const DEFAULT_ACCENT = "rust";
export const DEFAULT_ACCENT = "ocean";
// 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
@@ -23,7 +23,8 @@ 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.
// Blocks javascript: and data: hrefs before they can reach the DOM, and a
// protocol-relative `//host` (or `/\host`), which leaves the page for another site.
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
}
@@ -103,6 +104,26 @@ function inlineInto(parent, tokens) {
}
}
// What a fenced code block offers beside Copy, from its first non-empty line:
// `'run'` gets a Run it button (git commands — the one kind a person keeps
// copying into Ask by hand), `'hint'` a muted note that pasting it into Ask
// may get the agent to run it, and `null` nothing extra. A leading `/` is a
// skill command for a new conversation, never a terminal command, so it gets
// neither.
const COMMAND_WORDS =
/^(git|node|npm|npx|pnpm|yarn|bun|deno|python3?|pip3?|brew|curl|wget|docker|kubectl|terraform|make|cmake|cargo|go|java|mvn|gradle|gh|aws|az|gcloud|jq|ssh|scp|rsync|chmod|chown|mkdir|cp|mv|rm|ls|cd|cat|echo|export|source|bash|sh|zsh|fish|pwsh|powershell|cmd|systemctl|service|apt|apt-get|dnf|yum|pacman|tar|unzip|zip)\b/i;
export function runHint(text) {
const firstLine = (text || "")
.split("\n")
.map((line) => line.trim())
.find((line) => line.length > 0);
if (!firstLine || firstLine.startsWith("/")) return null;
if (/^git(\s|$)/.test(firstLine)) return "run";
if (firstLine.startsWith("#!")) return "hint";
return COMMAND_WORDS.test(firstLine) ? "hint" : null;
}
function blockInto(parent, tokens) {
for (const t of tokens || []) {
switch (t.type) {
@@ -140,7 +161,16 @@ function blockInto(parent, tokens) {
// textContent, so a fenced block containing markup is inert.
pre.appendChild(el("code", null, t.text));
wrap.appendChild(copyButton(t.text, "md-copy"));
const hint = runHint(t.text);
if (hint === "run") {
const run = el("button", "md-run", "Run it");
run.type = "button";
wrap.appendChild(run);
}
wrap.appendChild(pre);
if (hint === "hint") {
wrap.appendChild(el("p", "md-run-hint", "The agent may be able to run this — paste it into the Ask tab"));
}
parent.appendChild(wrap);
break;
}
@@ -21,8 +21,11 @@ import {
CHAT_CURSOR_FILE,
CHAT_FILE,
LEDGER_FILE,
HERE,
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
@@ -44,6 +47,7 @@ import {
readWorkspace,
remoteWarning,
typedCount,
withStateLock,
writeJsonAtomic,
writeWorkspace,
} from "./lib.mjs";
@@ -84,6 +88,12 @@ if (typeof args.token !== "string" || !args.token) {
}
const TOKEN = args.token;
const PROJECT = args.project || process.cwd();
// The checkout this session runs in, from `open`. PROJECT is the folder that
// holds .git, which for a linked worktree is the MAIN checkout: the wrong
// folder to seed the workspace with or resolve a typed path against. A fresh
// `open` starts this server before it writes the state, so until the state is
// there this is the only place the worktree can come from.
const WORKTREE = typeof args.worktree === "string" ? args.worktree : "";
const IDLE_MS = Number(args["idle-ms"] || 30 * 60 * 1000);
const MAX_LIFE_MS = Number(args["max-life-ms"] || 4 * 60 * 60 * 1000);
@@ -96,12 +106,12 @@ const CURSOR_PATH = path.join(DIR, CHAT_CURSOR_FILE);
// Images and documents attached to notes and quick questions. Only ever named
// by the server (a UUID, plus `jpg` or an extension from DOC_TYPES), and only
// ever resolved inside this directory: the client's file name is a label.
// Only images are served back; a document is written, read by the agent from
// disk, and deleted, never handed to a browser.
// Images are served back as JPEG. A document is served under a fixed type
// (PDF, or text/plain for everything else, sandboxed and never sniffed), so
// the page can link it without ever letting a browser run it.
const UPLOADS_DIR = path.join(DIR, "uploads");
const UPLOAD_EXTS = ["jpg", ...Object.keys(DOC_TYPES)];
const EXT_ALT = UPLOAD_EXTS.join("|");
const UPLOAD_ROUTE = /^\/uploads\/([0-9a-f-]{36})\.jpg$/;
const UPLOAD_ANY_ROUTE = new RegExp(`^/uploads/([0-9a-f-]{36})\\.(${EXT_ALT})$`);
const UPLOAD_NAME = new RegExp(`^[0-9a-f-]{36}\\.(${EXT_ALT})$`);
@@ -216,7 +226,7 @@ const SERVABLE = new Set([
// live in it). A stat says whether anything moved; refreshing through
// checkState also means a request that sees a new state first still counts
// it as a new revision and tells every other tab. Callers must not mutate
// what this returns -- /submit clones before it edits.
// what this returns -- /submit edits a fresh read of its own, under the lock.
function readState() {
checkState();
return stateNow;
@@ -302,6 +312,10 @@ const foldPath = (p) => (FOLD_CASE ? p.toLowerCase() : p);
let workspaceSeen = { stamp: null, ws: null };
// The folder the session runs in: the state's own once it is written, else
// the one `open` passed on the command line. Null while neither is known.
const sessionWorktree = () => stateNow?.worktree || WORKTREE || null;
// The session's workspace, created with just the original folder when absent.
function workspaceNow() {
const stamp = fileStamp(WORKSPACE_PATH);
@@ -311,10 +325,15 @@ function workspaceNow() {
workspaceSeen = { stamp, ws };
return ws;
}
const fresh = initialWorkspace(stateNow?.worktree || PROJECT);
const root = sessionWorktree();
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
// Nor saved while the session's folder is unknown: PROJECT is only a guess
// (the main checkout, for a linked worktree), and the file, once written,
// is what every later read trusts.
if (!root) return fresh;
try {
saveWorkspace(fresh);
} catch {}
@@ -405,7 +424,7 @@ function nextFolderId(ws) {
function addFolder(ws, body) {
const raw = typeof body.path === "string" ? body.path.trim().replace(/^(["'])(.*)\1$/, "$2").trim() : "";
const input = raw.replace(/^~(?=$|[\\/])/, () => os.homedir());
const resolved = raw ? path.resolve(stateNow?.worktree || PROJECT, input) : "";
const resolved = raw ? path.resolve(sessionWorktree() || PROJECT, input) : "";
if (!resolved || !isFolder(resolved)) return [400, { reason: "not-a-folder" }];
const same = ws.folders.find((f) => foldPath(path.resolve(f.path)) === foldPath(resolved));
if (same) return [400, { reason: "duplicate", name: same.name }];
@@ -455,7 +474,7 @@ function removeFolder(ws, body) {
// Where the picker opens: beside the last folder added, else the original.
function pickerStart(ws) {
const added = ws.folders.filter((f) => !f.original);
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || PROJECT;
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || sessionWorktree() || PROJECT;
}
// One picker at a time. Spawned, never spawnSync: the dialog can sit open for
@@ -464,6 +483,8 @@ function pickerStart(ws) {
let pickerBusy = false;
function bootWorkspace() {
// Nothing to check yet: the first read once the state is written makes it.
if (!sessionWorktree() && !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
const remote = remoteWarning().remote || "";
if ((ws.remote || "") !== remote) {
@@ -541,9 +562,14 @@ function recordSubmitted(state, actions) {
if (!Array.isArray(state.items)) return;
const at = nowIso();
for (const action of actions) {
if (!action || typeof action !== "object" || action.type === "comment") continue;
if (!action || typeof action !== "object") continue;
const item = state.items.find((i) => i && i.id === action.i);
if (!item) continue;
if (action.type === "comment") {
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
continue;
}
const { i, type, ...rest } = action;
// JSON.parse makes "__proto__" an own property, and it would then be
// written back into state.json and re-read forever.
@@ -577,12 +603,13 @@ function timingSafeEq(a, b) {
return crypto.timingSafeEqual(ab, bb);
}
// Named per port. Cookies ignore the port, so every console on 127.0.0.1 shares
// one jar: under a single name, opening a second session overwrote the first
// one's cookie and locked its tab out.
function cookieName(port = PORT) {
return `p2c_console_${port}`;
}
// One cookie per port. Browsers scope cookies by host and ignore the port, so
// with one shared name every session on 127.0.0.1 wrote over the one before
// it, and the first session's tab went on sending the second one's token and
// got nothing but 403s. The port is what makes a session's origin its own, and
// a resumed server on a new port is reached again only through its /s/ link,
// which sets the cookie under the new name.
const cookieName = () => `p2c_console_${PORT}`;
function cookieToken(req) {
const raw = req.headers.cookie || "";
@@ -623,6 +650,47 @@ function touch() {
lastContact = Date.now();
}
const MODEL_CLIS = ["claude", "devin"];
const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/;
// Devin's XHigh and Max efforts are never offered, curated or added.
const MODEL_EFFORT_BLOCKED = /-(xhigh|max)$/i;
/**
* The user's added models: { claude: [{id,label}], devin: [...] }. Returns { models } or
* { error }. Blank rows are dropped; ids are trimmed and made unique per CLI; a label
* defaults to the id. Nothing else in the body survives.
*/
function cleanModels(input) {
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "models must be an object" };
const models = {};
for (const cli of MODEL_CLIS) {
const list = input[cli] == null ? [] : input[cli];
if (!Array.isArray(list) || list.length > 50) return { error: `${cli} must be a list of at most 50 models` };
const seen = new Set();
models[cli] = [];
for (const row of list) {
const id = String((row && row.id) ?? "").trim();
if (!id) continue;
if (!MODEL_ID.test(id)) return { error: `"${id}" is not a valid model id` };
if (MODEL_EFFORT_BLOCKED.test(id)) return { error: `"${id}": only Low, Medium and High efforts are allowed` };
if (seen.has(id)) continue;
seen.add(id);
const label = String((row && row.label) ?? "").trim().slice(0, 80) || id;
models[cli].push({ id, label });
}
}
return { models };
}
function shippedModels() {
const file = readJson(SHIPPED_MODELS_FILE, null) || {};
const out = {};
for (const cli of MODEL_CLIS) {
out[cli] = (Array.isArray(file[cli]) ? file[cli] : []).filter((m) => m && typeof m.id === "string");
}
return out;
}
/**
* Whittle a POSTed settings object down to what a settings file may hold.
* The page only sends { theme, accent } today, but the file is shared and
@@ -668,8 +736,8 @@ function asset(rel) {
// The saved highlight color, painted from the very first frame. The page's
// script owns the colors once it runs (applyLooks clears the attribute these
// hang off), but until then the only way to avoid flashing the default rust
// at someone who picked ocean is a stylesheet rule the server can switch on
// hang off), but until then the only way to avoid flashing the default ocean
// at someone who picked violet is a stylesheet rule the server can switch on
// with an attribute: the CSP forbids inline styles, and the colors live in
// palette.js, so they are generated from there rather than copied into CSS.
function accentCss() {
@@ -742,7 +810,10 @@ function renderIndex() {
// `$'` in the inserted text as patterns, and titles and state are free text.
return indexTemplate
.replace('<html lang="en">', () => `<html lang="en"${htmlAttrs}>`)
.replace("<title>Plan2Code Console</title>", () => `<title>${escHtml(title)} · Plan2Code</title>`)
.replace(
"<title>Plan2Code Console</title>",
() => `<title>${escHtml(title)} · #${escHtml(String(SID).slice(-6))} · Plan2Code</title>`
)
.replace('<h1 id="title">Plan2Code Console</h1>', () => `<h1 id="title">${escHtml(title)}</h1>`)
.replace(
'<span class="badge" id="badge">Pathfinder</span>',
@@ -821,7 +892,7 @@ const server = http.createServer((req, res) => {
302,
baseHeaders({
location: "/",
"set-cookie": `${cookieName(port)}=${TOKEN}; HttpOnly; SameSite=Strict; Path=/`,
"set-cookie": `${cookieName()}=${TOKEN}; HttpOnly; SameSite=Strict; Path=/`,
})
);
return res.end();
@@ -887,6 +958,14 @@ const server = http.createServer((req, res) => {
return;
}
if (pathname === "/version" && req.method === "GET") {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const version = readJson(file, {}).version;
if (typeof version === "string" && version) return json(res, 200, { version });
}
return json(res, 404, { error: "no version" });
}
if (pathname === "/state" && req.method === "GET") {
const state = readState();
if (!state) return json(res, 404, { error: "no state" });
@@ -957,7 +1036,10 @@ const server = http.createServer((req, res) => {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, 400, { error: "body must be JSON" });
const looks = cleanLooks(body && body.looks);
// `set` carries only the keys one tab changed, merged onto what is on
// disk, so a tab holding stale settings cannot undo another tab's change.
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
const looks = set ? { ...(readJson(LOOKS_FILE, null)?.looks || {}), ...set } : cleanLooks(body && body.looks);
if (!looks) return json(res, 400, { error: "looks must be an object of simple settings" });
try {
ensureDir(path.dirname(LOOKS_FILE));
@@ -969,6 +1051,29 @@ const server = http.createServer((req, res) => {
});
}
// The launcher's model menu: what ships (read-only here) and what the user added.
if (pathname === "/models" && req.method === "GET") {
const saved = readJson(USER_MODELS_FILE, null) || {};
const { models } = cleanModels(saved);
return json(res, 200, { shipped: shippedModels(), user: models || { claude: [], devin: [] } });
}
if (pathname === "/models" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, 400, { error: "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
try {
ensureDir(path.dirname(USER_MODELS_FILE));
writeJsonAtomic(USER_MODELS_FILE, models);
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, { ok: true, user: models });
});
}
if (pathname === "/upload" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
const contentType = String(req.headers["content-type"] || "");
@@ -1008,8 +1113,8 @@ const server = http.createServer((req, res) => {
}
// A document: the extension comes from the allow-list via its name, and
// the bytes have to agree with it. No `url` comes back, because a
// document is never served.
// the bytes have to agree with it. No `url` comes back: the page builds
// the link from the path, as it does for the delete route.
if (contentType.startsWith("application/octet-stream")) {
// The extension comes from the whole name: the label is cut at 200
// characters, and a long name would lose it there.
@@ -1033,11 +1138,11 @@ const server = http.createServer((req, res) => {
// Matched on the raw request line as well as the parsed path: URL parsing
// folds `..` segments away, and nothing that needed folding is an upload.
// GET serves images only; DELETE takes documents too.
// GET and DELETE take images and documents alike.
if (pathname.startsWith("/uploads/") || req.url.startsWith("/uploads/")) {
if (req.method === "GET") {
const m = UPLOAD_ROUTE.exec(req.url);
const file = m && m[0] === pathname ? uploadPath(m[1]) : null;
const m = UPLOAD_ANY_ROUTE.exec(req.url);
const file = m && m[0] === pathname ? uploadPath(m[1], m[2]) : null;
if (!file) return json(res, 404, { error: "not found" });
let buf;
try {
@@ -1045,7 +1150,15 @@ const server = http.createServer((req, res) => {
} catch {
return json(res, 404, { error: "not found" });
}
return send(res, 200, buf, "image/jpeg", { "cache-control": "private, max-age=86400" });
const ext = m[2];
if (ext === "jpg") return send(res, 200, buf, "image/jpeg", { "cache-control": "private, max-age=86400" });
const pdf = DOC_TYPES[ext].kind === "pdf";
// A sandboxed PDF cannot load the browser's viewer, and one needs no
// sandbox: text is the only thing a browser might otherwise run.
return send(res, 200, buf, pdf ? "application/pdf" : "text/plain; charset=utf-8", {
...(pdf ? {} : { "content-security-policy": "sandbox" }),
"cache-control": "private, max-age=86400",
});
}
if (req.method === "DELETE") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
@@ -1079,16 +1192,6 @@ const server = http.createServer((req, res) => {
if (badAttachments) {
return json(res, 400, { error: "a comment carries at most 5 attachments, each uploaded to this session" });
}
// One send is one agent turn. Writing over a result the agent has not
// collected yet destroys everything in it, and the loss is silent: two
// tabs, or one impatient second press, and an approval disappears.
if (pendingResult()) {
return json(res, 409, {
error: "pending",
message:
"Your last answers have not been picked up yet. Nothing is lost, they are still on their way.",
});
}
const result = {
type: "submit",
at: nowIso(),
@@ -1097,26 +1200,68 @@ const server = http.createServer((req, res) => {
actions: body.actions,
reply: body.reply || "",
};
// The result and the state change together, under the state lock: a
// `post` or an `open` landing in the middle of a send would otherwise
// write back a state read before it, and the send's record would go, or
// this write would carry an older state over the agent's new one.
let refused = null;
let written = null;
let agentWrote = false;
try {
// Atomic: the waiter polls this file and will land mid-write eventually.
writeJsonAtomic(RESULT_FILE, result);
written = withStateLock(DIR, () => {
// One send is one agent turn. Writing over a result the agent has not
// collected yet destroys everything in it, and the loss is silent: two
// tabs, or one impatient second press, and an approval disappears.
if (pendingResult()) {
refused = "pending";
return null;
}
try {
// Atomic: the waiter polls this file and will land mid-write eventually.
writeJsonAtomic(RESULT_FILE, result);
} catch (e) {
refused = String(e.message);
return null;
}
try {
// Read fresh from disk, never from the cache: an agent write the
// watcher has not reached yet is in the file and must be kept.
const text = fs.readFileSync(STATE_FILE, "utf8");
const state = JSON.parse(text);
agentWrote = text !== lastStateText;
state.phase = "submitted";
recordSubmitted(state, body.actions);
return { state, text: writeJsonAtomic(STATE_FILE, state) };
} catch {
// The answers are safe in result.json; the stamp is only a courtesy.
return null;
}
});
} catch (e) {
return json(res, 500, { error: String(e.message) });
refused = String(e.message);
}
if (refused === "pending") {
return json(res, 409, {
error: "pending",
message:
"Your last answers have not been picked up yet. Nothing is lost, they are still on their way.",
});
}
if (refused) return json(res, 500, { error: refused });
appendEvent(DIR, { type: "submit", rev, count: body.actions.length });
const current = readState();
if (current) {
// A copy: the cached state is what every other reader is handed.
const state = structuredClone(current);
state.phase = "submitted";
recordSubmitted(state, body.actions);
try {
// Account for our own write here rather than letting the watcher find
// it: the watcher reads a changed state.json as proof the AGENT is
// alive, and this write is not that.
adoptStateText(writeJsonAtomic(STATE_FILE, state), state);
rev++;
} catch {}
if (written) {
// Account for our own write here rather than letting the watcher find
// it: the watcher reads a changed state.json as proof the AGENT is
// alive, and this write is not that. An agent write it swept up on the
// way is, and is handled as the watcher would have handled it.
adoptStateText(written.text, written.state);
rev++;
if (agentWrote) {
agentSeenAt = Date.now();
try {
ensureConversation(written.state);
} catch {}
}
}
// Name the items that went. A page with OTHER answers staged should drop
// only what was sent, and a brief request is a submit carrying no answers
@@ -1282,15 +1427,21 @@ const server = http.createServer((req, res) => {
if (pathname === "/cancel" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
if (pendingResult()) return json(res, 409, { error: "pending", message: "A send is still on its way." });
const result = { type: "cancel", at: nowIso(), sid: SID, rev, actions: [], reply: "" };
// As /submit: a cancel that never reached disk must not tell the page it
// did, or the page stands down while the agent waits on forever.
// Under the state lock like a send, so `open` clearing a collected result
// can never take this one with it. As /submit: a cancel that never reached
// disk must not tell the page it did, or the page stands down while the
// agent waits on forever.
let pending = false;
try {
writeJsonAtomic(RESULT_FILE, result);
withStateLock(DIR, () => {
pending = pendingResult();
if (!pending) writeJsonAtomic(RESULT_FILE, result);
});
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
if (pending) return json(res, 409, { error: "pending", message: "A send is still on its way." });
appendEvent(DIR, { type: "cancel", rev });
broadcast("cancelled", { rev });
return json(res, 200, { ok: true });
@@ -1319,6 +1470,8 @@ const server = http.createServer((req, res) => {
// Treat a departure as "shorten the deadline", never as "exit now": the user
// may simply be reloading.
if (pathname === "/bye") {
// It moves the shutdown deadline, so only the page itself may send it.
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
if (clients.size === 0) lastContact = Date.now() - (IDLE_MS - 2 * 60 * 1000);
return json(res, 200, { ok: true });
}
@@ -1382,7 +1535,9 @@ function readRaw(req, limit, cb) {
/* ------------------------------------------------------- state watching */
// The agent writes state.json through `console.mjs post`. Watch the DIRECTORY,
// The agent writes state.json through `console.mjs post`, and the server only
// through /submit; both under the state lock (updateState() in lib.mjs), so
// neither can write back a state read before the other's. Watch the DIRECTORY,
// not the file: on Windows a watch on a file breaks the moment that file is
// replaced by rename, which is exactly what an atomic write does.
let watchTimer = null;
@@ -1490,7 +1645,9 @@ setInterval(() => {
// the server deciding to stop. Do not "optimise" this away.
setInterval(() => {
const idle = Date.now() - lastContact;
if (idle > IDLE_MS) {
// Answers nobody has collected yet keep the server up (bounded by MAX_LIFE_MS):
// exiting would strand the tab and the send it holds.
if (idle > IDLE_MS && !resultFlags().pending) {
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle });
process.exit(0);
}
@@ -0,0 +1,22 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-02",
"mode": "utility"
}
+1 -1
View File
@@ -27,7 +27,7 @@ The FIRST thing you do, before anything else in this file — before Step 1, bef
- This mode modifies **`specs/` paths only** — do NOT implement code or modify any file outside `specs/`
- **Allowed file paths:** ONLY paths under `specs/`. Forbidden: `skills/`, `src/`, `.claude/`, `.agents/`, `.codeium/`, configs, source code. Creating, modifying, or deleting any file outside `specs/` is a violation.
- **Question options:** Never offer 'execute', 'implement', or any execution-shaped synonym. Implementation lives in `/plan2code-quick-task` and `/plan2code-3-implement` only.
- **Web console exception:** the console's temporary payload files (outside the repo, in the system temp directory) are the one allowed write outside `specs/`. They are messages to the page, never project files.
- **Web console exception:** the console's temporary payload files (outside the repo, in the session folder `open` prints) are the one allowed write outside `specs/`. They are messages to the page, never project files.
## Required Context
@@ -273,7 +273,7 @@ for whichever comes first:
| 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. |
| `wait` exit `20` | The server is gone, not necessarily the tab. Resume it (`open --resume <sid> --no-open --workflow <yours>`) and keep waiting. |
| 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:
@@ -406,15 +406,38 @@ post carries `"run": { "event": "implement-review-phase", "id": "phase-N" }`.
("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.
`"answer": { "verdict": "yes" }`) in the post that starts the build, and
open a **Build progress** tab in that same post, the way an Implement phase
gets its tasks tab. The plan's steps are the task list and `total` is their
number:
```jsonc
{
"stopWarning": "",
"items": [{ "id": "<the Build this plan? item's id>", "status": "answered", "answer": { "verdict": "yes" } }],
"headline": { "stage": "Building", "cleared": 0, "total": 4 },
"docs": [{ "id": "tasks", "title": "Build progress", "version": 1, "blocks": [
{ "id": "tasks", "state": "settled", "md": "- [ ] Step one\n- [ ] Step two\n- [ ] Step three\n- [ ] Step four" }
]}],
"agent": { "status": "working", "activity": "Step 1 of 4: step one", "quietMinutes": 10 }
}
```
Then post after every step, exactly as "While you build": bump the doc's
`version` and repost the whole list with that step ticked, raise
`headline.cleared`, and set `agent.activity` to the next step ("Step 2 of 4:
step two"). Never go silent for the whole build: a quick task with many steps
is the case this tab is for. Check for a Quick question between steps, and do
not call `wait` until the build is done.
- **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.
sign-off card to put it on — and `"dashboard": true`, so the finished screen
also offers **Back to the dashboard**. Both are required: a finish without
`dashboard` leaves the person on a dead end. Keep waiting for whichever
button is pressed, 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"`.
@@ -27,6 +27,12 @@ workflow still applies: the same questions, the same order, the same gates, the
same cap of three questions at a time, the same recap before anything is recorded.
You are not allowed to answer your own questions just because a form makes it easy.
> **The one rule that keeps the page alive: while the session is open, every
> turn ends on a `wait` call, never on text.** `wait` exit `10` means "nobody
> has answered yet", not "done": relay one line and run `wait` again in the
> same turn, as many times as it takes. A turn that ends without a `wait`
> running strands the person's next click. Details: The wait loop, below.
---
## Deciding whether to use it
@@ -172,7 +178,19 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
Do not poll faster than this. Do not spin on `status`. Exit 10 is not a finished
turn: never emit a final response or stop after an arbitrary number of slices;
relay one line and immediately call `wait` again. Do not give up: people step
away from a session and come back.
away from a session and come back. The same holds after a `finish`: keep
waiting (resuming the server on exit `20`) until the dashboard or done press
or about ten minutes with nothing, because the Ask tab stays live and its
messages only arrive through `wait`. Ending your turn earlier strands them.
**The turn never ends on a wait.** While a console session is open, including
after a finish that offers a button (Back to the dashboard, Review it now), the
last thing in every turn you take is a `wait` call, never a line of text. The
line you relay after exit `10` goes in the same turn as the next `wait`, so
write it and call `wait` straight after. A turn that ends with the session open
and no `wait` running is a bug the person feels at once: their button press
sits unread until they ask why. If you catch yourself about to write a closing
summary while the page is still open, call `wait` first.
**Collect promptly.** A question someone has sent is locked on the page for as
long as you are mid-turn on it: they can read, move around and answer the other
@@ -453,6 +471,14 @@ messages, `offline` when no agent is connected or the session has finished,
### Answering
**Every message gets a reply, always.** The Ask tab is the person talking to
you, and the page shows "working on the answer" until a reply lands. Never
leave one unanswered, whatever it asks and whatever mid-task you are in. When
a message asks you to do something, do it if you can, then say what happened; if
you will not, the reply says so and why. `post` and `wait` print
`unansweredChat` with a `warning` for every message handed over and not yet
replied to: treat that as a stop-and-reply.
1. Handle any card answers first, under the workflow's own rules.
2. Write the chat replies, in inbox order.
3. Send **one** `post` with the card updates and `chat: { replies: [...] }`.
@@ -510,8 +536,9 @@ enforces it, so never tell someone to keep asking past it.
proposal is a new reply.
- Hard limits: never touch the running skill's own files under
`specs/<idea>/` (`post` rejects a proposal that names them); run no commands
beyond read-only lookups; never commit; refuse a request outside these and
say why.
beyond read-only lookups, except one the person plainly asks you to run in
their message (a commit they spell out, a test run): run it, then report the
result in the reply; refuse anything else and say why, in the reply.
- Edits happen only at check-ins, never mid-task in a build.
```jsonc
@@ -715,8 +742,10 @@ review run from a build's review button stays in the build's session, under
its workflow: `building.md` → The review, mid-session. On completion the finish's `command` is the suggested
commit when fixes landed — filled in, in the AGENTS.md format, with
`"where": "When you are happy with it, commit it from your terminal:"` —
otherwise leave `command` out. A stop mid-review loses nothing on disk, so its
finish is the bare `/plan2code-review`.
otherwise leave `command` out. The completion finish carries `"dashboard": true`
so the finished screen offers **Back to the dashboard**; keep waiting for the
press. A stop mid-review loses nothing on disk, so its finish is the bare
`/plan2code-review` (a pause, so no dashboard button).
### Handoff (`handoff`)
@@ -892,6 +921,8 @@ Session meter) and `folderIssue` (Workspace → When a folder cannot be read).
### Every item
**Give every new question a new `id`.** An id names one question for the whole session. The server drops a stale `submitted` record if you reword a question under an old id, but never rely on it: a fresh id is the only unambiguous way to ask something new.
```jsonc
{
"id": "q7",
@@ -1141,7 +1172,7 @@ usual slices for up to about ten minutes:
| --- | --- |
| An action `{ "i": "__dashboard", "type": "dashboard" }` | `open --resume <sid> --no-open --workflow dashboard` (the resume re-runs the project scan), then ONE post with `"finish": null`, the `menu` payload and `"agent": { "status": "waiting" }`. Then read the dashboard skill (`~/.agents/skills/plan2code/SKILL.md`) and carry on as the dashboard from its "The menu" section, in this same conversation. The same action can also arrive before any finish, from the top bar's triangle: see Stop requests → "Back to the dashboard, mid-workflow". |
| An action `__review` or `__done` | As `building.md` says (quick task only). |
| `wait` exit `20` | They closed the tab. Do not resume: the session is over. |
| `wait` exit `20` | The server is gone, not necessarily the tab. `open --resume <sid> --no-open --workflow <yours>`, then keep waiting: their Ask messages and the dashboard button still need you. Give up only when the resume itself fails. |
| Nothing after about ten minutes | `stop` the server. The page swaps the button for the `/plan2code` command. |
### 2. Stop the server
@@ -54,6 +54,7 @@ import {
nowIso,
parseArgs,
pendingChatCount,
unansweredChat,
pendingWorkspaceChanges,
pidAlive,
print,
@@ -77,6 +78,7 @@ import {
sweepUploads,
switchWorkflow,
terminalLine,
updateState,
UPLOAD_MAX_AGE_MS,
validate,
validateChat,
@@ -88,6 +90,10 @@ import {
import { RUN_EVENTS } from "./public/meter.js";
import { changeLine } from "./public/workspace.js";
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
// still be one of our servers, so its pid gets no second look.
const MAX_SERVER_LIFE_MS = 4 * 60 * 60 * 1000;
const argv = process.argv.slice(2);
const cmd = argv[0];
const args = parseArgs(argv.slice(1));
@@ -102,8 +108,24 @@ function trace(what) {
/* ----------------------------------------------------------------- open */
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written by `open` alone, which starts every session: a
// `wait` or a `post` every few seconds need not rewrite it each time.
function leavePointer() {
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
}
async function cmdOpen() {
trace("open: start");
leavePointer();
const { project, worktree, branch } = repoRoots();
reapHandles(project);
trace("open: project found");
@@ -113,6 +135,11 @@ async function cmdOpen() {
let state;
// A new skill run for the meter: a fresh open, or a resume into another workflow.
let launched = true;
// Everything `open` does to a stored state, as a step it can take twice:
// once now, on the read below, so a bad payload is refused before anything
// starts, and again on a fresh read under the state lock when it writes, so
// a send the person made in between is kept rather than written over.
let reshape = (s) => s;
if (sid) {
sid = path.basename(sid);
@@ -120,27 +147,6 @@ async function cmdOpen() {
if (!fs.existsSync(dir)) die(`no session "${sid}" to resume`, 1);
state = readJson(path.join(dir, "state.json"));
if (!state) die(`session "${sid}" has no state`, 1);
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (state.finish && /^\s*paused\b/i.test(String(state.finish.headline || ""))) {
delete state.finish;
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
state.items = (state.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(state.items.map((i) => i.topic));
state.topics = (state.topics || []).filter((t) => liveTopics.has(t.id));
}
// A resume can also be a hand-off: the dashboard launches another skill
// into its own session, and the first thing that skill needs is for the
// page to stop being a dashboard. Letting the flags restate these fields
@@ -148,26 +154,51 @@ async function cmdOpen() {
// rather than a resume plus a whole extra post.
const switching = args.workflow && args.workflow !== state.workflow;
launched = Boolean(switching);
if (switching && (args.workflow === "dashboard" || state.workflow === "dashboard")) {
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. A skill run inline from another (a
// quick task's review) never passes the dashboard, so it keeps the page.
state = switchWorkflow(state, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
fs.rmSync(path.join(dir, "draft.json"), { force: true });
} else if (switching) state.workflow = args.workflow;
if (args.title) state.title = args.title;
if (args.spec) state.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete state.wake;
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. A skill run inline from another (a
// quick task's review) never passes the dashboard, so it keeps the page.
const hop = switching && (args.workflow === "dashboard" || state.workflow === "dashboard");
if (hop) fs.rmSync(path.join(dir, "draft.json"), { force: true });
reshape = (s) => {
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (s.finish && /^\s*paused\b/i.test(String(s.finish.headline || ""))) {
delete s.finish;
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
s.items = (s.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(s.items.map((i) => i.topic));
s.topics = (s.topics || []).filter((t) => liveTopics.has(t.id));
}
if (hop) {
s = switchWorkflow(s, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
} else if (switching) s.workflow = args.workflow;
if (args.title) s.title = args.title;
if (args.spec) s.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete s.wake;
return s;
};
} else {
sid = newSessionId();
// Named, not made: the folder is created once --file has passed, so a
@@ -185,22 +216,36 @@ async function cmdOpen() {
// Only a freshly opened dashboard plays Planny's wake-up.
if (args.workflow === "dashboard") state.wake = true;
}
// On every open, so a resume from another worktree refreshes both.
state.worktree = worktree;
state.branch = branch;
// A first payload's meter and folder reports, as `post` takes them: checked
// now, before anything is written, and appended once the launch is.
let openRun;
let openIssue;
let patch = null;
if (args.file) {
const patch = readJson(path.resolve(args.file));
patch = readJson(path.resolve(args.file));
if (!patch) die(`could not read --file ${args.file} as JSON`, 2);
({ run: openRun, folderIssue: openIssue } = patch);
delete patch.run;
delete patch.folderIssue;
}
const base = reshape;
const settle = (s) => {
s = base(s);
// On every open, so a resume from another worktree refreshes both.
s.worktree = worktree;
s.branch = branch;
return s;
};
reshape = (s) => (patch ? applyPatch(settle(s), patch) : settle(s));
state = settle(state);
if (patch) {
ledgerFromPost(dir, openRun, openIssue, state.workflow);
state = applyPatch(state, patch);
try {
state = applyPatch(state, patch);
} catch (e) {
die(e.message, 3);
}
const problems = validate(state);
if (problems.length) return failValidation(problems);
}
@@ -209,13 +254,15 @@ async function cmdOpen() {
// A fresh session needs a fresh server, and a server is a whole Node boot:
// the slowest thing `open` does, bar the browser. Start both now, before
// the scan and the state write, so their start-up runs alongside them
// instead of after. Neither can reach a page before the server is up, and
// the state is on disk long before that; the server reads it per request,
// never at boot.
// instead of after. The server does look at the state as it boots, and on
// a fresh session finds none yet: it takes the worktree from its command
// line, not from the state, and picks the state up on its first request or
// poll tick. No page can reach it before it is listening, and the state is
// on disk long before a browser gets there.
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null;
const reusable = existing && pidAlive(existing.pid) ? healthOk(existing) : Promise.resolve(false);
let boot = null;
if (!existing) boot = await startServer(project, sid, dir);
if (!existing) boot = await startServer(project, worktree, sid, dir);
// The dashboard's spec picker reads its inventory straight off the session
// state, so the scan belongs to `open` rather than to the agent: filesystem
@@ -223,23 +270,43 @@ async function cmdOpen() {
// never something a model has to remember to fetch. Rooted at the worktree's
// own top level: `project` is the common-dir key so linked worktrees share
// sessions, but each shows the specs on its own disk.
if (state.workflow === "dashboard") state.scan = scanProject(worktree);
const scan = state.workflow === "dashboard" ? scanProject(worktree) : null;
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
const carried = Boolean(waiting && !waiting.consumedAt);
// Under the state lock, which a send on the page takes too: the result and
// the state are read fresh here and the state is rebuilt from that read, so
// nothing the person sent since the read above is lost or stamped over.
let carried = false;
let written;
try {
written = updateState(dir, (fresh) => {
const next = fresh ? reshape(fresh) : state;
if (scan) next.scan = scan;
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) state.phase = "collecting";
writeJsonAtomic(path.join(dir, "state.json"), state);
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
carried = Boolean(waiting && !waiting.consumedAt);
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) next.phase = "collecting";
return next;
});
} catch (e) {
written = { error: e.message };
}
if (!written || written.error) {
// A server just started for this state would only serve a page that never starts.
if (boot) boot.kill();
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
@@ -288,14 +355,14 @@ async function cmdOpen() {
// A handle whose pid is alive but is not ours (the pid was reused) leaves
// this for last: nothing could be started until that was known.
let started = boot || (await startServer(project, sid, dir));
let started = boot || (await startServer(project, worktree, sid, dir));
let handle = await awaitHandle(started);
if (!handle && started.handoff) {
// The handover went wrong somewhere (a platform that will not pass the
// socket, a server that died taking it). Once more the old way, where
// the server binds its own port: slower, and certain.
started.kill();
started = await startServer(project, sid, dir, { handoff: false });
started = await startServer(project, worktree, sid, dir, { handoff: false });
handle = await awaitHandle(started);
}
if (!handle) {
@@ -372,7 +439,7 @@ function isFolder(p) {
* boot: a process's first listen() blocks for ~50ms on Windows while the
* socket stack loads, which is time the server spends booting anyway.
*/
async function startServer(project, sid, dir, { handoff = true } = {}) {
async function startServer(project, worktree, sid, dir, { handoff = true } = {}) {
const token = newToken();
const handlePath = handleFile(project, sid);
ensureDir(path.dirname(handlePath));
@@ -389,6 +456,9 @@ async function startServer(project, sid, dir, { handoff = true } = {}) {
`--session=${dir}`,
`--token=${token}`,
`--project=${project}`,
// The checkout the session runs in, which the state does not hold yet
// on a fresh open. See WORKTREE in server.mjs.
`--worktree=${worktree}`,
...(handoff ? ["--handoff"] : []),
...(args["idle-ms"] ? [`--idle-ms=${args["idle-ms"]}`] : []),
],
@@ -487,20 +557,37 @@ function cmdPost() {
delete patch.folderIssue;
const ledgerLines = ledgerFromPost(dir, run, folderIssue, before.workflow);
let next;
// The patch is applied to a fresh read under the state lock, never to the
// read above: a send the person made in between is in the file, and a write
// built on the older read would take it away. Nothing in here may exit, so
// the lock is always let go; a refusal is carried out and reported after.
let refused = null;
let problems = [];
let written;
try {
next = applyPatch(before, patch);
written = updateState(dir, (fresh) => {
if (!fresh) {
refused = ["that session has no state", 1];
return null;
}
let next;
try {
next = applyPatch(fresh, patch);
} catch (e) {
refused = [e.message, 3];
return null;
}
problems = validate(next);
if (!problems.length && patch.chat) problems = validateChat(next, readChat(dir));
return problems.length ? null : next;
});
} catch (e) {
die(e.message, 3);
die(e.message, 1);
}
const problems = validate(next);
if (refused) die(...refused);
if (problems.length) return failValidation(problems);
if (patch.chat) {
const chatProblems = validateChat(next, readChat(dir));
if (chatProblems.length) return failValidation(chatProblems);
}
const next = written.state;
writeJsonAtomic(statePath, next);
for (const line of ledgerLines) appendLedger(dir, line);
appendEvent(dir, { type: "post", items: (patch.items || []).length });
@@ -512,6 +599,7 @@ function cmdPost() {
items: next.items.length,
open,
phase: next.phase,
...unansweredNote(dir, next),
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
});
}
@@ -554,13 +642,15 @@ function ledgerFromPost(dir, run, issue, workflow) {
async function cmdWait() {
const dir = mustSession();
// A --seconds that is not a number would make the deadline NaN, and the
// slice would end at once with exit 10: a busy loop, not a wait.
// "240s" reads as 240. A --seconds with no number in it at all would make
// the deadline NaN, and the slice would end at once with exit 10: a busy
// loop, not a wait. So that is refused rather than guessed at.
const given = args.seconds;
if (given !== undefined && (typeof given !== "string" || !given.trim() || !Number.isFinite(Number(given)))) {
const asked = typeof given === "string" ? Number.parseFloat(given) : NaN;
if (given !== undefined && !Number.isFinite(asked)) {
die(`--seconds must be a number, got "${args.seconds}"`, 2);
}
const seconds = Math.max(5, Number(args.seconds || 240));
const seconds = Math.max(5, given === undefined ? 240 : asked);
const sid = path.basename(dir);
const project = projectRoot();
const resultPath = path.join(dir, "result.json");
@@ -580,6 +670,11 @@ async function cmdWait() {
// was a full read and parse every 400ms, which put up to 0.4s between the
// person pressing Send and the agent starting on it, on every single send.
let healthAt = 0;
// A busy server (right after a post, say) can miss one health check without
// being gone. Only a missing handle or dead pid is proof at once; a server
// that merely does not answer must fail three checks in a row, each with a
// longer look, before the slice ends with exit 20.
let healthMisses = 0;
// Null, not the current stamp: a result written between the check above and
// this line would otherwise read as already seen and wait out the slice.
let seen = null;
@@ -605,11 +700,17 @@ async function cmdWait() {
if (Date.now() - healthAt > 5000) {
healthAt = Date.now();
const handle = listHandles(project).find((h) => h.sid === sid);
if (!handle || !pidAlive(handle.pid) || !(await healthOk(handle))) {
if (!handle || !pidAlive(handle.pid)) {
print(serverGone(sid));
process.exitCode = 20;
return;
}
if (await healthOk(handle, 4000)) healthMisses = 0;
else if (++healthMisses >= 3) {
print(serverGone(sid));
process.exitCode = 20;
return;
} else healthAt = Date.now() - 3000; // look again in about 2s, not 5s
}
sleepSync(50);
}
@@ -630,7 +731,9 @@ async function cmdWait() {
staged,
url: handle ? handle.url : "",
message: "Waiting on your answer in the web console",
next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.",
pendingChat: 0,
...unansweredNote(dir, state),
// A workspace change alone never ends a slice: it rides on the next send.
pendingWorkspace: pendingWorkspaceChanges(dir).length,
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
@@ -638,11 +741,19 @@ async function cmdWait() {
process.exitCode = 10;
}
// Quick questions already handed over with no reply yet. Always empty when all are answered.
function unansweredNote(dir, state) {
const seqs = unansweredChat(dir, state);
return seqs.length
? { unansweredChat: seqs, warning: "Quick questions " + seqs.join(", ") + " have no reply yet and the page still shows them as pending. Reply to each now (chat.replies, re = seq): do what was asked when you can, or say why you will not." }
: {};
}
function serverGone(sid) {
return {
status: "server-gone",
sid,
message: "The console server is not running. Start it again with `open --resume` and give the person the new link.",
message: "The console server is not running. Start it again with `open --resume <sid> --no-open`, then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
};
}
@@ -943,10 +1054,13 @@ async function cmdStop() {
// reboot in the system temp directory, and PIDs get reused; without this
// check `stop --all` can kill an unrelated program that happens to have
// inherited the number. /health returning our own sid is the only proof:
// a young handle with a live pid is not, since the server may have died
// minutes ago and its number gone straight to something else. A server
// too wedged to answer /health still meets its own idle deadline.
if (!(await healthOk(h))) {
// a live pid and a young handle are not, since a server that died a
// minute ago leaves exactly that behind for any process to inherit. A
// busy server gets a second, longer look, and still has to answer as
// ours; one that does not is left alone, and only its handle goes.
const young = Date.now() - Date.parse(h.startedAt || 0) < MAX_SERVER_LIFE_MS;
const ours = (await healthOk(h)) || (young && pidAlive(h.pid) && (await healthOk(h, 5000)));
if (!ours) {
skipped++;
try {
fs.rmSync(h.handlePath, { force: true });
@@ -1074,18 +1188,6 @@ const COMMANDS = {
help: cmdHelp,
};
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written on every invocation, help and errors included.
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
// Say which Node is too old, rather than dying later inside a health check with
// "fetch is not defined". Whatever agent is driving this has to be able to read
// the failure, tell the person in one line, and carry on in the terminal.
@@ -1105,4 +1207,12 @@ if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
process.exit(2);
}
// A flag given with no value parses as `true`, and a boolean handed on as a
// path or a name crashes somewhere deep (path.basename(true) throws). Every
// flag that takes a value is checked once, here, and refused as bad usage.
const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "upload", "name", "from", "seconds", "limit", "idle-ms"];
for (const flag of VALUE_FLAGS) {
if (flag in args && typeof args[flag] !== "string") die(`--${flag} needs a value`, 2);
}
await COMMANDS[cmd]();
@@ -39,6 +39,13 @@ export const SESSIONS_DIR = path.join(HOME_DIR, "sessions");
// state: a browser ties localStorage to the origin, and the origin carries the
// ephemeral port, so the file under this dir is the only copy of a preference
// that survives the next session's new port.
// Model menus for the `plan2code` launcher. The shipped list (bin/models.json) is the
// authors' and is overwritten by every install; the user's additions (models.json) are
// theirs. The launcher reads both. PLAN2CODE_MODELS_DIR moves them, for tests.
const PLAN2CODE_DIR = process.env.PLAN2CODE_MODELS_DIR || path.join(os.homedir(), ".plan2code");
export const SHIPPED_MODELS_FILE = path.join(PLAN2CODE_DIR, "bin", "models.json");
export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
@@ -141,6 +148,91 @@ export function appendEvent(dir, event) {
return line;
}
/* ----------------------------------------------------- the state lock */
// state.json has two writers in two processes: console.mjs (`open` and `post`,
// the agent's side) and the server (`/submit` stamps the phase and records
// what was sent on each item). Each writer reads the file, changes it and
// writes it back, so two of them overlapping lose whichever wrote first. Every
// read-modify-write of state.json therefore runs under this lock, a file
// created with O_EXCL beside it. The sections it guards are a read, a merge
// and a write, milliseconds long, so a lock older than LOCK_STALE_MS, or one
// whose holder has died, is a crash left behind and is broken. The wait runs
// past the stale age, so a writer always gets in eventually.
export const STATE_LOCK_FILE = "state.json.lock";
const LOCK_STALE_MS = 5000;
const LOCK_WAIT_MS = 7000;
function lockStale(lock) {
try {
const st = fs.statSync(lock);
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) return true;
const pid = Number.parseInt(fs.readFileSync(lock, "utf8"), 10);
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && !pidAlive(pid);
} catch (err) {
// Gone between the failed create and this look: free, so try again.
return err.code === "ENOENT";
}
}
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn) {
const lock = path.join(dir, STATE_LOCK_FILE);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
try {
fd = fs.openSync(lock, "wx");
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
} catch {}
continue;
}
sleepSync(Math.min(5 * (attempt + 1), 50));
}
}
try {
try {
fs.writeSync(fd, String(process.pid));
} finally {
fs.closeSync(fd);
}
return fn();
} finally {
try {
fs.rmSync(lock, { force: true });
} catch {}
}
}
// The one way to change state.json: under the lock, read it fresh, hand it to
// fn (null when there is no state yet, with the raw text beside it), and write
// back whatever fn returns. A null return writes nothing. Returns the written
// state and its text, or null.
export function updateState(dir, fn) {
const file = path.join(dir, "state.json");
return withStateLock(dir, () => {
let text = null;
try {
text = fs.readFileSync(file, "utf8");
} catch {}
let state = null;
try {
state = text === null ? null : JSON.parse(text);
} catch {}
const next = fn(state, text);
if (!next) return null;
return { state: next, text: writeJsonAtomic(file, next) };
});
}
export function sleepSync(ms) {
// Node built-ins only, and this runs in short one-shot CLI commands.
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
@@ -827,6 +919,41 @@ const ITEM_DEFAULTS = {
thread: [],
};
// The question a card asks. If a patch rewrites any of these on a known id, it
// is a new question wearing an old id.
const QUESTION_FIELDS = ["kind", "title", "body", "options", "steps", "rows", "summary", "doc", "verdicts"];
/**
* Merge item patches by id, and keep a reused id from inheriting the person's
* old answer. `submitted` is the server's record of what they sent to the
* PREVIOUS question. When a patch changes what an item asks and doesn't itself
* settle it, that record (and any stale `answer`) is dropped, so the page shows
* the new question as open instead of "Sent, waiting for Plan2Code" forever.
*/
function dropStaleSubmissions(currentItems, before, patchList) {
const merged = mergeKeyed(currentItems, patchList, "id", ITEM_DEFAULTS, "items");
for (const entry of patchList) {
const prev = (before || []).find((x) => x.id === entry.id);
if (!prev || (prev.submitted === undefined && prev.answer === undefined)) continue;
const rewritten = QUESTION_FIELDS.some(
(f) => f in entry && JSON.stringify(entry[f]) !== JSON.stringify(prev[f]),
);
const settles = entry.status === "answered" || entry.status === "skipped" || "answer" in entry;
// A settled question edited in place (a typo in its body) stays settled; only an
// explicit reopen turns it into a new question.
const wasSettled = prev.status === "answered" || prev.status === "skipped";
// A different kind is never a typo fix: a multi turned confirm is another question.
const kindChanged = "kind" in entry && entry.kind !== prev.kind;
const reopens = entry.status === "open" || entry.status === "reopened" || kindChanged;
if (!rewritten || settles || (wasSettled && !reopens)) continue;
const item = merged.find((x) => x.id === entry.id);
if (wasSettled && !("status" in entry)) item.status = "open";
if (!("submitted" in entry)) delete item.submitted;
delete item.answer;
}
return merged;
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -868,7 +995,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = mergeKeyed(next.items, v, "id", ITEM_DEFAULTS, "items");
next.items = dropStaleSubmissions(next.items, state.items, v);
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1033,6 +1160,17 @@ export function validate(state) {
if ((item.kind === "choice" || item.kind === "multi") && !Array.isArray(item.options)) {
problems.push(`item "${item.id}" is a ${item.kind} and needs "options"`);
}
if ((item.kind === "choice" || item.kind === "multi") && Array.isArray(item.options)) {
for (const o of item.options) {
if (!o || typeof o.k !== "string" || !o.k.trim()) {
problems.push(`item "${item.id}" has an option with no "k" (its key, like "A")`);
} else if (typeof o.text !== "string" || !o.text.trim()) {
problems.push(
`item "${item.id}" option "${o.k}" needs "text" (the label) and optionally "detail". Options use "text"/"detail", not "label"/"desc".`
);
}
}
}
if (item.verdicts != null) {
if (!Array.isArray(item.verdicts) || !item.verdicts.length) {
problems.push(`item "${item.id}" "verdicts" must be a non-empty array of { id, label }`);
@@ -1051,16 +1189,18 @@ export function validate(state) {
if (item.templates != null && (item.kind !== "text" || item.templates !== "idea")) {
problems.push(`item "${item.id}" has "templates": only a text item can carry it, and its only value is "idea".`);
}
// The page compiles this to check the answer. One that will not compile
// is dropped there, so the check the agent asked for would silently not run.
// The page compiles it as the person types, and a pattern that does not
// compile throws there, on every keystroke, with nothing on screen to say why.
if (item.pattern != null) {
let compiles = typeof item.pattern === "string";
try {
if (compiles) new RegExp(item.pattern);
} catch {
compiles = false;
if (typeof item.pattern !== "string") {
problems.push(`item "${item.id}" "pattern" must be a string holding a JavaScript regular expression`);
} else {
try {
new RegExp(item.pattern);
} catch (e) {
problems.push(`item "${item.id}" "pattern" is not a valid JavaScript regular expression: ${e.message}`);
}
}
if (!compiles) problems.push(`item "${item.id}" "pattern" must be a string holding a valid JavaScript regular expression`);
}
const recs = (item.options || []).filter((o) => o.recommended);
if (recs.length > 1) problems.push(`item "${item.id}" marks ${recs.length} options recommended; at most one`);
@@ -1148,7 +1288,7 @@ export function validate(state) {
// server's record of an answer someone pressed Send on; if their own words
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
// would be rejected and the session would wedge with no way out.
const authored = state.items.map(({ submitted, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -1203,6 +1343,8 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
// chat.ndjson the server. One JSON line per entry: message / decision / reset.
// chat-cursor.json console.mjs. The last seq the agent was handed.
// state.json console.mjs `post`. The agent's replies, under chat.replies.
// (state.json as a whole has a second writer, the server's
// /submit, so every change to it goes through updateState().)
//
// The Workspace and the session meter follow the same rule, in files that
// switchWorkflow() never touches, so they carry across dashboard hops:
@@ -1351,6 +1493,19 @@ export function deliverableChat(entries) {
return entries.some((e) => e.kind !== "reset") ? entries : [];
}
// Things the person said that were handed over but never answered. The page keeps
// showing "working on the answer" for each until a reply lands, so the agent is
// told on every post and every wait slice until it has replied (a refusal is a reply).
export function unansweredChat(dir, state) {
const { conversation } = currentConversation(readChat(dir, 0));
const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re));
const cursor = readCursor(dir);
return readChat(dir, 0)
.filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation)
.filter((e) => e.seq <= cursor && !replied.has(e.seq))
.map((e) => e.seq);
}
// How many things the person said are still waiting to be collected.
export function pendingChatCount(dir, state) {
return collectChat(dir, state).filter((e) => e.kind !== "reset").length;
@@ -25,6 +25,7 @@ export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace"
export const WINDOWS_PICKER_SOURCE = `
using System;
using System.Runtime.InteropServices;
using System.Threading;
public static class Plan2CodeFolderPicker {
[ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
@@ -62,12 +63,40 @@ public static class Plan2CodeFolderPicker {
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
private static extern void SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid iid, out IShellItem item);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string className, string title);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int w, int h, uint flags);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int index);
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);
private static void Raise(string title) {
for (int i = 0; i < 100; i++) {
IntPtr hwnd = FindWindow(null, title);
if (hwnd != IntPtr.Zero) {
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
int h = Math.Min(750, GetSystemMetrics(1) - 80);
int x = (GetSystemMetrics(0) - w) / 2 + 40;
int y = (GetSystemMetrics(1) - h) / 2 + 40;
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
SetForegroundWindow(hwnd);
return;
}
Thread.Sleep(50);
}
}
public static string Pick(IntPtr owner, string title, string start) {
IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
try {
@@ -83,6 +112,9 @@ public static class Plan2CodeFolderPicker {
dialog.SetFolder(folder);
} catch (Exception) {}
}
Thread raiser = new Thread(delegate() { Raise(title); });
raiser.IsBackground = true;
raiser.Start();
int hr = dialog.Show(owner);
if (hr == ERROR_CANCELLED) return null;
Marshal.ThrowExceptionForHR(hr);
@@ -69,6 +69,22 @@ export function submittedAwaiting(item) {
return replied ? null : s;
}
/**
* The note (and its attachments) the person last sent on an item, while the
* agent has yet to say anything after it. The server records it as `sentNote`
* on every send, so the page can show it in the Notes pane and in the Sent
* box instead of letting it vanish into a send that shows no sign of arriving.
* Any thread message from the send onwards, or none with a clock to compare,
* means it has been picked up.
*/
export function noteAwaiting(item) {
const n = item && item.sentNote;
if (!n || typeof n !== "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -11,10 +11,10 @@
--ink-3: #8f8779;
--rule: #e4ddd1;
--rule-2: #cfc6b6;
--accent: #ae4f2b;
--accent-soft: #fbeee7;
--accent: #206cc3;
--accent-soft: #ecf2f9;
--accent-ink: #ffffff;
--accent-line: #dd9b7e;
--accent-line: #9ab4d3;
--ok: #2f6b45;
--ok-soft: #e4f0e8;
--stage: #9a6a12;
@@ -49,10 +49,10 @@
--ink-3: #8b8376;
--rule: #332e29;
--rule-2: #46403a;
--accent: #e8825a;
--accent-soft: #34211a;
--accent-ink: #1a120e;
--accent-line: #8a4f36;
--accent: #619fe5;
--accent-soft: #1a2533;
--accent-ink: #0c1117;
--accent-line: #3d5978;
--ok: #74c28f;
--ok-soft: #1c2d22;
--stage: #e0ab4c;
@@ -73,10 +73,10 @@
--ink-3: #8b8376;
--rule: #332e29;
--rule-2: #46403a;
--accent: #e8825a;
--accent-soft: #34211a;
--accent-ink: #1a120e;
--accent-line: #8a4f36;
--accent: #619fe5;
--accent-soft: #1a2533;
--accent-ink: #0c1117;
--accent-line: #3d5978;
--ok: #74c28f;
--ok-soft: #1c2d22;
--stage: #e0ab4c;
@@ -241,6 +241,19 @@ body {
}
.meter-pop[hidden] { display: none; }
.meter-tip { margin: 0 0 6px; font-size: 13px; color: var(--ink-2); }
.meter-list {
list-style: none; margin: 0 0 8px; padding: 6px 0 0;
border-top: 1px solid var(--rule);
max-height: 40vh; overflow-y: auto;
font-size: 12px; color: var(--ink-2);
}
.meter-list[hidden] { display: none; }
.meter-list li { display: flex; justify-content: space-between; gap: 16px; padding: 2px 0; }
.meter-fresh { margin: 0 0 8px; padding-top: 6px; border-top: 1px solid var(--rule); }
.meter-fresh[hidden] { display: none; }
.meter-fresh-text { margin: 0 0 6px; font-size: 12px; color: var(--ink-2); }
.meter-fresh-row .handoff-code { flex-basis: 180px; font-size: 12px; padding: 6px 10px; }
.meter-item-points { flex: none; font-weight: 600; color: var(--ink); font-variant-numeric: tabular-nums; }
.badge {
font-size: 11px;
@@ -652,6 +665,16 @@ h1 {
}
.wake.dormant .wake-hint { opacity: 1; }
/* Skip: muted, bottom right, so it never competes with the animation. */
.wake-skip {
position: absolute; right: 14px; bottom: 14px;
padding: 4px 12px; border: 1px solid var(--ink-3); border-radius: 4px;
background: transparent; color: var(--ink-3);
font: inherit; font-size: 0.8rem; letter-spacing: 0.08em; text-transform: uppercase;
cursor: pointer; opacity: 0.7;
}
.wake-skip:hover, .wake-skip:focus-visible { opacity: 1; color: var(--ink); border-color: var(--ink); }
/* 0.0 s, powered down: the resting state every beat starts from. Arms hang
slack against his sides, the star is shut and the smile not yet drawn. */
.wake-bot { filter: grayscale(1); opacity: 0.55; }
@@ -1132,6 +1155,20 @@ h1 {
.rail-mark { flex: none; width: 15px; text-align: center; font-size: 12px; color: var(--ink-3); margin-top: 1px; }
.rail-mark.done { color: var(--ok); }
.rail-mark.staged { color: var(--stage); font-weight: 700; }
/* Echoes the center pane's "Suggested" pill, which can scroll out of view;
the dot keeps the call-out visible while just scanning the rail. The
title grows to push the dot flush with the row's right edge. */
.rail-item > span:not(.rail-mark):not(.rail-suggested-dot) { flex: 1 1 auto; }
.rail-suggested-dot {
flex: none;
width: 7px;
height: 7px;
border-radius: 50%;
margin-top: 5px;
background: var(--accent);
}
.rail-item.is-suggested:not([aria-current="true"]) { color: var(--ink); }
.rail-mark.open { color: var(--accent); }
/* The session's own page, above the topic groups. It names the state it is
@@ -1618,7 +1655,7 @@ input[type="text"].invalid { border-color: var(--warn); }
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
}
#btn-send:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
.btn.ghost:hover { background: var(--panel-2); color: var(--ink); }
.btn.danger { border-color: var(--warn); color: var(--warn); }
@@ -1734,6 +1771,7 @@ input[type="text"].invalid { border-color: var(--warn); }
}
.attach-row { display: flex; align-items: center; margin: -4px 0 6px -13px; }
.attach-row.is-under { margin: 6px 0 4px -13px; }
.attach-tray { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }
.attach-thumb {
position: relative;
@@ -1784,6 +1822,10 @@ input[type="text"].invalid { border-color: var(--warn); }
font-size: 12.5px; font-weight: 600; color: var(--ink);
}
.attach-chip-size { color: var(--ink-2); font-size: 11.5px; }
.attach-link { color: inherit; text-decoration: none; border-radius: 8px; }
.attach-link:hover .attach-thumb, .attach-link:focus-visible .attach-thumb { border-color: var(--accent); }
.attach-link:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.msg.pending { border-style: dashed; border-color: var(--stage); background: transparent; }
.ask-row .attach-chip { padding-right: 10px; }
.footer-held { margin-top: 3px; color: var(--ink-2); font-size: 12.5px; }
@@ -1863,6 +1905,23 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
transition: opacity 0.12s;
}
.md-pre-wrap:hover .md-copy, .md-copy:focus { opacity: 1; }
/* Run it, on git blocks: Copy's twin, tucked under it so the wider
"Press Ctrl+C" fallback label can never collide. */
.md-run {
position: absolute; top: 34px; right: 8px;
font: 600 11.5px var(--sans);
background: var(--panel); color: var(--ink-2);
border: 1px solid var(--rule-2); border-radius: 6px;
padding: 4px 9px; cursor: pointer; opacity: 0;
transition: opacity 0.12s;
}
.md-pre-wrap:hover .md-run, .md-run:focus { opacity: 1; }
/* The muted nudge on other command-looking blocks, a caption under the block. */
.md-run-hint {
margin: -6px 2px 0;
font: 11px var(--sans); color: var(--ink-3);
opacity: 0.8;
}
.md-hr { border: 0; border-top: 1px solid var(--rule); margin: 20px 0; }
.md-table-wrap { overflow-x: auto; margin: 0 0 13px; }
.md-table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
@@ -1996,9 +2055,15 @@ kbd {
.icon-btn:hover .ab-mark, .icon-btn:hover .ab-dot { stroke: var(--accent); fill: none; }
.icon-btn:hover .ab-dot { fill: var(--accent); }
.icon-btn .sw-a { fill: var(--accent); }
.icon-btn .sw-b { fill: var(--ok); }
.icon-btn .sw-c { fill: var(--stage); }
a.icon-btn { box-sizing: border-box; text-decoration: none; }
.icon-btn .mg-body { fill: none; stroke: var(--ink-3); stroke-width: 1.4; stroke-linejoin: round; }
.icon-btn .mg-line { fill: none; stroke: var(--ink-2); stroke-width: 1.4; stroke-linecap: round; stroke-linejoin: round; }
.icon-btn:hover .mg-body, .icon-btn:hover .mg-line { stroke: var(--accent); }
.icon-btn .gr-teeth { fill: none; stroke: var(--ink-3); stroke-width: 2.2; }
.icon-btn .gr-ring { fill: none; stroke: var(--ink-3); stroke-width: 1.6; }
.icon-btn .gr-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
.icon-btn:hover .gr-teeth, .icon-btn:hover .gr-ring, .icon-btn:hover .gr-hub { stroke: var(--accent); }
/* ------------------------------------------------------------ swatches */
@@ -2132,7 +2197,8 @@ kbd {
flex-direction: column;
}
.modal.help[open] { display: flex; }
.modal.help .modal-actions { flex: none; margin-top: 16px; }
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
.help-layout {
display: grid;
@@ -2288,6 +2354,111 @@ kbd {
}
.modal::backdrop { background: rgba(0, 0, 0, 0.45); }
.modal h2 { font: 600 21px/1.25 var(--serif); margin: 0 0 10px; }
/* The Welcome: a dark poster with Planny, four columns, one button. */
.modal.welcome {
width: min(840px, calc(100vw - 32px));
max-width: none;
padding: 0;
overflow: hidden;
}
.modal.welcome[open] { display: flex; flex-direction: column; max-height: calc(100vh - 96px); }
.welcome-poster {
position: relative;
flex: none;
overflow: hidden;
padding: 52px 48px 40px;
text-align: center;
color: #fff;
background:
radial-gradient(circle at 50% 125%, color-mix(in srgb, var(--accent) 85%, #fff) 0, transparent 58%),
linear-gradient(180deg, #16181d, color-mix(in srgb, var(--accent) 50%, #16181d));
}
.welcome-sky i { position: absolute; width: 3px; height: 3px; border-radius: 50%; background: #fff; opacity: 0.55; }
.welcome-sky i:nth-child(1) { top: 18%; left: 11%; }
.welcome-sky i:nth-child(2) { top: 34%; left: 84%; }
.welcome-sky i:nth-child(3) { top: 12%; left: 66%; }
.welcome-sky i:nth-child(4) { top: 56%; left: 20%; }
.welcome-sky i:nth-child(5) { top: 62%; left: 91%; }
.welcome-sky i:nth-child(6) { top: 26%; left: 32%; width: 2px; height: 2px; }
.welcome-bot { display: flex; justify-content: center; }
/* The dock's own Planny, larger and in light ink for the dark poster. */
.welcome-bot .planny { width: 70px; height: 96px; }
.welcome-bot .planny .shell,
.welcome-bot .planny .smile,
.welcome-bot .planny .arm path { stroke: #f0ece5; }
.welcome-bot .planny .shell { fill: #1e2127; }
.welcome-bot .planny .arm circle,
.welcome-bot .planny .foot { fill: #f0ece5; }
.welcome-kicker {
margin: 20px 0 6px;
font-size: 12px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: rgba(255, 255, 255, 0.75);
}
.modal.welcome h2 { font: 600 38px/1.15 var(--serif); margin: 0 0 12px; color: #fff; }
.welcome-lead { margin: 0 auto; max-width: 52ch; font-size: 15px; line-height: 1.55; color: rgba(255, 255, 255, 0.85); }
.welcome-cols {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
min-height: 0;
overflow-y: auto;
padding: 34px 36px 8px;
text-align: center;
}
.welcome-col h3 { font: 600 15px/1.3 var(--sans); margin: 12px 0 4px; color: var(--ink); }
.welcome-col p { margin: 0; font-size: 13px; line-height: 1.5; color: var(--ink-2); }
.welcome-col strong { color: var(--ink); }
.welcome-col code {
font: 600 12px var(--mono);
padding: 1px 6px;
border-radius: 5px;
background: var(--accent-soft);
color: var(--accent);
}
.welcome-col kbd {
font: 600 11.5px var(--mono);
padding: 0 6px;
border-radius: 5px;
border: 1px solid var(--rule-2);
border-bottom-width: 2px;
background: var(--panel-2);
color: var(--ink);
}
.welcome-dot { display: inline-grid; place-items: center; width: 50px; height: 50px; border-radius: 50%; }
.welcome-dot svg {
width: 22px;
height: 22px;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.welcome-dot.is-accent { background: var(--accent-soft); color: var(--accent); }
.welcome-dot.is-stage { background: var(--stage-soft); color: var(--stage); }
.welcome-dot.is-plain { background: var(--panel-2); color: var(--ink-2); border: 1px solid var(--rule); }
.welcome-dot.is-ok { background: var(--ok-soft); color: var(--ok); }
.welcome-dot.is-bare { background: none; color: var(--ok); }
.welcome-dot.is-bare svg { width: 30px; height: 30px; }
.modal.welcome .modal-actions { flex: none; justify-content: center; margin: 0; padding: 24px 36px 36px; }
.modal.welcome .modal-actions .btn { padding: 12px 40px; font-size: 15px; border-radius: 999px; }
@media (max-width: 720px) {
.welcome-poster { padding: 36px 24px 28px; }
.modal.welcome h2 { font-size: 28px; }
.welcome-cols { grid-template-columns: 1fr 1fr; padding: 24px 20px 8px; }
}
.help-link {
background: none;
border: 0;
padding: 0;
font: inherit;
color: var(--accent);
text-decoration: underline;
cursor: pointer;
}
.help-link:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 2px; }
.modal-blurb { margin: 0 0 18px; color: var(--ink-2); font-size: 13.5px; }
.modal-ranges { border: 0; margin: 0; padding: 0; display: grid; gap: 8px; }
@@ -3190,3 +3361,24 @@ kbd {
.help-mood-bot, .help-mood-bot *, .help-mood-bot.is-work .eye { animation: none !important; }
#btn-send { animation: none; }
}
/* User Preferences: the launcher's model menu. */
.models-tabs { display: flex; gap: 6px; }
.models-tabs .btn[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
.models-note { font-size: 0.9em; opacity: 0.85; }
.models-note p, .models-note ul { margin: 0 0 6px; }
.models-note ul { padding-left: 18px; }
.models-list { display: grid; gap: 4px; max-height: 160px; overflow: auto; }
.models-list:empty { display: none; }
.models-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 6px; align-items: center; }
.models-row.locked { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); font-size: 0.88em; opacity: 0.75; }
.models-row input { min-width: 0; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* A word the person has to type, bold and in their highlight color so it
does not get lost in the status sentence. */
.agent-key {
color: var(--accent);
font-weight: 700;
}
@@ -10,7 +10,7 @@
// this, that reversibility is the whole point.
import { md, el, copyButton, selectContents } from "./render.js";
import { ACCENTS, DEFAULT_CARD_WIDTH, SOUND_EVENTS, cardWidth, soundKey, soundPrefs } from "./palette.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, SOUND_EVENTS, cardWidth, soundKey, soundPrefs } from "./palette.js";
import { activityLabel, workingLine } from "./labels.js";
import { playWake } from "./boot.js";
import {
@@ -64,6 +64,7 @@ import {
STOP_REPLY,
sentAnswer,
submittedAwaiting,
noteAwaiting,
suggestionFrom,
THUMB_EDGE,
turnGate,
@@ -128,7 +129,7 @@ const LOOKS_KEY = "p2c-console:looks";
// The per-event sound switches (SOUND_EVENTS) live in palette.js too.
const DEFAULT_LOOKS = {
theme: "system",
accent: "rust",
accent: DEFAULT_ACCENT,
sound: true,
...soundPrefs(null),
width: DEFAULT_CARD_WIDTH,
@@ -136,6 +137,8 @@ const DEFAULT_LOOKS = {
};
let looks = { ...DEFAULT_LOOKS };
let syncedLooks = null;
let looksReady = false;
function adoptLooks(saved) {
looks = { ...DEFAULT_LOOKS, ...saved };
@@ -178,25 +181,47 @@ async function syncLooks() {
}
if (saved && saved.looks && typeof saved.looks === "object") {
adoptLooks(saved.looks);
syncedLooks = { ...looks };
try {
localStorage.setItem(LOOKS_KEY, JSON.stringify(looks));
} catch {}
applyLooks();
renderSwatches();
} else if (localStorage.getItem(LOOKS_KEY)) {
pushLooks();
} else {
// Blocked storage throws on read, and that must not stop the page loading.
let held = false;
try {
held = Boolean(localStorage.getItem(LOOKS_KEY));
} catch {}
if (held) pushLooks();
}
looksReady = true;
// Not inline: with the server's copy in the page this runs before `S` exists.
setTimeout(maybeWelcome, 0);
}
// Fire-and-forget mirror. A failed POST costs nothing the next session would
// notice on this port; the localStorage copy still covers the reload case.
function pushLooks() {
try {
// Only what this tab changed since it last synced, so a tab with stale
// settings never overwrites another tab's change to a different key.
const set = {};
for (const [k, v] of Object.entries(looks)) if (!syncedLooks || syncedLooks[k] !== v) set[k] = v;
const before = syncedLooks;
const partial = Boolean(before);
if (partial && !Object.keys(set).length) return;
syncedLooks = { ...looks };
const body = partial ? { set } : { looks };
// A write that did not land must be sent again with the next change.
const undo = () => (syncedLooks = before);
fetch("/looks", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ looks }),
}).catch(() => {});
body: JSON.stringify(body),
})
.then((res) => res.ok || undo())
.catch(undo);
} catch {}
}
@@ -380,6 +405,24 @@ for (const evt of ["pointerdown", "keydown"]) {
});
}
// Run it, on a fenced git block (render.js): stage the block as the Ask
// draft and open the chat. The person still presses Send, so nothing runs
// on a stray click — the same fill-the-box pattern as the Ask starters.
document.addEventListener("click", (e) => {
const run = e.target.closest(".md-run");
if (!run) return;
const code = run.closest(".md-pre-wrap")?.querySelector("code");
if (!code || !code.textContent.trim()) return;
local.chat.draft = `run:\n${code.textContent}`;
view = "ask";
save();
render();
const ta = $("ask-input");
if (!ta) return;
ta.focus();
ta.setSelectionRange(ta.value.length, ta.value.length);
});
// The stars for Planny's flight, made once. Each gets its place and pace as
// custom properties set through the CSSOM: the CSP forbids style attributes
// in markup, and the stylesheet cannot roll dice. They sit still, invisible,
@@ -795,13 +838,16 @@ async function loadState() {
const res = await fetch("/state", { cache: "no-store" });
if (!res.ok) throw new Error(String(res.status));
const body = await res.json();
adopt(body);
// The server answers again: back to the stream, once the wait is up.
if (!es && pollTimer && Date.now() >= esRetryAt) {
clearInterval(pollTimer);
pollTimer = null;
connect();
// The same rev is the same state: adopting it again would redraw the page
// every few seconds while polling for nothing. Still proof of life, though.
if (S && typeof body.rev === "number" && body.rev === rev) {
lastContact = Date.now();
agentLastSeen = body.agentLastSeen || agentLastSeen;
markGone();
} else {
adopt(body);
}
retryStream();
} catch {
markGone();
}
@@ -1158,6 +1204,11 @@ function connect() {
esErrors = 0;
esRetryMs = ES_RETRY_MIN_MS;
lastContact = Date.now();
// Back on the stream: polling was only ever the stand-in.
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
};
es.onerror = () => {
esErrors++;
@@ -1179,6 +1230,18 @@ function startPolling() {
pollTimer = setInterval(loadState, 3000);
}
// While polling, every answer from the server is a cue to try the stream
// again, so polling lasts only as long as the outage did. Polling carries on
// while an attempt is open, so startPolling() never runs for a failed one; the
// wait is pushed back here instead, or a dead stream would be retried on every
// poll. One attempt at a time, since `es` is set while it is trying.
function retryStream() {
if (!pollTimer || es || Date.now() < esRetryAt) return;
esRetryAt = Date.now() + esRetryMs;
esRetryMs = Math.min(esRetryMs * 2, ES_RETRY_MAX_MS);
connect();
}
setInterval(() => {
fetch("/ping", { method: "POST" })
.then((r) => (r.ok ? r.json() : null))
@@ -1186,6 +1249,7 @@ setInterval(() => {
if (!body) return;
lastContact = Date.now();
agentLastSeen = body.agentLastSeen || agentLastSeen;
retryStream();
// A rev we have not seen means a state frame went missing -- a dropped
// SSE reconnect, a tab asleep in a background window. Ask for it rather
// than waiting for the next change to come along.
@@ -1442,6 +1506,31 @@ function renderMeter() {
$("meter-words").textContent = meterFrame.words;
pill.title = meterFrame.tooltip;
$("meter-tip").textContent = meterFrame.tooltip;
// What the points are made of: one row per piece of work that scored.
const list = $("meter-list");
const rows = Array.isArray(meterFrame.items) ? meterFrame.items : [];
list.hidden = !rows.length;
list.replaceChildren(
...rows.map((row) => {
const li = el("li");
li.appendChild(el("span", "meter-item-label", row.label));
li.appendChild(el("span", "meter-item-points", "+" + row.points));
return li;
})
);
// Once the session is past fresh, say how to start a new one.
const fresh = $("meter-fresh");
fresh.hidden = meterFrame.level === "green";
if (fresh.hidden || fresh.dataset.built) return;
fresh.dataset.built = "1";
const text = handoffText({ command: DASHBOARD_COMMAND });
const code = el("code", "handoff-code", text);
const row = el("div", "handoff-command meter-fresh-row");
row.append(code, copyButton(text, "btn small ghost handoff-copy", code));
fresh.append(
textWithCode("p", "meter-fresh-text", `To start a new session, run \`${DASHBOARD_COMMAND}\` in a new conversation:`),
row
);
}
function toggleMeterPop(open) {
@@ -1469,7 +1558,7 @@ function renderChrome() {
renderMeter();
$("title").textContent = S.title || "Session";
$("badge").textContent = workflowLabel(S.workflow);
document.title = (S.title || "Session") + " · Plan2Code";
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
const h = S.headline || {};
// On a finished session an open item is frozen: the send on it counts as
@@ -1529,7 +1618,18 @@ function renderStatus() {
moodVar = Math.floor(Math.random() * MOOD_VARIANTS[mood]);
}
bot.setAttribute("class", `planny is-${mood} v${moodVar}`);
if (text.textContent !== line) text.textContent = line;
if (text.dataset.line !== line) {
text.dataset.line = line;
text.replaceChildren(
...line.split(/\*\*(.+?)\*\*/).map((part, i) => {
if (i % 2 === 0) return document.createTextNode(part);
const key = document.createElement("strong");
key.className = "agent-key";
key.textContent = part;
return key;
})
);
}
tick.textContent = count || "";
$("agent-spin").hidden = !spin;
$("dock").classList.toggle("is-flying", Boolean(spin));
@@ -1584,7 +1684,7 @@ function renderStatus() {
if (agentStale()) {
return say(
"work",
"Plan2Code has not checked in for a few minutes. Your answers are saved. Have a look at your terminal (it may be happily working away, or waiting for your permission approval)."
"Still working on it. Longer tasks can go a few minutes between updates. Your answers are saved. If it stays quiet for a long while, check your terminal (it may be waiting on a permission approval)."
);
}
// Same clock as agentStale(), so the soft line at 30 s hands over to the
@@ -1602,8 +1702,8 @@ function renderStatus() {
return say(
"adrift",
stranded()
? "Plan2Code is not running. Your answers are saved and waiting for it. The terminal may be waiting for your permission approval."
: "Plan2Code is not running right now. Anything you answer here is saved. The terminal may be waiting for your permission approval."
? "Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval."
: "Plan2Code is not running right now. Anything you answer here is saved. If the terminal is idle, type **continue** there to wake it; it may also be waiting for your permission approval."
);
}
@@ -1740,7 +1840,7 @@ function renderViews() {
for (const t of tabs) {
const b = el("button", "view-tab", t.label);
b.type = "button";
b.setAttribute("aria-current", String(view === t.id));
b.setAttribute("aria-current", String(view === t.id || (t.id === "questions" && view === "end")));
if (t.count) {
const c = el("span", "tab-count", String(t.count));
b.appendChild(c);
@@ -1756,7 +1856,7 @@ function renderViews() {
chatDot = false;
save();
}
view = t.id;
view = t.id === "questions" && finish() ? "end" : t.id;
// The cached text paints at once; the fresh read repaints if the file
// changed on disk since.
render();
@@ -1821,16 +1921,20 @@ function renderSidebar() {
// session outline usually lives. The card that is mid-launch gets the
// half-filled mark the page uses for "sent, on its way".
if (isDashboard() && !fin) {
const menu = (S && S.menu) || {};
for (const g of CATALOG_GROUPS) {
const box = el("div", "rail-group");
const head = el("p", "rail-title");
head.appendChild(el("span", null, g.title));
box.appendChild(head);
for (const e of SKILL_CATALOG.filter((x) => x.group === g.id)) {
const av = cardAvailability(e, scan(), selSpec());
const av = cardPresentation(e, scan(), selSpec(), menu);
// Unavailable for the selected spec fades hard; the brief greying
// while a launch is in flight or the server is away does not.
const b = el("button", "rail-item" + (av.on ? "" : " is-unavailable"));
const b = el(
"button",
"rail-item" + (av.on ? "" : " is-unavailable") + (av.recommended ? " is-suggested" : "")
);
b.type = "button";
b.disabled = Boolean(local.launching) || gone || pendingResult || !av.on;
if (!av.on && av.reason) b.title = av.reason;
@@ -1845,6 +1949,13 @@ function renderSidebar() {
mark.title = isGoing ? "starting" : isPicked ? "picked" : "pick to start";
b.appendChild(mark);
b.appendChild(el("span", null, e.title));
// The center pane's own "Suggested" pill scrolls out of view, so the
// rail repeats the call-out here as a small dot next to the title.
if (av.recommended) {
const dot = el("span", "rail-suggested-dot", "");
dot.title = "Suggested next step";
b.appendChild(dot);
}
// Same as a card click: the pick goes to the confirm pane, never
// straight to a launch. From the Overview tab too, so the pane shows.
b.addEventListener("click", () => {
@@ -2465,6 +2576,34 @@ function renderDashboard(main) {
if (note) revealNote(note, wake.typed);
}
main.appendChild(wrap);
// Deferred: this runs inside render(), and the dialog is not part of it.
queueMicrotask(maybeWelcome);
}
/* ------------------------------------------------------------- welcome */
// The first dashboard a person ever sees gets a Welcome dialog. Closing it by
// any route (button, Esc, backdrop) saves looks.welcomeSeen, which rides in
// looks.json like every other preference. Waits out the wake-up animation and
// never lands on top of another open dialog.
function maybeWelcome() {
if (!looksReady || looks.welcomeSeen === true || !S || !isDashboard() || finish() || wake) return;
if (document.querySelector("dialog[open]")) return;
openWelcome();
}
function openWelcome() {
if ($("help-modal").open) $("help-modal").close();
const slot = $("welcome-bot");
if (!slot.firstElementChild) {
const bot = $("planny").cloneNode(true);
bot.removeAttribute("id");
bot.setAttribute("class", "planny is-point v1");
slot.appendChild(bot);
}
const dlg = $("welcome-modal");
if (!dlg.open) dlg.showModal();
$("welcome-done").focus();
}
/* ------------------------------------------------------------- wake-up */
@@ -2505,10 +2644,12 @@ function maybeWake() {
playWake({
stage,
bot: stage.querySelector(".wake-bot"),
skipEl: stage.querySelector(".wake-skip"),
target: $("planny"),
stir: stirWake,
onStart: () => sound("bootup"),
onGlide: wakeGlide,
onSkip: skipWakeSounds,
signal: wake.abort.signal,
}).then(({ skipped }) => {
stopSnore();
@@ -2541,6 +2682,14 @@ function stopSnore() {
snore = null;
}
// The Skip button: silence anything the intro already queued or started. The
// promise's .then does the snore and the bootup fade; this only clears cues
// still waiting to play.
function skipWakeSounds() {
soundQueued = null;
soundHeld = null;
}
// The glide: the menu rises in and the note starts typing. On a skip the run
// is already ending and its promise settles everything, so nothing here.
function wakeGlide({ instant }) {
@@ -2575,7 +2724,10 @@ function typeNote() {
// Done once the entrance has played and the note is all there. Nothing to
// redraw: what is on screen already is the finished dashboard.
function settleWake() {
if (wake && wake.entered && wake.typed == null) wake = null;
if (wake && wake.entered && wake.typed == null) {
wake = null;
maybeWelcome();
}
}
function finishWake() {
@@ -3206,6 +3358,34 @@ function inFlightFor(item) {
return sub ? { value: sub, summary: "" } : null;
}
// A sent note's attachments as links: an image opens full size, a document
// opens in its own tab. The page serves both by the upload's own file name.
function sentAttachments(note) {
const entries = [
...(note.images || []).map((e) => ({ ...e, kind: "image" })),
...(note.files || []).map((e) => ({ ...e, kind: "file" })),
];
if (!entries.length) return null;
const tray = el("div", "attach-tray");
for (const e of entries) {
const a = el("a", "attach-link");
a.href = uploadUrl(e);
a.target = "_blank";
a.rel = "noopener";
a.title = e.name || "attachment";
if (e.kind === "image") {
const fig = el("figure", "attach-thumb is-ready");
const pic = el("img");
pic.src = a.href;
pic.alt = e.name || "image";
fig.appendChild(pic);
a.appendChild(fig);
} else a.appendChild(docChip({ name: e.name || "file" }, "ready"));
tray.appendChild(a);
}
return tray;
}
function renderCard(item) {
const staged = local.staged[item.id];
const flight = inFlightFor(item);
@@ -3357,6 +3537,13 @@ function renderInFlight(card, item, flight) {
box.appendChild(ul);
}
if (text) box.appendChild(el("blockquote", "answered-text", text));
const note = noteAwaiting(item);
const sub = submittedAwaiting(item);
if (note && sub && note.at === sub.at) {
if (note.text) box.appendChild(el("blockquote", "answered-text", note.text));
const tray = sentAttachments(note);
if (tray) box.appendChild(tray);
}
// Say which of the two it actually is. Once the agent has collected the send,
// "waiting to be picked up" is no longer true, and a status line that lies is
@@ -3660,6 +3847,19 @@ function stageQuiet(id, value) {
save();
}
// The next answer for a click, carrying over the words typed on the card. Note
// boxes stage quietly, without a render, so the `staged` a builder closed over
// at render time can be missing everything typed since: read the live answer
// when the click lands instead. A click that clears the pick while text is
// still in the box keeps the text as a note on its own (`bare`), the same shape
// the note box stages when nothing is picked.
function withNote(item, value, bare = { type: "answer", kind: item.kind }) {
const cur = local.staged[item.id];
const text = cur && cur.text;
if (!text) return value;
return value ? { ...value, text } : { ...bare, text };
}
// Unique per question and option, and the same on every render.
const optionId = (item, o, i) => `pick-${item.id}-${o.k || i}`;
@@ -3724,12 +3924,18 @@ function buildMulti(card, item, staged) {
box.checked = on;
box.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
box.addEventListener("change", () => {
const next = new Set(chosen);
const cur = local.staged[item.id];
const next = new Set((cur && cur.ks) || []);
if (box.checked) next.add(o.k);
else next.delete(o.k);
// Unticking the last box keeps what is written in "Anything else".
stage(
item.id,
next.size ? { type: "answer", kind: "multi", ks: [...next], text: staged && staged.text } : null
withNote(item, next.size ? { type: "answer", kind: "multi", ks: [...next] } : null, {
type: "answer",
kind: "multi",
ks: [],
})
);
});
@@ -3772,7 +3978,14 @@ function renderPresets(card, item, staged) {
b.type = "button";
b.setAttribute("aria-pressed", String(on));
b.addEventListener("click", () =>
stage(item.id, on ? null : { type: "answer", kind: "multi", ks: [...p.ks], text: staged && staged.text })
stage(
item.id,
withNote(item, on ? null : { type: "answer", kind: "multi", ks: [...p.ks] }, {
type: "answer",
kind: "multi",
ks: [],
})
)
);
row.appendChild(b);
}
@@ -3858,6 +4071,20 @@ function buildText(card, item, staged) {
wrap.appendChild(templateRow(item, input, templatesFor(S.workflow, looks.role), check));
}
wrap.appendChild(input);
// Fresh-idea boxes take files as context, the same ones the note pane holds.
if (!single && TEMPLATE_WORKFLOWS.includes(S.workflow)) {
input.addEventListener("paste", (e) => {
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
if (!files.length) return;
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
attachFiles(item.id, files);
});
const under = attachRow(item.id, "Add files to this answer");
under.classList.add("is-under");
wrap.appendChild(under);
const attached = noteImages(item.id);
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
}
if (item.help) wrap.appendChild(el("p", "help", item.help));
wrap.appendChild(err);
card.appendChild(wrap);
@@ -3946,7 +4173,9 @@ function buildConfirm(card, item, staged) {
const on = staged && staged.yes === yes;
const b = el("button", "btn" + (on ? " primary" : "") + (danger && !on ? " danger" : ""), label);
b.type = "button";
b.addEventListener("click", () => stage(item.id, on ? null : { type: "answer", kind: "confirm", yes }));
b.addEventListener("click", () =>
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "confirm", yes }))
);
return b;
};
row.appendChild(mk(yesLabel, true, item.danger));
@@ -4031,7 +4260,7 @@ function buildReview(card, item, staged) {
const b = el("button", "btn" + (on ? " primary" : "") + (v.danger && !on ? " danger" : ""), verdictText(v));
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, on ? null : { type: "answer", kind: "review", verdict: v.id, text: staged && staged.text })
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }))
);
row.appendChild(b);
}
@@ -4044,6 +4273,15 @@ function buildReview(card, item, staged) {
function buildChecklist(card, item, staged) {
const doneSet = new Set((staged && staged.done) || []);
// Built from the live answer, so a note typed since the render rides along.
// Nothing ticked, no state and no note is no answer at all: stage nothing
// rather than an empty one that would still count as ready to send.
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
const list = el("ol", "steps");
(item.steps || []).forEach((step, i) => {
const li = el("li", "step");
@@ -4052,10 +4290,11 @@ function buildChecklist(card, item, staged) {
box.id = `step-${item.id}-${i}`;
box.checked = doneSet.has(i);
box.addEventListener("change", () => {
const next = new Set(doneSet);
const cur = local.staged[item.id];
const next = new Set((cur && cur.done) || []);
if (box.checked) next.add(i);
else next.delete(i);
stage(item.id, { ...(staged || { type: "answer", kind: "checklist" }), done: [...next] });
commitList({ done: [...next] });
});
const label = el("label");
label.htmlFor = box.id;
@@ -4079,14 +4318,7 @@ function buildChecklist(card, item, staged) {
const on = staged && staged.state === s.id;
const b = el("button", "btn" + (on ? " primary" : ""), s.label);
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, {
...(staged || { type: "answer", kind: "checklist" }),
type: "answer",
kind: "checklist",
state: on ? null : s.id,
})
);
b.addEventListener("click", () => commitList({ state: on ? null : s.id }));
row.appendChild(b);
}
card.appendChild(row);
@@ -4142,7 +4374,7 @@ function buildList(card, item, staged) {
const ul = el("ul", "rows");
let dragIndex = null;
const commit = (next) => stage(item.id, { type: "answer", kind: "list", rows: next });
const commit = (next) => stage(item.id, withNote(item, { type: "answer", kind: "list", rows: next }));
rows.forEach((row, i) => {
const li = el("li", "row-item");
@@ -4245,7 +4477,8 @@ function buildList(card, item, staged) {
if (staged) {
const reset = el("button", "linky", "Put it back how it was");
reset.type = "button";
reset.addEventListener("click", () => stage(item.id, null));
// Puts the rows back; a note typed below stays.
reset.addEventListener("click", () => stage(item.id, withNote(item, null)));
row.appendChild(reset);
}
card.appendChild(row);
@@ -4267,8 +4500,14 @@ function commentField(card, item, labelText, required) {
ta.addEventListener("input", () => {
setDraft(id, ta.value);
const cur = local.staged[item.id];
if (cur) stageQuiet(item.id, { ...cur, text: ta.value.trim() || undefined });
else if (ta.value.trim())
if (cur) {
const next = { ...cur, text: ta.value.trim() || undefined };
// Emptying the box of a note-only answer leaves nothing to send, so it
// unstages rather than counting as ready.
const empty = (v) => v == null || v === "" || (Array.isArray(v) && !v.length);
const bare = Object.keys(next).every((k) => k === "type" || k === "kind" || empty(next[k]));
stageQuiet(item.id, bare ? null : next);
} else if (ta.value.trim())
stageQuiet(item.id, { type: "answer", kind: item.kind, text: ta.value.trim() });
stagedChanged();
});
@@ -4424,8 +4663,8 @@ function askState() {
// frame for the moment after a 409 stale, before the new frame lands.
const askConversation = () => local.chat.conversation ?? askFrame().conversation;
// An upload's server path is `<session>/uploads/<uuid>.jpg`; the page serves
// it at /uploads/<uuid>.jpg.
// An upload's server path is `<session>/uploads/<uuid>.<ext>`; the page serves
// it at /uploads/<uuid>.<ext>.
const uploadUrl = (img) => img.url || "/uploads/" + String(img.path || "").split(/[\\/]/).pop();
function renderAsk(main) {
@@ -4983,7 +5222,7 @@ function renderAside() {
aside.appendChild(el("h2", null, "Notes on this"));
const thread = item.thread || [];
if (!thread.length) {
if (!thread.length && !(isOpen(item) && !finish() && noteAwaiting(item))) {
aside.appendChild(
el(
"p",
@@ -5004,6 +5243,21 @@ function renderAside() {
aside.appendChild(box);
}
// A note that has been sent but not yet picked up: shown at once, so the
// send is seen to have gone, and gone when the agent replies.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
if (waiting) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
box.appendChild(who);
if (waiting.text) box.appendChild(md(waiting.text, "md"));
const tray = sentAttachments(waiting);
if (tray) box.appendChild(tray);
aside.appendChild(box);
}
// A finished session has nobody left for a note to reach, so the box would
// be a place to type words that go nowhere.
if (!isOpen(item) || finish()) {
@@ -5018,24 +5272,7 @@ function renderAside() {
wrap.appendChild(label);
const attached = noteImages(item.id);
const addRow = el("div", "attach-row");
const addBtn = el("button", "btn small ghost", "+ Attach file");
addBtn.type = "button";
addBtn.setAttribute("aria-label", "Add files to this note");
addBtn.disabled = attached.length >= MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
addBtn.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(item.id, picker.files);
picker.value = "";
});
addRow.appendChild(addBtn);
addRow.appendChild(picker);
wrap.appendChild(addRow);
wrap.appendChild(attachRow(item.id, "Add files to this note"));
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
@@ -5079,8 +5316,8 @@ function pageIcon() {
return svg;
}
// A document in a tray: never an <img>, since documents are never served
// back. Icon, extension badge, name and size, and nothing to click but ×.
// A document in a tray: never an <img>, since a document is not a picture.
// Icon, extension badge, name and size; a sent one is wrapped in a link.
function docChip(entry, status) {
const ext = docExt(entry.name) || "";
const fig = el("figure", `attach-thumb attach-chip is-${status}`);
@@ -5096,6 +5333,29 @@ function docChip(entry, status) {
return fig;
}
// The + Attach file control and its hidden picker, for a note's box or a
// card's own. Files go to the item's note attachments either way.
function attachRow(itemId, ariaLabel) {
const row = el("div", "attach-row");
const btn = el("button", "btn small ghost", "+ Attach file");
btn.type = "button";
btn.setAttribute("aria-label", ariaLabel);
btn.disabled = noteImages(itemId).length >= MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
btn.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(itemId, picker.files);
picker.value = "";
});
row.appendChild(btn);
row.appendChild(picker);
return row;
}
function attachTray(itemId, attached) {
const tray = el("div", "attach-tray");
for (const img of attached) {
@@ -5220,8 +5480,8 @@ function setNoteImages(itemId, list) {
else delete local.images[itemId];
}
// Where an attachment is deleted from. Documents are never served back, so
// they have no `url`; their route is built from the path, as uploadUrl does.
// Where an attachment is deleted from. Documents have no `url`, so their
// route is built from the path, as uploadUrl does.
const deleteUrl = (entry) => entry.url || "/uploads/" + String(entry.path || "").split(/[\\/]/).pop();
// The files in a paste worth attaching: images and allowed documents. A paste
@@ -6461,7 +6721,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.md-table th, .md-table td { border: 1px solid #e4ddd1; padding: 8px 11px; text-align: left; }
.md-table th { background: #fbf9f6; font-weight: 600; }
.md-img { max-width: 100%; border-radius: 8px; }
.md a { color: #ae4f2b; }
.md a { color: #206cc3; }
@media print {
body { background: #fff; }
main { padding: 0; min-height: 0; }
@@ -6585,7 +6845,7 @@ function renderAbout() {
} else if (agentAdrift()) {
line.classList.add("is-bad");
line.textContent =
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there.";
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type continue there to wake it.";
} else {
line.classList.add("is-good");
line.textContent = "Right now: both halves are talking to each other.";
@@ -6594,6 +6854,18 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
try {
const res = await fetch("/version", { cache: "no-store" });
const { version } = res.ok ? await res.json() : {};
el.textContent = version ? "Plan2Code v" + version : "";
el.hidden = !version;
} catch {
el.hidden = true;
}
}
const HELP_MOODS = [
["point", "Your turn"],
["work", "Working"],
@@ -6683,6 +6955,7 @@ function openHelp() {
});
selectHelpTab(id);
renderAbout();
renderHelpVersion();
$("help-modal").showModal();
$("help-tab-" + id).focus();
}
@@ -6729,6 +7002,19 @@ function lightDismiss(dlg) {
lightDismiss($("looks-modal"));
lightDismiss($("help-modal"));
lightDismiss($("workspace-modal"));
lightDismiss($("welcome-modal"));
$("welcome-done").addEventListener("click", () => $("welcome-modal").close());
$("welcome-modal").addEventListener("close", () => {
if (looks.welcomeSeen !== true) {
looks.welcomeSeen = true;
saveLooks();
}
$("btn-about").focus();
});
$("help-panels").addEventListener("click", (e) => {
if (e.target.closest && e.target.closest('[data-action="welcome"]')) openWelcome();
});
$("btn-about").addEventListener("click", () => {
openHelp();
@@ -6757,6 +7043,8 @@ $("help-modal").addEventListener("keydown", (e) => {
$("btn-looks").addEventListener("click", () => {
renderSwatches();
setModelsStatus("", false);
loadModelsData();
$("looks-modal").showModal();
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
@@ -6764,7 +7052,7 @@ $("looks-modal").addEventListener("close", () => {
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET };
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
saveLooks();
render();
});
@@ -6812,6 +7100,101 @@ for (const box of document.querySelectorAll("input[data-sound]")) {
});
}
// Models: the launcher's menu. The built-in list ships with every install and is read-only
// here; what the person adds is saved to the server, which the launcher reads on its next run.
let modelsData = null;
let modelsTab = "claude";
function setModelsStatus(text, isError) {
const status = $("models-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function renderModels() {
for (const cli of ["claude", "devin"]) {
$("models-tab-" + cli).setAttribute("aria-pressed", String(cli === modelsTab));
}
const shipped = $("models-shipped");
const user = $("models-user");
shipped.replaceChildren();
user.replaceChildren();
if (!modelsData) {
setModelsStatus("Models could not be loaded.", true);
return;
}
for (const m of modelsData.shipped[modelsTab] || []) {
const row = el("div", "models-row locked");
row.append(el("span", null, m.id), el("span", null, m.label || ""));
shipped.appendChild(row);
}
const mine = modelsData.user[modelsTab];
mine.forEach((m, i) => {
const row = el("div", "models-row");
const id = el("input");
id.value = m.id;
id.placeholder = "Model id";
id.setAttribute("aria-label", "Model id");
const label = el("input");
label.value = m.label;
label.placeholder = "Name shown in the menu";
label.setAttribute("aria-label", "Name shown in the menu");
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
id.addEventListener("change", () => { m.id = id.value.trim(); saveModels(); });
label.addEventListener("change", () => { m.label = label.value.trim(); saveModels(); });
remove.addEventListener("click", () => {
mine.splice(i, 1);
saveModels();
renderModels();
});
row.append(id, label, remove);
user.appendChild(row);
});
}
async function saveModels() {
try {
const res = await fetch("/models", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ models: modelsData.user }),
});
const body = await res.json();
if (!res.ok) return setModelsStatus(body.error || "Could not save.", true);
setModelsStatus("Saved. Restart plan2code to use it.", false);
} catch {
setModelsStatus("Could not save.", true);
}
}
async function loadModelsData() {
try {
const res = await fetch("/models");
if (res.ok) modelsData = await res.json();
} catch {}
renderModels();
}
for (const cli of ["claude", "devin"]) {
$("models-tab-" + cli).addEventListener("click", () => {
modelsTab = cli;
renderModels();
});
}
$("models-add").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user[modelsTab].push({ id: "", label: "" });
renderModels();
$("models-user").querySelector(".models-row:last-child input")?.focus();
});
$("models-reset").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user = { claude: [], devin: [] };
saveModels();
renderModels();
});
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
@@ -24,10 +24,13 @@ export const DONE_AT_MS = 5000;
// 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 }) {
// out to the end with its sound; only `skipEl` (the muted Skip button, or the
// Escape key, for anyone without a mouse) and `signal` aborting (the page
// leaving the dashboard, dormant or mid-run) cut it short, as a skip.
// `onSkip` is the page's cue to silence the intro sounds
// once a skip lands. Under reduced motion nothing is shown and it resolves at
// once.
export function playWake({ stage, bot, target, skipEl, stir, onStart, onGlide, onSkip, signal }) {
return new Promise((resolve) => {
if (matchMedia("(prefers-reduced-motion: reduce)").matches || signal?.aborted) {
resolve({ skipped: false });
@@ -41,8 +44,18 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
if (e.target === bot && e.propertyName === "transform") end(false);
};
const skip = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through.
// The Skip button's events must reach it: the document handlers below run
// in the capture phase, ahead of the button's own click.
const hitsSkip = (e) => Boolean(skipEl && e.target instanceof Node && skipEl.contains(e.target));
const onSkipClick = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through;
// Escape skips, so the run can be left by keyboard too.
const swallow = (e) => {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
if (e.ctrlKey || e.metaKey || e.altKey) return;
e.preventDefault();
e.stopPropagation();
@@ -79,6 +92,8 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
document.removeEventListener("keydown", swallow, true);
bot.removeEventListener("transitionend", onGlideEnd);
signal?.removeEventListener("abort", skip);
skipEl?.removeEventListener("click", onSkipClick);
if (skipped) onSkip?.();
stage.hidden = true;
stage.classList.remove("dormant", "stirring", "booting", "gliding");
bot.style.removeProperty("--wake-glide");
@@ -89,6 +104,11 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
// 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) {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
e.preventDefault();
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
@@ -110,6 +130,7 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
document.addEventListener("pointerdown", start, true);
document.addEventListener("keydown", start, true);
skipEl?.addEventListener("click", onSkipClick);
signal?.addEventListener("abort", skip);
stage.hidden = false;
stage.classList.add("dormant");
@@ -211,13 +211,15 @@ export function shouldChime(prevDot, nextDot) {
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).
* Whether nobody is there to answer a chat message. A finished session's agent
* is often still listening through its last wait (the review and dashboard
* buttons on the hand-off card live as long as it does), so finish alone does
* not end the chat — going quiet does. Offline once the agent has been silent
* longer than the page would tolerate before calling it stuck (working) or
* adrift (anything else), which is also the only signal left once the server
* is gone.
*/
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);
@@ -57,6 +57,7 @@
</g>
</svg>
<p class="wake-hint">Click to wake Planny</p>
<button class="wake-skip" type="button">Skip</button>
</div>
<header class="topbar">
@@ -94,6 +95,8 @@
</button>
<div class="meter-pop" id="meter-pop" role="dialog" aria-label="Session meter" hidden>
<p class="meter-tip" id="meter-tip"></p>
<ul class="meter-list" id="meter-list" aria-label="What the points are made of" hidden></ul>
<div class="meter-fresh" id="meter-fresh" hidden></div>
<button type="button" class="linky" id="meter-help">What is this?</button>
</div>
</span>
@@ -128,13 +131,28 @@
title="Colors, theme and sound"
aria-label="Colors, theme and sound"
>
<!-- Three swatches, so the button says what it opens without a word. -->
<!-- A gear: ring, hub and eight teeth. -->
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<circle cx="5" cy="5.5" r="3.1" class="sw-a" />
<circle cx="11" cy="5.5" r="3.1" class="sw-b" />
<circle cx="8" cy="11" r="3.1" class="sw-c" />
<path class="gr-teeth" d="M12 8h2.6M8 12v2.6M4 8H1.4M8 4V1.4M10.83 10.83l1.84 1.84M5.17 10.83l-1.84 1.84M5.17 5.17L3.33 3.33M10.83 5.17l1.84-1.84" />
<circle cx="8" cy="8" r="4.2" class="gr-ring" />
<circle cx="8" cy="8" r="1.6" class="gr-hub" />
</svg>
</button>
<a
class="icon-btn"
id="btn-feedback"
href="https://github.com/jparkerweb/plan2code/issues/new/choose"
target="_blank"
rel="noopener noreferrer"
title="Report a bug or suggest an idea"
aria-label="Report a bug or suggest an idea (opens GitHub in a new tab)"
>
<!-- A megaphone: horn, handle and two sound waves. -->
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<path class="mg-body" d="M1.8 6.2h2.8L10.4 3v10L4.6 9.8H1.8z" />
<path class="mg-line" d="M4.6 9.8l.9 3.4h1.6l-.6-2.7M12.4 6.1a2.6 2.6 0 0 1 0 3.8M13.8 4.5a5 5 0 0 1 0 7" />
</svg>
</a>
</div>
<div class="topbar-row second">
<div class="row-left">
@@ -595,6 +613,9 @@
written and approving things, instead of typing it all into the
terminal.
</p>
<p>
New here? <button type="button" class="help-link" data-action="welcome">Show the welcome again</button>
</p>
<figure class="help-figure" data-figure="about">
<svg class="help-diagram" viewBox="0 0 560 160" role="img" aria-labelledby="hd-about-title hd-about-desc">
<title id="hd-about-title">You, this page, its program and Plan2Code, all on your machine</title>
@@ -680,7 +701,7 @@
A simplified outline of this page with six numbered areas, in the
same order as the sections below: 1, the top bar, with the title on
the left, the progress bar in the middle, the question mark and
swatch buttons on the right, and Stop session under the title;
gear buttons on the right, and Stop session under the title;
2, Planny and the outline down the left; 3, the view tabs, on the
top bar's second row at the right; 4, the question card in the
middle with Previous and Next under it; 5, the notes panel on the
@@ -738,10 +759,14 @@
"4 of 9 done" while something is being built.
</li>
<li>
The <strong>?</strong> button opens this Help, and the swatch button
The <strong>?</strong> button opens this Help, and the gear button
beside it opens <strong>User Preferences</strong>: your role first,
then your colors, theme, card width and sounds.
</li>
<li>
The <strong>megaphone</strong> button at the far right opens GitHub in a
new tab, where you can report a bug or suggest an idea.
</li>
<li>
<strong>Stop session</strong> ends the session and saves your place.
See "Stopping and finishing".
@@ -1339,7 +1364,8 @@
<p>
Each step you run here adds points: a plan or a set of documents
weighs more than a single answered question, and a built phase more
still. Click the ring to see the count. It is a rule of thumb, not a
still. Click the ring to see the count and a list of each step that added
points, with what it added. It is a rule of thumb, not a
reading of Plan2Code's real memory: long sessions tend to make it
miss things, and the ring is there to remind you.
</p>
@@ -1675,7 +1701,8 @@
</p>
<p>
If it stays quiet a couple of minutes longer, the line changes to
"Plan2Code has not checked in for a few minutes", with Planny still
"Still working on it. Longer tasks can go a few minutes between
updates", with Planny still
in his working pose. It may be busy, or still waiting on you in the
terminal; the terminal is where to look. A build that said a task may
take longer gets that long before the line changes.
@@ -1721,7 +1748,7 @@
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
Everything on the page works from the keyboard, and the swatch button
Everything on the page works from the keyboard, and the gear button
lets you make it look and sound the way you like.
</p>
<h4>Keyboard shortcuts</h4>
@@ -1761,7 +1788,7 @@
</p>
<h4>Your preferences</h4>
<p>
The swatch button at the top, beside <strong>?</strong>, opens
The gear button at the top, beside <strong>?</strong>, opens
<strong>User Preferences</strong>:
</p>
<ul>
@@ -1786,7 +1813,7 @@
</li>
<li>
<strong>Highlight color</strong>: one of
<span data-fact="accentCount">32</span>, rust to begin with. It marks
<span data-fact="accentCount">32</span>, ocean blue to begin with. It marks
what is yours to do, and Planny's star uses it while he works.
</li>
<li>
@@ -1936,6 +1963,29 @@
</div>
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
</fieldset>
<fieldset class="modal-ranges looks-models">
<legend>Models</legend>
<div class="models-tabs" role="group" aria-label="Which agent">
<button type="button" class="btn small ghost" id="models-tab-claude" aria-pressed="true">Claude</button>
<button type="button" class="btn small ghost" id="models-tab-devin" aria-pressed="false">Devin</button>
</div>
<div class="models-note">
<p><strong>You usually don't need to change this.</strong> Plan2Code ships an up-to-date model list with every release. Add a model here only when a new one comes out before Plan2Code has been updated.</p>
<ul>
<li>Restart <code>plan2code</code> to see a change in its model menu.</li>
<li>At any time, run <code>plan2code --model &lt;id&gt;</code>, or pick your model inside your agent before running a skill.</li>
<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>
<li>Devin models are limited to Low, Medium and High effort.</li>
</ul>
</div>
<div class="models-list" id="models-shipped" aria-label="Built-in models"></div>
<div class="models-list" id="models-user" aria-label="Models you added"></div>
<div class="models-actions">
<button type="button" class="btn small" id="models-add">Add a model</button>
<button type="button" class="btn small ghost" id="models-reset">Reset to default</button>
<span class="help" id="models-status" role="status"></span>
</div>
</fieldset>
<div class="modal-actions">
<button type="button" class="btn ghost" id="looks-reset">Back to default</button>
<button type="button" class="btn primary" id="looks-done">Done</button>
@@ -1994,10 +2044,61 @@
<div id="help-panels" class="help-panels"></div>
</div>
<div class="modal-actions">
<span class="help-version" id="help-version" hidden></span>
<button type="button" class="btn primary" id="help-done">Close</button>
</div>
</dialog>
<!-- Shown once, on the first dashboard a person sees. Closing it by any
route saves looks.welcomeSeen; Help's first tab reopens it. -->
<dialog class="modal welcome" id="welcome-modal" aria-labelledby="welcome-title">
<div class="welcome-poster">
<div class="welcome-sky" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i></div>
<!-- Planny is cloned in from #planny by app.js, so he is always the
same robot as the one in the dock. -->
<div class="welcome-bot" id="welcome-bot" aria-hidden="true"></div>
<p class="welcome-kicker">Plan2Code Web Console</p>
<h2 id="welcome-title">Ideas in. Working code out.</h2>
<p class="welcome-lead">
Answer questions, read what gets written and approve each step here,
instead of in the terminal. It runs on this machine only.
</p>
</div>
<div class="welcome-cols">
<div class="welcome-col">
<span class="welcome-dot is-accent">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3.5" y="9" width="12" height="9" rx="1.6" transform="rotate(-12 9.5 13.5)" /><rect x="8.5" y="6" width="12" height="9" rx="1.6" /></svg>
</span>
<h3>Pick a card</h3>
<p>Start with <strong>Suggested</strong>. Pathfinder for a foggy idea, Quick Task for something small.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-stage">
<svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><circle cx="10" cy="10" r="7" opacity="0.35" /><circle cx="10" cy="10" r="7" pathLength="100" stroke-dasharray="50 100" stroke-dashoffset="25" transform="rotate(-90 10 10)" /></svg>
</span>
<h3>Refresh at half way</h3>
<p>Once the session meter passes half, finish the step and start a new conversation.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-bare">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3.5" y="5" width="17" height="14" rx="2" /><path d="M7.5 10l3 2-3 2M12.5 14.5h4" /></svg>
</span>
<h3>Come back</h3>
<p><code>/plan2code</code> in your agent, or <code>plan2code</code> in any folder.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-plain">
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M12 8h2.6M8 12v2.6M4 8H1.4M8 4V1.4M10.83 10.83l1.84 1.84M5.17 10.83l-1.84 1.84M5.17 5.17L3.33 3.33M10.83 5.17l1.84-1.84" /><circle cx="8" cy="8" r="4.2" /><circle cx="8" cy="8" r="1.6" /></svg>
</span>
<h3>Get help</h3>
<p><kbd>?</kbd> opens Help. The gear holds your role, theme and sounds.</p>
</div>
</div>
<div class="modal-actions">
<button type="button" class="btn primary" id="welcome-done">Start building</button>
</div>
</dialog>
<dialog class="modal" id="stop-modal" aria-labelledby="stop-title">
<h2 id="stop-title">Stop this session?</h2>
<p class="modal-blurb" id="stop-blurb"></p>
@@ -35,23 +35,68 @@ export const RUN_EVENTS = new Set(Object.keys(WEIGHTS));
const weightOf = (key) => (Object.prototype.hasOwnProperty.call(WEIGHTS, key) ? WEIGHTS[key] : 0);
// What each scoring event is called in the meter's list of contributions.
const LAUNCH_LABELS = Object.freeze({
plan: "Plan started",
"revise-plan": "Revise plan started",
document: "Document started",
review: "Review started",
"quick-task": "Quick task started",
init: "Init started",
"init-update": "Init update started",
finalize: "Finalize started",
});
const RUN_LABELS = Object.freeze({
"pathfinder-chart": "Pathfinder map written",
"pathfinder-question": "Pathfinder question settled",
plan: "Plan drafted",
"revise-plan": "Plan revised",
document: "Spec documented",
"implement-phase": "Implement phase built",
"implement-review-phase": "Implement + Review phase built",
review: "Code review run",
"quick-task": "Quick task built",
init: "Init run",
"init-update": "Init update run",
finalize: "Finalize run",
handoff: "Handoff written",
});
// The unit a run names, from its ledger id ("L3:phase-2" -> "phase-2").
const unitOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(id.indexOf(":") + 1) : "");
/**
* The session's points, folded from ledger entries in order. An id seen
* before is skipped, so a repeated `post` never counts twice.
* What the count is made of: one { label, points } per ledger entry that
* scored, in order. An id seen before is skipped, so a repeated `post` never
* counts twice. Entries that weigh nothing are left out.
*/
export function pointsFrom(entries) {
export function breakdownFrom(entries) {
const seen = new Set();
let points = 0;
const rows = [];
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);
let points = 0;
let label = "";
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
points = weightOf(entry.workflow);
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
} else if (entry.kind === "run") {
points = weightOf(entry.event);
const unit = unitOf(entry.id);
label = (RUN_LABELS[entry.event] || entry.event) + (unit ? `: ${unit}` : "");
}
if (points > 0) rows.push({ label, points });
}
return points;
return rows;
}
/** The session's points, folded from ledger entries in order. */
export function pointsFrom(entries) {
return breakdownFrom(entries).reduce((sum, row) => sum + row.points, 0);
}
export const YELLOW_AT = 4;
@@ -94,5 +139,12 @@ export const RED_BANNER =
export function meterView(entries) {
const points = pointsFrom(entries);
const level = levelFor(points);
return { points, level, fraction: ringFraction(points), words: WORDS[level], tooltip: tooltipFor(points) };
return {
points,
level,
fraction: ringFraction(points),
words: WORDS[level],
tooltip: tooltipFor(points),
items: breakdownFrom(entries),
};
}
@@ -187,7 +187,7 @@ export const ACCENTS = {
},
};
export const DEFAULT_ACCENT = "rust";
export const DEFAULT_ACCENT = "ocean";
// 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
@@ -23,7 +23,8 @@ 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.
// Blocks javascript: and data: hrefs before they can reach the DOM, and a
// protocol-relative `//host` (or `/\host`), which leaves the page for another site.
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
}
@@ -103,6 +104,26 @@ function inlineInto(parent, tokens) {
}
}
// What a fenced code block offers beside Copy, from its first non-empty line:
// `'run'` gets a Run it button (git commands — the one kind a person keeps
// copying into Ask by hand), `'hint'` a muted note that pasting it into Ask
// may get the agent to run it, and `null` nothing extra. A leading `/` is a
// skill command for a new conversation, never a terminal command, so it gets
// neither.
const COMMAND_WORDS =
/^(git|node|npm|npx|pnpm|yarn|bun|deno|python3?|pip3?|brew|curl|wget|docker|kubectl|terraform|make|cmake|cargo|go|java|mvn|gradle|gh|aws|az|gcloud|jq|ssh|scp|rsync|chmod|chown|mkdir|cp|mv|rm|ls|cd|cat|echo|export|source|bash|sh|zsh|fish|pwsh|powershell|cmd|systemctl|service|apt|apt-get|dnf|yum|pacman|tar|unzip|zip)\b/i;
export function runHint(text) {
const firstLine = (text || "")
.split("\n")
.map((line) => line.trim())
.find((line) => line.length > 0);
if (!firstLine || firstLine.startsWith("/")) return null;
if (/^git(\s|$)/.test(firstLine)) return "run";
if (firstLine.startsWith("#!")) return "hint";
return COMMAND_WORDS.test(firstLine) ? "hint" : null;
}
function blockInto(parent, tokens) {
for (const t of tokens || []) {
switch (t.type) {
@@ -140,7 +161,16 @@ function blockInto(parent, tokens) {
// textContent, so a fenced block containing markup is inert.
pre.appendChild(el("code", null, t.text));
wrap.appendChild(copyButton(t.text, "md-copy"));
const hint = runHint(t.text);
if (hint === "run") {
const run = el("button", "md-run", "Run it");
run.type = "button";
wrap.appendChild(run);
}
wrap.appendChild(pre);
if (hint === "hint") {
wrap.appendChild(el("p", "md-run-hint", "The agent may be able to run this — paste it into the Ask tab"));
}
parent.appendChild(wrap);
break;
}
@@ -21,8 +21,11 @@ import {
CHAT_CURSOR_FILE,
CHAT_FILE,
LEDGER_FILE,
HERE,
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
@@ -44,6 +47,7 @@ import {
readWorkspace,
remoteWarning,
typedCount,
withStateLock,
writeJsonAtomic,
writeWorkspace,
} from "./lib.mjs";
@@ -84,6 +88,12 @@ if (typeof args.token !== "string" || !args.token) {
}
const TOKEN = args.token;
const PROJECT = args.project || process.cwd();
// The checkout this session runs in, from `open`. PROJECT is the folder that
// holds .git, which for a linked worktree is the MAIN checkout: the wrong
// folder to seed the workspace with or resolve a typed path against. A fresh
// `open` starts this server before it writes the state, so until the state is
// there this is the only place the worktree can come from.
const WORKTREE = typeof args.worktree === "string" ? args.worktree : "";
const IDLE_MS = Number(args["idle-ms"] || 30 * 60 * 1000);
const MAX_LIFE_MS = Number(args["max-life-ms"] || 4 * 60 * 60 * 1000);
@@ -96,12 +106,12 @@ const CURSOR_PATH = path.join(DIR, CHAT_CURSOR_FILE);
// Images and documents attached to notes and quick questions. Only ever named
// by the server (a UUID, plus `jpg` or an extension from DOC_TYPES), and only
// ever resolved inside this directory: the client's file name is a label.
// Only images are served back; a document is written, read by the agent from
// disk, and deleted, never handed to a browser.
// Images are served back as JPEG. A document is served under a fixed type
// (PDF, or text/plain for everything else, sandboxed and never sniffed), so
// the page can link it without ever letting a browser run it.
const UPLOADS_DIR = path.join(DIR, "uploads");
const UPLOAD_EXTS = ["jpg", ...Object.keys(DOC_TYPES)];
const EXT_ALT = UPLOAD_EXTS.join("|");
const UPLOAD_ROUTE = /^\/uploads\/([0-9a-f-]{36})\.jpg$/;
const UPLOAD_ANY_ROUTE = new RegExp(`^/uploads/([0-9a-f-]{36})\\.(${EXT_ALT})$`);
const UPLOAD_NAME = new RegExp(`^[0-9a-f-]{36}\\.(${EXT_ALT})$`);
@@ -216,7 +226,7 @@ const SERVABLE = new Set([
// live in it). A stat says whether anything moved; refreshing through
// checkState also means a request that sees a new state first still counts
// it as a new revision and tells every other tab. Callers must not mutate
// what this returns -- /submit clones before it edits.
// what this returns -- /submit edits a fresh read of its own, under the lock.
function readState() {
checkState();
return stateNow;
@@ -302,6 +312,10 @@ const foldPath = (p) => (FOLD_CASE ? p.toLowerCase() : p);
let workspaceSeen = { stamp: null, ws: null };
// The folder the session runs in: the state's own once it is written, else
// the one `open` passed on the command line. Null while neither is known.
const sessionWorktree = () => stateNow?.worktree || WORKTREE || null;
// The session's workspace, created with just the original folder when absent.
function workspaceNow() {
const stamp = fileStamp(WORKSPACE_PATH);
@@ -311,10 +325,15 @@ function workspaceNow() {
workspaceSeen = { stamp, ws };
return ws;
}
const fresh = initialWorkspace(stateNow?.worktree || PROJECT);
const root = sessionWorktree();
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
// Nor saved while the session's folder is unknown: PROJECT is only a guess
// (the main checkout, for a linked worktree), and the file, once written,
// is what every later read trusts.
if (!root) return fresh;
try {
saveWorkspace(fresh);
} catch {}
@@ -405,7 +424,7 @@ function nextFolderId(ws) {
function addFolder(ws, body) {
const raw = typeof body.path === "string" ? body.path.trim().replace(/^(["'])(.*)\1$/, "$2").trim() : "";
const input = raw.replace(/^~(?=$|[\\/])/, () => os.homedir());
const resolved = raw ? path.resolve(stateNow?.worktree || PROJECT, input) : "";
const resolved = raw ? path.resolve(sessionWorktree() || PROJECT, input) : "";
if (!resolved || !isFolder(resolved)) return [400, { reason: "not-a-folder" }];
const same = ws.folders.find((f) => foldPath(path.resolve(f.path)) === foldPath(resolved));
if (same) return [400, { reason: "duplicate", name: same.name }];
@@ -455,7 +474,7 @@ function removeFolder(ws, body) {
// Where the picker opens: beside the last folder added, else the original.
function pickerStart(ws) {
const added = ws.folders.filter((f) => !f.original);
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || PROJECT;
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || sessionWorktree() || PROJECT;
}
// One picker at a time. Spawned, never spawnSync: the dialog can sit open for
@@ -464,6 +483,8 @@ function pickerStart(ws) {
let pickerBusy = false;
function bootWorkspace() {
// Nothing to check yet: the first read once the state is written makes it.
if (!sessionWorktree() && !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
const remote = remoteWarning().remote || "";
if ((ws.remote || "") !== remote) {
@@ -541,9 +562,14 @@ function recordSubmitted(state, actions) {
if (!Array.isArray(state.items)) return;
const at = nowIso();
for (const action of actions) {
if (!action || typeof action !== "object" || action.type === "comment") continue;
if (!action || typeof action !== "object") continue;
const item = state.items.find((i) => i && i.id === action.i);
if (!item) continue;
if (action.type === "comment") {
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
continue;
}
const { i, type, ...rest } = action;
// JSON.parse makes "__proto__" an own property, and it would then be
// written back into state.json and re-read forever.
@@ -577,12 +603,13 @@ function timingSafeEq(a, b) {
return crypto.timingSafeEqual(ab, bb);
}
// Named per port. Cookies ignore the port, so every console on 127.0.0.1 shares
// one jar: under a single name, opening a second session overwrote the first
// one's cookie and locked its tab out.
function cookieName(port = PORT) {
return `p2c_console_${port}`;
}
// One cookie per port. Browsers scope cookies by host and ignore the port, so
// with one shared name every session on 127.0.0.1 wrote over the one before
// it, and the first session's tab went on sending the second one's token and
// got nothing but 403s. The port is what makes a session's origin its own, and
// a resumed server on a new port is reached again only through its /s/ link,
// which sets the cookie under the new name.
const cookieName = () => `p2c_console_${PORT}`;
function cookieToken(req) {
const raw = req.headers.cookie || "";
@@ -623,6 +650,47 @@ function touch() {
lastContact = Date.now();
}
const MODEL_CLIS = ["claude", "devin"];
const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/;
// Devin's XHigh and Max efforts are never offered, curated or added.
const MODEL_EFFORT_BLOCKED = /-(xhigh|max)$/i;
/**
* The user's added models: { claude: [{id,label}], devin: [...] }. Returns { models } or
* { error }. Blank rows are dropped; ids are trimmed and made unique per CLI; a label
* defaults to the id. Nothing else in the body survives.
*/
function cleanModels(input) {
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "models must be an object" };
const models = {};
for (const cli of MODEL_CLIS) {
const list = input[cli] == null ? [] : input[cli];
if (!Array.isArray(list) || list.length > 50) return { error: `${cli} must be a list of at most 50 models` };
const seen = new Set();
models[cli] = [];
for (const row of list) {
const id = String((row && row.id) ?? "").trim();
if (!id) continue;
if (!MODEL_ID.test(id)) return { error: `"${id}" is not a valid model id` };
if (MODEL_EFFORT_BLOCKED.test(id)) return { error: `"${id}": only Low, Medium and High efforts are allowed` };
if (seen.has(id)) continue;
seen.add(id);
const label = String((row && row.label) ?? "").trim().slice(0, 80) || id;
models[cli].push({ id, label });
}
}
return { models };
}
function shippedModels() {
const file = readJson(SHIPPED_MODELS_FILE, null) || {};
const out = {};
for (const cli of MODEL_CLIS) {
out[cli] = (Array.isArray(file[cli]) ? file[cli] : []).filter((m) => m && typeof m.id === "string");
}
return out;
}
/**
* Whittle a POSTed settings object down to what a settings file may hold.
* The page only sends { theme, accent } today, but the file is shared and
@@ -668,8 +736,8 @@ function asset(rel) {
// The saved highlight color, painted from the very first frame. The page's
// script owns the colors once it runs (applyLooks clears the attribute these
// hang off), but until then the only way to avoid flashing the default rust
// at someone who picked ocean is a stylesheet rule the server can switch on
// hang off), but until then the only way to avoid flashing the default ocean
// at someone who picked violet is a stylesheet rule the server can switch on
// with an attribute: the CSP forbids inline styles, and the colors live in
// palette.js, so they are generated from there rather than copied into CSS.
function accentCss() {
@@ -742,7 +810,10 @@ function renderIndex() {
// `$'` in the inserted text as patterns, and titles and state are free text.
return indexTemplate
.replace('<html lang="en">', () => `<html lang="en"${htmlAttrs}>`)
.replace("<title>Plan2Code Console</title>", () => `<title>${escHtml(title)} · Plan2Code</title>`)
.replace(
"<title>Plan2Code Console</title>",
() => `<title>${escHtml(title)} · #${escHtml(String(SID).slice(-6))} · Plan2Code</title>`
)
.replace('<h1 id="title">Plan2Code Console</h1>', () => `<h1 id="title">${escHtml(title)}</h1>`)
.replace(
'<span class="badge" id="badge">Pathfinder</span>',
@@ -821,7 +892,7 @@ const server = http.createServer((req, res) => {
302,
baseHeaders({
location: "/",
"set-cookie": `${cookieName(port)}=${TOKEN}; HttpOnly; SameSite=Strict; Path=/`,
"set-cookie": `${cookieName()}=${TOKEN}; HttpOnly; SameSite=Strict; Path=/`,
})
);
return res.end();
@@ -887,6 +958,14 @@ const server = http.createServer((req, res) => {
return;
}
if (pathname === "/version" && req.method === "GET") {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const version = readJson(file, {}).version;
if (typeof version === "string" && version) return json(res, 200, { version });
}
return json(res, 404, { error: "no version" });
}
if (pathname === "/state" && req.method === "GET") {
const state = readState();
if (!state) return json(res, 404, { error: "no state" });
@@ -957,7 +1036,10 @@ const server = http.createServer((req, res) => {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, 400, { error: "body must be JSON" });
const looks = cleanLooks(body && body.looks);
// `set` carries only the keys one tab changed, merged onto what is on
// disk, so a tab holding stale settings cannot undo another tab's change.
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
const looks = set ? { ...(readJson(LOOKS_FILE, null)?.looks || {}), ...set } : cleanLooks(body && body.looks);
if (!looks) return json(res, 400, { error: "looks must be an object of simple settings" });
try {
ensureDir(path.dirname(LOOKS_FILE));
@@ -969,6 +1051,29 @@ const server = http.createServer((req, res) => {
});
}
// The launcher's model menu: what ships (read-only here) and what the user added.
if (pathname === "/models" && req.method === "GET") {
const saved = readJson(USER_MODELS_FILE, null) || {};
const { models } = cleanModels(saved);
return json(res, 200, { shipped: shippedModels(), user: models || { claude: [], devin: [] } });
}
if (pathname === "/models" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, 400, { error: "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
try {
ensureDir(path.dirname(USER_MODELS_FILE));
writeJsonAtomic(USER_MODELS_FILE, models);
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, { ok: true, user: models });
});
}
if (pathname === "/upload" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
const contentType = String(req.headers["content-type"] || "");
@@ -1008,8 +1113,8 @@ const server = http.createServer((req, res) => {
}
// A document: the extension comes from the allow-list via its name, and
// the bytes have to agree with it. No `url` comes back, because a
// document is never served.
// the bytes have to agree with it. No `url` comes back: the page builds
// the link from the path, as it does for the delete route.
if (contentType.startsWith("application/octet-stream")) {
// The extension comes from the whole name: the label is cut at 200
// characters, and a long name would lose it there.
@@ -1033,11 +1138,11 @@ const server = http.createServer((req, res) => {
// Matched on the raw request line as well as the parsed path: URL parsing
// folds `..` segments away, and nothing that needed folding is an upload.
// GET serves images only; DELETE takes documents too.
// GET and DELETE take images and documents alike.
if (pathname.startsWith("/uploads/") || req.url.startsWith("/uploads/")) {
if (req.method === "GET") {
const m = UPLOAD_ROUTE.exec(req.url);
const file = m && m[0] === pathname ? uploadPath(m[1]) : null;
const m = UPLOAD_ANY_ROUTE.exec(req.url);
const file = m && m[0] === pathname ? uploadPath(m[1], m[2]) : null;
if (!file) return json(res, 404, { error: "not found" });
let buf;
try {
@@ -1045,7 +1150,15 @@ const server = http.createServer((req, res) => {
} catch {
return json(res, 404, { error: "not found" });
}
return send(res, 200, buf, "image/jpeg", { "cache-control": "private, max-age=86400" });
const ext = m[2];
if (ext === "jpg") return send(res, 200, buf, "image/jpeg", { "cache-control": "private, max-age=86400" });
const pdf = DOC_TYPES[ext].kind === "pdf";
// A sandboxed PDF cannot load the browser's viewer, and one needs no
// sandbox: text is the only thing a browser might otherwise run.
return send(res, 200, buf, pdf ? "application/pdf" : "text/plain; charset=utf-8", {
...(pdf ? {} : { "content-security-policy": "sandbox" }),
"cache-control": "private, max-age=86400",
});
}
if (req.method === "DELETE") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
@@ -1079,16 +1192,6 @@ const server = http.createServer((req, res) => {
if (badAttachments) {
return json(res, 400, { error: "a comment carries at most 5 attachments, each uploaded to this session" });
}
// One send is one agent turn. Writing over a result the agent has not
// collected yet destroys everything in it, and the loss is silent: two
// tabs, or one impatient second press, and an approval disappears.
if (pendingResult()) {
return json(res, 409, {
error: "pending",
message:
"Your last answers have not been picked up yet. Nothing is lost, they are still on their way.",
});
}
const result = {
type: "submit",
at: nowIso(),
@@ -1097,26 +1200,68 @@ const server = http.createServer((req, res) => {
actions: body.actions,
reply: body.reply || "",
};
// The result and the state change together, under the state lock: a
// `post` or an `open` landing in the middle of a send would otherwise
// write back a state read before it, and the send's record would go, or
// this write would carry an older state over the agent's new one.
let refused = null;
let written = null;
let agentWrote = false;
try {
// Atomic: the waiter polls this file and will land mid-write eventually.
writeJsonAtomic(RESULT_FILE, result);
written = withStateLock(DIR, () => {
// One send is one agent turn. Writing over a result the agent has not
// collected yet destroys everything in it, and the loss is silent: two
// tabs, or one impatient second press, and an approval disappears.
if (pendingResult()) {
refused = "pending";
return null;
}
try {
// Atomic: the waiter polls this file and will land mid-write eventually.
writeJsonAtomic(RESULT_FILE, result);
} catch (e) {
refused = String(e.message);
return null;
}
try {
// Read fresh from disk, never from the cache: an agent write the
// watcher has not reached yet is in the file and must be kept.
const text = fs.readFileSync(STATE_FILE, "utf8");
const state = JSON.parse(text);
agentWrote = text !== lastStateText;
state.phase = "submitted";
recordSubmitted(state, body.actions);
return { state, text: writeJsonAtomic(STATE_FILE, state) };
} catch {
// The answers are safe in result.json; the stamp is only a courtesy.
return null;
}
});
} catch (e) {
return json(res, 500, { error: String(e.message) });
refused = String(e.message);
}
if (refused === "pending") {
return json(res, 409, {
error: "pending",
message:
"Your last answers have not been picked up yet. Nothing is lost, they are still on their way.",
});
}
if (refused) return json(res, 500, { error: refused });
appendEvent(DIR, { type: "submit", rev, count: body.actions.length });
const current = readState();
if (current) {
// A copy: the cached state is what every other reader is handed.
const state = structuredClone(current);
state.phase = "submitted";
recordSubmitted(state, body.actions);
try {
// Account for our own write here rather than letting the watcher find
// it: the watcher reads a changed state.json as proof the AGENT is
// alive, and this write is not that.
adoptStateText(writeJsonAtomic(STATE_FILE, state), state);
rev++;
} catch {}
if (written) {
// Account for our own write here rather than letting the watcher find
// it: the watcher reads a changed state.json as proof the AGENT is
// alive, and this write is not that. An agent write it swept up on the
// way is, and is handled as the watcher would have handled it.
adoptStateText(written.text, written.state);
rev++;
if (agentWrote) {
agentSeenAt = Date.now();
try {
ensureConversation(written.state);
} catch {}
}
}
// Name the items that went. A page with OTHER answers staged should drop
// only what was sent, and a brief request is a submit carrying no answers
@@ -1282,15 +1427,21 @@ const server = http.createServer((req, res) => {
if (pathname === "/cancel" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
if (pendingResult()) return json(res, 409, { error: "pending", message: "A send is still on its way." });
const result = { type: "cancel", at: nowIso(), sid: SID, rev, actions: [], reply: "" };
// As /submit: a cancel that never reached disk must not tell the page it
// did, or the page stands down while the agent waits on forever.
// Under the state lock like a send, so `open` clearing a collected result
// can never take this one with it. As /submit: a cancel that never reached
// disk must not tell the page it did, or the page stands down while the
// agent waits on forever.
let pending = false;
try {
writeJsonAtomic(RESULT_FILE, result);
withStateLock(DIR, () => {
pending = pendingResult();
if (!pending) writeJsonAtomic(RESULT_FILE, result);
});
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
if (pending) return json(res, 409, { error: "pending", message: "A send is still on its way." });
appendEvent(DIR, { type: "cancel", rev });
broadcast("cancelled", { rev });
return json(res, 200, { ok: true });
@@ -1319,6 +1470,8 @@ const server = http.createServer((req, res) => {
// Treat a departure as "shorten the deadline", never as "exit now": the user
// may simply be reloading.
if (pathname === "/bye") {
// It moves the shutdown deadline, so only the page itself may send it.
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
if (clients.size === 0) lastContact = Date.now() - (IDLE_MS - 2 * 60 * 1000);
return json(res, 200, { ok: true });
}
@@ -1382,7 +1535,9 @@ function readRaw(req, limit, cb) {
/* ------------------------------------------------------- state watching */
// The agent writes state.json through `console.mjs post`. Watch the DIRECTORY,
// The agent writes state.json through `console.mjs post`, and the server only
// through /submit; both under the state lock (updateState() in lib.mjs), so
// neither can write back a state read before the other's. Watch the DIRECTORY,
// not the file: on Windows a watch on a file breaks the moment that file is
// replaced by rename, which is exactly what an atomic write does.
let watchTimer = null;
@@ -1490,7 +1645,9 @@ setInterval(() => {
// the server deciding to stop. Do not "optimise" this away.
setInterval(() => {
const idle = Date.now() - lastContact;
if (idle > IDLE_MS) {
// Answers nobody has collected yet keep the server up (bounded by MAX_LIFE_MS):
// exiting would strand the tab and the send it holds.
if (idle > IDLE_MS && !resultFlags().pending) {
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle });
process.exit(0);
}
@@ -0,0 +1,22 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-02",
"mode": "utility"
}
+2 -2
View File
@@ -14,7 +14,7 @@ Technical writer transforming planning documents into precise, complete implemen
## Interface
The FIRST thing you do, before anything else — before Auto-Discovery: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow document` before reading (<D>: references/web-console/ beside this SKILL.md; `--spec` once known), then <D>/console.md → Documentation: questions, sign-off, each phase as a doc. 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 Auto-Discovery. `__stop` ends it; post `finish` BEFORE `stop` at every end.
The FIRST thing you do, before anything else — before Auto-Discovery: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow document` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec` once known), then <D>/console.md → Documentation. 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 Auto-Discovery. `__stop` ends it; post `finish` BEFORE `stop` at every end.
## Rules
@@ -32,7 +32,7 @@ The FIRST thing you do, before anything else — before Auto-Discovery: ask **we
**Before asking user for input:**
1. Run `ls specs/` (not Glob) then check each folder for `PLAN-DRAFT-*.md`
1. Run `ls specs/` then check each folder for `PLAN-DRAFT-*.md`
2. **One found:** Use it, inform user: "Found: `specs/<feature>/PLAN-DRAFT-<date>.md`"
3. **Multiple found:** List all, ask which to document
4. **None found:** Fall back to Required Context below
@@ -273,7 +273,7 @@ for whichever comes first:
| 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. |
| `wait` exit `20` | The server is gone, not necessarily the tab. Resume it (`open --resume <sid> --no-open --workflow <yours>`) and keep waiting. |
| 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:
@@ -406,15 +406,38 @@ post carries `"run": { "event": "implement-review-phase", "id": "phase-N" }`.
("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.
`"answer": { "verdict": "yes" }`) in the post that starts the build, and
open a **Build progress** tab in that same post, the way an Implement phase
gets its tasks tab. The plan's steps are the task list and `total` is their
number:
```jsonc
{
"stopWarning": "",
"items": [{ "id": "<the Build this plan? item's id>", "status": "answered", "answer": { "verdict": "yes" } }],
"headline": { "stage": "Building", "cleared": 0, "total": 4 },
"docs": [{ "id": "tasks", "title": "Build progress", "version": 1, "blocks": [
{ "id": "tasks", "state": "settled", "md": "- [ ] Step one\n- [ ] Step two\n- [ ] Step three\n- [ ] Step four" }
]}],
"agent": { "status": "working", "activity": "Step 1 of 4: step one", "quietMinutes": 10 }
}
```
Then post after every step, exactly as "While you build": bump the doc's
`version` and repost the whole list with that step ticked, raise
`headline.cleared`, and set `agent.activity` to the next step ("Step 2 of 4:
step two"). Never go silent for the whole build: a quick task with many steps
is the case this tab is for. Check for a Quick question between steps, and do
not call `wait` until the build is done.
- **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.
sign-off card to put it on — and `"dashboard": true`, so the finished screen
also offers **Back to the dashboard**. Both are required: a finish without
`dashboard` leaves the person on a dead end. Keep waiting for whichever
button is pressed, 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"`.
@@ -27,6 +27,12 @@ workflow still applies: the same questions, the same order, the same gates, the
same cap of three questions at a time, the same recap before anything is recorded.
You are not allowed to answer your own questions just because a form makes it easy.
> **The one rule that keeps the page alive: while the session is open, every
> turn ends on a `wait` call, never on text.** `wait` exit `10` means "nobody
> has answered yet", not "done": relay one line and run `wait` again in the
> same turn, as many times as it takes. A turn that ends without a `wait`
> running strands the person's next click. Details: The wait loop, below.
---
## Deciding whether to use it
@@ -172,7 +178,19 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
Do not poll faster than this. Do not spin on `status`. Exit 10 is not a finished
turn: never emit a final response or stop after an arbitrary number of slices;
relay one line and immediately call `wait` again. Do not give up: people step
away from a session and come back.
away from a session and come back. The same holds after a `finish`: keep
waiting (resuming the server on exit `20`) until the dashboard or done press
or about ten minutes with nothing, because the Ask tab stays live and its
messages only arrive through `wait`. Ending your turn earlier strands them.
**The turn never ends on a wait.** While a console session is open, including
after a finish that offers a button (Back to the dashboard, Review it now), the
last thing in every turn you take is a `wait` call, never a line of text. The
line you relay after exit `10` goes in the same turn as the next `wait`, so
write it and call `wait` straight after. A turn that ends with the session open
and no `wait` running is a bug the person feels at once: their button press
sits unread until they ask why. If you catch yourself about to write a closing
summary while the page is still open, call `wait` first.
**Collect promptly.** A question someone has sent is locked on the page for as
long as you are mid-turn on it: they can read, move around and answer the other
@@ -453,6 +471,14 @@ messages, `offline` when no agent is connected or the session has finished,
### Answering
**Every message gets a reply, always.** The Ask tab is the person talking to
you, and the page shows "working on the answer" until a reply lands. Never
leave one unanswered, whatever it asks and whatever mid-task you are in. When
a message asks you to do something, do it if you can, then say what happened; if
you will not, the reply says so and why. `post` and `wait` print
`unansweredChat` with a `warning` for every message handed over and not yet
replied to: treat that as a stop-and-reply.
1. Handle any card answers first, under the workflow's own rules.
2. Write the chat replies, in inbox order.
3. Send **one** `post` with the card updates and `chat: { replies: [...] }`.
@@ -510,8 +536,9 @@ enforces it, so never tell someone to keep asking past it.
proposal is a new reply.
- Hard limits: never touch the running skill's own files under
`specs/<idea>/` (`post` rejects a proposal that names them); run no commands
beyond read-only lookups; never commit; refuse a request outside these and
say why.
beyond read-only lookups, except one the person plainly asks you to run in
their message (a commit they spell out, a test run): run it, then report the
result in the reply; refuse anything else and say why, in the reply.
- Edits happen only at check-ins, never mid-task in a build.
```jsonc
@@ -715,8 +742,10 @@ review run from a build's review button stays in the build's session, under
its workflow: `building.md` → The review, mid-session. On completion the finish's `command` is the suggested
commit when fixes landed — filled in, in the AGENTS.md format, with
`"where": "When you are happy with it, commit it from your terminal:"` —
otherwise leave `command` out. A stop mid-review loses nothing on disk, so its
finish is the bare `/plan2code-review`.
otherwise leave `command` out. The completion finish carries `"dashboard": true`
so the finished screen offers **Back to the dashboard**; keep waiting for the
press. A stop mid-review loses nothing on disk, so its finish is the bare
`/plan2code-review` (a pause, so no dashboard button).
### Handoff (`handoff`)
@@ -892,6 +921,8 @@ Session meter) and `folderIssue` (Workspace → When a folder cannot be read).
### Every item
**Give every new question a new `id`.** An id names one question for the whole session. The server drops a stale `submitted` record if you reword a question under an old id, but never rely on it: a fresh id is the only unambiguous way to ask something new.
```jsonc
{
"id": "q7",
@@ -1141,7 +1172,7 @@ usual slices for up to about ten minutes:
| --- | --- |
| An action `{ "i": "__dashboard", "type": "dashboard" }` | `open --resume <sid> --no-open --workflow dashboard` (the resume re-runs the project scan), then ONE post with `"finish": null`, the `menu` payload and `"agent": { "status": "waiting" }`. Then read the dashboard skill (`~/.agents/skills/plan2code/SKILL.md`) and carry on as the dashboard from its "The menu" section, in this same conversation. The same action can also arrive before any finish, from the top bar's triangle: see Stop requests → "Back to the dashboard, mid-workflow". |
| An action `__review` or `__done` | As `building.md` says (quick task only). |
| `wait` exit `20` | They closed the tab. Do not resume: the session is over. |
| `wait` exit `20` | The server is gone, not necessarily the tab. `open --resume <sid> --no-open --workflow <yours>`, then keep waiting: their Ask messages and the dashboard button still need you. Give up only when the resume itself fails. |
| Nothing after about ten minutes | `stop` the server. The page swaps the button for the `/plan2code` command. |
### 2. Stop the server
@@ -54,6 +54,7 @@ import {
nowIso,
parseArgs,
pendingChatCount,
unansweredChat,
pendingWorkspaceChanges,
pidAlive,
print,
@@ -77,6 +78,7 @@ import {
sweepUploads,
switchWorkflow,
terminalLine,
updateState,
UPLOAD_MAX_AGE_MS,
validate,
validateChat,
@@ -88,6 +90,10 @@ import {
import { RUN_EVENTS } from "./public/meter.js";
import { changeLine } from "./public/workspace.js";
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
// still be one of our servers, so its pid gets no second look.
const MAX_SERVER_LIFE_MS = 4 * 60 * 60 * 1000;
const argv = process.argv.slice(2);
const cmd = argv[0];
const args = parseArgs(argv.slice(1));
@@ -102,8 +108,24 @@ function trace(what) {
/* ----------------------------------------------------------------- open */
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written by `open` alone, which starts every session: a
// `wait` or a `post` every few seconds need not rewrite it each time.
function leavePointer() {
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
}
async function cmdOpen() {
trace("open: start");
leavePointer();
const { project, worktree, branch } = repoRoots();
reapHandles(project);
trace("open: project found");
@@ -113,6 +135,11 @@ async function cmdOpen() {
let state;
// A new skill run for the meter: a fresh open, or a resume into another workflow.
let launched = true;
// Everything `open` does to a stored state, as a step it can take twice:
// once now, on the read below, so a bad payload is refused before anything
// starts, and again on a fresh read under the state lock when it writes, so
// a send the person made in between is kept rather than written over.
let reshape = (s) => s;
if (sid) {
sid = path.basename(sid);
@@ -120,27 +147,6 @@ async function cmdOpen() {
if (!fs.existsSync(dir)) die(`no session "${sid}" to resume`, 1);
state = readJson(path.join(dir, "state.json"));
if (!state) die(`session "${sid}" has no state`, 1);
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (state.finish && /^\s*paused\b/i.test(String(state.finish.headline || ""))) {
delete state.finish;
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
state.items = (state.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(state.items.map((i) => i.topic));
state.topics = (state.topics || []).filter((t) => liveTopics.has(t.id));
}
// A resume can also be a hand-off: the dashboard launches another skill
// into its own session, and the first thing that skill needs is for the
// page to stop being a dashboard. Letting the flags restate these fields
@@ -148,26 +154,51 @@ async function cmdOpen() {
// rather than a resume plus a whole extra post.
const switching = args.workflow && args.workflow !== state.workflow;
launched = Boolean(switching);
if (switching && (args.workflow === "dashboard" || state.workflow === "dashboard")) {
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. A skill run inline from another (a
// quick task's review) never passes the dashboard, so it keeps the page.
state = switchWorkflow(state, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
fs.rmSync(path.join(dir, "draft.json"), { force: true });
} else if (switching) state.workflow = args.workflow;
if (args.title) state.title = args.title;
if (args.spec) state.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete state.wake;
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. A skill run inline from another (a
// quick task's review) never passes the dashboard, so it keeps the page.
const hop = switching && (args.workflow === "dashboard" || state.workflow === "dashboard");
if (hop) fs.rmSync(path.join(dir, "draft.json"), { force: true });
reshape = (s) => {
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (s.finish && /^\s*paused\b/i.test(String(s.finish.headline || ""))) {
delete s.finish;
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
s.items = (s.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(s.items.map((i) => i.topic));
s.topics = (s.topics || []).filter((t) => liveTopics.has(t.id));
}
if (hop) {
s = switchWorkflow(s, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
} else if (switching) s.workflow = args.workflow;
if (args.title) s.title = args.title;
if (args.spec) s.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete s.wake;
return s;
};
} else {
sid = newSessionId();
// Named, not made: the folder is created once --file has passed, so a
@@ -185,22 +216,36 @@ async function cmdOpen() {
// Only a freshly opened dashboard plays Planny's wake-up.
if (args.workflow === "dashboard") state.wake = true;
}
// On every open, so a resume from another worktree refreshes both.
state.worktree = worktree;
state.branch = branch;
// A first payload's meter and folder reports, as `post` takes them: checked
// now, before anything is written, and appended once the launch is.
let openRun;
let openIssue;
let patch = null;
if (args.file) {
const patch = readJson(path.resolve(args.file));
patch = readJson(path.resolve(args.file));
if (!patch) die(`could not read --file ${args.file} as JSON`, 2);
({ run: openRun, folderIssue: openIssue } = patch);
delete patch.run;
delete patch.folderIssue;
}
const base = reshape;
const settle = (s) => {
s = base(s);
// On every open, so a resume from another worktree refreshes both.
s.worktree = worktree;
s.branch = branch;
return s;
};
reshape = (s) => (patch ? applyPatch(settle(s), patch) : settle(s));
state = settle(state);
if (patch) {
ledgerFromPost(dir, openRun, openIssue, state.workflow);
state = applyPatch(state, patch);
try {
state = applyPatch(state, patch);
} catch (e) {
die(e.message, 3);
}
const problems = validate(state);
if (problems.length) return failValidation(problems);
}
@@ -209,13 +254,15 @@ async function cmdOpen() {
// A fresh session needs a fresh server, and a server is a whole Node boot:
// the slowest thing `open` does, bar the browser. Start both now, before
// the scan and the state write, so their start-up runs alongside them
// instead of after. Neither can reach a page before the server is up, and
// the state is on disk long before that; the server reads it per request,
// never at boot.
// instead of after. The server does look at the state as it boots, and on
// a fresh session finds none yet: it takes the worktree from its command
// line, not from the state, and picks the state up on its first request or
// poll tick. No page can reach it before it is listening, and the state is
// on disk long before a browser gets there.
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null;
const reusable = existing && pidAlive(existing.pid) ? healthOk(existing) : Promise.resolve(false);
let boot = null;
if (!existing) boot = await startServer(project, sid, dir);
if (!existing) boot = await startServer(project, worktree, sid, dir);
// The dashboard's spec picker reads its inventory straight off the session
// state, so the scan belongs to `open` rather than to the agent: filesystem
@@ -223,23 +270,43 @@ async function cmdOpen() {
// never something a model has to remember to fetch. Rooted at the worktree's
// own top level: `project` is the common-dir key so linked worktrees share
// sessions, but each shows the specs on its own disk.
if (state.workflow === "dashboard") state.scan = scanProject(worktree);
const scan = state.workflow === "dashboard" ? scanProject(worktree) : null;
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
const carried = Boolean(waiting && !waiting.consumedAt);
// Under the state lock, which a send on the page takes too: the result and
// the state are read fresh here and the state is rebuilt from that read, so
// nothing the person sent since the read above is lost or stamped over.
let carried = false;
let written;
try {
written = updateState(dir, (fresh) => {
const next = fresh ? reshape(fresh) : state;
if (scan) next.scan = scan;
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) state.phase = "collecting";
writeJsonAtomic(path.join(dir, "state.json"), state);
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
carried = Boolean(waiting && !waiting.consumedAt);
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) next.phase = "collecting";
return next;
});
} catch (e) {
written = { error: e.message };
}
if (!written || written.error) {
// A server just started for this state would only serve a page that never starts.
if (boot) boot.kill();
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
@@ -288,14 +355,14 @@ async function cmdOpen() {
// A handle whose pid is alive but is not ours (the pid was reused) leaves
// this for last: nothing could be started until that was known.
let started = boot || (await startServer(project, sid, dir));
let started = boot || (await startServer(project, worktree, sid, dir));
let handle = await awaitHandle(started);
if (!handle && started.handoff) {
// The handover went wrong somewhere (a platform that will not pass the
// socket, a server that died taking it). Once more the old way, where
// the server binds its own port: slower, and certain.
started.kill();
started = await startServer(project, sid, dir, { handoff: false });
started = await startServer(project, worktree, sid, dir, { handoff: false });
handle = await awaitHandle(started);
}
if (!handle) {
@@ -372,7 +439,7 @@ function isFolder(p) {
* boot: a process's first listen() blocks for ~50ms on Windows while the
* socket stack loads, which is time the server spends booting anyway.
*/
async function startServer(project, sid, dir, { handoff = true } = {}) {
async function startServer(project, worktree, sid, dir, { handoff = true } = {}) {
const token = newToken();
const handlePath = handleFile(project, sid);
ensureDir(path.dirname(handlePath));
@@ -389,6 +456,9 @@ async function startServer(project, sid, dir, { handoff = true } = {}) {
`--session=${dir}`,
`--token=${token}`,
`--project=${project}`,
// The checkout the session runs in, which the state does not hold yet
// on a fresh open. See WORKTREE in server.mjs.
`--worktree=${worktree}`,
...(handoff ? ["--handoff"] : []),
...(args["idle-ms"] ? [`--idle-ms=${args["idle-ms"]}`] : []),
],
@@ -487,20 +557,37 @@ function cmdPost() {
delete patch.folderIssue;
const ledgerLines = ledgerFromPost(dir, run, folderIssue, before.workflow);
let next;
// The patch is applied to a fresh read under the state lock, never to the
// read above: a send the person made in between is in the file, and a write
// built on the older read would take it away. Nothing in here may exit, so
// the lock is always let go; a refusal is carried out and reported after.
let refused = null;
let problems = [];
let written;
try {
next = applyPatch(before, patch);
written = updateState(dir, (fresh) => {
if (!fresh) {
refused = ["that session has no state", 1];
return null;
}
let next;
try {
next = applyPatch(fresh, patch);
} catch (e) {
refused = [e.message, 3];
return null;
}
problems = validate(next);
if (!problems.length && patch.chat) problems = validateChat(next, readChat(dir));
return problems.length ? null : next;
});
} catch (e) {
die(e.message, 3);
die(e.message, 1);
}
const problems = validate(next);
if (refused) die(...refused);
if (problems.length) return failValidation(problems);
if (patch.chat) {
const chatProblems = validateChat(next, readChat(dir));
if (chatProblems.length) return failValidation(chatProblems);
}
const next = written.state;
writeJsonAtomic(statePath, next);
for (const line of ledgerLines) appendLedger(dir, line);
appendEvent(dir, { type: "post", items: (patch.items || []).length });
@@ -512,6 +599,7 @@ function cmdPost() {
items: next.items.length,
open,
phase: next.phase,
...unansweredNote(dir, next),
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
});
}
@@ -554,13 +642,15 @@ function ledgerFromPost(dir, run, issue, workflow) {
async function cmdWait() {
const dir = mustSession();
// A --seconds that is not a number would make the deadline NaN, and the
// slice would end at once with exit 10: a busy loop, not a wait.
// "240s" reads as 240. A --seconds with no number in it at all would make
// the deadline NaN, and the slice would end at once with exit 10: a busy
// loop, not a wait. So that is refused rather than guessed at.
const given = args.seconds;
if (given !== undefined && (typeof given !== "string" || !given.trim() || !Number.isFinite(Number(given)))) {
const asked = typeof given === "string" ? Number.parseFloat(given) : NaN;
if (given !== undefined && !Number.isFinite(asked)) {
die(`--seconds must be a number, got "${args.seconds}"`, 2);
}
const seconds = Math.max(5, Number(args.seconds || 240));
const seconds = Math.max(5, given === undefined ? 240 : asked);
const sid = path.basename(dir);
const project = projectRoot();
const resultPath = path.join(dir, "result.json");
@@ -580,6 +670,11 @@ async function cmdWait() {
// was a full read and parse every 400ms, which put up to 0.4s between the
// person pressing Send and the agent starting on it, on every single send.
let healthAt = 0;
// A busy server (right after a post, say) can miss one health check without
// being gone. Only a missing handle or dead pid is proof at once; a server
// that merely does not answer must fail three checks in a row, each with a
// longer look, before the slice ends with exit 20.
let healthMisses = 0;
// Null, not the current stamp: a result written between the check above and
// this line would otherwise read as already seen and wait out the slice.
let seen = null;
@@ -605,11 +700,17 @@ async function cmdWait() {
if (Date.now() - healthAt > 5000) {
healthAt = Date.now();
const handle = listHandles(project).find((h) => h.sid === sid);
if (!handle || !pidAlive(handle.pid) || !(await healthOk(handle))) {
if (!handle || !pidAlive(handle.pid)) {
print(serverGone(sid));
process.exitCode = 20;
return;
}
if (await healthOk(handle, 4000)) healthMisses = 0;
else if (++healthMisses >= 3) {
print(serverGone(sid));
process.exitCode = 20;
return;
} else healthAt = Date.now() - 3000; // look again in about 2s, not 5s
}
sleepSync(50);
}
@@ -630,7 +731,9 @@ async function cmdWait() {
staged,
url: handle ? handle.url : "",
message: "Waiting on your answer in the web console",
next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.",
pendingChat: 0,
...unansweredNote(dir, state),
// A workspace change alone never ends a slice: it rides on the next send.
pendingWorkspace: pendingWorkspaceChanges(dir).length,
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
@@ -638,11 +741,19 @@ async function cmdWait() {
process.exitCode = 10;
}
// Quick questions already handed over with no reply yet. Always empty when all are answered.
function unansweredNote(dir, state) {
const seqs = unansweredChat(dir, state);
return seqs.length
? { unansweredChat: seqs, warning: "Quick questions " + seqs.join(", ") + " have no reply yet and the page still shows them as pending. Reply to each now (chat.replies, re = seq): do what was asked when you can, or say why you will not." }
: {};
}
function serverGone(sid) {
return {
status: "server-gone",
sid,
message: "The console server is not running. Start it again with `open --resume` and give the person the new link.",
message: "The console server is not running. Start it again with `open --resume <sid> --no-open`, then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
};
}
@@ -943,10 +1054,13 @@ async function cmdStop() {
// reboot in the system temp directory, and PIDs get reused; without this
// check `stop --all` can kill an unrelated program that happens to have
// inherited the number. /health returning our own sid is the only proof:
// a young handle with a live pid is not, since the server may have died
// minutes ago and its number gone straight to something else. A server
// too wedged to answer /health still meets its own idle deadline.
if (!(await healthOk(h))) {
// a live pid and a young handle are not, since a server that died a
// minute ago leaves exactly that behind for any process to inherit. A
// busy server gets a second, longer look, and still has to answer as
// ours; one that does not is left alone, and only its handle goes.
const young = Date.now() - Date.parse(h.startedAt || 0) < MAX_SERVER_LIFE_MS;
const ours = (await healthOk(h)) || (young && pidAlive(h.pid) && (await healthOk(h, 5000)));
if (!ours) {
skipped++;
try {
fs.rmSync(h.handlePath, { force: true });
@@ -1074,18 +1188,6 @@ const COMMANDS = {
help: cmdHelp,
};
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written on every invocation, help and errors included.
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
// Say which Node is too old, rather than dying later inside a health check with
// "fetch is not defined". Whatever agent is driving this has to be able to read
// the failure, tell the person in one line, and carry on in the terminal.
@@ -1105,4 +1207,12 @@ if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
process.exit(2);
}
// A flag given with no value parses as `true`, and a boolean handed on as a
// path or a name crashes somewhere deep (path.basename(true) throws). Every
// flag that takes a value is checked once, here, and refused as bad usage.
const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "upload", "name", "from", "seconds", "limit", "idle-ms"];
for (const flag of VALUE_FLAGS) {
if (flag in args && typeof args[flag] !== "string") die(`--${flag} needs a value`, 2);
}
await COMMANDS[cmd]();
Loaded 100 of 288 files, more files were not shown because too many files have changed in this diff. Show more