mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
11 KiB
11 KiB
Code Style & Gotchas
Part of AGENTS.md — project guidance for AI coding agents.
Code Style
- install.js: CommonJS, Node.js built-ins only (no external deps), ANSI colors via
COLORSconstant, readline-based prompts - plan2code-loop, plan2code-metrics & plan2code-bot: TypeScript + ESM, built with tsup (target ES2022, moduleResolution: bundler)
- External deps (loop, metrics):
@inquirer/prompts,chalk,execa,fs-extra,ora - External deps (bot):
@anthropic-ai/claude-agent-sdk,chalk,fs-extra,ora - Interactive CLI via
@inquirer/prompts(select, input, confirm)
- External deps (loop, metrics):
- File operations: Synchronous fs by default; the web console's fire-and-forget sweeps and
readOverview()usefs.promises - src/web-console: ESM, Node built-ins only, no build step. It is bundled into every skill, so it must stay dependency-free and runnable as a plain
node console.mjs. Anything added undersrc/web-console/ships to users — put tests inscripts/instead.
Gotchas / Pitfalls
- Version sync: When adding a new version to
CHANGELOG.md, also updateversion.jsonandpackage.json(root) to match.README.mdanddocs/index.html(footerVersion X.Y.Z) also carry the version.version.jsonis copied into every skill'sreferences/web-console/(the console's Help shows it), so after a bump runnpm run build:skillsornpm test(--verify-skills) fails. The installer displays the version fromversion.jsonin its header. All three files (CHANGELOG.md,version.json,package.json) must always show the same version number. - CHANGELOG ordering: Entries in
CHANGELOG.mdmust be in reverse-chronological order — newest version at the top, oldest at the bottom. New entries are always inserted immediately after the file header. - CHANGELOG house format is not Keep a Changelog: version headings are
## vX.Y.Z— with avprefix and no date. The release date is recorded only inversion.json'sreleaseDate. Category headings carry emoji:### ✨ Added,### 🔧 Changed,### 🐛 Fixed,### 💥 Breaking,### 🗑️ Removed,### 📚 Documentation. Older entries contain one-off variants (🎁 Added,📦 Updated,📝 Documentation,🏎️ Improved,🧪 Testing) — do not introduce new ones. The.claude/skills/plan2code-changelog/skill automates version selection and formatting; use it rather than hand-rolling an entry. - PowerShell mangles the CHANGELOG emoji:
Get-Content/Select-Stringrender the###heading emoji as?under the default Windows console encoding, so a heading audit done that way reports garbage. ReadCHANGELOG.mdwith a file-read or grep tool instead. .claude/skills/is tracked: a new repo-local skill only needsgit add(see Architecture → Repo-Local Skills). A correction that is a workflow belongs there as a skill, linked from AGENTS.md, not as a Failure log line.- Loop
.gitignoresetup:ensureGitignore()runs at startup inController.run()as a pre-flight step, not just insidecreateTaskCommit(). This is critical for phase mode where the Node controller doesn't handle commits — without it,git add -Awould stage spec files. - Workflow file character limit: All
src/plan2code-*.mdfiles (and the dashboard promptsrc/plan2code.md) must be ≤ 20,000 characters (about 5k tokens, the usual Agent Skills guidance for a SKILL.md body). A husky pre-commit hook enforces this, andplan2code-metrics(improver.ts,applier.ts) applies the same number to proposed prompt edits, so change them together. History: 11,000 originally (headroom under Windsurf's old 12,000-char limit for platform-specific files, gone since 2.1.0's single-format build), 11,500 in 2.4.0, 20,000 in 2.4.1. The limit is now a prompt-size discipline only: the whole SKILL.md loads on every invocation while references load on demand, so situational detail still belongs in a reference file, and anything with one correct answer belongs in a script (see Skill scripts in the architecture doc). - Keep LF line endings:
.gitattributespinseol=lfbecausevalidate-char-count.jscounts the characters on disk, and a CRLF checkout adds about one per line to every prompt. Measure withnode scripts/validate-char-count.jsbefore trusting a near-limit prompt. - The pre-commit hook runs only the char-count check:
.husky/pre-commitisnode scripts/validate-char-count.jsalone.skills/drift, parse errors and test failures are caught only bynpm test, so run it before committing. Sub-package tests are separate; see Development Commands. skills/is a committed build artifact: editsrc/, runnpm run build:skills, and commit the regenerated skills in the same change.npm testrunsinstall.js --verify-skillsand fails on missing, unexpected, or stale files. Never editskills/by hand.- Metrics internal prompts have no char limit: Files in
plan2code-metrics/src/prompts/are NOT subject to the 20,000 char limit — onlysrc/plan2code-*.mdconsumer-facing prompts are. - User Feedback table format: The
## User Feedbackmarkdown table inoverview.mdhas a strict format the collector regex depends on. Field names must be exactlyRating,Reason,Went Well,Went Poorly. Pipe characters in values must be escaped as\|. - PLAN-DRAFT confidence numbers are scraped by regex:
collector.tsscrapes the latestspecs/<feature>/PLAN-DRAFT-*.mdprose. Overall confidence falls back to prose only when<!-- METRICS_JSON ... -->lacksconfidence(collector.ts:186-196):Confidence: 95%, or a table row| Confidence | 95with no%. The four breakdown patterns (collector.ts:200-203) run on every draft, METRICS_JSON or not:/[Rr]equirements?[:\s|]+(\d{1,2})/and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than/plan2code-1-planPhase 7 must keepConfidencefollowed by a number (with%, or as a table row) and bareRequirements/Feasibility/Integration/Riskfollowed by a number off the page — including innocent table rows like| Requirements | 11 |. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced./plan2code-0-pathfinderworks around this by hyphenating the labels (Requirements-clarity 22/25), which breaks the character class. - Web console result-handoff invariant:
result.jsonholds answers a person pressed Send on. An uncollected result (noconsumedAt) is never overwritten and never deleted./submitand/cancelreturn 409 while one is pending,openclears the file only when it is already consumed, andwaitstampsconsumedAtafter printing the result, never before, and exits by settingprocess.exitCoderather than callingprocess.exit(). That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", andprocess.exit()can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touchesresult.jsonmust preserve the invariant, andscripts/test-web-console.mjsguards it. Related: the server writes each submitted answer onto its item assubmitted, andvalidate()inlib.mjsmust keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typedTASK_COMPLETEinto an answer would otherwise make every later patch unpostable. - Web console oversized bodies:
readBody()inserver.mjscallsreq.destroy()pastMAX_BODY, so an oversized JSON body gets no response at all: the client sees a connection reset, never a status code. A route that must answer 413 has to stop buffering and drain the rest of the body instead, asreadRaw()(thePOST /uploadreader) does; memory still stays capped. - Web console commands are tied to the directory
openran in:console.mjsfinds a running server through a handle file under a hash of the project directory (handleFile(project, sid)→runtimeDirFor(project)→<RUNTIME_DIR>/<cwdHash(project)>/<sid>.jsoninlib.mjs, withRUNTIME_DIR=os.tmpdir()/plan2code-console, or$PLAN2CODE_CONSOLE_HOME/runtime), and the project is the working directory ofopen/open --resume. Runstatus,chat,waitandstopfrom that same directory. From anywhere elsestatussayslive: false,chat/waitreportserver-gone(exit 20) andstopstops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; checkserver.logandevents.ndjson(a real exit writes anexitevent or a stack) before chasing one. - Windows temp paths in web console tests:
os.tmpdir()can be an 8.3 short path (C:\Users\JUSTIN~1.PAR\...), whileserver.mjscanonicalises its session dir withfs.realpathSync.nativeto the long form. Any test comparing a server-returned path (e.g. an upload'spath) against the test'ssessionmust pass the test side throughfs.realpathSync.native()first, and compare case-insensitively on Windows. - Web console assets:
computeExpectedSkills()copies references asBuffers, so binary files are fine. Adding apublic/file needs the three edits in Architecture → Web Console. The vendoredmarked.esm.jssha256 is in.readme/web-console.md. - The default highlight color lives in two places: changing it means editing
DEFAULT_ACCENTinpublic/palette.jsand the light, system-dark and explicit-dark--accent*values inpublic/app.css. No test ties them together. - Reference file sizing guideline: Files in
src/plan2code-*-references/directories target ~100-200 lines each (soft guideline; evaluate splitting above 300). They are NOT subject to the 20,000 character limit. The pre-commit hook (validate-char-count.js) only checkssrc/plan2code-*.mdflat files — subdirectory contents are automatically excluded. - The splitting guideline has a hard ceiling — reference files cannot always be split: each new reference costs the orchestrator a
Read references/<file>.mdline plus its fallback blockquote (~150-200 chars), which adds up across a prompt's 20,000-char budget. When a reference legitimately exceeds 300 lines (e.g.plan2code-0-pathfinder-references/chart.md), that is an accepted trade-off, not an oversight. Nested folders under-references/work:references/is the real path on every agent. - Windows global bins for loop, metrics and bot are wrappers, not
npm link: on win32 the installer writes<name>.cmdand<name>.ps1intonpm config get prefix, each runningnode <package>/dist/bin/<name>.js(install.js:1302-1323for the loop; the metrics and bot installers do the same). After a source change,npm run buildin the package is enough; no reinstall. - plan2code-metrics only runs from a repo checkout:
analyzer.tsandimprover.tsloadsrc/prompts/analyze.md/improve.mdat runtime throughnew URL('../src/prompts/...', import.meta.url), resolved relative todist/(analyzer.ts:11,improver.ts:13). A packed or copieddist/withoutsrc/prompts/fails.