Files
plan2code/AGENTS.md
T

119 lines
24 KiB
Markdown

# AGENTS.md
This file provides guidance to AI coding agents working with code in this repository.
## Project Overview
Plan2Code is a structured 4-step workflow methodology for AI-assisted software development. It provides prompt templates (skills) that the `skills` CLI installs globally or per-project into any agent it supports (README's "Supported tools" lists them). The `plan2code` command and the desktop app launch the dashboard directly in the built-in agents of `src/launcher/agents.json` (Claude Code, Devin, Codex); Copilot CLI, OpenCode, Gemini CLI, Pi and Cursor CLI are starter templates there, and any other agent CLI can be added as a custom agent.
**Version:** Check `version.json` for current version
**Author:** Justin Parker
**License:** MIT
Plan2Code is started from the project the person works in (`cd` into it, then run `plan2code`), not from this repository; every newcomer doc says so, next to the Node.js 18+ requirement.
## How to Use This File
This file is an index — each section below contains a brief summary and a link to a detail file in `.agents-docs/`. Read only the sections relevant to your current task. Full details (commands, tables, file lists) are in the linked files. The sections "Project Overview", "How to Use This File", "Mascot", and "Keeping this file current" / "Failure log" are fully inline here and are never split into `.agents-docs/`.
## Architecture
High-level directory structure, key files, workflow prompt inventory, and file naming conventions.
Details: [Architecture index](./.agents-docs/AGENTS-architecture.md) (layout, prompts, install: [AGENTS-architecture-install.md](./.agents-docs/AGENTS-architecture-install.md))
## Plan2Code Metrics
Recursive self-improvement toolchain (`plan2code-metrics/`) for collecting run metrics, aggregating by prompt generation, diagnosing weak steps, and proposing prompt edits.
Details: [Plan2Code Metrics](./.agents-docs/AGENTS-plan2code-metrics.md)
## Plan2Code Status Line (Claude CLI)
Optional CLI status bar (`src/statusline-claude/`) for Claude Code. Displays model (+ effort), project/worktree, branch, git diff stats, duration + session cost, context usage, and usage stats (rate limits or token counts). Reads data directly from Claude Code's stdin JSON (plus timeout-bounded git calls): no API calls, no auth, no background processes.
Details: [Status line](./.agents-docs/AGENTS-architecture-statusline.md)
## Web Console
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console/<version>/` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, a spec's saved prototypes (a **Prototypes** tab: an `.md` read in place, an `.html` opened in the default browser), an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task, Diagnose, UI Prototype or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker of game rows in two columns, ordered Recently played or A to Z (saved in `activityOrder`), with never-picked games under Not played yet, once two are listed, that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest<Id>` keys in `looks.json` (and the time each game was last picked in `activityPlayed<Id>`) (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 23-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, setup, Changelog, Git, Handoff and UI Prototype) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the seventeen helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is a card plus pointers: `console.md` (the card) once per conversation, then a topic file (`console-*.md` such as `console-docs.md`, `notes/<workflow>.md`, `building*.md`) only when the console names it in its own `read` output, once per session per topic (remembered in `pointers.json` in the session folder, owned by `pointers.mjs`); the console refuses the slips it can see (a `stop` with no `finish`, a `finish` while `stopWarning` is set, with `stop --force` for a dead page) instead of the docs repeating each rule. Byte budgets for the card, every notes file and a sample session's outputs run in `npm test` (`scripts/test-console-wire-budgets.mjs`). The server never writes into a project; the one thing it deletes there is an old `specs--completed/<feature>` the person picks in Cleanup, and only when git tracks it (an untracked one is refused, with the reason on the page).
One agent list and one lookup rule serve the launcher, the console and the app: `src/launcher/agents.json` (the built-ins and starter templates with per-OS install data) and `src/web-console/agent-lookup.mjs` (`loadAgentList()` and `findAgent()`, both copied by `install.js` into `~/.plan2code/bin/`); the app carries a Rust twin held to the same cases by `scripts/fixtures/agent-lookup-cases.json`.
**Learning** (lessons about a codebase, kept with it): the dashboard draws a Learning row (Not set up, Off, On or Paused for you, with a Pause for me switch and a More menu) and, while lessons are waiting, a banner with Review, both from the scan's `learning` field (`public/screens/learning-row.js`, `public/styles/learning.css`); skills ask for approval through the `lessons` card kind. The server's only write for it is the personal pause, on this machine only (`POST /learning/pause`, under `~/.plan2code/learning/`); every change to the project's Learning files (`.plan2code/settings.json` and `.plan2code/lessons/`) goes through the `lessons.mjs` skill script, which shares one core with the scan, `src/web-console/learning.mjs`.
Building or changing an Activities game: follow the game rules in [Activities](./.agents-docs/AGENTS-architecture-activities.md) ("Building an Activities game": lives in the solid lives pill, the endless-lives code (`cheat(on)`) in every game with lives, banners placed away from the player and see-through over what matters, pausing left to the window).
Details: [Web console server and contract](./.agents-docs/AGENTS-architecture-console.md), [page](./.agents-docs/AGENTS-architecture-console-page.md), [design points](./.agents-docs/AGENTS-architecture-console-design.md), [Activities](./.agents-docs/AGENTS-architecture-activities.md) (and the Ghoul Rush and Bounce Road files it links) and [.readme/web-console.md](./.readme/web-console.md)
Why the agent-facing console docs are shaped as they are (the card, pointers, refusals): [Web Console Contract](./.agents-docs/AGENTS-web-console-contract.md); it never ships.
## Skill Scripts
Deterministic workflow steps run as Node scripts shipped in each skill's `scripts/` (shared ones in `src/skill-scripts/`, a skill's own in `src/<skill>-scripts/`, listed per skill in `SOURCE_PROMPTS` → `scripts`). Prose keeps the judgment. JSON on stdout, documented exit codes, tests run against the built `skills/` tree.
Details: [Skill scripts](./.agents-docs/AGENTS-architecture-skill-scripts.md)
## Development Commands
Build commands, installer menu options, non-interactive skill-build verification, skills CLI delegation, skill format, and how to edit workflow prompts.
Run the targeted suites for the part you changed, not the full `npm test`, when a change stays inside one area (a game, one console page, the launcher, one skill script); the full run is for changes to shared code, sync merges, version bumps and before a PR. The area-to-suite table is in "Targeted tests first".
Details: [Development Commands](./.agents-docs/AGENTS-development-commands.md)
## Test map
The area-to-check table PR Prep and Test read (`| Area | Paths | Run | Shared |`); `Shared` rows mean the full `npm test`.
Details: [Test map](./.agents-docs/AGENTS-test-map.md)
## Code Style & Gotchas
Language/toolchain conventions for `install.js` vs TypeScript packages, US English spelling, and pitfalls to avoid (version sync, `.gitignore` pre-flight, character limits, User Feedback table format).
Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
## Mascot
The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` and appear in workflow markdown files: arms down at rest, one arm waving when he is asking something, both arms up when he is celebrating. The eye is always the star.
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight color and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. Every skill start pose, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
```
╭───╮
│ ★ │╱
╱│ ◡ │
╰┬─┬╯
```
## Keeping this file current
The `Failure log` section below is a recording of mistakes made by previous AI Agents while working with this code base.
When you make a mistake, get corrected, or discover something about this codebase that wasn't written down:
1. Add one line to the `Failure log` below, in the imperative, describing the correct behavior.
2. Keep it specific to this repo. General advice belongs nowhere.
3. If this fix is a workflow rather than a rule, put it in `.claude/skills/` and link it from here.
4. Include the change in the same commit and mention it in your summary.
5. A skill rule broken twice becomes a script check (a `scripts/` test or a skill-script check), not more prose.
6. Before adding a line, look for one on the same topic: sharpen or extend that one rather than adding a near-duplicate.
7. Keep the log to 17 entries at most. Over the cap, first merge entries that share a cause, then drop the lowest-value ones: one-offs unlikely to recur, rules a test or script now enforces, and entries about code that no longer exists.
## Failure log
- 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. Keep plan2code's ticket-free `commit-msg.mjs` (`<subject>`, `AI Assisted`) through every sync: upstream's ticket-from-branch rule was ported by mistake once and removed in v2.6.0.
- After a sync merge, check it before trusting a "clean" file: extract upstream files in Git Bash with `git show <ref>:<path>` under `MSYS_NO_PATHCONV=1` and `C:/` style paths (never `/c/`), since path conversion rewrites `origin/main:.readme/x.md` into `origin\main;.readme\x.md` and the merge silently runs against an empty "theirs" (check every extracted file is non-empty); then run `npm test`, since 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`).
- After a sync, grep the result for every upstream name the rebrand map can miss (the `/sync-repo` body lists them): the owner slug and company name in any case, the bare brand word inside identifiers and fixtures, and the ticket key followed by anything, not only digits. Each slipped through once: an owner slug in `feedback-payload.mjs` and its test (fixed by hand to `jparkerweb/plan2code`); in v2.7.0 a `KEPT_<BRAND>_ENTRIES` constant, a `<brand>Dir` option, a `"<brand>"` test folder and an owner slug in a git remote URL; in v2.8.0 git board fixtures built as `` `feature/<KEY>-${11000 + i}-…` `` template literals, which a digits-only rewrite to `ABC-<n>` misses. No upstream name may appear in plain text anywhere in this repo.
- When a new first-run dialog is added to the web console, set its seen flag in `scripts/capture-screenshots.mjs`'s `looks.json` too: the Welcome dialog once covered the regenerated dashboard screenshots until `welcomeSeen: true` was added.
- Import `scripts/skill-script-helpers.mjs` in any test that builds git fixtures for a skill script or `git-repo.mjs`: it scrubs the whole test process's git config, so fixtures, imported modules and spawned scripts agree. Mixed configs broke `git plan switch` once (a global `core.autocrlf=true` checked fixtures out with CRLF the scrubbed script read as changed). It also rebuilds `skills/` and prunes any skill folder `install.js` does not list, so register a new skill in `SOURCE_PROMPTS` before running its `scripts/test-script-<name>.mjs` or the script under test vanishes.
- Before deleting a test file that upstream split or removed, diff plan2code's copy against the rebranded upstream base and port the plan2code-only tests: v2.7.0's split of the web console suite would otherwise have dropped seven hardening tests (now in `scripts/test-web-console-hardening.mjs`).
- When a `CHANGELOG.md` heading gets a version number, write the heading by hand, then run `npm run set-version` (with no version on a terminal it shows the current one and asks, Enter taking the next patch; `npm run set-version -- <x.y.z>` sets one directly), which sets the same number in every file that carries it in the same change, then run `npm run build:skills`: `version.json` (with its `releaseDate`), the root `package.json`, README's `Version X.Y.Z` line, and under `plan2code-app/`: `package.json`, `package-lock.json` (two lines), `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml`, `fake-agent/Cargo.toml` and `Cargo.lock` (the `plan2code-app` and `fake-agent` entries). `node scripts/check-versions.mjs` compares all of them and runs in `npm test`; widen its `SOURCES` when a new file carries the version. The changelog skill only touches `package.json`: v2.9.0 nearly shipped with `version.json` at 2.8.1, and README's line sat at 2.6.0 for three releases.
- When a page test (`scripts/test-web-console-page-*.mjs`) fails only on CI or only in a full run, look for a race with a redraw before suspecting the change, and fix the test, not the timeout: read styles and set scrolls through `styleOf()`, `stylesOf()` and `scrollCard()` in `page-test-helpers.mjs` (a card a redraw replaced reads "" for every style and scrolls nothing; `test-web-console-shape.mjs` now fails a raw `locator.evaluate` that does either), and wait for the page to hold what the next step needs before acting (the workspace frame before typing `@`, the notepad's drawn marks, a newly selected tab). Keep `npm test`'s file concurrency under `scripts/node-test.mjs`'s cap of one file per spare core: a flat `--test-concurrency=8` ran 8 browsers on 3 and 4 core runners and failed a different page test on every CI run. On a busy local machine, rerun the failing files alone first; the chat stress test and the session suite's "no submitted frame within 5s" cascade still fail that way under load.
- Run `npm test` and `cargo test` from a terminal outside the desktop app, or with `PLAN2CODE_IN_APP`, `PLAN2CODE_APP_TOKEN`, `PLAN2CODE_APP_VERSION`, `PLAN2CODE_APP_ANNOUNCE`, `PLAN2CODE_EMBED_ORIGIN`, `PLAN2CODE_CONSOLE_SID` and `PLAN2CODE_LOOP_STRENGTH` unset (`env -u ... npm test`; a Loop phase's agent has the last one, and two `loop_driver` strength tests then fail with `never saw the env line`): inherited from the app they fail about 34 tests that check behavior outside the app (the update banner, the terminal line, cookies, open's browser launch), and a test console announces itself to the live window. A `cargo test` run mid-build once took the window over that way, then left an agent-less dashboard in it, and the build's question was never seen. The app now ignores sessions outside its console store (`take_announced` in `main.rs`), and the Rust console tests scrub the variables, but the JS suites do not. Before pushing a change under `plan2code-app/`, also run `cargo fmt --check` and `cargo clippy --workspace --all-targets -- -D warnings` there, not only `cargo test`: CI's `app` workflow fails on either, and the Rust code once reached a PR never formatted (20 files) with three clippy errors, one only macOS and Linux could see (see plan2code-app/README.md "Tests"). `loop_driver` tests failing with `never saw ... agent generations` and no `ARGS` line in the output mean `target/debug/fake-agent` is older than its source (a file restored with an old time, so Cargo never rebuilds it): `touch plan2code-app/fake-agent/src/main.rs` and rerun. A stale binary once read as 2 real failures in PR Prep.
- Never fix CRLF by hand, one file at a time: run `npm run fix:eol` (`scripts/fix-line-endings.mjs`). Windows Python in text mode, among other tools, writes CRLF into files git keeps as LF; a whole session's edits once came out CRLF and 14 other files were found the same way. It now also runs as `pretest`, in the pre-commit hook and after every agent Write or Edit (see the LF gotcha in Code Style).
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → System → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
- When a test checks how `cmd.exe` finds a `.cmd`/`.bat` (current folder before PATH), clear `NoDefaultCurrentDirectoryInExePath` for the run under test (`env_remove` in Rust, `undefined` in a `test-launcher.mjs` `box.run` env): some shells (Claude Code's among them) already set it, and the decoy `.cmd` test for custom agents passed without its fix until it did.
- Never set a `Secure` cookie for the app's `tauri://localhost` frame (Linux and macOS): WebKit drops a Secure cookie sent over plain `http://127.0.0.1`, so every request after the sign-in got a 403 and the Linux app showed "its page did not show in this window" while working on Windows, where WebView2 counts loopback as secure. `cookieSameSite()` in `src/web-console/routes.mjs` sends Lax there and None; Secure only to `tauri.localhost`; check an embed change in a WebKit view, not only Chrome.
- On Windows, treat a console the agent opened as dying with the agent: the app ends the agent's whole Job Object, so a `detached` server goes too, with no `exit` event. A `console.mjs post` still succeeds because it writes the session's files, so it proves nothing about the server; only the window's reconnect brings the page back. Every loop phase ends this way, and a reconnect budget that never refilled once lost the loop's stop card after Phase 3.