56 KiB
Architecture
Part of AGENTS.md — project guidance for AI coding agents.
Directory Structure
plan2code/
├── src/ # Source workflow prompts (13 markdown files)
│ ├── plan2code-0-pathfinder-references/ # Reference files for pathfinder skill
│ │ ├── brief.md # Dated plain-English decision briefs
│ │ ├── chart.md # MODE A: destination + frontier grills, templates
│ │ ├── github-issues.md # Issue-backed map (loaded only when Backend is github)
│ │ ├── grilling.md # Folded-in grilling + domain-modeling
│ │ ├── questions.md # On-disk question-file format + markers
│ │ ├── resolve.md # Per-type resolution + graduating the fog
│ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff
│ │ └── trail.md # Every-response map visual + pathed resume command
│ ├── plan2code-review-references/ # Reference files for review skill
│ │ ├── verification-protocol.md # Deep verification + confidence calibration
│ │ ├── dimensions.md # 11 dimensions with detailed checklists
│ │ ├── false-positives.md # Known false-positive patterns
│ │ └── session-end.md # Next-step routing at review session end
│ ├── plan2code-init-update-references/ # Reference files for init-update skill
│ │ └── ai-agent-file-sync.md # Step 7: replace AI configs with AGENTS.md refs
│ └── plan2code-4-finalize-references/ # Reference files for finalize skill
│ └── community-feedback-submission.md # STEP 6.5 payload schema + submission tiers
├── plan2code-loop/ # Autonomous loop CLI tool (Node.js/TypeScript)
│ ├── src/ # TypeScript source
│ └── dist/ # Built output (tsup)
├── plan2code-bot/ # Autonomous end-to-end workflow test runner (TypeScript, tsup, Claude Agent SDK, vitest); user docs in .readme/test-bot.md
├── plan2code-metrics/ # Recursive self-improvement toolchain
│ ├── src/ # TypeScript source
│ │ └── prompts/ # Internal AI prompt templates (no char limit)
│ └── dist/ # Built output (tsup)
├── src/statusline-claude/ # Claude CLI status line (Node.js, zero deps, single file)
│ ├── statusline.js # Self-contained: config, git, formatters, render
│ └── statusline-config.json # Default config template
├── src/launcher/ # Global `plan2code` command (Node.js, zero deps)
│ ├── plan2code.js # Opens /plan2code in Claude Code or Devin in the cwd (or a picked folder)
│ ├── models.json # Curated model menu, copied to ~/.plan2code/bin/ on install
│ └── plan2code.ico # Desktop shortcut icon (Windows)
├── src/web-console/ # Local browser UI bundled into every skill (Node.js, zero deps, no build)
│ ├── console.mjs # CLI the agent drives: open, post, wait, chat, keep, status, stop, help
│ ├── server.mjs, lib.mjs, picker.mjs
│ ├── console.md, building.md # Agent-facing contract
│ └── public/ # Page assets served to the browser
├── scripts/ # Development scripts
│ ├── bench-web-console.mjs # Start-path timing
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs puppeteer-core)
│ ├── check-skill-table.mjs # src/plan2code.md "What each skill reads and writes" table vs each skill's prompt and references
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
│ ├── test-web-console.mjs, test-launcher.mjs # node --test suites
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, skill-script-helpers.mjs # Skill script suites and fixtures
│ └── 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/ and scripts/ where present
│ # Generated by npm run build:skills; consumed by skills add
├── .husky/ # Git hooks (husky)
│ └── pre-commit # Runs character count validation
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/
├── .github/ISSUE_TEMPLATE/ # bug.yml, idea.yml, config.yml (target of the console's feedback button)
├── .readme/ # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, autonomous-loop.md, metrics.md, status-line.md, test-bot.md)
├── docs/ # Landing page `index.html` served at plan2code.jparkerweb.com (GitHub Pages, `CNAME`) 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)
├── version.json # Version metadata
├── CHANGELOG.md, QUICK-REFERENCE.md, LICENSE
├── .gitattributes, .editorconfig # Pin LF (see Code Style & Gotchas)
├── prototypes/, specs--completed/, dist/ # Local only, gitignored: design prototypes, archived specs, stale pre-2.2 build output. Ignore root dist/.
└── README.md # User documentation
Key Files
| File | Purpose |
|---|---|
install.js |
Interactive installer — builds skills/ from src/, then delegates installation to the skills CLI |
src/plan2code-*.md |
Source workflow prompts (the "source of truth") |
skills/ |
Generated Agent Skills committed for installation and drift verification |
scripts/validate-char-count.js |
Pre-commit validator ensuring all source prompts ≤ 20,000 chars |
version.json |
Version metadata (name, version, description) |
QUICK-REFERENCE.md |
User quick-reference card |
src/statusline-claude/ |
Claude CLI status bar (see Status Line below) |
src/launcher/plan2code.js |
Global plan2code command that opens the dashboard skill in Claude Code or Devin (installed by I and A; also via Custom → D) |
Workflow Prompts (in src/)
| File | Step | Purpose |
|---|---|---|
plan2code.md |
— | The dashboard: opens the web console's skill menu and launches the picked skill into its own session |
plan2code-init.md |
Init | Generate AGENTS.md as index + .agents-docs/ section files (progressive discovery) |
plan2code-init-update.md |
Update | Update AGENTS.md with learnings; detects and routes edits to .agents-docs/ files |
plan2code-0-pathfinder.md |
0 | Chart a foggy idea as a map (local files, or GitHub Issues) of decision questions under specs/<idea>/pathfinder/, resolve them one at a time, hand a seeded PLAN-DRAFT to Step 1 |
plan2code-quick-task.md |
quick | Lightweight planning for small tasks (standalone — not a pipeline step) |
plan2code-1-plan.md |
1 | Requirements analysis & architecture |
plan2code-1b-revise-plan.md |
1b | Mid-implementation revisions |
plan2code-2-document.md |
2 | Create implementation specs |
plan2code-3-implement.md |
3 | Execute implementation (phase by phase) |
plan2code-3-implement-review.md |
3 | Execute one phase, run focused review and fixes, then request approval |
plan2code-review.md |
review | Post-implementation comprehensive review |
plan2code-4-finalize.md |
4 | Validate, summarize, feedback, archive (steps 1–7, +optional 6.5) |
plan2code-handoff.md |
handoff | Compact the conversation into a self-contained handoff document for a fresh session |
Naming Convention
Workflow files follow a strict naming pattern:
- The hub:
plan2code.md(bare name —bare: trueinSOURCE_PROMPTS, no suffix; it is the dashboard the rest hang off, not a step) - Utilities:
plan2code-<name>.md(single dash) - Numbered steps:
plan2code-<N>-<name>.md(single dash, number, single dash)
Examples:
plan2code-init.md(utility)plan2code-1-plan.md(step 1)plan2code-1b-revise-plan.md(step 1b)
Reference Files
Some workflows use companion reference files for depth that does not need to load on every invocation. The orchestrator (main workflow file) loads them via Read directives during execution.
Pattern: src/<source-filename-without-extension>-references/ (e.g., plan2code-review-references/)
How the installer handles them: the directory is copied verbatim to skills/<skill-name>/references/, so Read references/<file>.md resolves consistently for every agent. There is one output format, with no flat-file sibling directory or path rewrite.
Reference files are NOT subject to the 20,000 character limit. The review workflow pioneered this pattern (verification-protocol, dimensions, false-positives, session-end); the init-update workflow also uses it (ai-agent-file-sync for its Step 7), plan2code-4-finalize.md uses it for STEP 6.5 (community-feedback-submission), and plan2code-0-pathfinder.md leans on it hardest (brief, chart, github-issues, grilling, questions, resolve, handoff, trail — the orchestrator is a dispatcher, the depth lives in the references). Other workflows can adopt it when a source file carries detail that is only needed some of the time. The implement-review skill is a generated composition: additionalReferences in SOURCE_PROMPTS packages the canonical implement prompt, review prompt, and review reference directory into its own references/ directory so those workflows are reused without source duplication.
Skill Scripts
Anything a workflow step decides with one correct answer (parsing a spec's checkboxes, rebuilding Pathfinder's map markers, the commit message, which AI config files exist) lives in a script the agent runs, not in prose it follows. Prose keeps the judgment.
| Source | Ships to | How |
|---|---|---|
src/skill-scripts/<name>.mjs |
skills/<skill>/scripts/<name>.mjs |
Shared: a skill lists the ones it runs in scripts: [...] on its SOURCE_PROMPTS entry. Skills install independently, so each gets its own copy |
src/skill-scripts/common.mjs |
every skill that has scripts | SHARED_SCRIPTS_ALWAYS in install.js |
src/<source>-scripts/<name>.mjs |
skills/<skill>/scripts/<name>.mjs |
A skill's own scripts, mirroring -references/. A name that collides with a shared script is a build error |
version.json (repo root) |
skills/<skill>/scripts/version.json |
Copied at build, so an installed skill can report its version |
| Script | Skills | Does |
|---|---|---|
specs.mjs |
plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | list / status (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / metrics / mark / archive. Imports scanProject() from the bundled web-console/lib.mjs, so the dashboard and the skills share one spec classifier |
commit-msg.mjs |
implement(-review), review, quick-task, finalize, init-update | The <subject> / ticket / AI Assisted command from the branch name |
review-scope.mjs |
review, implement(-review), quick-task | Review Mode's git fallback: files, lines, doc share, base branch |
agents-md.mjs |
init, init-update | AGENTS.md structure, budget, orphans, broken links, always-inline sections |
agent-files.mjs |
init, init-update | Detect and replace other agents' config files with AGENTS.md pointers |
pathfinder.mjs (own) |
0-pathfinder | reconcile, frontier, claim, resolve, rule-out, trail, gate, lint, brief-data |
feedback-payload.mjs (own) |
4-finalize | STEP 6.5's payload (real sha256 prompt hashes) and the gh / browser / print submission tiers |
handoff-path.mjs (own) |
handoff | Timestamped path, OS temp dir, git ignore check |
Conventions (common.mjs): Node 18+ built-ins only; one JSON object on stdout (ok: false plus error, message, next on a handled failure, the same line on stderr); exit 0 ok, 1 crash, 2 bad arguments, 3 not found, 4 invalid or check failed, 5 refused; --help documents commands and exit codes; writes take --dry-run; PLAN2CODE_NOW pins the clock for tests. A SKILL.md names a script as node "<S>/<name>.mjs", where <S> is scripts/ beside it.
Tests: scripts/test-skill-scripts.mjs (installer plumbing and the shared scripts), scripts/test-script-<skill>.mjs (a skill's own), with fixtures from scripts/skill-script-helpers.mjs. They run the built skills/ tree, and one test fails if any SKILL.md or shipped reference names a <S>/<name>.mjs that skill does not ship. The per-skill scripts import ./common.mjs, which only sits beside them in the built tree, so run them from skills/, not src/.
Repo-Local Skills (.claude/skills/)
Maintainer-only skills committed to the repo but deliberately excluded from the generated skills/ product artifact:
plan2code-publish/— publishes a GitHub Release after version files agree.plan2code-changelog/— validates release classification and keeps version files synchronized.sync-repo/— decrypts the protected upstream-sync workflow in memory.
Do not run skills add against the repository root: recursive discovery also finds these maintainer skills. install.js targets skills/ and passes explicit workflow names instead. Global install/uninstall cleanup removes plan2code-* workflow skills from user skill directories; it never operates on this repository's .claude/skills/ directory, and sync-repo intentionally has no plan2code- prefix.
Web Console
Optional local browser UI shipped with every skill. Source lives in src/web-console/ and is fanned into each skill by an additionalReferences: [{ source: 'web-console', target: 'web-console' }] entry in SOURCE_PROMPTS, landing at skills/<skill>/references/web-console/. The bare plan2code skill is the hub: it opens the console as --workflow dashboard, the page draws the skill menu itself (from SKILL_CATALOG in public/answers.js, kept in sync with the install set by a test), and a card click reaches the agent as a { "i": "__launch", "skill": ..., "workflow": ... } send — the dashboard then resumes its own session under the launched skill's workflow (open --resume <sid> --workflow <w> restates workflow/title/specDir on the live server) and runs that skill's file. plan2code-review now has a console of its own AND still runs inside builds on the page (a review verdict on Implementation's sign-off card, or the Review it now button on a finished quick task), so plan2code-3-implement and plan2code-quick-task also carry review.md and the review references, the same way implement-review does. The list of skills with a console is duplicated as CONSOLE_WORKFLOWS in public/answers.js (it decides whether a copied hand-off asks the next session for the console); a test fails if the two disagree.
| File | Role |
|---|---|
console.mjs |
the CLI the agent drives: open, post, wait, chat (the instant Quick question check), keep (copy a cited note attachment into specs/<idea>/attachments/), status, stop, help (a compact summary for an agent that found the binary but not console.md) |
server.mjs |
HTTP server, spawned detached by open (never as a harness background task, which get killed on compaction and at assorted timeouts) |
lib.mjs |
session paths, atomic writes, the patch merge, validate() (which also allows templates only as "idea" on a text item; anything else exits 3), attachmentName() (the kept-file name <slug>-<id8>.<ext>: the same upload always gets the same name), repoRoots() (returns { project, worktree, branch }), readOverview(), and the three sweeps open runs fire-and-forget after it prints (see the cleanup design point below): sweepUploads(), staleSessions() / removeSessions() and staleScratch() / removeScratch() |
public/ |
index.html, app.js, answers.js, labels.js, boot.js, chat.js, help.js, starters.js, workspace.js, meter.js, mentions.js, favicon.js, app.css, render.js, palette.js, favicon.svg (Planny peeking up from the tab bar, served as image/svg+xml) with favicon.png (the same icon at 192 px, served as image/png) as the fallback, vendor/marked.esm.js, the chimes (start-skill.mp3, bootup.mp3, start-stop.mp3, next.mp3, insert.mp3, sleeping.mp3; which moment plays which is SOUND_EVENTS in palette.js, one switch per event saved in looks.json), and a package.json that only says "type": "module", so Node (the server, console.mjs, lib.mjs and the tests import several public/*.js modules) parses them as ES modules without a reparse warning |
public/help.js |
the Help dialog's PURE rules: HELP_TABS (16 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color), helpTabFor() (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a build, else What this page is) and helpKeyTarget() (roving arrow keys, Home, End, wrapping). No module-scope DOM, so node --test covers it |
public/workspace.js |
PURE, no imports: the Workspace's name rules (nameProblem(), NAME_MAX, defaultName(), freeName() for the -2 suggestion), the footer label and its width tiers (footerLabel(), FOOTER_TIERS) and changeLine(), the Workspace: … reply line an agent is handed per change. Imported by the server, console.mjs, lib.mjs and the page |
public/meter.js |
PURE, no imports: the session meter. WEIGHTS (the one place per-event points live; its keys are also RUN_EVENTS, the run events post accepts), LAUNCH_COUNTED (workflows whose launch itself scores), the built-phase sizing (TASK_EVENTS, the keys of TASK_BONUS: implement-phase +0 and implement-review-phase +1; isTaskCount() accepts a whole tasks from 1 to MAX_TASKS 999; runPoints() scores such a run ceil(tasks / TASKS_PER_POINT) (3) plus its bonus, and any other run its WEIGHTS value), ANSWERS_PER_POINT 2 (answer entries score per skill run, floor(count / 2)), breakdownFrom() (the click-the-ring list: one row per scoring entry plus one answers row per skill run), pointsFrom() (the count, its sum, folded from ledger.ndjson and deduplicated by id, never stored), levelFor() with YELLOW_AT 5 / RED_AT 10, ringFraction() (full at RING_FULL 15), WORDS, tooltipFor(), RED_BANNER and meterView() |
public/mentions.js |
PURE, no imports: the @name popover's logic — mentionAt() finds an @partial at the caret, matchNames() filters the workspace names, applyMention() splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
public/favicon.js |
The tab icon's status bar. faviconState({ mood, spin, finished }) (PURE) maps the call renderStatus() makes for Planny's line to busy (the spinning ring), ready (point), attention (adrift, gone, or work without the ring — the stale line) or plain (finished, happy); faviconSvg() is FAVICON_BODY (kept equal to favicon.svg by a test) plus a bar along the bottom edge in the FAVICON_COLORS color (busy dashed on a white strip, so the states differ by pattern; the rest solid); setFavicon() swaps both <link rel=icon> hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from say() in renderStatus(), which runs every second |
picker.mjs |
the per-OS native folder picker behind Browse… (pickerCommand() → { command, args, env } or null; pickFolder() runs it with async spawn, so the server keeps serving while the dialog is open). Copied from src/launcher/plan2code.js (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
public/chat.js |
the Quick question chat's PURE rules, shared by the server and the page: CHAT_LIMIT / CHAT_MAX_CHARS / CHAT_MAX_ATTACHMENTS (the combined image + document cap; CHAT_MAX_IMAGES is kept as an alias of it), chatOffline() (the server's 409 offline guard), and the page's view model (chatView, sendState, nextAbout, contextOptions, unreadDot / shouldChime). Ask context is the { history, about } model: nextAbout() records the last 3 places visited in history and sets about only when the person picks one from + Add context (contextOptions() lists that history plus This spec); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only answers.js, no module-scope DOM, so node --test covers it |
public/starters.js |
PURE, no imports: the Role list (ROLES, ROLE_NOT_SET, normalizeRole(), needsRoleNudge(): the dashboard banner shows until looks.json carries any role), the 13 starter templates and their per-role orders (TEMPLATES, TEMPLATE_ORDERS, templatesFor(), templateSwap() for the replace prompt), and the Ask starter sets (STARTER_SETS, STARTER_SET_FOR, startersFor()). Imported by app.js and the tests; in SERVABLE, preloaded by index.html and parse-checked. The page owns the wording; a skill only flags its fresh-idea text card with "templates": "idea" |
public/answers.js |
the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Split out of app.js because app.js cannot be imported outside a browser, so anything left in it is untestable. scripts/test-web-console.mjs imports this directly. |
public/labels.js |
taskLabel() / activityLabel(): rewrites a build's Task 4.2 of 6 activity line to Task 2 of 6 (only for implement / implement-review; a plan's Task 2.1 is a real section number). A separate module for the same reason as answers.js: pure, so node --test can import it |
public/boot.js |
playWake(): the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's stir() callback times the nudge between the click and the boot, which app.js fills with one snore; 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) saveslooks.welcomeSeen: truetolooks.json, which survives "Back to default". Help's first tab has a Show the welcome again link (data-action="welcome"). Logic:maybeWelcome()/openWelcome()inapp.js. -
Top-bar icons.
#btn-looks(gear) opens#looks-modal, titled User Preferences: Role, Theme, Card width, Highlight color, Sounds and Models.#btn-feedback(megaphone) is a plain link tohttps://github.com/jparkerweb/plan2code/issues/new/choose, backed by.github/ISSUE_TEMPLATE/bug.ymlandidea.yml(config.ymlsetsblank_issues_enabled: false).DEFAULT_ACCENTinpalette.jsisocean. -
Version in Help.
GET /versionreadsversion.jsonbesideserver.mjs, falling back to../../version.jsonfor a run fromsrc/(server.mjs/versionroute).renderHelpVersion()inapp.jsfills#help-version.computeExpectedSkills()ininstall.jsinjects the rootversion.jsoninto everyreferences/web-console/, so a version bump changes every skill. -
Models in User Preferences.
GET/POST /modelsinserver.mjsread the shipped~/.plan2code/bin/models.jsonand read/write the user's~/.plan2code/models.json(SHIPPED_MODELS_FILE/USER_MODELS_FILEinlib.mjs).PLAN2CODE_MODELS_DIRrelocates both for tests. The launcher reads the same two files for its model menu. -
The wait is bounded.
wait --seconds 240exits0(answers),10(still waiting,message: "Waiting on your answer in the web console"to relay),20(server gone, resume it) or30(cancelled). The agent loops. Nothing blocks for the whole time a person takes. -
The CLI hands the agent its terminal line.
open,postandwait(exits0and10) printterminalLine: "→ Look at the web console: <url>"(terminalLine()inconsole.mjs), andconsole.mdasks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. Inwaitit is added to the printed result only; the collectedresult.jsonon disk never carries it.openalso printsswept: { sessions, scratch }when it found anything to clean. -
State fields written by
open, not the agent. Everyopen(fresh or resume) recordsstate.worktreeandstate.branchfromrepoRoots()— the branch is read off<gitdir>/HEADon 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, orfolder + N folders · branchonce folders are added, stepping down through narrower tiers); a click opens the Workspace dialog.state.wake = trueis set only by a freshopen --workflow dashboardand deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sidsessionStorageguard so a reload never replays it. -
looks.widthis a person-level preference alongside theme, accent and sounds inlooks.json.CARD_WIDTHSinpublic/palette.js(narrow720,comfortable880 — default —wide1080) is read by the page (cardWidth()validates a saved value) and byserver.mjs, which paintsdata-widthon first load;app.cssmapsdata-widthonto the single--card-widthvariable that every column rule uses. -
GET /overviewis the one route that reads a project file. It serves<spec>/overview.mdastext/markdownwithcache-control: no-store(so the Overview tab is always fresh), or404 { "error": "no overview" }. A dashboard session honours?spec=only when it equals adirinstate.scan.specs; every other workflow usesstate.specDirand ignores the query. The root isstate.worktree(fallbackstate.project), andreadOverview()resolves andrealpaths the file and refuses anything outside the root's realpath, so../, absolute paths and outward symlinks all 404. -
Month-old sessions are deleted whole.
openlistsstaleSessions()(directories matching the session-id pattern whosestate.jsonmtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) andstaleScratch()(top-level regular.json/.mjsfiles in the console folder older than 30 days, neverlooks.jsonorconsole-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 thestale*listing already decided, so never hand them names that did not come from it.console.mdtells 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 and the~/.plan2code/console/console-dirfallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path~/.agents/skills/<skill>/references/web-console/(the skills CLI's real store; every agent dir links into it), and everyconsole.mjs openwritesHEREto~/.plan2code/console/console-dir(onlyopen, so ahelpor dev run fromsrc/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. -
openneeds no payload, and runs first.--fileand--titleare optional (the title defaults to the folder name). Every skill's Interface line putsnode "<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 bystartStage()inapp.jsfrom<template id="start-poses">inindex.htmland animated under.poseinapp.css;START_POSES/startPose()inanswers.jsis 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 anactivityand 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
openis built around it. Measure withnode scripts/bench-web-console.mjs(--browser-delay 900for a real Chrome launch,--roundtripfor Send→agent and post→page,PLAN2CODE_CONSOLE_TRACE=1onopenfor a step timeline). Four things make it fast, and each is load-bearing:- No git process.
repoRoots()inlib.mjsfinds the common dir and worktree top by walking to.git(followinggitdir:andcommondirfiles) — eachgit rev-parsecost 150ms+ on Windows. It asks git only whenGIT_DIR/GIT_WORK_TREE/GIT_COMMON_DIRrelocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would. - The socket handover.
openspawns the server first, then binds the loopback port itself (the firstlisten()blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome viastarttakes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (bindLoopback()/handOff()inlib.mjs,--handoffinserver.mjs). Requests queue in the socket until the server takes it; oneopenalready accepted is passed across as a socket and acknowledged (conn-held) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port;openthen opens the real URL. - The first paint needs no fetch.
server.mjsrendersindex.htmlwith the session's title, badge and saved theme (data-theme,data-looks-accent, matched by accent rules generated frompalette.jsand appended toapp.css) and the whole first state as an inline<script type="application/json" id="boot">(every<escaped; data blocks are not executed, so the CSP is unchanged).modulepreloadhints fetch every module in parallel, the page draws in the same task as the script runs, and/events?have=<key>skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up. - Reads are stat-gated.
fileStamp()(mtime:size:ino) decides whetherstate.json,result.jsonandlooks.jsonchanged before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (readState()returns it;/submitclones before editing).waitstatsresult.jsonevery 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
- No git process.
-
The Workspace and the session meter live beside
state.json, one writer each, and outlive every hop. Three session files, none of whichswitchWorkflow()ever touches, so both survive dashboard → skill → dashboard (a new console session starts with a count of 0, and with the folders remembered for its folder and spec, below):File Writer Holds workspace.jsonserver.mjsthe folders ( id,path,name,description,original,nested),version, thechangeslog,missingids, andremote(remoteWarning(), now inlib.mjs, computed by the server at boot)ledger.ndjsonconsole.mjsappend-only, one JSON line per entry. Meter events: launch(every freshopenand every resume into another workflow),run(a post'srun, id scoped by launch, withtaskswhen a built phase reports one) andanswer(one per item the person answered in a collected send, written byledgerAnswers(), id<launch>:answer:<send stamp>:<item>). Alsofolder-issuereportsworkspace-cursor.jsonconsole.mjsthe last workspace versionhanded to the agent; advanced after the print, never backwardsThe page changes the workspace only through five routes:
GET /workspace(?check=1re-stats every folder first),POST /workspace/add(path resolved againststate.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) andPOST /workspace/browse(one picker at a time, 409busy; 404no-pickerwhenremoteis set or no picker exists;PLAN2CODE_PICKER_ECHOstands in for the dialog in tests).stateFrame()carriesworkspace(folders,missing,remote, the current launch's folderissues) andmeter(meterView()over the ledger), and both files are on the 1s poll. The agent hears of the workspace throughopenoutput (workspace: { folders, missing? }, which also seeds the cursor) and then each change once, asworkspace: [...]plusWorkspace: …reply lines onwaitexit 0 orchat; a change alone never ends awaitslice (pendingWorkspaceon exit 10).postandopen --fileliftrunandfolderIssueout of the patch into the ledger, never intostate.json; an unknown event or a malformed issue is exit 3. Remembered workspaces.lib.mjskeeps~/.plan2code/console/workspaces.json(WORKSPACES_FILE, underPLAN2CODE_CONSOLE_HOMEin tests):projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }, each entry{ original: { name, description }, folders: [{ path, name, description, nested? }], at }.rememberedWorkspace()answers spec, else project, else nothing;initialWorkspace(worktree, entry)builds from it, both in the server's firstworkspaceNow()and inopen's read-onlyworkspaceOnOpen(), so they agree.workspace.jsoncarriesscope(the spec key or""). Every user change (bumpWorkspace, notmissing/found) callsrememberWorkspace().setScope()swaps the list, loggingremoved/added/renamed/describedchanges so the cursor stays truthful;POST /workspace/scope { spec }(the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, andfollowSpecDir()(state poll, boot) moves the scope to a postedspecDir, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server andconsole.mjs forget --spec(Finalize Step 6). The contract is inconsole.md(Workspace; Posting an update → Session meter) andbuilding.md(per-phaserun), so the skill prompts stay unchanged. -
The filesystem is the transport. Sessions live in
~/.plan2code/console/sessions/<sid>/, deliberately not underspecs/, so the console cannot trip the metrics scraper or the loop's marker parser, and survivesgit 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>withextfromDOC_TYPESinanswers.js(text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes toPOST /uploadasimage/jpeg; documents go as-is asapplication/octet-stream, the extension taken bydocExt()from the uncutx-p2c-name.readRaw(req, limit, cb)inserver.mjscaps images atMAX_BODY(4 MB) and documents atMAX_DOC_BYTES(10 MB), and drains rather than destroys so the client gets its 413. Images need theFF D8 FFmagic; documents passcheckDocument()inlib.mjs(%PDF-for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file withcrypto.randomUUID().GET /uploads/<id>.<ext>serves images asimage/jpegand documents under a fixed type (application/pdf, elsetext/plain) withnosniffand, on text, CSPsandbox(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 assentNote { at, text, images, files }(paths and names only), whichnoteAwaiting()inanswers.jsturns 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 underuploads/.isOwnUpload()returns the kind ("image"/"file"/false), andattachmentsOk()makes/submitcomments and/chatmessages carry images only inimages[]and documents only infiles[], this session's uploads only, at most 5 together (MAX_ATTACHMENTS). A comment'sreplygains oneImage: <path> (<name>)orFile: <path> (<name>)line per attachment, in attach order; a chat entry's lines come fromchatReplyLines(), 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 byconsole.mjs keep(--session --upload --name --spec [--from]): it checks both paths (the upload must sit under the session'suploads/, and the spec folder understate.project, real paths included, so a symlinked folder cannot carry the copy outside), copies withCOPYFILE_EXCLand reuses an existing copy, prints{ ok, path, link, image, reused }with a forward-slash link relative to--from, and logs akeepevent. 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
fallbackTextandtoken, 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 whileworking) stretches the stuck, adrift and Send-grace thresholds;quietLimitMs()inanswers.jsis 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 carriesreview, 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: trueshows the button; a press arrives as{ "i": "__dashboard", "type": "dashboard" }, and the agent runsopen --resume <sid> --no-open --workflow dashboardthen posts"finish": nullwith a freshmenu. The agent waits ~10 minutes after the finish for it (alongside__review/__doneon a quick task); after that the page swaps the button for the/plan2codecommand.finish.commandis optional — without one the page shows the "All done" line — andvalidate()rejects a<placeholder>command and a non-booleandashboard. The session-level actions are therefore__brief,__stop,__launch,__review,__doneand__dashboard; a new post-finish button should copy this precedent. -
__dashboardalso 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 purehomeButtonState()inanswers.js: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the sameturnGate()Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (#home-modal) reusesstopWarning(), and the submit carries the staged answers plus__dashboard, withHOME_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.homewarddrives 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) andPOST /chat/decision(Approve / Decline on an edit the agent proposed). The server is the only writer of<sid>/chat.ndjson(one JSON line permessage/decision/reset, each with aseq;appendChat()inlib.mjs);console.mjsis the only writer of<sid>/chat-cursor.json(the last seq handed over, advanced only after printing) and of the agent's replies instate.json→chat.replies(merged byid, checked byvalidateChat(): realre, proposal paths outside the runningspecs/<idea>/). The server never writes chat intostate.json—postread-modify-writes it underwithStateLock()— andstateFrame()merges inbox and replies into the frame'schatblock (conversation,messages,typed,limit,offline) in memory./chatnever checkspendingResult(), so neither channel can block the other.waitkeeps its exit codes 0/10/20/30: exit 0 gainschat(or istype: "chat"with no actions), and the instantconsole.mjs chatanswers 0/10/20 without touchingresult.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 offlinewhenchatOffline()says no agent is there,409 stalefor an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends aresetand starts a new conversation. A lone reset never ends awaitslice (deliverableChat()); it rides along with the next message. -
validate()inlib.mjsenforces 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'sdata-looks-accentstand-in only lasts untilapplyLooks()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">inindex.html(after#start-poses), cloned into#help-panelsthe first time ? is pressed, so first load builds nothing and Help still reads fully once the server is gone.help.jssupplies the tab list and rules,app.jsthe 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 — astyle=attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in adata-factspan a test checks against the constant it comes from. -
Markdown is rendered to DOM nodes, never to an HTML string (
public/render.js), so agent-authored text that quotes a hostile source cannot execute. Onlymarked.lexer()is used.
Tests: npm test runs, in order, validate-char-count.js, install.js --verify-skills, parse-check.mjs, check-skill-table.mjs, then node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs. The parse check exists because node --check parses a .js file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in scripts/, not src/web-console/, because everything under the latter ships into every skill.
Adding a file under public/ needs three edits, not one: the file itself, the SERVABLE allow-list in server.mjs, and (for a module the page imports) a <link rel="modulepreload"> in index.html. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a new module missing from it 404s and the page dies at import with no useful error (a test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after app.js and slows the first paint.
Status Line
Optional Claude Code status bar living in src/statusline-claude/. Three-line bar beside a Planny icon: two content lines with a dashed rule between, showing model (+ effort), project/worktree, branch, uncommitted diff stats, session duration + cost, context window usage, and plan/quota usage.
Design constraints:
- Zero runtime dependencies —
statusline.jsis self-contained (config loader, git helpers, formatters, render). Copied verbatim to~/.claude/plan2code-statusline.json install; no bundler step. - Stdin-driven — all data comes from Claude Code's stdin JSON (
model,workspace,context_window,rate_limits,cost). No API calls, no auth, no background processes. - Silent failure — outer
try/catcharoundmain()plusprocess.exit(0)on missing stdin guarantees the script never crashes the CLI. All git ops are timeout-bounded (1.5s) and non-git workspaces short-circuit viaisGitRepo()(walks up to 10 parent dirs looking for.git). - Atomic settings writes — installer writes
~/.claude/settings.jsonvia temp file + rename so a crash never leaves the file truncated. - Custom-config respect — installer detects non-plan2code
statusLineentries, prompts before replacing, and backs up tostatusline-previous.json. Uninstall only removessettings.statusLineif it points to the plan2code bundle.
Layout:
src/statusline-claude/
├── statusline.js # Self-contained: config, git, formatters, render
├── statusline-config.json # Default config template
└── README.md # User docs: install, config, debugging
Adaptive plan-usage display: the formatter auto-selects between 5h/7d rate-limit percentages (Pro/Max/Teams — when rate_limits present in stdin) and Nk in · Nk out session-token counts (Bedrock/Vertex/PAYG — when rate_limits absent). Segment is hidden when neither shape is available.
Installer integration lives in install.js under the STATUS LINE INSTALLATION section (installStatusLine, uninstallStatusLine). Included in A (Install All + dev tools); also available individually via Custom → S.
Global plan2code Command
Typing plan2code in any directory opens the dashboard skill against the current project, in that directory, in one of two CLIs (the CLIS table in the launcher):
| CLI | Runs |
|---|---|
| Claude Code | claude /plan2code --permission-mode bypassPermissions [args] |
| Devin | devin --permission-mode bypass [args] -- /plan2code |
With both on PATH it asks Which CLI should open Plan2Code? as a numbered menu, the last pick pre-selected (Enter keeps it; a number, claude or devin also work); with one installed it uses that without asking; with neither it exits 127 naming both. --cli claude / --cli devin (or --cli=<name>) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as lastCli in ~/.plan2code/launcher.json, merged beside lastFolder. Before spawning, unless the forwarded args carry --model / --model=, it asks Which model should <CLI> use? from the curated src/launcher/models.json (copied to ~/.plan2code/bin/models.json, overwritten by every install) merged with the user's additions in ~/.plan2code/models.json (edited in the console's User Preferences → Models). Enter keeps the model the CLI last used; a pick appends --model <id>. Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed), and it only prints which model will be used. Other arguments are forwarded to the CLI (plan2code --model opus), and its exit code is passed back. Tests: scripts/test-launcher.mjs (run by npm test) spawns the launcher against stand-in claude/devin commands and a temp home.
Design constraints:
- Stable copy, not the package dir — the installer normally runs from an npx cache directory npm may delete, so
installLauncher()copiessrc/launcher/plan2code.jsto~/.plan2code/bin/plan2code.jsand the shims point there. (The loop/metrics/bot wrappers point into__dirnameand don't have this protection.) - npm-style shims — written into npm's global bin (
npm config get prefix;<prefix>/binoff Windows): an sh shim everywhere, plus.cmdand.ps1on Windows, so cmd.exe, PowerShell and Git Bash all resolve it. On macOS/Linux, when the npm bin isn't writable (system Node), it falls back to~/.local/bin. - Marker-based ownership — every shim contains
plan2code-launcher;uninstallLauncher()removes only files carrying it, leaving any otherplan2codebin alone. - Resolving the CLI — the launcher walks
PATH(+PATHEXTon Windows) itself. An.exeis spawned directly; a.cmd/.batwrapper goes throughcmd.exe /d /s /cwith quoted args, since Node refuses to spawn batch files without a shell. The installer warns only when neitherclaudenordevinis onPATH. - No bin-name overlap — the installer's own bin in
package.jsonisplan2code-install(→install.js), soplan2codebelongs to the launcher alone. npx runs a package's only bin whatever it's named, so the README'snpx … plan2code.gitcommand is unaffected; keep it the only bin, or npx will need-c plan2code-install. --pick-folderis shortcut-only — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-styleIFileOpenDialog(FOS_PICKFOLDERS) viapowershell -STA -EncodedCommand, its C# interop (WINDOWS_PICKER_SOURCE) passed in an env var and compiled withAdd-Type(~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell'sFolderBrowserDialogis the old tree-only dialog, and is kept only as the fallback whenAdd-Typeis blocked (Constrained Language Mode, AppLocker);osascript choose folderon macOS, andzenitythenkdialogon Linux (only whenDISPLAY/WAYLAND_DISPLAYis set). If there's no picker, or the picker fails, it falls back to a typedProject folder [last]:prompt. A picker that exits 0/1 with nothing printed means the person cancelled, so the launcher exits 0. The picker starts on the last pick, stored in~/.plan2code/launcher.json. From the shortcut, a non-zero exit other than Ctrl+C (130 /0xC000013A) waits for Enter so the error doesn't vanish with the window. Typed in a terminal,plan2codebehaves exactly as before.
Desktop shortcut — after the shims are written, installLauncher() (now async) calls offerDesktopShortcut(). It asks Also add a Plan2Code shortcut to your desktop? (y/N), skips the question when stdin isn't a TTY, and refreshes an existing marked shortcut without asking. installDesktopShortcut() writes it to the real desktop ([Environment]::GetFolderPath('Desktop') on Windows, which covers OneDrive redirection; xdg-user-dir DESKTOP on Linux; ~/Desktop otherwise):
| OS | File | Runs |
|---|---|---|
| Windows | Plan2Code.lnk (written by WScript.Shell) |
pwsh.exe (else Windows PowerShell) -NoLogo -ExecutionPolicy Bypass -File "<bin>\plan2code.ps1" --pick-folder, icon src/launcher/plan2code.ico (the web console's Peek-a-boo favicon, 16–256 px) copied to ~/.plan2code/bin/plan2code.ico |
| macOS | Plan2Code.command (0755) |
exec "<bin>/plan2code" --pick-folder in Terminal |
| Linux | plan2code.desktop (0755, Terminal=true, gio … metadata::trusted) |
"<bin>/plan2code" --pick-folder, Icon= the web console's favicon.png copied to ~/.plan2code/bin/plan2code.png |
The macOS and Linux shortcuts carry the plan2code-launcher marker as a comment line. A .lnk has nowhere to hide one (its Description is the hover tooltip), so it's recognized by what it runs: the UTF-16 strings plan2code.ps1 and --pick-folder stored in the file (plan2code.cmd also matches, so shortcuts from before the PowerShell switch get refreshed). uninstallLauncher() removes only a recognized shortcut, plus the icons (plan2code.ico, plan2code.png), bin/models.json and launcher.json (never the user's ~/.plan2code/models.json). A shortcut failure prints a warning and never fails the command install.
Installer integration lives in install.js under the PLAN2CODE COMMAND section (installLauncher, uninstallLauncher, plus the shortcut helpers). install() awaits it after a successful skills install (so both I and A get it), U removes it, and Custom → D installs it alone.