mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
9.7 KiB
9.7 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: TypeScript + ESM, built with tsup (target ES2022, moduleResolution: bundler)
- External deps:
@inquirer/prompts,chalk,execa,ora - Interactive CLI via
@inquirer/prompts(select, input, confirm)
- External deps:
- File operations: Synchronous fs in all packages
- src/web-console: ESM, Node built-ins only, no build step. It is bundled into every skill, so it must stay dependency-free and runnable as a plain
node console.mjs. Anything added 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. CheckREADME.mdfor any version badges or references that need updating. 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, not ignored: repo-local skills (plan2code-changelog,plan2code-publish,sync-repo) live there and are committed. Nothing in.gitignoretouches.claude/, so a new skill only needsgit add. Per the Failure Log convention inAGENTS.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
.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 must be ≤ 11,500 characters. 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. 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 generatedSKILL.mdheader 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: 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 11,500 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: when a
specs/<feature>/PLAN-DRAFT-*.mdcontains no<!-- METRICS_JSON ... -->comment,collector.tsfalls back to prose scraping (collector.ts:186-241). The overall-confidence pattern requires a literal%, but the four breakdown patterns (collector.ts:201-204) do not —/[Rr]equirements?[:\s|]+(\d{1,2})/and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than/plan2code-1-planPhase 7 must keep both the%sign 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(cwdHash(project))inlib.mjs), 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 require build and serving coverage:
computeExpectedSkills()copies references asBuffers, so binary files are supported and the bundled MP3 chimes exercise that path. Any browser-served asset undersrc/web-console/public/must also be added to the hardcodedSERVABLEallow-list inserver.mjsand covered by a test; otherwise the generated skill contains it but the server returns 404. The vendoredmarked.esm.jssha256 is recorded in.readme/web-console.md. - Reference file sizing guideline: Files in
src/plan2code-*-references/directories target ~100-200 lines each (soft guideline; evaluate splitting above 300). They are NOT subject to the 11,500 character limit. The pre-commit hook (validate-char-count.js) only 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), and orchestrators near the 11,500 limit have no room to spend. When a reference legitimately exceeds 300 lines (e.g.plan2code-0-pathfinder-references/chart.md), that is an accepted trade-off, not an oversight. (The second constraint here — that the flat-fileReadpath rewrite was non-recursive — went away in 2.1.0 along with the rewrite itself;references/is now the real path on every agent, nested references included.)