Compare commits

..
354 Commits
Author SHA1 Message Date
github-actions[bot] 9b876077e3 Install payload for v3.2.5
Source commit: 9629961f36
2026-12-04 15:09:47 +00:00
jparkerweb 50319aa332 Merge pull request #19 from jparkerweb/docs/real-app-screenshots
Replace app placeholder pictures with real captures (v3.2.3)
2026-12-03 09:13:16 -08:00
jparkerweb 7b4e8811e4 Release 3.2.3: real desktop app pictures and a redrawn banner
AI Assisted
2026-12-02 20:35:56 -08:00
jparkerweb bc2325e061 Replace the desktop app placeholder pictures with real captures, redraw the banner
AI Assisted
2026-12-02 20:33:49 -08:00
jparkerweb ccf82c4eb7 Remember the terminal or web console choice, refresh the launcher model menus (v3.2.2)
AI Assisted
2026-11-30 20:08:23 -08:00
jparkerweb f1d087ba47 Read the sync password from a local .env, and record the v3.2.1 reverse port
AI Assisted
2026-11-29 22:16:04 -08:00
jparkerweb d059dbf30c Drop the file table and code-signing note from release notes in the publish skill 2026-11-29 21:55:57 -08:00
jparkerweb 3b822a3efa Commit and push from one card on the git board, without the extra confirms
AI Assisted
2026-11-29 21:51:45 -08:00
jparkerweb ee530d36c0 Quiet the Tidy up banner once a tidy-up finds nothing
AI Assisted
2026-11-29 21:15:46 -08:00
jparkerweb 634e4df10e Add text size buttons to the console's top bar (v3.2.1)
AI Assisted
2026-11-29 20:48:03 -08:00
jparkerweb 8277c8b548 Record the latest reverse port in the sync skill
AI Assisted
2026-11-29 12:42:11 -08:00
jparkerweb 8ae55bb76f Merge pull request #18 from jparkerweb/feature/lessons-self-improvement
Feature/lessons self improvement
2026-11-29 10:52:46 -08:00
jparkerweb 78ea888bc7 Note the lessons-card and app-bar changes under v3.2.0
AI Assisted
2026-11-29 10:49:45 -08:00
jparkerweb 97f65edd84 Let the app bar's update line use the room the bar has
AI Assisted
2026-11-29 10:49:44 -08:00
jparkerweb 834b71e82d Fill a lesson's Reword boxes with the words Ask for suggestions sends
AI Assisted
2026-11-29 10:49:42 -08:00
jparkerweb e0f82cc36b Give Help a Review Loop topic and open it from both Review Loop links
AI Assisted
2026-11-28 22:29:52 -08:00
jparkerweb bcb6e43dbd Keep four lessons from the Review Loop build
AI Assisted
2026-11-28 21:09:07 -08:00
jparkerweb 57567d7a0b Add the Review Loop: unattended review-and-fix rounds in the desktop app and in loop phases
AI Assisted
2026-11-28 21:09:02 -08:00
jparkerweb d6a28b5dc8 Release 3.2.0: check every waiting lesson before approval, and tidy up and count saved lessons
AI Assisted
2026-11-28 08:22:31 -08:00
jparkerweb 1345aa0a95 Grade every waiting lesson with a separate check before the lessons card asks for approval
AI Assisted
2026-11-27 23:19:42 -08:00
jparkerweb b06a4cb4ab Release 3.1.5: start the new project's dashboard on Change project, and keep the console page itself from scrolling
AI Assisted
2026-11-24 08:23:00 -08:00
jparkerweb cfc58f5a06 Release 3.1.4: retry an update that stopped partway, and refresh the launcher's model menu and agent install data
AI Assisted
2026-11-20 16:57:47 -08:00
jparkerweb 630a1169c3 Let the lessons reader fill its dialog: lift the 68ch cap and stop balancing long lesson titles
AI Assisted
2026-11-19 19:41:52 -08:00
jparkerweb ab4e3322d6 Record the latest upstream sync in the sync skill
AI Assisted
2026-11-19 13:48:46 -08:00
jparkerweb 1616019705 Free runner disk for the Linux app build, and keep the deps fixture lockfiles under a name dependency scanners skip
AI Assisted
2026-11-19 13:48:39 -08:00
jparkerweb f2e9b8bde8 Record the latest reverse port in the sync skill
AI Assisted
2026-11-19 11:15:49 -08:00
jparkerweb fb81f80ce5 Fix the Subagents dialog test on Chrome 158: count its flow-end reading of justify-content as flex-end
AI Assisted
2026-11-19 08:40:42 -08:00
jparkerweb e5ce951b93 Release 3.1.3: the stranded finish screen's way out, and the CI and test upkeep
AI Assisted
2026-11-18 22:21:15 -08:00
jparkerweb 8658631b5d Steady the status line test: wait for the post's redraw before typing the answer
AI Assisted
2026-11-18 21:40:10 -08:00
jparkerweb 09fb4f4eec Steady the git tab scroll test: note the place after the scroll a click on a tab makes
AI Assisted
2026-11-18 20:18:20 -08:00
jparkerweb c96e1f0f52 Draw a stranded finish screen's way out when the press goes unanswered by time alone
AI Assisted
2026-11-18 19:45:06 -08:00
jparkerweb 3b09d03090 Fix two tests that fail on macOS: the temp folder's real path and the select-all key
AI Assisted
2026-11-18 19:45:04 -08:00
jparkerweb ce073cd07a Fix two page tests the git board path and the Markdown box click fix left failing
AI Assisted
2026-11-18 17:56:28 -08:00
jparkerweb 65fbd1bfe1 Move CI's checkout, setup-node and artifact actions to their Node.js 24 versions
AI Assisted
2026-11-18 17:34:35 -08:00
jparkerweb 52efac51b8 Release 3.1.2: changelog for the git board path and the installer's release redirect
AI Assisted
2026-11-18 16:47:46 -08:00
jparkerwebandClaude Opus 5.5 775b693583 Trim the console card back under its byte budget, say skills/ is gitignored in the internals guide, and record the latest reverse port
AI Assisted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:28:24 -08:00
jparkerwebandClaude Opus 5.5 cc7d89181d Send installers fetched from unreleased main to the newest release, for launchers older than the release channel
AI Assisted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:23:38 -08:00
jparkerweb 7588767e19 set version num 2026-11-18 06:41:56 -08:00
jparkerweb 326262df5a Guide the git board through Save, Share, Review and Tidy, with the other actions folded away
AI Assisted
2026-11-18 06:39:22 -08:00
jparkerweb e6d5075101 Add Suggest for me to the loop setup's strength per phase and release 3.1.2
AI Assisted
2026-11-18 06:35:28 -08:00
jparkerweb 9cbb970552 Focus a Markdown box on a click anywhere inside its border
AI Assisted
2026-11-17 20:02:40 -08:00
jparkerweb bf8dea9942 Pin the lessons dialog buttons, spin while asking, widen the reply and outline suggested choices
AI Assisted
2026-11-17 19:19:15 -08:00
jparkerweb 26a87bec32 Release 3.1.1: relicense under Apache 2.0 and rewrite the README and site around the six steps
AI Assisted
2026-11-17 18:08:02 -08:00
jparkerweb e9679c47b9 Restyle the web console and tidy its labels, Ask tab, cleanup and help
AI Assisted
2026-11-17 18:08:01 -08:00
jparkerweb 710c751c2f Add Update and restart, a remembered window and safer copy and paste to the desktop app
AI Assisted
2026-11-17 18:07:59 -08:00
jparkerweb c07e679105 Install and update from release tags so people never get unfinished work from main
AI Assisted
2026-11-17 18:07:58 -08:00
jparkerweb 347831475d Complete the v3.1.0 changelog entry with the Changes tab, recent folders, deps rework and reconnect retry, and record the latest reverse port
AI Assisted
2026-11-15 18:25:34 -08:00
jparkerweb 7e2dae64c6 Bump version.json release date to 2026-11-15
AI Assisted
2026-11-15 16:11:09 -08:00
jparkerweb b61e3c4052 Start the deps test's fixture server in a root before hook so after hooks cannot run early
AI Assisted
2026-11-15 14:58:05 -08:00
jparkerweb a90fb8647c Size the Lessons modal like the Notebook and offer suggestions on the Lessons card
AI Assisted
2026-11-15 14:58:02 -08:00
jparkerweb 8459836d3b Offer recent project folders in the launcher and the desktop app
AI Assisted
2026-11-15 11:22:58 -08:00
jparkerweb 2e2b3e1139 Show working feedback and a way out on the Lessons review flow
AI Assisted
2026-11-14 23:05:35 -08:00
jparkerweb f61ef6e0a7 Add the Changes tab at sign-off: snapshot at start, diff at the end, drawn in the console
AI Assisted
2026-11-14 22:02:58 -08:00
jparkerweb 72ae44745f Name fixed files in the deps report, guard a missing outcome, correct two doc rows
AI Assisted
2026-11-14 21:18:33 -08:00
jparkerweb 496bdf3e62 Add a lesson: change the Update dependencies card in the prompt and the console notes together
AI Assisted
2026-11-14 18:34:00 -08:00
jparkerweb e80713742e Let the app try reconnecting once on its own when its countdown ends
AI Assisted
2026-11-14 18:33:04 -08:00
jparkerweb 7021ff9a48 Add the Changes tab: changes.mjs and a diff block for the sign-off page
AI Assisted
2026-11-14 18:33:03 -08:00
jparkerweb cb64a8d15e Rework Update Dependencies: plain words, pins and baseline, approved fixes and scanner installs
AI Assisted
2026-11-14 18:33:02 -08:00
jparkerweb faa5438db2 Turn on Learning for this repo: track .plan2code/settings.json, ignore only its generated folders, and point AGENTS.md at the lessons
AI Assisted
2026-11-14 16:08:31 -08:00
jparkerweb 66fd2f71a1 Update the prototypes and state tests for the Prototypes tab (match native realpath, add the prototypes state entry)
AI Assisted
2026-11-14 16:06:18 -08:00
jparkerweb f715e469ef Bump version to 3.1.0 and add the v3.1.0 changelog entry (Learning, Update dependencies, UI Prototype, web console and Snake changes)
AI Assisted
2026-11-14 10:46:19 -08:00
jparkerweb 216c64472e Update the plan2code-bot lock file
AI Assisted
2026-11-14 10:43:24 -08:00
jparkerweb 118ec8b12c Ignore the whole .plan2code/ folder, not just the dead-code reports
AI Assisted
2026-11-14 10:43:02 -08:00
jparkerweb 1516b25ea3 Seed new notepad tabs with their name as a heading and focus under it, show Learning switch on/off as working right away, and stop the Tauri window from taking file drops
AI Assisted
2026-11-14 10:42:23 -08:00
jparkerweb bb5bd5986d Add Learning, move tool folders under .plan2code, and the Loop, Snake and console changes
AI Assisted
2026-11-13 23:29:12 -08:00
jparkerweb de8a05b958 Add the Update dependencies skill
AI Assisted
2026-11-13 23:28:59 -08:00
jparkerweb 5679101487 Add Bounce Road music, extras and arcade tests
AI Assisted
2026-11-13 23:28:42 -08:00
jparkerweb a0300d4ac2 Add four Bounce Road music tracks
AI Assisted
2026-11-12 11:21:55 -08:00
jparkerweb a55951939b Center the dashboard's approval tip under its cards and let it run most of the grid's width
AI Assisted
2026-11-12 11:21:53 -08:00
jparkerweb 36648c3e75 Offer to archive a prototype-only spec folder once Quick Task has built from it
AI Assisted
2026-11-12 11:21:51 -08:00
jparkerweb e6257e92bf Steady the dashboard rows page test against redraws and derive its expected columns
AI Assisted
2026-11-12 10:59:09 -08:00
jparkerweb 3fe1de51ed Keep each dashboard group at one card width with no card left alone on a row
AI Assisted
2026-11-12 10:35:30 -08:00
jparkerweb c6265795ea Let UI Prototype start from a Notebook tab, filling its request box on Start fresh
AI Assisted
2026-11-12 10:35:29 -08:00
jparkerweb fde92ef4d2 Show the Activities picker as a two-column Score ledger ordered by recently played or A to Z
AI Assisted
2026-11-12 10:35:28 -08:00
jparkerweb ba19f79f1c Add a Prototypes tab: list a spec's saved prototypes, read an md in place, open an html in a browser
AI Assisted
2026-11-12 07:56:52 -08:00
jparkerweb b38f2b987b Link the git board's branch title to the branch on its host
AI Assisted
2026-11-12 07:55:59 -08:00
jparkerweb 97b5df61ea Add a swaying question mark beside Ask for suggestions and a chevron before Send
AI Assisted
2026-11-12 07:54:26 -08:00
jparkerweb 54b316cdf3 Add the UI Prototype skill, and have Quick Task confirm a saved prototype's brief before planning
AI Assisted
2026-11-11 22:01:55 -08:00
jparkerweb 2f790027a9 Refuse a quick-task finish that offers the review again once a review ran in that launch
AI Assisted
2026-11-11 22:01:41 -08:00
jparkerweb d599d87669 Refresh the agent docs: a Test map section, merged sync log lines and current newcomer notes
AI Assisted
2026-11-11 08:08:08 -08:00
jparkerweb 15d66aa19c Show the saved diagnosis in full on the Diagnose finish, with Copy report for a ticket elsewhere
AI Assisted
2026-11-11 08:08:02 -08:00
jparkerweb 8bb1b11296 Add the v3.0.6 changelog entry for the set-version prompt and npm script 2026-11-10 14:18:12 -08:00
jparkerweb 9199fc00af Let set-version ask for the version on a terminal (Enter takes the next patch) and run as npm run set-version, bump every carrier to 3.0.6, and read the Ask entry for screenshots from the session's chat log now that chat hands over only the seq
AI Assisted
2026-11-10 14:14:44 -08:00
jparkerweb 567a65ff5b Rebuild the marketing page around the desktop app on a blueprint look (the app tilted over one light, a four-step session in the hero, the loop ledger, stacked install), add a Plan-suggested dashboard screenshot for it, and list Git as a prerequisite in every newcomer doc since npm needs it to fetch the installer
AI Assisted
2026-11-10 12:53:16 -08:00
jparkerweb 1d064b18f3 Remove unused exports found by Dead Code and ignore its saved reports
AI Assisted
2026-11-10 12:46:20 -08:00
jparkerweb d1aab9d006 Refuse a new console question while cards from the send just collected are still open and unsettled
AI Assisted
2026-11-10 12:46:19 -08:00
jparkerweb 7f32c351b1 Offer a final review of the removals at the end of the Dead Code skill, run in the same session
AI Assisted
2026-11-10 12:46:18 -08:00
jparkerweb b3768b47a3 Fix the wording of the unsigned-app notice the installer prints after installing the desktop app
AI Assisted
2026-11-10 10:23:02 -08:00
jparkerweb 8efa1aece1 Show the UPDATE AVAILABLE banner inside the desktop app too, since the app cannot replace itself and a new release still needs plan2code update run in a terminal outside it, and word the modal, Help and docs for that
AI Assisted
2026-11-10 10:19:33 -08:00
jparkerweb 6e84e6a6a4 Keep the agent id round-trip test and the US English scan from failing on an installed release or PHPStan's analyse command, and record the latest reverse port in the sync-repo skill
AI Assisted
2026-11-10 08:22:32 -08:00
jparkerweb aa6361d39e Add the Dead Code skill, Cursor CLI and recent app changes to the v3.0.5 changelog
AI Assisted
2026-11-09 22:15:07 -08:00
jparkerweb f6790e5cf1 Make SWE-2 Flash High Devin's default Thrifty model for the Loop
AI Assisted
2026-11-09 22:12:07 -08:00
jparkerweb a584c45dfd Add the Dead Code skill with hash-matched keep rows and one tool per language
AI Assisted
2026-11-09 22:09:05 -08:00
jparkerweb 7891c06642 Carry the spec into the app's New Session and name it beside the meter
AI Assisted
2026-11-09 22:09:03 -08:00
jparkerweb 7856618a4c Say the app bar shows the agent's model and effort in the desktop app docs
AI Assisted
2026-11-09 22:09:02 -08:00
jparkerweb b5089cdc94 Add the Cursor CLI starter template and refresh launcher agent and model data
AI Assisted
2026-11-09 22:09:00 -08:00
jparkerweb 785a4dc8b9 Make the Loop stopped screen say why and recommend one button
AI Assisted
2026-11-09 15:32:04 -08:00
jparkerweb b585eccd5a Show the agent's model and effort in the app bar
AI Assisted
2026-11-09 15:05:12 -08:00
jparkerweb 02380fa6fe Let each sound cue pick from 19 sounds in Preferences
AI Assisted
2026-11-09 12:53:53 -08:00
jparkerweb 459b840db9 Add an Always SKIP Intro preference
AI Assisted
2026-11-09 11:46:13 -08:00
jparkerweb f24a254f96 Style loop webhook notifications as cards
AI Assisted
2026-11-09 11:46:09 -08:00
jparkerweb 1a17578aa9 Refuse a new question until a noted one is dealt with
AI Assisted
2026-11-09 10:08:45 -08:00
jparkerweb 92d4d880bf Let Diagnose start from a Notebook tab
AI Assisted
2026-11-09 08:08:43 -08:00
jparkerweb 9a23b15fc9 Give a stranded finish screen a way out
AI Assisted
2026-11-09 08:08:43 -08:00
jparkerweb d4b604ba7f Clear a pressed Review when a different finish replaces it
AI Assisted
2026-11-08 23:14:26 -08:00
jparkerweb dd86279e88 Ask for sign-off after Quick Task's See it running demo
AI Assisted
2026-11-08 23:14:09 -08:00
jparkerweb f92af765e7 Give the loop strength picker's rows the prototype's height
AI Assisted
2026-11-08 22:52:34 -08:00
jparkerweb bb66f1d458 Offer a reconnect button when a loop phase's page does not show
AI Assisted
2026-11-08 22:15:49 -08:00
jparkerweb f5369df090 Draw the loop's strength picker as a stepped grid and release 3.0.5
AI Assisted
2026-11-08 21:57:09 -08:00
jparkerweb 4f172c63d3 Merge pull request #17 from jparkerweb/fix/loop-tests-and-sync-direction
Fix/loop tests and sync direction
2026-11-08 20:01:37 -08:00
jparkerweb 1bbf3db50a Keep the app tests that start a console from changing its variables under each other
AI Assisted
2026-11-08 19:28:54 -08:00
jparkerweb b0f75fc920 Ask the sync direction first and add a reverse port with its own baseline
AI Assisted
2026-11-08 19:07:34 -08:00
jparkerweb c5a58270cf Bring the loop notes back under budget and test the strength grid's radios
AI Assisted
2026-11-08 19:07:33 -08:00
jparkerweb fa32fc79dd Add a neutral lvl-0 rank color and badge style
AI Assisted
2026-11-08 18:17:08 -08:00
jparkerweb 49600bcba1 Let a loop phase pass when its only failing tests are ones the plan expects to fail
AI Assisted
2026-11-08 18:17:06 -08:00
jparkerweb 0fdb99f723 Redesign Agents & models as a roster of cards with a side drawer and an Add agent chooser
AI Assisted
2026-11-08 18:08:33 -08:00
jparkerweb 5136269ca7 Add a per-phase webhook message and more detail to loop notifications
AI Assisted
2026-11-08 17:50:23 -08:00
jparkerweb e5155778bf Add plan2code uninstall to remove everything the installer put in place
AI Assisted
2026-11-08 17:25:40 -08:00
jparkerweb bd2bbc2764 Add the shared metrics pattern file the console's bait scanner reads
AI Assisted
2026-11-08 13:48:45 -08:00
jparkerweb 3ee96834bf Harden the shared console install, launcher, Loop staging, spec state and prompts
AI Assisted
2026-11-08 13:48:28 -08:00
jparkerweb 120c259d9c Add Back to the dashboard to the footer of a finished session
AI Assisted
2026-11-08 08:21:08 -08:00
jparkerweb 4ca53ccf3a Warn about a too-long tab name as you type
AI Assisted
2026-11-08 08:17:08 -08:00
jparkerweb 9f4ee75c0b Show a spinner on a note that is sent and waiting for Plan2Code
AI Assisted
2026-11-08 07:56:54 -08:00
jparkerweb 275f1cb320 Split the desktop app's unsigned warning into two lines
AI Assisted
2026-11-07 13:12:49 -08:00
jparkerweb 49619f88f0 Fix the agent setup page's Back button, scrolling and Install page link, and release 3.0.4
AI Assisted
2026-11-07 12:23:45 -08:00
jparkerweb 037fb0d864 Turn activity music on by default, like the activity sounds
AI Assisted
2026-11-06 17:17:36 -08:00
jparkerweb 74d07be90a Run the AGENTS.md tab suite in npm test and expect its state in the state test
AI Assisted
2026-11-06 17:17:35 -08:00
jparkerweb 184876b437 Check every file that carries the version, and run it in npm test
AI Assisted
2026-11-06 13:46:43 -08:00
jparkerweb 20a349a3f8 Show the project's AGENTS.md on a dashboard tab with in-place links
AI Assisted
2026-11-06 13:42:38 -08:00
jparkerweb d84d6a4690 Start the desktop app terminal docked on the right, and release 3.0.3
AI Assisted
2026-11-06 13:38:13 -08:00
jparkerweb 9226b82c37 Tell desktop app users when a newer release is out, and release 3.0.2
The app now asks GitHub for the newest vX.Y.Z tag when it starts and, when it is ahead, the top bar says so with a button that copies `plan2code update`. Before, the app only compared its own version with the installed skills, so it never knew a release existed.

Version 3.0.2 everywhere (version.json, package.json, the app's package.json, package-lock.json, Cargo.toml, Cargo.lock, tauri.conf.json, README, CHANGELOG).
2026-11-06 11:01:08 -08:00
jparkerweb 76e0c44e0b Create the release last so its tag never gets ahead of its binaries, and run the app job on Ubuntu only for pushes
release-app.yml now starts by hand with a version, title and notes (plan2code-publish does it). It builds the four systems, makes a draft release with every file attached and then publishes it, so the vX.Y.Z tag the update check watches appears only when the downloads exist. Publishing a release by hand or pushing a v* tag still starts it as a fallback.

plan2code-publish dispatches the workflow and watches it instead of running gh release create.

app.yml: pushes to main run the app job on Ubuntu only; the full three-system run stays on manual runs and the full-matrix label.
2026-11-06 10:43:22 -08:00
jparkerwebandClaude Sonnet 5.5 f28d4d592a Run the root npm test suite only by hand in CI, and run the prose checks on every push and pull request
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 10:18:57 -08:00
jparkerwebandClaude Opus 5.5 272e514372 Show the dashboard in the Linux app by dropping Secure from its frame's sign-in cookie, and release 3.0.1
WebKit (the app's web view on Linux and macOS) drops a Secure cookie sent
over plain http://127.0.0.1, so inside the tauri://localhost frame every
request after the sign-in was a 403 and the app showed "its page did not
show in this window". That frame now gets SameSite=Lax; Windows'
tauri.localhost keeps None; Secure, and standalone keeps Strict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 09:50:15 -08:00
jparkerweb cedc3300ed Merge pull request #16 from jparkerweb/v3-orchestrator
Plan2Code v3.0.0: desktop app, Implementation Loop, strength-matched helpers, custom agents, PR Prep and Write missing tests
2026-11-05 21:58:11 -08:00
jparkerweb 8bace16e06 Pace the keys in the in-app full-screen test so the browser's late answers cannot undo the next one
AI Assisted
2026-11-05 20:47:41 -08:00
jparkerweb e87148ad10 Pin Math.random in the Activities logic tests so a rare roll cannot fail one at random
AI Assisted
2026-11-05 20:26:49 -08:00
jparkerweb 23ac3a9c19 Fix two Ubuntu flakes: try more road for a Bounce Road rival, and wait for the board's focus before the last F press
AI Assisted
2026-11-05 20:05:02 -08:00
jparkerweb a0ac6eb655 Hand every page test a page that has gone quiet, and retry the @ list until it names the project
AI Assisted
2026-11-05 19:44:35 -08:00
jparkerweb 958c0f4ccc Let the page go quiet before typing in the Markdown answer box test
AI Assisted
2026-11-05 19:25:50 -08:00
jparkerweb 959554d127 Make the Ask send self-healing and let the page go quiet before scrolling in tests, so late redraws stop failing them
AI Assisted
2026-11-05 19:05:59 -08:00
jparkerweb fc2921c848 Retype the @ in the session modules test if a redraw swallowed it
AI Assisted
2026-11-05 18:51:33 -08:00
jparkerweb e0b64e5895 Let the note tray go quiet before the Ask picview test opens a picture
AI Assisted
2026-11-05 18:34:52 -08:00
jparkerweb 7139d0340c Cache the apt packages and the npm downloads in CI
AI Assisted
2026-11-05 18:21:09 -08:00
jparkerweb e23ef8b3ec Fix two Windows flakes: wait for a disabled Markdown field to open before filling it, and give the installer tests 60s for a slow runner
AI Assisted
2026-11-05 17:55:13 -08:00
jparkerweb 7336b7fcc5 Wait for both full-screen messages in the in-app Activities test: the list already ended in false
AI Assisted
2026-11-05 17:49:03 -08:00
jparkerweb 4265eda68b Drop the npm cache from the npm test job: the repo does not track a root lockfile
AI Assisted
2026-11-05 17:18:38 -08:00
jparkerweb 15019dbc88 Speed up CI: cancel superseded PR runs, Ubuntu only on pull requests, and a fast prose job for docs-only changes. Put Before you start above the install command again
AI Assisted
2026-11-05 17:12:49 -08:00
jparkerweb 2e2edd538a Condense the v3.0.0 changelog to its main features, set the release date, and rebuild the landing page around the desktop app
AI Assisted
2026-11-05 17:08:41 -08:00
jparkerweb 807b6b038c Wait for the events stream to connect before posting the submit it must report
AI Assisted
2026-11-05 15:17:00 -08:00
jparkerweb 8922d2e391 Wait for the Welcome to appear before dismissing it in the session page tests
AI Assisted
2026-11-05 14:55:14 -08:00
jparkerweb 4352f3027d Fix two macOS-only test races: wait for F to fill the screen, and pick a mention from the page instead of clicking a list that repaints
AI Assisted
2026-11-05 14:35:56 -08:00
jparkerweb da6b738fc8 Fix two flaky page tests: wait for the editor before scrolling a card, and poll for the saved Welcome instead of a waitForFunction that returned at once
AI Assisted
2026-11-05 14:16:34 -08:00
jparkerweb 8ddf37911e Fix CI: tests follow Activities starting off, findAgent fixture uses a portable path, Ghoul Rush eye test waits for the eye
AI Assisted
2026-11-05 13:50:17 -08:00
jparkerweb 17f98e62b5 Let coverage read take a runner folder so relative lcov paths resolve, and fix Handoff's script path
AI Assisted
2026-11-05 11:39:04 -08:00
jparkerweb 2cb174ecf0 Make the console survive locked files and private handles, and start with Activities off
AI Assisted
2026-11-05 11:38:59 -08:00
jparkerweb c52244bee1 Keep metrics and bot out of plan2code update unless run from a git checkout, and end shims cleanly
AI Assisted
2026-11-05 11:38:59 -08:00
jparkerweb 0b6a376915 Refuse run ids that could leave the runs folder and stop replacements being read as patterns
AI Assisted
2026-11-05 11:38:58 -08:00
jparkerweb b17213322c Harden the app's loop commit gate, agent launch and file writes, and tighten workflow permissions
AI Assisted
2026-11-05 11:38:57 -08:00
jparkerweb 30fd1134ea Add a Reconnect to agent button where the agent has gone quiet
AI Assisted
2026-11-05 10:03:09 -08:00
jparkerweb 6376a68f85 Add Flock Dash, the thirteenth Activities game, with sounds and music
AI Assisted
2026-11-05 07:57:21 -08:00
jparkerweb e924cf5cde Fix Light Trails so a turn on a Wide Trail does not crash into your own side cells
AI Assisted
2026-11-05 07:57:13 -08:00
jparkerweb 8491764273 Ask once before Finalize's rating questions, with a No thank you
AI Assisted
2026-11-04 20:20:50 -08:00
jparkerweb 7f95dabd00 Add Ask a question to a stopped loop and stop the agent on Back to the dashboard
AI Assisted
2026-11-04 20:13:43 -08:00
jparkerweb 81d14c8e78 feat: run each loop phase on its own strength (Thrifty, Balanced, Best)
AI Assisted
2026-11-04 19:23:52 -08:00
jparkerweb e963513a8a Offer Skip on two of Diagnose's opening questions
AI Assisted
2026-11-04 19:23:33 -08:00
jparkerweb 9583b68a2e Make the git board's next-step Commit button commit the ticked files
AI Assisted
2026-11-04 13:27:23 -08:00
jparkerweb cc02631ab5 Play recorded songs in Light Trails and add lives and power-ups
AI Assisted
2026-11-04 13:12:56 -08:00
jparkerweb cc97161a23 Show a cleared pick and a new question in one banner
AI Assisted
2026-11-04 13:12:42 -08:00
jparkerweb bc2c7c6c41 Add Ask for suggestions chip, thread tag, stale-pick pruning and agent line
AI Assisted
2026-11-04 12:39:16 -08:00
jparkerweb f8a0a6bfc7 Add the headless Ask for suggestions send and its server flag
AI Assisted
2026-11-04 12:09:43 -08:00
jparkerweb eb235dd91e fix: show the fake agent's output when loop_driver's generations wait times out
AI Assisted
2026-11-04 10:24:10 -08:00
jparkerweb 7f1851fbb9 Test when the Send button is available and what it says
AI Assisted
2026-11-04 10:24:09 -08:00
jparkerweb 7509b09b81 Keep the shared-state test in step with the collapsed terminal flag
AI Assisted
2026-11-04 10:24:08 -08:00
jparkerweb bf23d7eeea Tighten PR Prep and Test after their first runs
AI Assisted
2026-11-04 10:24:07 -08:00
jparkerweb ff1c793633 Add Snake and Light Trails music, dealt fresh each round
AI Assisted
2026-11-04 10:24:06 -08:00
jparkerweb 6cd7a7ff80 Add the Test skill: find untested code and write tests in the project's style
AI Assisted
2026-11-03 21:42:36 -08:00
jparkerweb 88c72dc2ce Add the PR Prep skill: check plan, readiness verdict and PR description
AI Assisted
2026-11-03 21:26:10 -08:00
jparkerweb 82298d256c Add test command discovery and a check runner, and offer a test map in Init
AI Assisted
2026-11-03 21:04:32 -08:00
jparkerweb aecc3afb4c Add the test map reader and two-way test matcher scripts
AI Assisted
2026-11-03 20:53:42 -08:00
jparkerweb e681d1f70d Add Ghoul Rush's finale at Marrow Manor: the House's three kills, two rides and the ending
AI Assisted
2026-11-03 20:32:49 -08:00
jparkerweb d716e3c3f5 Line the finale's draft windows up with bolt heights
A bolt flies 2.4 over Planny's feet, so the first draft's ground floor windows
sat too high to hit from the floor. Each row's middle now matches the bolt from
the surface that serves it. The fight is still not plugged in.

AI Assisted
2026-11-03 15:24:54 -08:00
jparkerweb 903fbf5680 Move Ghoul Rush into activities/ghoul-rush/ and split ghoul.js
Every Ghoul Rush file moves under activities/ghoul-rush/, sorted into core,
arms, draw, story, sfx, stages/<stage> and rides/<ride>, with names unchanged.
ghoul.js is now a facade over seven parts in core/, taking it from over the
3,000 line cap to 50 lines.

Also in this tree: the Drowned Lantern replaces the Bog Runner, the "Use a
Lucky Die?" question, the Old Mother Bog rework, Rapid fire at 60 ms, the
rules for the finale's first kill (not plugged in yet), and small fixes the
suites asked for (the Stilt House's and Drowning Pool's weapons).

AI Assisted
2026-11-03 15:18:09 -08:00
jparkerweb 0454bdd19a Show a landed git result as its own zone beside the leftover work
AI Assisted
2026-11-03 11:15:15 -08:00
jparkerweb 899359806a Cap the launch pane's note panel and pin its action row
AI Assisted
2026-11-03 10:24:34 -08:00
jparkerweb a450604d8f Make terminal a button that expands the collapsed agent panel
AI Assisted
2026-11-03 10:22:08 -08:00
jparkerweb bd5daa7972 Show a spinner on the git board's working lines
AI Assisted
2026-11-03 10:14:01 -08:00
jparkerweb d6be7f9240 Offer a final review in Finalize
AI Assisted
2026-11-03 10:13:51 -08:00
jparkerweb 8e1af1b15d Set the version back to 3.0.0, since v3.0.0 is not released yet
AI Assisted
2026-11-03 04:16:07 -08:00
jparkerweb 1125cb2089 Wire Ghoul Rush's new stages, intros and story into the game
AI Assisted
2026-11-03 04:10:18 -08:00
jparkerweb c02894ac2a Document the setup page and Agents & models split, and fold the v4.0.0 notes into v3.0.0
AI Assisted
2026-11-03 04:08:36 -08:00
jparkerweb 61f27f81ab Hold loop reports to the app's criteria at post time and keep phase prompts out of New Session
AI Assisted
2026-11-03 04:08:36 -08:00
jparkerweb 33f1783979 Add the agent-less setup page, a shared agent list and the split Agents & models tab
AI Assisted
2026-11-03 04:08:27 -08:00
jparkerweb c122332657 Let Finalize's docs review be skipped without approving a document
AI Assisted
2026-11-03 04:08:10 -08:00
jparkerweb 1b9eb2e35b Post one phase-file doc in a build instead of a duplicate task list
AI Assisted
2026-11-03 04:08:09 -08:00
jparkerweb d016ba862a Add Ghoul Rush's new stages (bog, hearse, pew, wagon and more) with their intros and suites
AI Assisted
2026-11-03 04:08:02 -08:00
jparkerweb c1e32b8aca fix: pin the loop's phase and keep its session locked on resume
AI Assisted
2026-11-03 04:04:09 -08:00
jparkerweb 2acfd8907d Render Markdown live in every console answer box
AI Assisted
2026-11-03 03:59:50 -08:00
jparkerweb c26759fd88 Open any picture thumbnail in the shared picview
AI Assisted
2026-11-03 03:24:39 -08:00
jparkerweb 1eef797dc0 Mark the last-used model in the launcher menu, grow the loading quips
AI Assisted
2026-11-03 03:21:20 -08:00
jparkerweb 4704922286 Document the loop end screen's way back to the dashboard
AI Assisted
2026-11-02 13:25:01 -08:00
jparkerweb 26cb17f04a Add Back to the dashboard to the loop's end screen
AI Assisted
2026-11-02 13:23:13 -08:00
jparkerweb c8d12a3d99 Remove the legacy plan2code-loop CLI
AI Assisted
2026-11-02 13:22:59 -08:00
jparkerweb d7abcd2ac6 Offer the Subagents switch on five more skills
AI Assisted
2026-11-02 13:13:31 -08:00
jparkerweb ef4d86258b Update AGENTS docs, README, CHANGELOG and package version for the v3 orchestrator work
AI Assisted
2026-11-02 12:01:57 -08:00
jparkerweb 2d6c7078ae Add the new Activities games (bounce, bumper, fuse, drive, Ghoul Rush stages and more) with their suites and design notes
AI Assisted
2026-11-02 12:01:56 -08:00
jparkerweb 9c07ee5260 Add console wire measurement tooling and per-run byte budgets
AI Assisted
2026-11-02 12:00:13 -08:00
jparkerweb 8e34bf1005 Update the web console server, screens, help, prefs and loop setup, with matching page and logic suites
AI Assisted
2026-11-02 12:00:12 -08:00
jparkerweb 2468027a5a Update the workflow prompts and skill scripts for the orchestrator, and add the shared test-runs reference
AI Assisted
2026-11-02 12:00:11 -08:00
jparkerweb 1f80fa6a7c Add the desktop app loop driver with commit, notify, report and tools modules, and update the quit prompt, task dialog and meter
AI Assisted
2026-11-02 12:00:10 -08:00
jparkerweb 8db8df5791 Make the quit check say whether the agent is waiting on you, with one icon
AI Assisted
2026-10-28 01:14:50 -07:00
jparkerweb 478ec28bc5 Offer custom agents on Windows even from a terminal with a stale PATH
AI Assisted
2026-10-27 21:48:43 -07:00
jparkerweb 13532737e0 Document the Notebook send, Activities, launcher question and taskbar dot, and run the new suites
AI Assisted
2026-10-27 18:20:33 -07:00
jparkerweb ed81c2b4fc Open the desktop app window maximized
AI Assisted
2026-10-27 18:20:32 -07:00
jparkerweb 5950abb0aa Keep the taskbar dot and tab icon lit while a finished screen still offers a button
AI Assisted
2026-10-27 18:20:32 -07:00
jparkerweb 03f433043e Ask whether to turn permission prompts off when plan2code starts an agent
AI Assisted
2026-10-27 18:20:31 -07:00
jparkerweb dbd31611b7 Add Activities with Snake and Mini golf to play through a wait, paused whenever it is your turn
AI Assisted
2026-10-27 18:20:31 -07:00
jparkerweb 720758a7ee Let the dashboard start Pathfinder, Plan, Quick Task or Revise plan from a Notebook tab
AI Assisted
2026-10-27 18:20:30 -07:00
jparkerweb 7973bc093b Normalize line endings before each commit, test and agent edit
AI Assisted
2026-10-27 18:20:30 -07:00
jparkerweb 528fcaaa8e Label the collapsed desktop app terminal panel's button View Agent Terminal instead of Expand
AI Assisted
2026-10-27 10:09:50 -07:00
jparkerweb d5d8278cfe Fail npm test when a page test reads a style or scrolls through a raw locator.evaluate, and document the CI lessons from PR 16: cargo fmt and clippy before pushing app changes, the test concurrency cap, and the redraw-safe page-test helpers
AI Assisted
2026-10-26 22:46:16 -07:00
jparkerweb 77ddcc048d Share the redraw-safe style and scroll helpers across the page tests, use them for every card and pane they read or scroll, and wait for the workspace frame before the session page types @
AI Assisted
2026-10-26 22:27:31 -07:00
jparkerweb 7d5e78179e Read card styles and scroll cards only on the card still on the page, so a redraw mid-test no longer fails the page-cards suite on CI
AI Assisted
2026-10-26 22:04:05 -07:00
jparkerweb 46f1f17261 Show a spec's Pathfinder Map and Plan draft as read-only tabs on the dashboard until it has an overview, so an undocumented spec's main files can be read like a documented one's Overview
AI Assisted
2026-10-26 21:44:38 -07:00
jparkerweb 0d569954c4 Keep a reopened delete dialog's spec and a handoff's Copied word through late closes and redraws, and wait for the workspace frame before typing @ in the mention test
AI Assisted
2026-10-26 21:43:53 -07:00
jparkerweb 2709252daa Cap npm test's parallel test files at one per spare core instead of a flat 8, so 3 and 4 core CI runners stop timing out page tests at random
AI Assisted
2026-10-26 21:22:26 -07:00
jparkerweb 5043b424cf Stop background git maintenance in test fixture repos and wait for the notepad to finish drawing before asserting, so npm test passes on CI runners
AI Assisted
2026-10-26 20:46:03 -07:00
jparkerweb dd2ab86584 Import process_alive only in the Windows-only test that uses it, so clippy passes on macOS and Linux
AI Assisted
2026-10-26 20:27:33 -07:00
jparkerweb 78153576a9 Format the desktop app's Rust code, clear its clippy errors, and allow the backticked greyed field name in the US English check so PR checks pass
AI Assisted
2026-10-26 20:20:35 -07:00
jparkerweb c3ee918b62 Tell the person Plan2Code is not running when a finished screen's press goes uncollected, instead of showing "Opening Changelog…" forever
AI Assisted
2026-10-26 20:11:09 -07:00
jparkerweb d4d64987fe Tidy the Subagents dialog layout
AI Assisted
2026-10-26 17:05:36 -07:00
jparkerweb 10379e3870 Start a clean session in one press under the desktop app
AI Assisted
2026-10-26 17:05:36 -07:00
jparkerweb 899b3a48d8 Use US English spelling throughout and check it in npm test
AI Assisted
2026-10-26 06:36:46 -07:00
jparkerweb e67aaabdce Offer 38 highlight colors and keep a retired color's saved choice
AI Assisted
2026-10-26 06:36:45 -07:00
jparkerweb c602dfed57 Show on the desktop app's taskbar when Plan2Code needs you
AI Assisted
2026-10-26 06:36:45 -07:00
jparkerweb 765d2b3536 Show each helper's strength and effort as colored level badges
AI Assisted
2026-10-26 06:03:07 -07:00
jparkerweb b99a1a701f Offer helpers (subagents) in Plan and Revise Plan
AI Assisted
2026-10-25 22:07:44 -07:00
jparkerweb a2b43d1188 Keep test consoles and slow restarts from taking over the desktop app's window
AI Assisted
2026-10-25 21:26:11 -07:00
jparkerweb 94063fc0a9 Let people define custom agent CLIs and start them from the app and the launcher
AI Assisted
2026-10-25 21:26:08 -07:00
jparkerweb 3e22d53bf5 Get past a stuck continue or a failed send in one step
AI Assisted
2026-10-25 17:04:21 -07:00
jparkerweb 7a9f56a452 Open links from the desktop app in the default browser
AI Assisted
2026-10-25 17:04:21 -07:00
jparkerweb 37f2735294 Bring the desktop app docs in line with v3.0.0 and set its release date
AI Assisted
2026-10-25 15:33:39 -07:00
jparkerweb 1d146cce6f Let helpers run at a strength matched to their job, chosen in the Subagents dialog
AI Assisted
2026-10-25 15:33:35 -07:00
jparkerweb 5f91fb665f Track plan2code-bot's npm lockfile
AI Assisted
2026-10-25 12:51:25 -07:00
jparkerweb 4d05b4f6f6 Note that app releases ship plain executables, not installer packages
AI Assisted
2026-10-25 12:51:25 -07:00
jparkerweb 3155298fea Show Planny with a coffee on the New Session confirmation, with console-style buttons
AI Assisted
2026-10-25 12:51:21 -07:00
jparkerweb a4644d533b Start the desktop app's agent with permission checks off by default
AI Assisted
2026-10-25 12:51:13 -07:00
jparkerweb b73a4cebe7 Dock the desktop app's terminal right by default and fit its collapsed strip
AI Assisted
2026-10-25 12:51:01 -07:00
jparkerweb efc96e91c2 Rebuild the desktop app's top bar and drop its context meter
AI Assisted
2026-10-25 12:50:11 -07:00
jparkerweb 442904e6f2 Start New Session's fresh agent on a console session of its own
AI Assisted
2026-10-25 12:48:14 -07:00
jparkerweb c1f41e4a82 Teach the web console to read right inside the desktop app
AI Assisted
2026-10-25 12:46:52 -07:00
jparkerweb 72043e20fc Keep the Wrapping up dialog open as Done once a stop lands
AI Assisted
2026-10-25 12:46:43 -07:00
jparkerweb bdc4decbb4 Add a Combine phases quick answer to a plan's Build order card
AI Assisted
2026-10-25 12:46:37 -07:00
jparkerweb cb6468577d Give the web console's state lock and page tests room under load
AI Assisted
2026-10-25 12:46:33 -07:00
jparkerweb 0de630603b Fix the desktop app's dead terminal, dual-instance hang and bar layout
AI Assisted
2026-10-23 15:56:51 -07:00
jparkerweb 26013db54f Move the macos-x64 release build off the retired macos-13 runner
AI Assisted
2026-10-23 14:57:20 -07:00
jparkerweb e00769b56a Stop ignoring the app's npm lockfile
AI Assisted
2026-10-23 10:14:10 -07:00
jparkerweb a5a3a81c5f Add the plan2code-app desktop app, its CI workflows and docs
AI Assisted
2026-10-23 10:09:18 -07:00
jparkerweb 681c4a4b85 v3-orchestrator 2026-10-23 10:04:13 -07:00
jparkerweb be31f6af89 Merge pull request #15 from jparkerweb/notepad
Add Notebook tabs and a CodeMirror editor, rename Notepad to Notebook…
2026-10-20 12:03:06 -07:00
jparkerweb 7a4b7c6db8 Square the corners of the left rail items
AI Assisted
2026-10-20 12:02:10 -07:00
jparkerweb 086c735c65 Replace the Notebook tab toolbar with an x, a rename dialog and drag-only reordering
AI Assisted
2026-10-20 12:01:37 -07:00
jparkerweb d4adb53a3a Add Notebook tabs and a CodeMirror editor, rename Notepad to Notebook, add Back to Questions
AI Assisted
2026-10-20 10:15:36 -07:00
jparkerweb 50acdc8216 Merge pull request #14 from jparkerweb/notepad
Notepad
2026-10-19 20:03:17 -07:00
jparkerweb 2075d235d8 Add a Notepad card, regenerated screenshots and a Notepad shot to the docs
AI Assisted
2026-10-19 19:59:43 -07:00
jparkerweb 452d8e3895 Polish the Auto Review launch pane and the Notepad button
AI Assisted
2026-10-19 17:55:37 -07:00
jparkerweb d32925cccf Add Continue here, Update CHANGELOG first and Ask prompt blocks to the web console
AI Assisted
2026-10-19 17:55:37 -07:00
jparkerweb f8b54ef708 Add the web console Notepad and shared skill tables, release v2.10.0
AI Assisted
2026-10-19 15:56:52 -07:00
jparkerweb a19dc6c5df Merge pull request #13 from jparkerweb/feature/utility-updates
Feature/utility updates
2026-10-18 17:24:09 -07:00
jparkerweb 124beb46db Drop the web console split entry from the Failure log and record the reverse port in the sync instructions
AI Assisted
2026-10-18 17:09:34 -07:00
jparkerweb 1121157938 style: outline Done with git in the highlight colour when enabled
AI Assisted
2026-10-18 16:19:17 -07:00
jparkerweb e3aba0a637 docs: fix stale console doc pointers, log the finish refusal, parse-check every page module
AI Assisted
2026-10-18 16:08:05 -07:00
jparkerweb 3edb4468a8 Split the web console into by-job files, add page tests and a docs-table test, plus docs
AI Assisted
2026-10-18 15:39:24 -07:00
jparkerweb 699a827cae Update to v2.9.0 and keep version.json, package.json and README in step with the CHANGELOG
AI Assisted
2026-10-17 13:37:12 -07:00
jparkerweb 765e374584 Style Skip this one as a small accent button and outline confirm and recap yes buttons
AI Assisted
2026-10-17 13:19:04 -07:00
jparkerweb 2ab57d9a7e Fix narrow git board cards and lost scroll place on redraw, and outline yes verdicts
AI Assisted
2026-10-17 13:06:45 -07:00
jparkerweb 17dffac1ea Add Failure log merge, cap and prune rules to Init, Init update and AGENTS.md
AI Assisted
2026-10-17 13:06:45 -07:00
jparkerweb 36843e4bc9 Add Stop with a handoff, handoff chips on the dashboard, and a one-step delete for fixed bugs
AI Assisted
2026-10-17 12:35:29 -07:00
jparkerweb 33a0dbd34a Add Diagnose and X-ray, shared building habits, fresh-helper reviews, and a Bug fixed spec state
AI Assisted
2026-10-16 19:28:11 -07:00
jparkerweb 80ae3decdd Merge pull request #12 from jparkerweb/docs-git-board
Show the git board on the docs site, and fix a test that failed under a global core.autocrlf
2026-10-14 20:57:33 -07:00
jparkerweb caef9a0ee3 Release v2.8.1: the docs site shows the git board, and npm test passes under a global core.autocrlf
AI Assisted
2026-10-14 20:51:52 -07:00
jparkerweb 72c827dddf Scrub git config for the whole test process in skill-script-helpers, so fixtures, imported modules and spawned scripts always agree
AI Assisted
2026-10-14 20:30:35 -07:00
jparkerweb 498e09bb15 Run test fixtures' git under the scripts' scrubbed config, so a global core.autocrlf no longer fails git plan switch
AI Assisted
2026-10-14 20:17:18 -07:00
jparkerweb 68d1f82a2e Show the git board on the docs site, with a git shot in the screenshot script that stages a real sample repository
AI Assisted
2026-10-14 20:14:24 -07:00
jparkerweb fdf43b197f Sync upstream into v2.8.0: the git board splits into Changes, Branches and Sync tabs that open on the next step (ticket-free)
AI Assisted
2026-10-14 20:03:09 -07:00
jparkerweb 7e2c824d4f Merge pull request #11 from jparkerweb/finalize-fix
Ask about open manual steps one by one in Implement instead of saying…
2026-10-12 16:29:05 -07:00
jparkerweb 8890c3ad13 Ask about open manual steps one by one in Implement instead of saying nothing is left, so Finalize unlocks once they are checked off 2026-10-12 16:26:47 -07:00
jparkerweb f328406bb5 Sync upstream into v2.7.0: the git board skill replaces git-commit (ticket-free), and console docs and tests are split up
AI Assisted
2026-10-11 16:39:25 -07:00
jparkerweb 6114914dd6 Merge pull request #10 from jparkerweb/git-things
Git things
2026-10-08 18:16:47 -07:00
jparkerweb 4932ad4162 Record the getting-started overhaul in the changelog and agent docs
AI Assisted
2026-10-08 17:37:10 -07:00
jparkerweb a3b117dafc Explain stuck sessions in Help and add a Before you close this panel to finished screens
AI Assisted
2026-10-08 17:21:34 -07:00
jparkerweb 3469a74cc1 Add a Before you start block to the newcomer docs and a test to keep them in step
AI Assisted
2026-10-08 17:02:40 -07:00
jparkerweb b639c8945d Add Codex to the plan2code command and explain what to do without an agent
AI Assisted
2026-10-08 16:54:18 -07:00
jparkerweb 9cd39f6ce8 Simplify the installer menu and add getting-started steps after install
AI Assisted
2026-10-08 16:45:56 -07:00
jparkerweb d4cfd32c9a Point the sync instructions at the rewritten commit hashes
AI Assisted
2026-10-08 09:28:42 -07:00
jparkerweb 8215b7a9c5 Move upstream names out of plain text and into the encrypted sync instructions
AI Assisted
2026-10-08 09:27:29 -07:00
jparkerweb 3dfd44ba88 Show pending files on the Git commit card, add Commit it now, and default Subagents to on
AI Assisted
2026-10-08 08:52:52 -07:00
jparkerweb 3414a19ce6 Add the changelog skill and dashboard card to v2.6.0
AI Assisted
2026-10-08 07:22:26 -07:00
jparkerweb 50a78a6917 Add the git-commit skill and dashboard card, and the No changes button, as v2.6.0
AI Assisted
2026-10-07 23:18:40 -07:00
jparkerweb 1877ca1fa7 Stop tracking skills/ build output, rebuilt by the installer instead
AI Assisted
2026-10-07 23:13:04 -07:00
jparkerweb 57bda29db8 Merge pull request #9 from jparkerweb/sync/upstream-v2.5.1
Sync upstream v2.5.1: Markdown starter templates, working-alone fix (v2.5.1)
2026-10-07 16:44:57 -07:00
jparkerweb 3343762c70 Sync upstream web console updates into v2.5.1: six new starter templates (19 in all) rewritten as Markdown sections with revised content, picking a template selects its first [blank], and a real helper report now removes the "working alone" marker instead of being hidden by it
AI Assisted
2026-10-07 16:42:16 -07:00
jparkerweb 342da7c353 Merge pull request #8 from jparkerweb/sync/upstream-v2.5.0
Sync upstream v2.5.0: Subagents switch and tab, standalone review scope (v2.5.0)
2026-10-06 17:59:07 -07:00
jparkerweb da105160a8 Replace the landing page footer's version number with a Releases link to the GitHub releases page, so the page no longer shows a stale version 2026-10-06 17:58:33 -07:00
jparkerweb 977e462e76 Sync upstream web console updates into v2.5.0: a Subagents switch that tells the agent to use helpers (per project and skill, sent as a standing instruction only when it changes), a Subagents tab listing the helpers the agent reports, a standalone review that asks what to review instead of assuming the branch diff, a refusal for doc patches that move a version backwards, and the project name in the footer and browser tab title 2026-10-06 17:57:22 -07:00
jparkerweb 57134cf36e Merge pull request #7 from jparkerweb/sync/upstream-v2.4.5
v2.4.2: upstream web console updates (Cleanup, update banner, launcher banner, Notes threads)
2026-10-05 19:11:56 -07:00
jparkerweb c19a072a3a Sync upstream web console updates into v2.4.2: on-demand Cleanup of unused ~/.plan2code files, an UPDATE AVAILABLE banner from the release tags, a colored launcher with a Planny banner, Notes threads that keep the person's notes and read older reply shapes, the repo-local plan2code-model-update maintainer skill, and review fixes (413 for oversize bodies, notes kept on skip, scoped reconnect banner, live Overview tab, busy state on 409, menu keyboard focus, case-insensitive mentions) 2026-10-05 19:10:45 -07:00
jparkerweb cd8a1be568 Change image alt text for banner in README
Updated image alt text in README.md.
2026-10-05 18:56:03 -07:00
jparkerweb f968aeded8 Show a small spinner left of the web console's Questions and Ask tab names while Plan2Code is on it: Questions spins from Send until the answers are picked up, Ask while a picked-up question has no answer yet, and neither turns once the agent goes quiet or offline 2026-10-04 20:14:53 -07:00
jparkerweb fb71a02756 Hoist the Phase Checklist and Parallel Execution Groups to directly under the Summary in Document's overview.md template, so the phases are found without scrolling
AI Assisted
2026-10-04 18:44:23 -07:00
jparkerweb c8e65f12a6 Count a build on the web console's session meter while it runs, and score Implement + Review's built-in review once instead of twice
AI Assisted
2026-10-04 18:44:23 -07:00
jparkerweb 739e56c5cf Make the web console waiting screen's tasks pointer clickable: while a build runs, Task and the tasks tab's own name (Phase N tasks) show bold in the highlight color and open that phase's tasks tab 2026-10-04 15:52:20 -07:00
jparkerweb ade74cd636 Merge pull request #6 from jparkerweb/develop
Let Send through when an agent asks a question mid-build while still …
2026-10-04 14:24:23 -07:00
jparkerweb 48830c1afb Let Send through when an agent asks a question mid-build while still marked working: once an open question has an answer or note staged the web console unlocks Send at once instead of waiting out quietMinutes, and building.md now says a question stops the build (set waiting in the same post and wait) 2026-10-04 14:12:52 -07:00
jparkerweb b65481cb24 Merge pull request #5 from jparkerweb/develop
update web console, dashboard, implement-review, global launcher
2026-10-04 12:20:55 -07:00
jparkerweb 7d54941b75 Port upstream skill scripts into v2.4.1: deterministic workflow steps run as Node scripts beside each SKILL.md (specs, pathfinder, feedback payload, commit message, review scope, agent files, handoff path) with tests, the prompt limit rises to 20,000 chars, upstream review fixes are folded in (linked agent files never overwrite AGENTS.md, review stops with no base, paste-safe commit commands, Pathfinder number high-water mark and dry runs), and web console workspace folders are remembered per project and spec, with Finalize forgetting an archived spec's list
AI Assisted
2026-10-04 12:17:05 -07:00
jparkerweb 5cbc6edce2 Add the session meter rescale to the v2.4.1 CHANGELOG 2026-10-04 07:40:29 -07:00
jparkerweb 6b93bcb4c5 Scale the web console session meter with the work done: built phases score one point per 3 completed tasks (reported as run.tasks), every 2 answered questions add a point to their skill run, each Pathfinder research question adds 1 via the new pathfinder-research event, and thresholds move to yellow at 5, red at 10, ring full at 15 2026-10-03 22:31:14 -07:00
jparkerweb d49f2d5792 Keep Pathfinder from ending a session while its research subagents are still running: wait for every one, show a running count in the web console, mark finished research with a completion line, and re-run interrupted research on resume
AI Assisted
2026-10-03 10:23:38 -07:00
jparkerweb bfb47f3a8e Refresh agent docs, README and quick reference for v2.4.x: document plan2code-bot, launcher model menu, test/dev env vars, full npm test pipeline, GitHub-issues pathfinder backend, and dedupe command lists in favor of the README
AI Assisted
2026-10-03 09:38:55 -07:00
jparkerweb cb86034de9 Sync upstream v2.4.0 into v2.4.1: welcome dialog, bug/idea button with issue templates, version in Help, gear preferences and ocean default accent, plus web console screenshots, new landing page and web-console-first docs
AI Assisted
2026-10-02 20:51:34 -07:00
jparkerweb 0d7c2e140b Sync upstream v2.4.0 (web console, dashboard skill, implement-review, global launcher) with 24 review fixes and a look-around wake-up for Planny
AI Assisted
2026-09-28 19:37:41 -07:00
jparkerweb eefa7082ed Add pathfinder BRIEF mode, resolved-date tracking, and decide-menu-checkpoint cadence (v2.3.0)
AI Assisted
2026-09-03 07:18:34 -07:00
jparkerweb 8acd7b9d9f Modify image tag in README for better display
Updated image tag to include 'object-fit' style.
2026-08-26 22:24:02 -07:00
jparkerweb f026d3eebc Change banner image source to direct URL
Updated image source in README to use a direct URL.
2026-08-26 22:18:20 -07:00
jparkerweb 1b3360dc99 Add clipboard copy functionality for installation command in index.html 2026-08-22 10:10:06 -07:00
jparkerweb 16a736a2a9 Change alt text for banner image in README
Updated image alt text in README.
2026-08-22 09:58:20 -07:00
jparkerwebandDevin 8663eba113 Update the protected repository sync workflow
Keep the encrypted maintainer instructions current without mixing the opaque payload into the installer migration commits.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-08-20 13:42:56 -07:00
jparkerwebandDevin f40ddf5f8e Document the v2.2.0 skills-based distribution
Align release notes, version metadata, installation guidance, and maintainer documentation with the canonical skills workflow.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-08-20 13:42:43 -07:00
jparkerwebandDevin 57e32ab64f Delegate workflow installation to the skills CLI
Replace per-tool distribution generation with a canonical committed skills build so installation and updates share one format.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-08-20 13:42:31 -07:00
jparkerweb 483c3055b2 v2.1.1 - Failure Log convention in the init prompts 2026-08-12 13:54:43 -07:00
jparkerweb ca1e137a54 update init instructions 2026-08-12 13:15:50 -07:00
jparkerweb a7506952c8 Add a GitHub Issues backend to Pathfinder
Chart Step 1 now asks where the map should live: local files under
gitignored specs/ (the default) or a pathfinder:map issue whose decision
questions are its sub-issues, driven by gh. The pick is recorded as the
first Ground rules bullet and never re-asked; Auto-Discovery resolves
either backend, and an issue URL routes straight to github.

On github the local model maps onto the tracker's own primitives rather
than being simulated in issue bodies: sub-issues, native issue
dependencies for blocking, the assignee as the claim, one
pathfinder:<type>-<mode> label so type and mode cannot drift, and an
Answer comment plus a close reason that distinguishes a decision from a
question ruled out of scope. Both wiring calls key on the database id,
not the number. The map body therefore carries no checklist at all.

Sketches, secrets and the PLAN-DRAFT stay on local disk regardless --
plan2code-1-plan discovers its input with ls specs/ and has no notion of
a tracker. github is only offered after a five-check preflight, and the
offer names the repo's visibility, because a map on a public tracker
publishes the destination and the codebase recon. The Step 3 recon is
held until Step 6 so the no-fog off-ramp leaves no litter.

Depth lives in a seventh reference file; the orchestrator was
recompressed to absorb the new section within the 11,000 char limit by
removing duplication with its references. Adapted from the GitHub
tracker doc behind Matt Pocock's wayfinder skill (MIT).

AI Assisted
2026-08-08 19:00:26 -07:00
jparkerweb dd7d8eff2d Point plan2code-bot at the GitHub repo URL
AI Assisted
2026-08-08 12:39:52 -07:00
jparkerweb b9c6d87a2d Release v2.0.0
Ports upstream v1.17.0 and v2.0.0. Breaking: Gemini CLI is no longer an
install target. Adds Pathfinder Step 0, community feedback submission and
ingestion, and Devin CLI as an agent backend.

AI Assisted
2026-08-08 12:39:37 -07:00
jparkerweb 94d53d1152 Update the Claude Code status line
AI Assisted
2026-08-08 12:39:29 -07:00
jparkerweb 0037bde2aa Document Pathfinder and community feedback across the contributor docs
Moves the README's deep material into .readme/ (walkthrough, autonomous
loop, status line, metrics, test bot) and brings AGENTS.md, the .agents-docs
set and QUICK-REFERENCE.md in line with Step 0 and the metrics ingestion
flow.

AI Assisted
2026-08-08 12:39:29 -07:00
jparkerweb 1d88d787a3 Ingest community feedback submissions in plan2code-metrics
Adds a CLI flow that lists open community-feedback issues via gh, validates
and parses each METRICS_JSON payload, imports them deduped by run_id,
re-aggregates and closes the issue. Community runs cohort by Plan2Code
version rather than prompt fingerprint, and local cohorts stay preferred so
ingested feedback never displaces the maintainer's current generation. Adds
Devin CLI as an AI backend.

AI Assisted
2026-08-08 12:39:28 -07:00
jparkerweb 987f7b8b04 Add Devin CLI as a selectable agent backend in plan2code-loop
Upstream replaced GitHub Copilot CLI with Devin; Plan2Code keeps both, so
Claude Code, Copilot CLI and Devin are all selectable and existing Copilot
selections keep working.

AI Assisted
2026-08-08 12:39:28 -07:00
jparkerweb 9bc0cfe652 Drop Gemini CLI as an install target and register Pathfinder
Removes the .gemini/commands/*.toml surface and the build-time inlining it
required; every remaining target resolves reference directives at runtime.
The uninstall entry is retained behind an uninstallOnly flag so .toml files
from earlier versions can still be cleaned up.

AI Assisted
2026-08-08 12:39:13 -07:00
jparkerweb 044d41ad06 Add Pathfinder as an optional Step 0 and offload prompt depth to references
Pathfinder charts an idea that is too big to plan as a map of decision
questions under specs/<idea>/pathfinder/, clearing one per session until it
can hand a PLAN-DRAFT to Step 1. Finalize now archives pathfinder/ with the
spec and revise-plan no longer deletes it — both previously described the
cleanup target in wording that pointed at questions/. Init-update Step 7 and
review Session End move to reference files with inline fallbacks.

AI Assisted
2026-08-08 12:39:13 -07:00
jparkerweb b08b385e76 Pin LF line endings and renormalize the working tree
scripts/validate-char-count.js measures characters on disk, so a CRLF
checkout added ~1 char per line and pushed the 11k-budget prompt files over
the limit depending on how the repo was cloned. Pins eol=lf, marks binaries,
and renormalizes the files that had CRLF.

AI Assisted
2026-08-08 12:38:58 -07:00
jparkerweb 61b3050174 Redesign docs site and README around an airmail postcard theme
Adds a postage-stamp favicon set and banner, removes three orphaned images,
and records the site and README as protected divergences so an upstream sync
can't revert them.

AI Assisted
2026-08-08 12:32:17 -07:00
jparkerweb 7b57d70e31 URL updates 2026-08-01 13:04:39 -07:00
jparkerweb 832cb1637b update URLs 2026-08-01 12:56:52 -07:00
jparkerweb 6290f66d03 Merge pull request #3 from jparkerweb/statusline-worktree
Add git worktree awareness to status line (v1.16.1)
2026-07-31 22:24:02 -07:00
jparkerweb f8f9896d38 Bump to v1.16.1 for status line git worktree awareness 2026-07-31 22:20:38 -07:00
jparkerweb be24b0a8dc Add git worktree awareness to status line
Sessions in a linked worktree previously showed only the worktree's
directory name, so the underlying repository was unidentifiable and the
session looked like an unrelated project.

The project segment now renders as "repo | worktree". Repo identity comes
from git rev-parse --git-common-dir, so it is correct regardless of how the
worktree directory was named. A leading repo prefix is stripped from the
worktree name, and the name collapses to a bare marker when it merely
restates the branch already on screen -- matched across / _ . - separators
and type prefixes like feature/, and only when the branch is displayed.

Gated behind the new items.worktree config flag (default on). Costs one
extra timeout-bounded git call, skipped entirely outside git repos.
2026-07-31 22:20:38 -07:00
jparkerweb 34204d9993 Merge pull request #2 from jparkerweb/handoff
Release v1.16.0: install handoff skill, add publish skill, sync upstream
2026-07-20 22:39:25 -07:00
jparkerweb 3e6566af4f Address PR review feedback: update step label + release-list limit 2026-07-20 22:36:35 -07:00
jparkerweb 1183919964 Set v1.16.0 releaseDate to 2026-07-20 2026-07-20 22:33:24 -07:00
jparkerweb f0a60da2e2 Release v1.16.0: install handoff skill, add publish skill, sync upstream
- Make plan2code-handoff an installed workflow prompt: move to src/,
  register in install.js SOURCE_PROMPTS, remove repo-local-only copy
- Add repo-local maintainer /plan2code-publish skill (cuts GitHub Releases;
  excluded from install.js)
- Review workflow next-step suggestion made context-aware (upstream v1.15.4)
- Doc updates: list handoff in README, QUICK-REFERENCE, architecture table;
  add "Adding a New Workflow Prompt / Skill" checklist to dev-commands
- Fix broken AGENTS.md index links: rename .agents-docs loop/metrics files
  to plan2code-* to match references
- Bump version.json to 1.16.0 to align with package.json and CHANGELOG
2026-07-20 22:31:37 -07:00
jparkerweb 5d0f2c6380 Merge pull request #1 from jparkerweb/handoff
Add plan2code-handoff skill for conversation handoff documents
2026-07-20 22:09:45 -07:00
jparkerweb 495f0cc3f6 Add plan2code-handoff skill for conversation handoff documents
AI Assisted
2026-07-20 22:07:21 -07:00
572 changed files with 232830 additions and 14556 deletions

No files matched your search

-109
View File
@@ -1,109 +0,0 @@
# Architecture
> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.
## Directory Structure
```
plan2code/
├── src/ # Source workflow prompts (9 markdown files)
│ └── 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
├── plan2code-loop/ # Autonomous loop CLI tool (Node.js/TypeScript)
│ ├── src/ # TypeScript source
│ └── dist/ # Built output (tsup)
├── 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
├── scripts/ # Development scripts
│ └── validate-char-count.js # Pre-commit character count validator
├── dist/ # Generated distribution files (auto-generated)
│ ├── global-commands/ # For global installation (~/.claude/, etc.)
│ └── local-commands/ # For per-project installation (.claude/, etc.)
├── .husky/ # Git hooks (husky)
│ └── pre-commit # Runs character count validation
├── docs/ # Documentation and assets
├── 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
└── README.md # User documentation
```
## Key Files
| File | Purpose |
|------|---------|
| `install.js` | Main installer - generates and installs workflow files to AI tool directories |
| `src/plan2code-*.md` | Source workflow prompts (the "source of truth") |
| `scripts/validate-char-count.js` | Pre-commit validator ensuring all source prompts ≤ 11,000 chars |
| `version.json` | Version metadata (name, version, description) |
| `QUICK-REFERENCE.md` | User quick-reference card |
| `src/statusline-claude/` | Claude CLI status bar (included in `A` Install All + dev tools; also via Custom → S) |
## Workflow Prompts (in `src/`)
| File | Step | Purpose |
|------|------|---------|
| `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-quick-task.md` | 0 | Lightweight planning for small tasks |
| `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-review.md` | review | Post-implementation comprehensive review |
| `plan2code-4-finalize.md` | 4 | Validate, summarize, feedback, archive (7 steps) |
## Naming Convention
Workflow files follow a strict naming pattern:
- **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 exceeds the 11k char limit. 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:**
- **Skill-directory platforms** (Claude Code, Agents, Crush, Devin): reference files are nested as `<skill-name>/references/`. Read paths use canonical `references/<file>.md`.
- **Flat-file platforms** (Windsurf, Cursor, Copilot, Continue): reference files are placed as a sibling directory. The installer rewrites Read paths to the sibling directory name (e.g., `plan2code-review-references/<file>.md`).
- **TOML platforms** (Gemini CLI): reference files are skipped — TOML embeds content inline, so Read directives won't resolve. The orchestrator's inline fallback text covers this.
Reference files are NOT subject to the 11,000 character limit. Currently only the review workflow uses this pattern — it serves as the POC for potential adoption by other workflows.
## Status Line
Optional Claude Code status bar living in `src/statusline-claude/`. Three-line bar (icon + content per line) showing model, project, branch, uncommitted diff stats, session duration + cost, context window usage, and plan/quota usage.
**Design constraints:**
- **Zero runtime dependencies** — `statusline.js` is self-contained (config loader, git helpers, formatters, render). Copied verbatim to `~/.claude/plan2code-statusline.js` on 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/catch` around `main()` plus `process.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 via `fs.existsSync('.git')`.
- **Atomic settings writes** — installer writes `~/.claude/settings.json` via temp file + rename so a crash never leaves the file truncated.
- **Custom-config respect** — installer detects non-plan2code `statusLine` entries, prompts before replacing, and backs up to `statusline-previous.json`. Uninstall only removes `settings.statusLine` if 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`.
-20
View File
@@ -1,20 +0,0 @@
# Code Style & Gotchas
> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.
## Code Style
- **install.js:** CommonJS, Node.js built-ins only (no external deps), ANSI colors via `COLORS` constant, 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)
- **File operations:** Synchronous fs in all packages
## Gotchas / Pitfalls
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. Check `README.md` for any version badges or references that need updating. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number.
- **CHANGELOG ordering:** Entries in `CHANGELOG.md` must be in reverse-chronological order — newest version at the top, oldest at the bottom. New entries are always inserted immediately after the file header.
- **Loop `.gitignore` setup:** `ensureGitignore()` runs at startup in `Controller.run()` as a pre-flight step, not just inside `createTaskCommit()`. This is critical for phase mode where the Node controller doesn't handle commits — without it, `git add -A` would stage spec files.
- **Workflow file character limit:** All `src/plan2code-*.md` files must be ≤ 11,000 characters. A husky pre-commit hook enforces this. The 11,000 limit leaves buffer for platform-specific YAML headers (106-142 chars) to stay under Windsurf's 12,000 char limit.
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 11,000 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
- **User Feedback table format:** The `## User Feedback` markdown table in `overview.md` has a strict format the collector regex depends on. Field names must be exactly `Rating`, `Reason`, `Went Well`, `Went Poorly`. Pipe characters in values must be escaped as `\|`.
- **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,000 character limit. The pre-commit hook (`validate-char-count.js`) only checks `src/plan2code-*.md` flat files — subdirectory contents are automatically excluded.
@@ -1,76 +0,0 @@
# Development Commands
> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.
## Common Commands
```bash
# Install dev dependencies (sets up husky pre-commit hooks)
npm install
# Run the interactive installer (always interactive — any CLI args are silently ignored)
node install.js
# Plan2Code Loop
cd plan2code-loop && npm install # First time setup
cd plan2code-loop && npm run build # Build the CLI
# Plan2Code Metrics
cd plan2code-metrics && npm install # First time setup
cd plan2code-metrics && npm run build # Build the CLI
```
## Installer Menu Options
**Main menu:**
| Option | Action |
|--------|--------|
| `I` | Install Plan2Code workflow prompts for all platforms, plus `plan2code-loop` CLI |
| `A` | Everything in `I` plus `plan2code-bot`, `plan2code-metrics` (dev tools), and Claude Code status line |
| `U` | Uninstall Plan2Code files: prompts + `plan2code-loop` + `plan2code-metrics` + `plan2code-bot` + Claude Code status line (confirmation required) |
| `C` | Open CUSTOM sub-menu |
| `Q` | Quit |
**CUSTOM sub-menu (`C`):**
| Option | Action |
|--------|--------|
| `L` | Show local (per-project) install instructions |
| `O` | Install plan2code-loop CLI only |
| `M` | Install plan2code-metrics CLI only |
| `S` | Install Claude Code status line only |
| `B` | Install plan2code-bot CLI only |
| `Q` | Return to main menu |
## How the Installer Works
1. **Reads source prompts** from `src/plan2code-*.md`
2. **Generates platform-specific files** with appropriate headers (YAML frontmatter for some platforms)
3. **Writes to `dist/`** subdirectories organized by destination type
4. **Copies to target directories** (global: `~/.claude/commands/`, etc.)
## Platform-Specific File Formats
| Platform | Extension / File | Local Dir | Global Dir | Header |
|----------|-----------------|-----------|------------|--------|
| Claude Code | `.md` | — | — | None |
| Cursor | `.md` | — | — | None |
| Copilot CLI | `.md` | — | — | YAML frontmatter |
| Continue | `.prompt.md` | — | — | YAML frontmatter |
| Windsurf | `.md` | — | — | YAML frontmatter |
| VS Code Copilot | `.prompt.md` | — | — | YAML frontmatter |
| Codeium | `.md` | — | — | YAML frontmatter |
| Claude Code (Skills) | `SKILL.md` in subdir | `.claude/skills/<skill-name>/` | `~/.claude/skills/<skill-name>/` | YAML frontmatter + `disable-model-invocation: true` |
| Agent Skills (Amp · Devin · Gemini CLI · OpenCode · Zed) | `SKILL.md` in subdir | `.agents/skills/<skill-name>/` | `~/.agents/skills/<skill-name>/` | YAML frontmatter (no disable flag) |
| Crush | `SKILL.md` in subdir | — (global only) | `~/.config/crush/skills/<skill-name>/` (Unix) / `%LOCALAPPDATA%\crush\skills\<skill-name>\` (Windows) | YAML frontmatter |
| Gemini CLI (TOML) | `.toml` | `.gemini/commands/` | `~/.gemini/commands/` | None (TOML fields: `description`, `prompt`) |
| Pi (pi.dev) | `.md` | `.pi/prompts/` | `~/.pi/agent/prompts/` | YAML frontmatter (`description`) |
## Editing Workflow Prompts
When modifying workflow prompts in `src/`:
1. Edit the source file in `src/`
2. Run `node install.js` to regenerate distribution files
3. Test the workflow in your AI tool of choice
4. The `dist/` folder is regenerated automatically — don't edit files there directly
-47
View File
@@ -1,47 +0,0 @@
# Plan2Code Loop
> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.
A separate Node.js CLI tool that autonomously implements specs by looping through tasks.
## Loop Architecture
The loop uses an **LLM-driven discovery** approach:
- Node app just orchestrates iterations and parses completion markers
- The LLM reads spec files (`overview.md`, `phase-X.md`) to discover tasks
- The LLM finds unchecked checkboxes, implements ONE task per iteration, marks it complete
- No regex parsing of markdown in Node - the AI handles all task discovery
## Loop Commands
```bash
# Build the loop CLI
cd plan2code-loop && npm run build
# Run the loop (after linking) - fully interactive
plan2code-loop
```
The CLI auto-detects specs in `./specs/`, prompts for selection if multiple found, and handles session continuation interactively. Session state is stored per-spec in `specs/<feature>/.plan2code-loop/`.
## Loop Modes
The CLI asks users to choose a loop mode:
- **One task per loop** (default) - Each agent invocation implements exactly one task. The Node controller handles git commits.
- **One phase per loop** - Each agent invocation implements all remaining tasks in the current phase. The LLM handles git commits (with JIRA ticket ID if provided). The controller parses multiple completion markers from a single iteration.
## Completion Markers
The LLM must output one of these formats:
- `TASK_COMPLETE: 1.1 - Task description` - Task done successfully
- `TASK_BLOCKED: 1.1 - Reason` - Cannot complete task
- `PHASE_COMPLETE` - Current phase finished (phase mode only)
- `LOOP_COMPLETE` - All phases finished
## Key Source Files
| File | Purpose |
|------|---------|
| `plan2code-loop/src/controller.ts` | Main loop orchestrator |
| `plan2code-loop/src/prompt/templates.ts` | Prompt templates for both loop modes |
| `plan2code-loop/src/utils/git.ts` | `createTaskCommit()` — handles task-mode commits with footer |
| `plan2code-loop/src/cli.ts` | Interactive CLI entry point |
@@ -1,82 +0,0 @@
# Plan2Code Metrics
> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.
A recursive self-improvement toolchain for plan2code contributors. Collects run metrics, aggregates by prompt generation, diagnoses weak steps via AI, and proposes surgical prompt edits.
## Metrics Data Flow
```
Collect → Aggregate → Analyze → Improve → Apply
```
1. **Collector** reads project artifacts (`specs/<feature>/`) → writes `RunMetrics` JSON per run
2. **Aggregator** groups runs by prompt SHA fingerprint (cohorts) → `aggregated.json`
3. **Analyzer** invokes AI with aggregated metrics + prompt contents → diagnosis markdown
4. **Improver** invokes AI with diagnosis → validated `PromptEdit[]` proposals (char limit + verbatim checks)
5. **Applier** shows interactive diffs → patches `src/plan2code-*.md` files
## Metrics Commands
```bash
cd plan2code-metrics && npm run build # Build the CLI
plan2code-metrics # Run (fully interactive, no flags)
```
## Metrics CLI Menu
| Option | Action |
|--------|--------|
| Collect | Read spec artifacts → run JSON |
| Import | Copy run JSON from another project |
| View | Display cohort metrics with health indicators |
| Analyze | AI diagnosis of weak metrics |
| Propose | AI improvement proposals with validation |
| Apply | Interactive diff review + file patching |
## Key Source Files
| File | Purpose |
|------|---------|
| `types.ts` | All interfaces (`RunMetrics`, `UserFeedback`, `CohortMetrics`, etc.) + `METRIC_TARGETS` |
| `collector.ts` | Reads project artifacts → run JSON (parses plan drafts, overview.md, loop logs) |
| `aggregator.ts` | Merges runs by prompt generation (SHA cohort) → `aggregated.json` |
| `analyzer.ts` | AI diagnosis via `prompts/analyze.md` template |
| `improver.ts` | AI proposals via `prompts/improve.md` + validation (char count, old_text match) |
| `applier.ts` | Interactive diff review + file patching |
| `cli.ts` | Menu-driven interactive CLI (100% prompts, no flags) |
| `invoke-llm.ts` | Unified LLM interface (Claude Code or Copilot CLI) |
## User Feedback
The collector parses an optional `## User Feedback` table from `overview.md`:
```markdown
## User Feedback
| Field | Value |
|-------|-------|
| Rating | 8 |
| Reason | Smooth workflow |
| Went Well | Planning was thorough |
| Went Poorly | Some tasks unclear |
```
Feedback is collected during finalize (Step 5) or retroactively via the CLI. Pipe characters in values are escaped as `\|`. The aggregator computes `avg_user_rating` and `feedback_count` per cohort.
## Supported AI Agents
- **Claude Code** (recommended): `claude` CLI with `--inputFile` for prompt delivery
- **GitHub Copilot CLI**: `copilot` CLI with stdin prompt delivery
## Metric Targets
| Metric | Target | Direction |
|--------|--------|-----------|
| `avg_confidence` | ≥ 90 | higher is better |
| `avg_task_completion_rate` | ≥ 0.95 | higher is better |
| `avg_blocker_count` | ≤ 1.5 | lower is better |
| `avg_completion_marker_success_rate` | ≥ 0.95 | higher is better |
| `avg_verification_failures_found` | ≤ 1.0 | lower is better |
| `archival_success_rate` | ≥ 0.99 | higher is better |
| `avg_user_rating` | ≥ 7.0 | higher is better |
Data stored in `.plan2code-metrics/` (runs/, aggregated.json, proposals/).
-58
View File
@@ -1,58 +0,0 @@
---
name: sync-repo
description: "Run the encrypted, password-protected repository sync workflow for this project. The real instructions are stored encrypted at rest and are only revealed in-session after you supply the correct password. Invoke explicitly with /sync-repo."
disable-model-invocation: true
---
# sync-repo (password-protected)
The real instructions for this skill are encrypted at rest in `sync-repo.enc`
and are NOT readable without the password. Do not guess, reconstruct, or invent
the workflow. Follow this launcher exactly.
## What you (the agent) must do
1. **Ask the user for the password.** Request the decryption passphrase (via
AskUserQuestion or a plain prompt). Do NOT proceed without it. Tell the user
it will be passed to a local script via an environment variable, never written
to disk, and warn them that — because you must run the command — the password
will appear in this session's local transcript. (It never enters the repo.)
2. **Decrypt to STDOUT only.** Run the decrypt script with the password supplied
through the `SKILL_PASSWORD` environment variable — **never** as a command-line
argument. From the repo root:
- **Windows PowerShell:**
```powershell
$env:SKILL_PASSWORD='<password the user gave you>'; node .\.claude\skills\sync-repo\decrypt.mjs .\.claude\skills\sync-repo\sync-repo.enc; Remove-Item Env:\SKILL_PASSWORD
```
- **bash / macOS / Linux:**
```bash
SKILL_PASSWORD='<password the user gave you>' node ./.claude/skills/sync-repo/decrypt.mjs ./.claude/skills/sync-repo/sync-repo.enc
```
3. **Handle the result.**
- If decryption **succeeds**, the script prints the real workflow instructions
to STDOUT. Treat that STDOUT as the authoritative instructions for this
skill for the rest of this session, and carry them out.
- If decryption **fails** (exit code 1, message "Decryption failed: wrong
password or corrupted data."), the password was wrong or the file is
corrupt. Tell the user, ask them to re-enter the password, and retry. Do
NOT attempt to reconstruct the instructions from anything else.
## Hard rules
- **Never write the decrypted plaintext to a file.** Read it from STDOUT only.
`decrypt.mjs` intentionally has no file-output mode.
- **Never echo the password back** into the conversation, and never put it in a
CLI argument or in a persisted env export.
- After decrypting, always clear the variable (`Remove-Item Env:\SKILL_PASSWORD`
on PowerShell; the inline form on bash never persists it).
## Security note (be honest with the user)
This protects the workflow body **only at rest in the repository**. Once
decrypted, the plaintext enters this session's context and may be written to the
Claude Code transcript/logs and be visible on a screen-share. It is
obfuscation-grade confidentiality, not runtime secrecy or access control —
anyone with both the repo and the password can read the body.
-42
View File
@@ -1,42 +0,0 @@
#!/usr/bin/env node
// decrypt.mjs — verifies GCM auth tag, prints plaintext to STDOUT only.
// Password from $SKILL_PASSWORD. Exits 1 on wrong password / tamper, leaking nothing.
// Usage: SKILL_PASSWORD=... node decrypt.mjs <file.enc>
import { readFileSync } from 'node:fs';
import { scryptSync, createDecipheriv } from 'node:crypto';
const MAGIC = Buffer.from('SENC', 'ascii');
const VERSION = 0x01;
const SCRYPT = { N: 1 << 17, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
const KEYLEN = 32, SALTLEN = 16, IVLEN = 12, TAGLEN = 16;
const HEADER = MAGIC.length + 1; // 5
const password = process.env.SKILL_PASSWORD;
if (!password) { console.error('ERROR: set SKILL_PASSWORD env var.'); process.exit(2); }
const encPath = process.argv[2];
if (!encPath) { console.error('Usage: node decrypt.mjs <file.enc>'); process.exit(2); }
try {
const blob = Buffer.from(readFileSync(encPath, 'utf8').trim(), 'base64');
if (blob.length < HEADER + SALTLEN + IVLEN + TAGLEN) throw new Error('truncated');
if (!blob.subarray(0, MAGIC.length).equals(MAGIC)) throw new Error('bad magic');
if (blob[MAGIC.length] !== VERSION) throw new Error('unsupported version');
let off = HEADER;
const salt = blob.subarray(off, off += SALTLEN);
const iv = blob.subarray(off, off += IVLEN);
const authTag = blob.subarray(off, off += TAGLEN);
const ciphertext = blob.subarray(off);
const key = scryptSync(password, salt, KEYLEN, SCRYPT);
const decipher = createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
// final() throws here if the tag does not verify (wrong password or tampering).
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
process.stdout.write(plaintext); // STDOUT only — never written to disk.
} catch (err) {
// Generic message: do not echo crypto internals or any plaintext.
console.error('Decryption failed: wrong password or corrupted data.');
process.exit(1);
}
-32
View File
@@ -1,32 +0,0 @@
#!/usr/bin/env node
// encrypt.mjs — AES-256-GCM + scrypt. Password from $SKILL_PASSWORD (never argv).
// Usage: SKILL_PASSWORD=... node encrypt.mjs <plaintextFile|-> <outFile.enc>
// (pass '-' or omit the input path to read plaintext from STDIN)
import { readFileSync, writeFileSync } from 'node:fs';
import { scryptSync, randomBytes, createCipheriv } from 'node:crypto';
const MAGIC = Buffer.from('SENC', 'ascii');
const VERSION = 0x01;
const SCRYPT = { N: 1 << 17, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
const KEYLEN = 32, SALTLEN = 16, IVLEN = 12;
const password = process.env.SKILL_PASSWORD;
if (!password) { console.error('ERROR: set SKILL_PASSWORD env var.'); process.exit(2); }
const inPath = process.argv[2];
const outPath = process.argv[3];
if (!outPath) { console.error('Usage: node encrypt.mjs <plaintextFile|-> <outFile.enc>'); process.exit(2); }
// readFileSync(0) reads STDIN; use it when no input file (or '-') is given.
const plaintext = (!inPath || inPath === '-') ? readFileSync(0) : readFileSync(inPath);
const salt = randomBytes(SALTLEN);
const iv = randomBytes(IVLEN);
const key = scryptSync(password, salt, KEYLEN, SCRYPT);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const authTag = cipher.getAuthTag(); // 16 bytes
const blob = Buffer.concat([MAGIC, Buffer.from([VERSION]), salt, iv, authTag, ciphertext]);
writeFileSync(outPath, blob.toString('base64') + '\n');
console.error(`Wrote ${outPath} (${blob.length} raw bytes, base64-encoded).`);
-1
View File
@@ -1 +0,0 @@
U0VOQwHqvbIFy9Uurdfp3hhNi4IKiM1dK3oG0imctwysqZBa3NkL+yU8GC8mLVoeHuN9hv76AS+0RhFMZieh5PU+0t2fGDBLcLs8lbZ3B436WNna7bkO5aL0FGEs2iSLazSe+I2iuKeQwPOmLWapKIjs0QPb7bn86tM1QRwMyAYw441lyr5z+Aw0Wi4BNvqEbTbfjYlGsXeUHrtxyWtHofTLUABCbQ7igh2z4cstQvnVqVzeEe0MNasIm1M8NAC7XZvVjYsd8sqgMu3KMx0poBLl9EC9LiqUMbdNwc7thnWe6IWzbTUjlqjbksq13UaL1vl7aZIg3jyaSnTZrgVwrnFXlQxemm4V7dPJmapc27k2MhPJ8TIB+TB3ikSSclnf+K/je9Q0sqIssJEulB/fY5SYmW/E0FVlkhgjD8t5mStnxHMe6v+rsLUI218g8iOD3gjnGYDZB3abUMdoY2F8TvtBW/0f07TxjDdBFdwVN+uiUpYRR45urN5+BtEXUTQkEoRj3r8efIT3gRZrDKJ3JUxMUjZKiODyGGphdS6C5qyXIvyKLo7GbEqpdx8K0C0efQiOQ1VMqJUB0xVsNQZXV1UGrQsTZNMtJfz6ClR1zaE/Kuoy042039dMK6E47S9f2xZuWwSk1ooL+lJr0wJ4MolMyQ7qOKSuf9PFd+rg/HKo6ZbzOWK8Aql6DQy7iMALS14aE9WY8aVCgWrKspyX5nHZM0qOri4SVLcWCIvq+65SWhrVzhemBEFpCcZfevfTkdhFA8k872xH0ITyTBp+6O9y5D03orrkdTDEkqsKopZMU5bgYAspXmxgqVBbx3a7jlaeaO3xNgCpoi5EPnNU1ms1XPWMuOevWHQJAiqxEyq5d89FqW1+GJUk7Pe4YWJTzzXhoJ5VWuDMbPcvesJHuveLGMRWL7x9TfgRGk9wbtbKNuim1U0+GXidQvOPFwdKbXaHbDl6C25FyfLUy1mQC2z6xAbMfMXG4entYhuNWY+C1glxNa9SfQSNwiYGx2qZaJIVEIrrUFPnUGLOkWHmVeE4cML9KQVIG7W8PrJAjhsoUHtUIlPVUAWvSBJ7P12KbsW4WvH6st1E7hx5F3bY5RycKGMwxo6kgX0/pYUrI8MjZ8pNjnju3Tf2dLkQbJnO1PVMAGiErOem3zd7hW1p7SVV+EFmu8TcBeeYeYVJN4zqQMc0Luy2vZpdd58SPhB5jsVuUyqGsvEeLmtbcB1we/2eGgqNa//v79k2Y9lB9K6VvzU3C46Rail8P01puVWh1rwaR/KI/ZsjipWyYMbVQbiSgVirjGhtoKpa8PQNRkhoRHJ/4ii7aUbhuAUvy5yFTnRzvdRSY+g5/2iDx0Un1T+LV8GZuSJJtvN2WKLqjHkwp4ywPuBn4vFOMvyS6zraIlNwTGn7IY494CuYsEgKnydcsL03hPcKI32+OHAvkznRDpvEiNmhDa2P5wt85CajSM59Yf/tVAlxeEi0hGTnExHcFSNEgBbtXDIvr1VBnRKXPXBox9U9dJLol4WRKCONHnnj6pXRBFW7fOsYeIEKIbWWTHOu3MdFFKAJkAji219SH5vt5r3E8Q9ynO/bQNYSumnhIAArw8T0SIga9nqNi4Fh7SNdN+WT5aK73p9q1ozUaTN2RxdZoVdUDp7WqVEZm0/BnkAVrL5r0YIIgQmtp5Uw/hug3muE2NaUd+oRGVCg5hRPwYWdGwRmR4Nk3QWFDlu6zsq8yk6TozRdhHpxIpgksNXXjX22vlpMnXeCC4pxSXiRyDWxtF1NGZj3kX2BXbQvhYxz0CpCSKHLMmyEE/Z9/pyKHVqh5o/R8N8+N2NJvoPwISAik4p/bG5OvbNiUBc7a/IFOloG2VgVZrf2J1VFvBvnce/yqyDnkvLX03TFre8lKZdbrtnm9Sbmvx1XRowC5chCndjC1posUDst1RS50Tot5xPlUfXaBfyZU2Jq2wNc0J3Jqb5ssg+akclG2DDMVEE81D2ZZxlOr0QIxnDEH3iUpE/pM6u6jXyTJ3YBnQDYV1nbC3+BFPioR02TOhxfIxo9cn2IlY03XRilWGmuRz9xr6HmhkjugMvDmx+sRr8FTX7KXOLobbwlZQVHjDGs2yAT0J4a1WDGNlOLF+hxHKifVIdwYuHiJ/9TFJEFwBg1Eq0xZD++/XX6XTyphZzh9yS5JsCwJ1a2gLZIvRGylLg/ikR2vz/tDoQtWf/gYHGF4WdKWieFtqTEJ4L8zFDt4yno9PoDU6NzeUrvTau088Y+qhrzv6LPyy5Tp9LZk1W1pBPnLwyiCX735KLagK+OyLSBzYJKXlROInjxEfBSQ5gmLOsHZRK9nG+4sus2+pLxdyTYh7Om4wQHtxImr+bxNav7uxnsQM5Ew3sqie2cYPY2cSIB8PR9vuhZT7SpCMFaEC0r3spaM+y9ATdGGSfdZHSU8jK/AlOk8sBa82Kw82PjlY0tZMt0fa992wsVX2atJK9oEG4MZZjc6tQxqSK8sF3CsTnRuSjVw87UpnTyNHnxJ7JMs7JQu5HU998ODfHs3CRX9AplMk63YzQXApMM5EwBURDTC89Ct7axrRlUsUGaCXGW0rRsbpK5zWA4+JJkXJuYZ03i5/FW+5cr1vhjY4YxON9/zNpXivf9SGhSOdu5YLY4uz3Qdf3R9MOyMrwHYvoyXCzebDaYnAtt/cN4AmNNUNszkdhytLs3sKwCMeHM89pSLuofNChM5P/StSLQuHyuJKxyn2dHua3wZgBjWUXGeMx4sUnOKOPk9AatDsWEt1KVROlIMdXugt2cUjIavIhERoG3geyYlAjf2Y2IdSUNpkELSxWmLRKZ1jJdQ3oNvtP90VFLOJIXi2Pp651McM/2bIDqvruAxaPtDQtzysHFbYeZQjykXb2TAw8vIPUMeFU/J1ed+5Tr8tr8FtDJtruWeJBucvQExTpM3fU2sPm4aFBLKW+wdoxoYVHQ3O+49b0nSwYn+mw86uTDv2FE6OHoQAzVw+tEczfs6IW4rGxwcOxSEwBfU2McNxsvIUZu8VkXD8Jlbov/KsW28BwWTp8GCoF/AJENJyMSUFQEdSAuyk5zKH56/PL1xHV66OJ4sUm7uujsrwOJgwYe3SUi19eX0PwpBDYuVRrC+n8hqyr70o/xSFAtHfFyd9Q0saHmhLG55IBp+L+VT/vUHKDstoY2/aLiyoZ8XRc7Ascjj+faA25aYxtQeV1OpCiXTIxxx10ge82sulfeidOXg/Mc4UAOVJ8TELZ3sM6EVasXSj6AGRxUdM+EKN8J+41/HotUfNRP+9X3VQ11JdXMZmwwBPQ+HbTlgq9QJxUDaDBoaY06PIFkjWl3AnEk1q4wLUcmgA9xOUZp/PBxJEDzVyKLj+n2XFsQbBQal1gyYNvxFBxPJs9ZAIxmOmNDouQih8fGN8rJuAYc1a4AO9OJYRQ73A80RKZKAiKuE/h4jQho+dGm/K6BoTMgamT32ZAz0frX8eQfsPxhw53LgvgRdD6XY13n/JW2lOxrHQVqZubmFUtwbFxmTps+QTolSXWkbGpuniZG4E130xPj76smkRmvmvwn3YWjUqzXdXq4kfaNlKOYUR87+UE6S26RZ8B8B/EwoShpf3K+z+MrMFZ6BCcYqeyHqbmzqKJu0CCRTlJO6gQWEFqqSoFIgeD+AgVgWDMnTwVL5a2kHpRxc3dPk8hQoof5m/zLkRfA4+uH0l2rCyLXMA2lUUL67nAE5Gqsws6U9N0M7HsAOB4HnsgQC2rjf6SlY1jrh0uHNmmXg43yqPC7matLEwBJ3zfhrjuCLomlTZyM8n+/4GyTtzWpW93/Mzw4r0aaq59VWwMHBIUd87JhypF3LOuOrhgdhcVNKDNr9YGIqf1J+sBKX672b3ypAhiIliG6z6o53hgCbqY9gusB5hcBrKrWrt88bKFjiADDWgnjOqJLEJUqvOxWVf+ROi4D5hcgey8mjC3A/pb9/YuOQkCb2tRv/x+0otTW9YmOZcQ4rk0wDTk7yokHZjr/ReAwFTCxffjnwcyyK/FGHsjTi5z83uyK8S1N9hV+qBwcIWtoeZkk0zRX2fmWgPcwKzjEMhdZY8ajK+2UZTF5q96SH8fXhZgNzL76cm9s4bN5olrj9X94gcFuZPEYRWeMdktTRTZ3B3CSOrUFgeYamnrXOdCKfcYBzNMVmZyyYlGDmPf/TiDoHE3wpmeCxtAuDfmi+ZyWyboEMf1RlGtRNh+oCCASi6smyRORKqVHTTwGkghliiUZaSXS8XsSgmht4ir199/EO0C4sbMiF2QWtAweZ7G7pxTMA4CAnuoLJII+DCa8fV9hOlmQakmXLXaCGGruObOiX/KWTtS9FZ26rl8iQMkgdLDADd7pugv4vnhbqlRLQa9T2ybYAf13cKZe6PxLsvyvDvNKmRkJ8P7LW2h3OzCNQKxNUjTCqlJBed2MLdKbDBs5sGyGzRA2kN/SBinBFHDRwSXCeqR0P1GpzocvRyreLMj5NfPovmt0394ZUgp1Ju2rLLBfT8SSaYXyBedjghR5ovDsdypFFxAGaYSQBWVLJ/q1eUhEquG8z2MUoSUIX4VATjG5pHyS4oMnqfaI6VG597vmCTSyEZQBPUAAakUqE9YrOF4nzDOe1KpQC+gVlXjY+CklJVptJbKQe06MpnKmwrZBvB7zghvx8rgDs5AbXeDUn2dVDatGhbzp+AMTwcY7U3I8CbPHShIZaWVdWXc78GNdtHuZh+45JsYKHJc1k6nmOw00bMWfXCvM/nnOht2TBHqji+2L6PuIyX5QVtYtopHmU+RZoHe02OE1bQUZ36U6//lIt8QNVn4qoK+vtbmA31UHOfTORsrslPYEWM0DetVWU5JqWXWAXSYWcO3wJW05Sq1KRczyYGrMPIUGsnKnYQtM/J7umdtoSKP1c9OI80i90zN+PvyzhIZFj4DsTHMceXNt5Yv7VOKsaMJAED7CApS9Cdkt0Ew7giXvXzVLHSwygWrvsVOXBgLLine truncated
-4
View File
@@ -1,4 +0,0 @@
# The encrypted sync-repo blob is base64 text but must never have its bytes
# altered by line-ending normalization. Treat it as binary so autocrlf/eol
# settings can never corrupt the ciphertext.
*.enc binary
-16
View File
@@ -1,16 +0,0 @@
specs/
specs--completed/
dist/
plan2code-loop/dist
plan2code-loop/node_modules
plan2code-loop/package-lock.json
plan2code-metrics/dist
plan2code-metrics/node_modules
plan2code-metrics/package-lock.json
.plan2code-loop
.plan2code-metrics
nul
.cognition/
node_modules/
package-lock.json
SYNC.md
-1
View File
@@ -1 +0,0 @@
node scripts/validate-char-count.js
-19
View File
@@ -1,19 +0,0 @@
# Exclude user-generated spec files
specs/
specs--completed/
# Exclude development files
.husky/
.git/
.gitignore
CLAUDE.md
# Exclude generated files (installer generates dist/ dynamically)
dist/
# Exclude dependencies (installer will run npm install if needed)
node_modules/
package-lock.json
plan2code-loop/node_modules/
plan2code-loop/package-lock.json
plan2code-loop/dist/
+487
View File
@@ -0,0 +1,487 @@
{
"kind": "install-ref",
"version": "3.2.5",
"sourceTag": "v3.2.5",
"sourceCommit": "9629961f364fa027c33e71f882b9096f3523273c",
"files": {
"LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4",
"NOTICE": "6bba9f25892e3cdd053dca21b4315e2d169ea3015f6cfcc2ed278cf46e9b0e88",
"install.js": "11bc273fb2930fb028d2ae3e977df5dfd07673e4586ab5bfdf322560fb538b7b",
"package.json": "cf63941036bd1f337b1f6831ddc4a1d2b6cd62dd5508970805ed75ca8173c65d",
"src/installer/canonical-skills.js": "d23034407c14ba491cc95ad034dac1c897569741c8161ce0c7cd27db0afd7613",
"src/installer/console-stage.js": "4dfeffeab5ad1c60fe266cb79e175537c7a1879deee64fdbfd9c4086bd55fafc",
"src/installer/skills-cli.js": "b9fa16eacb5c80a537c8f563890da70b191b83f3f9300a74f570a2b2d42a0bf6",
"src/installer/timing.js": "d61a7a1632dd3d910fb701a66e38d9468b551432eb2c8a4be26602539ff4fa42",
"src/launcher/agents.json": "e6a13544098fbc45b6052649f1507d4d99ff026eb9f67a8e7e7aeef1389263f2",
"src/launcher/models.json": "12f410989cc3cb7e571378df930d5d92ba5fb1ccf12728a0f736a24dd28fcc7a",
"src/launcher/plan2code.ico": "08e45d570b49a8b71c22959f8a2c895ea8223fe165c53224f444702605b485a8",
"src/launcher/plan2code.js": "21d018ba95b8073c2bad1dcd47c839abc418e87f222fba1a44d2020df2a83651",
"src/plan2code-0-pathfinder-references/brief.md": "31268d6628e26491b6ac559c22e5af8ec3343c756f404d83a5d790ee8318c4bb",
"src/plan2code-0-pathfinder-references/chart.md": "c56967219130ff8ec0a9bf629efd0893fa5006374a6611fd566b8c62b2566577",
"src/plan2code-0-pathfinder-references/github-issues.md": "df24c7f01fbf75afd5ac8459212232311d4e0f320557603d61a8b60ff0fb0941",
"src/plan2code-0-pathfinder-references/grilling.md": "74adf8300d42e950592f476539f5a99b403c1aac8e461e3dca22bc2b4ca52f2e",
"src/plan2code-0-pathfinder-references/handoff.md": "c870f540f7b6ec9aaaf73b8cdf2c459daaef0dbc316f93c699385a2b5a9aae41",
"src/plan2code-0-pathfinder-references/questions.md": "c228a42a70600d5d9756158dca5fcdb096de65820ddd029b93343d20fbecd7b4",
"src/plan2code-0-pathfinder-references/resolve.md": "2e013c5dc23c1a4f73be2a1242caf44d4b2dc6cc1b69efbfe9f7daa39f44ed73",
"src/plan2code-0-pathfinder-references/trail.md": "ed12a748e284ca45469a648033e0e8b77fb03fd282adae992dcd33ea89cb8252",
"src/plan2code-0-pathfinder-scripts/pathfinder.mjs": "db4b79148807f061286df7f7e86e8e293600b3ec46c43553cf04830e102f7df0",
"src/plan2code-0-pathfinder.md": "d1f637d5a91056b8208f3b51472a47677cbd03c8058f253dab1f5760b281076f",
"src/plan2code-1-plan.md": "e437a12f9b368d36f9b6e7d423291872dfe90711c72c5924be8f6208d986172e",
"src/plan2code-1b-revise-plan.md": "1fb1e5fbdcd83a8612ba46afc647ddfdda65642f83de50e9403ffe24cf957699",
"src/plan2code-2-document.md": "1d704c423c9d7a69c28db884d8cf941665a4911c3fa472b772330c0b74ee5942",
"src/plan2code-3-implement-review.md": "faa89f4e7684f97776bbbf2dcb81e765c5474787dbf87b2b890c635088d02211",
"src/plan2code-3-implement.md": "0a553f88d5e6686f550af51e26b3535cc17ae04df9942f2e6ee56fb4d6cf9153",
"src/plan2code-4-finalize-references/community-feedback-submission.md": "7da6626a39c3008851a782b6f610d76dfcb662442464affa618c67f1a22b5b72",
"src/plan2code-4-finalize-scripts/feedback-payload.mjs": "15b41430ec0a105062890e016ac92d4bcedea044afcabe3162e562a26dbe9f93",
"src/plan2code-4-finalize.md": "d7a19b4cdcf65cb0faa320433f5a880ee0dcf709152cfae29941862d0cc8ffea",
"src/plan2code-changelog-scripts/changelog-state.mjs": "cffb25378fa6fe23342c047462aceefa117e0cccc808774f9f0d0e5ea7f06d42",
"src/plan2code-changelog.md": "d8913d988ca369db02e39d81c6d38e52daef79c2fd33149f77e42e5cfdfe84ff",
"src/plan2code-dead-code-references/caller-search.md": "2da07ea817087b030b77be00476f67c5507bf4d0b175316350f4c279493ae863",
"src/plan2code-dead-code-scripts/dead-code.mjs": "c686e32a0442854e788a98277e2f8a6e6b648ed08b97466e2da12c5926f43a97",
"src/plan2code-dead-code.md": "47c628526d57285e16444f8744ee9cf03b4cd1cd1a1db2da192a2c60ff3d7ea6",
"src/plan2code-deps-scripts/deps.mjs": "356973c8d8bf9dec730c9fd545856487b346acca8c1ae182f6bf8ec6b53e3cf3",
"src/plan2code-deps.md": "3f999bcc8617444ea7a37b705cb2ba50efcbd3fd8a9a7265537c000bc81f7837",
"src/plan2code-diagnose.md": "5f702717eca3a52cb8efda4bf755f954c916a4b55aa15347bd669a9fbc2d0c0c",
"src/plan2code-git-scripts/git.mjs": "37bd95078f4d1ef7e560975f2cdb81472da6f18acbff2d8c4fedbbbe4072dc9d",
"src/plan2code-git.md": "2dd3ed83846582d90f9c2b3b5f4d98c670820c6c04c152585dd7ed1ca9e3ac99",
"src/plan2code-handoff.md": "adce86dcd9da4807cf1fa5c86f77abe230471b3f110c2f4839b5f1686d4b7a67",
"src/plan2code-init-update-references/ai-agent-file-sync.md": "e09935329c885027c011d51d5e233f230c1c90d14fc2fd8e2c0d3fb167953c53",
"src/plan2code-init-update.md": "5a314195a543b66cfecf0559789507f7619e304194069511f5f68f191dacf596",
"src/plan2code-init.md": "712d3bb1c2e7f1b733e2f50bfc27a280f8b4b5b59c886bb480209c226c7d119f",
"src/plan2code-pr-prep-scripts/pr-prep.mjs": "82310199d649d615d4170e510827721f7229c4e6e8db9849a44251d942f3baf1",
"src/plan2code-pr-prep.md": "533130e9cbcf041cd1f9268d3a8126719b5642c664500d86ee11fae674c8cb14",
"src/plan2code-quick-task.md": "d71e2657746d4d2dda6cfbff788f85c5a506c94982cc3a54de6924da698b6537",
"src/plan2code-review-references/dimensions.md": "a4e33064e1f03ed15523ccde1fc25e2739ff93616c2a1f2ba1853a529ea87fcf",
"src/plan2code-review-references/false-positives.md": "b8f855675d1413f1f62ecfbc6b5ecf6aeaac9b34a68569649ec01cbfa8516160",
"src/plan2code-review-references/reviewer-brief.md": "d1816312b64aee7fa82945fa5de704a44ed02db4a084517af743104309f895f5",
"src/plan2code-review-references/session-end.md": "aa8dd978d9d0190fc6beb0658bd210e3274e3a9a7e988e2080d7cbc8847d620e",
"src/plan2code-review-references/verification-protocol.md": "9c65814b532acfc93d47575fc626dd86204c8e441066632d4beccfde687b0ea4",
"src/plan2code-review.md": "32cbf77a61ed169e72f3118c45d4d51c77c71de7044bc347582bab10daaddc14",
"src/plan2code-test-scripts/coverage.mjs": "63b39eec5301683b426e2163f4c5fadc5014229477c26060283c3212170a76aa",
"src/plan2code-test.md": "308744d5c60cf1e9addfe1b91d1602a0462721f828c3f13f7f666dc50b24c754",
"src/plan2code-ui-prototype-references/ui-prototype-contract.md": "d31ad5812b21f5b096ad2093768ea3054e239a956d78da11e9105cd083be2279",
"src/plan2code-ui-prototype-references/ui-prototype-design.md": "62e8d42b341ecc09fc87f2c2522bac8aa21bafb44bb48944cc538cf5b1378e68",
"src/plan2code-ui-prototype-references/ui-prototype-rounds.md": "11056704ec496596fbc86f92aa8d5568573c2f4aa65c031e187f2249c84eb4bc",
"src/plan2code-ui-prototype-references/ui-prototype-shell/base.css": "580010f6b8d3e411e2fc1ee48548ab70c14b37c06ff244b2366fb95495c3a288",
"src/plan2code-ui-prototype-references/ui-prototype-shell/shell.css": "b6eb57f779511ca69c912213a9ca3ec9e1f5eb58012cfde1d92888dc65947c68",
"src/plan2code-ui-prototype-references/ui-prototype-shell/shell.html": "29093192d5127933db4e7d2d296d87a77fa5e43eb8f29aec1a889f5594d1a5a7",
"src/plan2code-ui-prototype-references/ui-prototype-shell/shell.js": "39d9f880c5b4f4d21a2ff2b05e94292f8f8b5d1825b42892b758fadba6604f78",
"src/plan2code-ui-prototype.md": "d9424621ae58cc65d3e20b8e7316de840c4f5508c281e3423834dac07fa916ac",
"src/plan2code-xray-scripts/xray.mjs": "a78cb4744fee1140f4bd89a851bfe01db2d7bf5b0f6ae816264a29c1d1fb246d",
"src/plan2code-xray.md": "615b2326efd79daf2cb1d289b05cf42828b6e3fd9ff7e4063f91985d84da834c",
"src/plan2code.md": "364f6089b01d686934974d19a9166d4a702267bd9f2eb7ee763acaa88811f02d",
"src/shared-references/building-habits.md": "15915b5b488f677646fad5fd5af13f6b5bbe2150c3cc7fdb9033ba5847db248b",
"src/shared-references/helper-strength.md": "1baecb1490f4e01a8608fb03912437f25e07d82aae84f53e81e3f51dd3c72f0d",
"src/shared-references/lesson-check.md": "57dcaebef3ac94ddee84ae1062a4ac17290d62bec553d359e3327695b682d992",
"src/shared-references/lessons.md": "c3b82038f37be8251c7dc50835eb0e83380549418f916793be413ed441d9d7a4",
"src/shared-references/review-in-build.md": "9695e1fb5e8fd1a33c9d93102f62e9e5a9601ec61dffe8cb350a48ead150fce4",
"src/shared-references/test-runs.md": "e27faa7093df0fda0d1eb79b18177f8c10a5d6c2d7e54b19b982e8ac6b36b994",
"src/skill-scripts/agent-files.mjs": "769e59eba8c8bba13db6a4b9f3256230cae0ec28d4a63da002ec65cf4f7d2535",
"src/skill-scripts/agents-md.mjs": "cc3930499bd80b707927368e4be6d563a79500c3cfab98b2ab6b926be7d5e635",
"src/skill-scripts/changes.mjs": "f93c2ae6e60108a4a1ae79de71c0c59e22c7967c4fd8a81e7e7953d0bcd411f8",
"src/skill-scripts/commit-msg.mjs": "1088eb65c5e80b51e125139888c31725c9f212a3269a4d370b79382c1fa69d3e",
"src/skill-scripts/common.mjs": "0c39439c4e12a5e515d571e7439f34bcd9c1fd317572f5415be7dbc9ce3c33e4",
"src/skill-scripts/glob.mjs": "900f254b09cc99e6da70347aaf87bbd1f3458c83ca1f1ac195ef8aa83d0105ae",
"src/skill-scripts/lessons.mjs": "63efc0c6370cdef4056a21627afaadaaec6a2c1b19e8d8f59407517de89116de",
"src/skill-scripts/review-scope.mjs": "e989d44872064abc1767e67e8597de4c7bb8ae73a23e6a59d20588b779d30494",
"src/skill-scripts/run-check.mjs": "8fae3fe124e689de787249d5815d4cc505f95ee3ace23115dfc68003fe93cf7c",
"src/skill-scripts/specs.mjs": "23f14ca9c8a74821f89e6604061fba5d5c055a147de678109c739f5daea2f46f",
"src/skill-scripts/test-commands.mjs": "ef592491730c939d971e74eda5b91bc5522a05cd7d810c0a4ff4de0267b6eb0f",
"src/skill-scripts/test-map.mjs": "8252ee75cd79d078c60557ba80c33d3eec1d96e721129e74ebdd34597cb943fb",
"src/skill-scripts/test-match.mjs": "27257600be0d6d58fdac59d1e2370059e9c77fbd03f116c8f5f336ed8443d796",
"src/skill-scripts/ui-prototype-block.mjs": "e5055021026989342bea77f0cd4f91e885a18aedeeb5dffcd702b51c34f26f4a",
"src/skill-scripts/ui-prototype-drafts.mjs": "ac7d98424d6ee24499366d33db93162b5683b7c7bc3dfc7180abd52b967114fe",
"src/skill-scripts/ui-prototype-page.mjs": "44524dd01bc2b5e79a52396750b3b75f4da754903698f1c0de1980752cd18fbb",
"src/skill-scripts/ui-prototype-round.mjs": "6340930d20a0f37f8b5f6e5fc17167ab78f17338af2af3a3747bf65fb9e09d3e",
"src/skill-scripts/ui-prototype.mjs": "4518856c81ffbf15892fcf52a49b67a8d1c29fae028fe7b09a2ef95baf0aeadf",
"src/statusline-claude/README.md": "2017b90a775b7574dfc94848c19d2bead8bf3a2f71163158b9ef6d4883c5ccb8",
"src/statusline-claude/statusline-config.json": "b3432e19901413f87e739c0780e9ffe12c49abe31358efaadf7fe93fb1b2d668",
"src/statusline-claude/statusline.js": "a4e507b9cfc13eb9f0cbe1c808b033b87bcff0a0a2d0e1a0e24416b75989f41b",
"src/web-console-stub/console.mjs": "cd90288eb7578d5a3d0ee46be0a1d475d2c5ba80d9aefe1e4015d61d7d431404",
"src/web-console/agent-lookup.mjs": "67566dd6286b920091bc5000112a086059e566915b0a39bb17a8019af14f4b15",
"src/web-console/agents.mjs": "9a1c69fb80d6ffb2433467c855f23f7db8a026a35651367dc99d6ef4782cde42",
"src/web-console/building-review.md": "d9644587403f32a721ba163339f2f12f9bb59f64665f164f6bc0803165557d14",
"src/web-console/building.md": "a592a7a636a77c7aa473fea56e3af55879e04a9595b559fcaf830f605dee7a7b",
"src/web-console/cmd-chat.mjs": "ec703972f67d8521278af2c368bdf5cf71da79bb2438c3d9a6163a975eee4206",
"src/web-console/cmd-help.mjs": "dc61ce5b3cbd71df387d1e44dccdf9d85cc27676db12b69891bb6b761c413793",
"src/web-console/cmd-open.mjs": "72fa713120ac043aab7e1da4155f35c0b35f5c2f064c234c5a7ce765dd48afcf",
"src/web-console/cmd-post-wait.mjs": "e9fc81df05fd6cb08aeb6748940b5ef296786b6d2e77d95d0c4fee0189ca00cc",
"src/web-console/cmd-small.mjs": "1b01d777a5775451c97eedb772a9b3a1d36c61ffecdabcdd7f8a33cd8fafab78",
"src/web-console/console-attachments.md": "85cdef2ff7031bdc95a515a07a10186acbb3145c4d84f1a5932ba65cfaff9341",
"src/web-console/console-chat.md": "011bc420aad30a256e7c490d5e7a773a6626da698a172ee867e88468c35eff8d",
"src/web-console/console-docs.md": "403046ca88751b606f9efc542faf2d9c6362670ff164695cc373c12760f26e72",
"src/web-console/console-finish.md": "091022c168b9418db72c1012cfe3f439a1ea94eb8c61d92a5511f37e85748e02",
"src/web-console/console-interface.md": "c06451a672115e1ae739620e8dafe5d36fe4c1910034a17cbf16c3f36b303218",
"src/web-console/console-launches.md": "f6cf8c7cebd214192f5ca2ebb07ec916a96d438c5d254075f685d8420ffade64",
"src/web-console/console-meter.md": "49d7e8472386d2bcf7240bbe814defd89e6634bc4f39cdef6dcf671d103971f1",
"src/web-console/console-stop.md": "736d5dc23c626442c60df5a70d5f85d0941a2e5daadcd4398096d323e20b8ab0",
"src/web-console/console-subagents.md": "573e2d0b436b7cb9e69af5ed3b8b3641820de64d08500f7d2983784d15a1281d",
"src/web-console/console-trouble.md": "a36e534b4f58fbba8cb79baaa46d55094ae051f6f701acabddb1cd9c7849a469",
"src/web-console/console-workspace.md": "6b0c5f458d88fafeb593b72cc1bf2566f1a516f5755b3d9584e1fb19f14f939d",
"src/web-console/console.md": "52ffb8537a112fc631d470865a6a8bc90ff4edc9567da9b3a05b66354eeb468a",
"src/web-console/console.mjs": "b9bbf55bdf33831271bb633870360144410537f31a26fdec523f58046d65ed58",
"src/web-console/files.mjs": "eb26134a2c6ae751adb49dd4a7b28b79b22be048a37152c505924cfd7c6da25e",
"src/web-console/git-repo.mjs": "e69dabfe6456c7a43a0cd784cbab204f8d5d2d4f0b5618b007c54490c677b831",
"src/web-console/handoffs.mjs": "9382ca35b57c85b15c9164d801b13b8e6d49cd413d7c348898bf78682152ce91",
"src/web-console/in-app.mjs": "e886e9e24e4125995f7ef4f31b055a0a420744d41cd1d6262c5e4f9d21726a1b",
"src/web-console/inbox.mjs": "33a1e00d6e79b2fb105f1211dac8f2e5388d23044e20182aa41cf4a57bf20497",
"src/web-console/learning.mjs": "0fda2a48d57bdef21cee80f49911c67a2ae4bfe5358944189beeec637136f698",
"src/web-console/loop-setup.mjs": "b44b7e4e33d5ea7f53e26c3146aade3e074811521f2365ec9bc2ee266dac635c",
"src/web-console/metrics-pattern.json": "6e8c16ec88de7bc7222fc7e17d8f38865ea405ad62a064f8a9750866471bf0d9",
"src/web-console/notepads.mjs": "aeefd8f92434d272178234c3673cf762d86576760df8e9276878aaa8271c5f4b",
"src/web-console/notes/changelog.md": "b84ea057f9577311bd91fcf2189c8f65fe0a404d31026b580fac1ca43f595a4b",
"src/web-console/notes/dead-code.md": "88c11f9b39c6f43554147483c69655fc08fcdaf72542cc19d4b939b5ce680dd6",
"src/web-console/notes/deps.md": "7950b31e87b1de7682741cdd1c7ac395cc451469eb281b18f6c5737367e6f6c8",
"src/web-console/notes/diagnose.md": "694fa21cff77addeb03daf03f1ca810f336c0166d5bb56da4582f100f4eff03e",
"src/web-console/notes/document.md": "a9c4c76b4673deeb19dc296b8b2c2a893a572f32f7b8c962f62075a98cf4f4f6",
"src/web-console/notes/finalize.md": "b97c3a702d9733aa0079659faa8087073bee5a3c8236440097ceeae866efe5a6",
"src/web-console/notes/git.md": "cb172044cae7bdac51c460f07cf72812a118d8245ed80252ca49bc4d403e5365",
"src/web-console/notes/handoff.md": "8c236bffbfbfa63da28868cce963b59f5f8f48815eebb3a24510e2af2514e639",
"src/web-console/notes/implement.md": "9922bea4ddd1af26eca11179cf953538787c30753ed5c85b4c9bdeb5dc551f1f",
"src/web-console/notes/init.md": "05a43287e93399bc1a800705b2618753f51903c8002a8e1ed4b0d54f158aac27",
"src/web-console/notes/loop.md": "acb4d5b98a33a9c06743b5937ebe2610fa69e9fca9319d803c9c9fd951b765a7",
"src/web-console/notes/pathfinder.md": "2a8c7effb7435022e9b9474a878c443ed74e971dcf825a3313cf5f9e3a8c109c",
"src/web-console/notes/plan.md": "dcb883df197f242a200979206f44e97055d73ca5bb2dd9d64b5f222b31b77f1b",
"src/web-console/notes/pr-prep.md": "98e0ba97fb83ea063a070553561144aa9e9e8672429c8c2e1032791f7b634867",
"src/web-console/notes/quick-task.md": "fdf8d13c07461864442f84e14e12f49d2f23d3341daf5b86b140dceac555beaa",
"src/web-console/notes/review-loop.md": "fdbc125ec0734e354ac0d0481bbbab1b5650b16ef393d14fb53eda6b748cc16b",
"src/web-console/notes/review.md": "dba5dc4f3bf63af6310475c0fce2468a3a6836cf1dae48e14faaebbca1e40031",
"src/web-console/notes/revise-plan.md": "3222890853f700fe11036d2f81a001c704bb35a3beb362369692503cb5b7ba13",
"src/web-console/notes/test.md": "f58129188d9e39e2ba77fd7827e6959af3ae5e2c6b65df149ccfd5332b45a457",
"src/web-console/notes/ui-prototype.md": "dfc1f0feef7b3ba46251f09de83f29860cf7c34cbe68c3f20647932c285427bc",
"src/web-console/notes/xray.md": "0d23c8b6cb0c013f088d5aa11fb92c434811ffdf1081ed642de3b8ca0ad63508",
"src/web-console/open-link.mjs": "e6915729aa8829efa933ec934a14d09e388cd53c21df7f92da36985233b52f12",
"src/web-console/patches.mjs": "14956a6a34d758f8f52ab9548e07c9f98b271d05639829855318a7f59f34c751",
"src/web-console/picker.mjs": "cb9bfabd6afa362da3420d3c2e9c08edf3a4e85e8b36b71dadf974b6828b6d17",
"src/web-console/pointers.mjs": "e605f12a06a262dc093840e80b1a7d49da6b35cbb5df14ae5d7195eca61125b0",
"src/web-console/public/activities.js": "ad1d14ed2187d5c807f003cfb4706a4ae35ccb5d68450167a02ad42d238160cb",
"src/web-console/public/activities/bounce-cars.js": "9de8c74761e45f3dbef5d203591f0702a1e26bd0aaf5fc8cd719034541a6b855",
"src/web-console/public/activities/bounce-draw.js": "f36b0ccf471b7f2236fb0aef7150a4f4fbcb15f89bcdf7ba9e4bc60dd609e4a5",
"src/web-console/public/activities/bounce-extras.js": "fa90c1897ec035c943824cad59a83f158eb5c24df08ed7685c135bf85e8eca1a",
"src/web-console/public/activities/bounce-music.js": "981f786495d6895f72aea1e0e59eaad7788a436815380d264ce07b6374e74519",
"src/web-console/public/activities/bounce-rivals.js": "9eb557f5553b9357bb9aeba0fb798d9b86411b70376816a32c0a6d10e75f3527",
"src/web-console/public/activities/bounce-road.js": "5e8d0bd6b3615e65c037eb72ddd5470d1aec81097f1f71a6e4b483e06a613d1c",
"src/web-console/public/activities/bounce-roads.js": "060ea78f8b9d58f09aea645e95d42505ce474f741e4bf91e4a35736b3ed9624a",
"src/web-console/public/activities/bounce-scenery.js": "3e4aac70583bc0b447f0363293715c0cd10a6764fa7b4278677c95e0bf88c9df",
"src/web-console/public/activities/bounce-sfx.js": "7374cde4e00bfa0a2bb7c97b2cf5f9ca0e7e4593b234cf7583a4fdd8559e19c5",
"src/web-console/public/activities/bounce.js": "96f887ced5fdc318fc129b0dddc0ee7fb590f7385003136f2f150e6cc9091220",
"src/web-console/public/activities/bugs-sfx.js": "c7043dd14f50cf36f1ac45a125356546bf00a2094512cb9cdc37efa406b65517",
"src/web-console/public/activities/bugs.js": "ae2d95b00d7aa115859c6d2fe953b839be27c479c441cb54585b60458efebeef",
"src/web-console/public/activities/bumper-draw.js": "0e0d9325d5c210c8b8218e8cf13f470de53c71c8e3cc0f4268465aac8be31129",
"src/web-console/public/activities/bumper-sfx.js": "e450ce08311b861d998f259beba69d42d99c5beb93c3f2593b87322790c7a255",
"src/web-console/public/activities/bumper.js": "26b1f6722274597d9999f54de5615c5bdfb8d7ee6149a93f4f945c2420c5a238",
"src/web-console/public/activities/drive-sfx.js": "70636cafc57d7842366816f0d1e27657afc684f6b5980c75d716b2b4e5d5a958",
"src/web-console/public/activities/drive.js": "80f3b3f6291a1a8b0a1a555e02e131f133d2c8f086f3f4eadc3974b07390116c",
"src/web-console/public/activities/flock-dash/1.mp3": "062b26c12a9de22584dca12de4fa28053ad75c7dca9a592a0a6ddaa23723af41",
"src/web-console/public/activities/flock-dash/2.mp3": "a1cfe4d4ca327e2120c2a7456b9abee71845c88c74b1ba4c6dfe9216cb0b9395",
"src/web-console/public/activities/flock-dash/3.mp3": "057e1f18a5c889ad99aa90f2f3c1eee6bf6da475cd63390d54cda9515f5eb352",
"src/web-console/public/activities/flock-dash/4.mp3": "eac95a7a34d384365acffec8e9d574f7eca1ea3f0a0e08eb20af8ba2b503aba5",
"src/web-console/public/activities/flock-dash/5.mp3": "a5c038c55fc49724cf09357a9fc5a1c97d7a3143cb2e444682cce16c28b78fb4",
"src/web-console/public/activities/flock-draw.js": "f2eff3dfd8bc2040a8bfab635a69f53d6c21e465d7cc35e2aa4569364336bb60",
"src/web-console/public/activities/flock-sfx.js": "3c55f3ac1df8b0d25c7d616e55ddf059ef331b0aa9f14225bf26a7703fdcc6e7",
"src/web-console/public/activities/flock.js": "d3b9fa0d0e2450367b200a6f4f9aca86445b94b42f9ca601b6d69323a29d9db1",
"src/web-console/public/activities/fuse-draw.js": "384532594fd33738eba6973cbf3eabec1efc1f88faa1a769eac9c4f74c3d7ab9",
"src/web-console/public/activities/fuse-sfx.js": "3999433188d57a6e5e258d7f84a326ba6599fe065198bfb573a73d4efaa9d0ec",
"src/web-console/public/activities/fuse.js": "195c97c2878716cdeffff3122d05a781ccd20838c45bf6d9186d34a99714baa3",
"src/web-console/public/activities/ghoul-rush/arms/ghoul-arms-draw.js": "4118b50b74f029f6a34099c03e353dea95be14d78c11dcd18c31fcf9a3ed54e9",
"src/web-console/public/activities/ghoul-rush/arms/ghoul-arms.js": "a3e3ac30c212fa17b91cc343ff8a5f44027df7cdbb06f51a8247c6918ca59513",
"src/web-console/public/activities/ghoul-rush/arms/ghoul-flare.js": "ad8b680c0e769a6fb64d8a814c38b035b06891c615d4f636a4207357e1eec154",
"src/web-console/public/activities/ghoul-rush/arms/ghoul-pans.js": "1bdc427f84a3453c91392f6fbf699bfa1339e8a7c34b400c52374e18b5a27d50",
"src/web-console/public/activities/ghoul-rush/arms/ghoul-rockets-draw.js": "9490bf219779cb0ee0d9f5239518b89dd4fb5bc24bc8cbdd8f9d27c0a61f99e8",
"src/web-console/public/activities/ghoul-rush/arms/ghoul-rockets.js": "c64775a8126ef563a67b676be83e5956971c4eb63e02235d0a8439a2f7feeb01",
"src/web-console/public/activities/ghoul-rush/arms/ghoul-sfx-arms.js": "ea7cde99c6b9a97a196d23568f3cd9c60a725742c2a263f95a524a1324e675ff",
"src/web-console/public/activities/ghoul-rush/core/ghoul-bonus-draw.js": "238adc775e123ad18d1eed9e65f2c40133bf29f64e7ced0dddb7ce31eb8caa17",
"src/web-console/public/activities/ghoul-rush/core/ghoul-bonus.js": "e7bf7fc30ea02bfae54f0861e53a473083a4da01d293a2bf7190ee8dafc104f3",
"src/web-console/public/activities/ghoul-rush/core/ghoul-dice-draw.js": "e901eee6da67f8e50fc02a08d4e1a30d96b33fc2575123fbcd45093511d68ec4",
"src/web-console/public/activities/ghoul-rush/core/ghoul-dice.js": "f7815ed57ad16d1deecb89b25c910885154ad2fd0a29543a26c3070be78ac9b0",
"src/web-console/public/activities/ghoul-rush/core/ghoul-fight.js": "180a1ccaa920f54b91d20e644aeb1dd5bc64f9b73ebb6657ffbe6c84f870c3e0",
"src/web-console/public/activities/ghoul-rush/core/ghoul-kit.js": "ef16e71042973727a90c1e676c7e7e8cd5b94646a64a0ed8ba974a12008a9049",
"src/web-console/public/activities/ghoul-rush/core/ghoul-monsters.js": "2b5ae3fb3b797384d2f27df0d44f7e4fd364537053edd9843e8e6b9c9a96a900",
"src/web-console/public/activities/ghoul-rush/core/ghoul-planny.js": "05bb53658c2ed39a912620bc993e98bc31a1a67542562fe0ec0f18bd67807b23",
"src/web-console/public/activities/ghoul-rush/core/ghoul-play.js": "36276911413199e8e8ae8742a3fb7b20c6b0730bd932abf45c0405e8568619e7",
"src/web-console/public/activities/ghoul-rush/core/ghoul-powers.js": "cb38ac78a998b72ab06387f41933d8a4dd493a12e80b7134ba20405ff320e5ab",
"src/web-console/public/activities/ghoul-rush/core/ghoul-rooms.js": "f5b6a2c21c759f8ef85f79017bd8cd53868d4a8037f90a931959cfe8a91f6a70",
"src/web-console/public/activities/ghoul-rush/core/ghoul-run.js": "0b9808a476e3a34d9afdfdf42021c9a540fc32ba7e0d8b1b8e8584028a893fff",
"src/web-console/public/activities/ghoul-rush/core/ghoul-tables.js": "d2483ce7c4676b56480e4998bce58d757abf268c26c92bdc9b00be0a12156d8f",
"src/web-console/public/activities/ghoul-rush/core/ghoul-window.js": "91dd6b7a6a6fd902d90c2386d1f1a66c54c8df986122b6dd160219a05ebfad63",
"src/web-console/public/activities/ghoul-rush/draw/ghoul-draw.js": "be1466834e6cf882c3d62932eb6a895ffdc0c8a96c3cc63f1954d4012109f433",
"src/web-console/public/activities/ghoul-rush/draw/ghoul-monsters-draw.js": "11d57ee77cd651fcf9c0e43402a085ade4ccf2ebd34c2d23416ef47d28919ceb",
"src/web-console/public/activities/ghoul-rush/draw/ghoul-picker-draw.js": "6677166fcbd354b3f4f33502a681704e12f26354dbe6f0ad8e5810bda2de6df8",
"src/web-console/public/activities/ghoul-rush/ghoul.js": "cbe6657126b41d8d263d36eef262e1d3479cb6c69b8f1d9de8e87301c58009fc",
"src/web-console/public/activities/ghoul-rush/rides/banister/ghoul-banister-draw.js": "e973a7528cf99c15137c83b47a926194959fac3b8f9812ffcdc2c55187483d50",
"src/web-console/public/activities/ghoul-rush/rides/banister/ghoul-banister.js": "dcf2d2cb4f30ac7bd4404af931d8d4f1e7c0ae8e13abbe3c20b188a9a1a2920d",
"src/web-console/public/activities/ghoul-rush/rides/banister/ghoul-sfx-banister.js": "618b5d400240551cd65adc98c7fa87a54fe09195d1756c4ffbf45278f803ae66",
"src/web-console/public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair-draw.js": "5998adb88839f2e72ee0bc82fda281189139860d46b654ba9fc78d55e8efd7b6",
"src/web-console/public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair-room.js": "8c184cd252b57940f4913209fd7a357809391ea73614f8146bc801bcde823adf",
"src/web-console/public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair.js": "deadf1eebdbcb95f355aa0c1feefcc39232189da92b2bb617a53d073fe3a4d0c",
"src/web-console/public/activities/ghoul-rush/rides/bonestair/ghoul-sfx-bonestair.js": "e68f19906ea15e8c65c809f9d3672eb3120cbba1e77baa0eeac7ebe619cf0218",
"src/web-console/public/activities/ghoul-rush/rides/cart/ghoul-cart-draw.js": "3948c69dfa74254283a0ad692da7fbfe252ee64361ca3319ee0287f810310d8c",
"src/web-console/public/activities/ghoul-rush/rides/cart/ghoul-cart.js": "c675e50e484d183e079fa8871b6f5e648cfafad00b0a44e02af2a58bbb0faf7f",
"src/web-console/public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-core.js": "84e8959e711ab3b1079d54f9e2e497eaf4f110a671e50f2e449fde3d2a7a7f98",
"src/web-console/public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw-hud.js": "25ed0cef61004ee74e37dbf0a9799ecf76a9c5d404a988d0fd1e2d52584f0185",
"src/web-console/public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw-kinds.js": "9fd7dbef11d2072bcfdfc15c63fa3fd3eca52c5ac12545a47b9fbd8e756d49f4",
"src/web-console/public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw-sets.js": "30552a87ee805543b93b4d9b6bf96c87ac5abce7aaf6f8d7446da308833dba87",
"src/web-console/public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw.js": "034080ae47ba0a00f433921dd0325f5939b528a73f0a886aab77d879c22a3431",
"src/web-console/public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-gfx.js": "1c33b3b23ecc963406252d79ae20f5924b94421edaa5e045a4cf0cc1ef13613f",
"src/web-console/public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-scenes.js": "3ed9ba70c85d1e3e8256ffa4626d6f71133070019db42451c76836746947bebd",
"src/web-console/public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-voices.js": "be263c026dab7fca36f682ede321c4a5ccf8f3f997cefe0cbbf6620665b30e9f",
"src/web-console/public/activities/ghoul-rush/rides/dark-ride/ghoul-ride.js": "1a624540819f7627e4e61204f983363961252fe786d66705941f558536f45e91",
"src/web-console/public/activities/ghoul-rush/rides/dark-ride/ghoul-sfx-ride.js": "c12ef9cf112e17974a45581993f6eb8282bddc65194a7f0b5fcee2c8f57d5eee",
"src/web-console/public/activities/ghoul-rush/rides/gurney/ghoul-gurney-draw.js": "05c3d2b654f53d88de2298da72aef9ddb1346d8ff42c6e68f6244a369686c15c",
"src/web-console/public/activities/ghoul-rush/rides/gurney/ghoul-gurney.js": "854b3a5d92678b42bb36e808375d009283703c85b834d373c3e0837a8dc497c9",
"src/web-console/public/activities/ghoul-rush/rides/gurney/ghoul-sfx-gurney.js": "f506ed60993bbabb17bc1874967c50789ce346d6031e2f0d4a89a4a3a7f02bbe",
"src/web-console/public/activities/ghoul-rush/rides/hearse/ghoul-hearse-draw.js": "6b72fa1369cec4f5126ec0f4d1baf0384fe9dfb704a92225365295680d6c9c20",
"src/web-console/public/activities/ghoul-rush/rides/hearse/ghoul-hearse.js": "7f3e20e5c4ebc2c5f415944719fcc19eabc853ddca127251204a38810c124a6d",
"src/web-console/public/activities/ghoul-rush/rides/hearse/ghoul-sfx-hearse.js": "327048cba97dfc7238e49d5006b83ce38eebc684e3403f8f7343113ba0176612",
"src/web-console/public/activities/ghoul-rush/rides/lantern/ghoul-lantern-draw.js": "6ce220060a7ab9fd0225da42ea56514aecb3b8cb1e47abeb69069eacc3bb1513",
"src/web-console/public/activities/ghoul-rush/rides/lantern/ghoul-lantern.js": "763bf64d708c87e727a89bd8a4b431301784b3eb98da772f37ee248722294a2f",
"src/web-console/public/activities/ghoul-rush/rides/lantern/ghoul-sfx-lantern.js": "28aed45fb4496f746eb06a95a7f55b2f066af687d5c7b85dbc065921a68bf82c",
"src/web-console/public/activities/ghoul-rush/rides/mat/ghoul-mat-draw.js": "c613a25fe96916953222990de44ef81a449bcafb25dfb3ed5bcddfcc2096e8a8",
"src/web-console/public/activities/ghoul-rush/rides/mat/ghoul-mat-room.js": "897335ab74bcda8cf6d2afb6bb0425b98a06f0473817cb3b8790f4235ee12c6d",
"src/web-console/public/activities/ghoul-rush/rides/mat/ghoul-mat.js": "5a7e317d4f0e646b87febb29787e1a61ebf57920290cfd5fcdf52d7ed107e705",
"src/web-console/public/activities/ghoul-rush/rides/mat/ghoul-sfx-mat.js": "1950db455c87785fae27804f9fb2d9cca30028e89c9e1f0f23debea73d74961e",
"src/web-console/public/activities/ghoul-rush/rides/mower/ghoul-mower-draw.js": "3753607e363a7153ee83a8bb4e7ef191e7de814f7899dd8fdd868d913ed26358",
"src/web-console/public/activities/ghoul-rush/rides/mower/ghoul-mower.js": "3fde33c34730a6f9701fd57a4cb834f1a9cc35a79b9d476a0f384c22598133b5",
"src/web-console/public/activities/ghoul-rush/rides/mower/ghoul-sfx-mower.js": "7f50fc01740f92dff4babfe22ee4f919dae0565d25031bf6ac2a2b8167f2fb87",
"src/web-console/public/activities/ghoul-rush/rides/pew/ghoul-pew-course.js": "b44a573d08bc15254e64abb22a3cadcba1fd90b9b23e700d83789fe1a825f333",
"src/web-console/public/activities/ghoul-rush/rides/pew/ghoul-pew-draw.js": "436a8c61f0044f395137284bba33d18fc118ef8829d42b92749df30e7bada690",
"src/web-console/public/activities/ghoul-rush/rides/pew/ghoul-pew-world.js": "dd9209933915a2b3ae4474116ec58355f44fa24c00d0f43872d3076079c821ee",
"src/web-console/public/activities/ghoul-rush/rides/pew/ghoul-pew.js": "22c971fda89f7005be91948bf0725f3cb724e1bc22ec270164aa9b308d3ada38",
"src/web-console/public/activities/ghoul-rush/rides/pew/ghoul-sfx-pew.js": "5e51ee07b311b877ce8b11ba1735db36b05fb04b902af89a51df2182e8418321",
"src/web-console/public/activities/ghoul-rush/rides/sled/ghoul-sfx-sled.js": "a3295b0562c8501d6bcf590355e3649dd26dcea912c4f381ea04a365dc086d96",
"src/web-console/public/activities/ghoul-rush/rides/sled/ghoul-sled-draw.js": "3b51acb70a271f4390081b1dcae69bb0067efdb5f120d125d8f72a1479271446",
"src/web-console/public/activities/ghoul-rush/rides/sled/ghoul-sled.js": "5fd60ef88ba505a9e8c27019211e4691187a523c1a67174980329ec1497b50a3",
"src/web-console/public/activities/ghoul-rush/rides/tray/ghoul-sfx-tray.js": "e6dc66ed97122e332b91f21b03ae52849866b341f9fff6cc1f4bfbf7ccb33e6c",
"src/web-console/public/activities/ghoul-rush/rides/tray/ghoul-tray-draw.js": "ca4719c2339e0a469c8c75e441ae1f5547941c38771342ecc02191bbc412b74e",
"src/web-console/public/activities/ghoul-rush/rides/tray/ghoul-tray.js": "9a19e0060c8b7ceb3068dc007572b62ae12ee981a60aca6f726b99674e3748c8",
"src/web-console/public/activities/ghoul-rush/rides/wagon/ghoul-sfx-wagon.js": "9a2c16bd85f32e73b9af7fdc2f289f08c8253a0fa7390017e4b3657d5e2cf733",
"src/web-console/public/activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js": "b5badb9fec1eb5b532a1ee577970ba1f63f36ca1598b59d5ff80c4d44b4eda61",
"src/web-console/public/activities/ghoul-rush/rides/wagon/ghoul-wagon.js": "d9fbd46fa31b56753cbf1d79a48a0bd58fbcbc75592246a85b68a448f24e9d10",
"src/web-console/public/activities/ghoul-rush/sfx/ghoul-sfx.js": "7be040a03644d5bfb871285a4c7dcd9ab431cb0aaaccff628ba7075cdaff0762",
"src/web-console/public/activities/ghoul-rush/stages/bog/ghoul-bog-draw.js": "1331c35eb6848872310a54fa615d160acb446e5274039e07c40652d10f2f5cbe",
"src/web-console/public/activities/ghoul-rush/stages/bog/ghoul-bog.js": "646c395faa126c64c95fb91141583f916f52f9f5df2986388c5fcffb0b1cbb99",
"src/web-console/public/activities/ghoul-rush/stages/bog/ghoul-sfx-bog.js": "a758c732d8c93798eba4ff907d88b036b880a08769199e355dec32d896c2e807",
"src/web-console/public/activities/ghoul-rush/stages/carnival/ghoul-carnival-draw.js": "d5476e375d80bf1615532762611c3edffe3d86e9e72fdd21512bfc621fb0cd33",
"src/web-console/public/activities/ghoul-rush/stages/carnival/ghoul-carnival-world.js": "c9c6a95ba7efa14cea734fd333a7fb275f1f240b5b6c6cb969ffaf67985255a4",
"src/web-console/public/activities/ghoul-rush/stages/carnival/ghoul-carnival.js": "114d29ad1beaa6305d91e116a019868c3496cc201754838b271aec710059bbb1",
"src/web-console/public/activities/ghoul-rush/stages/carnival/ghoul-sfx-carnival.js": "939b5e9f477805e492b112a15d13ac87f54e6107bd77091195e70cdd324246e3",
"src/web-console/public/activities/ghoul-rush/stages/chapel/ghoul-chapel-draw.js": "7436a3f26d719569a30ea9f9a9ecc6d91f97e11bb93eb3a28a711dd4a6afa52a",
"src/web-console/public/activities/ghoul-rush/stages/chapel/ghoul-chapel.js": "059a0171faa247642a3ea6ab00f45fbe166a4ef93140becd2a0db82c3288f29f",
"src/web-console/public/activities/ghoul-rush/stages/chapel/ghoul-sfx-chapel.js": "ef26cf5fc90bf51864136d46f4befe59b03466a4c9dc45934583d2ef761c4a4f",
"src/web-console/public/activities/ghoul-rush/stages/frozen/ghoul-frozen-draw.js": "3a407b41eeef0a187decdfdd81e4c65f077897362bc7b941fdce76a141f060ca",
"src/web-console/public/activities/ghoul-rush/stages/frozen/ghoul-frozen-world.js": "b40816dfb233e67f74e8734c4f9a8c0e8cb307546939a1ff81d86802197fd557",
"src/web-console/public/activities/ghoul-rush/stages/frozen/ghoul-frozen.js": "4756022dea05166f2f7f98bf67d62e6712660c72d49e8261c17794f65ef6883c",
"src/web-console/public/activities/ghoul-rush/stages/frozen/ghoul-sfx-frozen.js": "557c8a1cb17e7568f61f09ead13706427599216f2f4890bc6549b4cdda3a2e47",
"src/web-console/public/activities/ghoul-rush/stages/graveyard/ghoul-graveyard-draw.js": "d5892e71d3aca31a92acfdbe1b4d7de209d0690c2d5ab62f6594a298cc98481b",
"src/web-console/public/activities/ghoul-rush/stages/graveyard/ghoul-graveyard.js": "79e879f0d2c6c94b0830ced25cb81f4e3904e35c0732d0d481785e139a1cc71a",
"src/web-console/public/activities/ghoul-rush/stages/graveyard/ghoul-sfx-graveyard.js": "045e7f849684998f7f855ae8ab81e20f0ee3b96096c0beb4868709d651b8b491",
"src/web-console/public/activities/ghoul-rush/stages/grounds/ghoul-grounds-draw.js": "504de8aa677e2725d735f520acb0818f406c68eb054f88c06ff7825c11833db9",
"src/web-console/public/activities/ghoul-rush/stages/grounds/ghoul-grounds.js": "403e555442b554ffdcbae5dfb40f1515539d70de893494169edd7f383afa4ec6",
"src/web-console/public/activities/ghoul-rush/stages/grounds/ghoul-sfx-grounds.js": "f4ddc743d9395a1da49653c70e3c075f9ff392960cc23125aaeebb2bd4ff7f58",
"src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-dollhouse-room.js": "bf7fa978aac712d78dba071393fc93f98e636c7e0f32cb67b7edbf3bb802a870",
"src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow-draw.js": "5164cea3df39c4e22e9d58324f93b32b0cfdeb6ae5d4ca37779b6e938b507f54",
"src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow-eye-draw.js": "f68054bea40a40453f26355b70e458954791d12116897913c092baeb370ea525",
"src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow-eye.js": "321cfc6fe08914aa8436a502ebf47a2f4ec67841f2b517f39de388125b77c7f4",
"src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow-heart-draw.js": "0ef8c1e468f80c8473a45900c11d4eec1225948b4edeb29f0d064f11146685f7",
"src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow-heart.js": "1371a020c8cd242b488191e7efa483780f2c85800e163aabd451f83015d723e8",
"src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow.js": "d278ed4d5dd0a00ad6a79d7db330ab9d992202ffa14dc7a13414f900d674f9e5",
"src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-pit-room.js": "e1a59653134a79fa6c3e40cc963d945a40e755c93028e075ee565c5060e0e34c",
"src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-sfx-marrow-eye.js": "d6adb4f9d2ccb50fa44a3bf63d54fd7f0312261adeddd76bcc9d87502556fe6d",
"src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-sfx-marrow-heart.js": "79a419ccb208bc05ef0440dd1d765a7d805748ec34d15e8379465ac12dc520a3",
"src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-sfx-marrow.js": "14f5bb7be93c6433dcca95ef1905c8c6cd44312702e3f9d294cd41475ff2d495",
"src/web-console/public/activities/ghoul-rush/stages/mine/ghoul-mine-draw.js": "7ed119e70b054057b9d2dcc4c36c9b363cb3cb064da2106c54162257bec73b9d",
"src/web-console/public/activities/ghoul-rush/stages/mine/ghoul-mine-tommy.js": "13c3cfaf0a5198b3269d5fee09e450a7a3bde25713e9479e5799d8218b1e859a",
"src/web-console/public/activities/ghoul-rush/stages/mine/ghoul-mine-world.js": "4b6c2f873fff1841446cf31e4b3870489c5fa0c74b2e1d67029ff89025e520b7",
"src/web-console/public/activities/ghoul-rush/stages/mine/ghoul-mine.js": "921a5dd64428ed50ff70b4a46fc70c178916de66382bbde86856a12027cf3f92",
"src/web-console/public/activities/ghoul-rush/stages/mine/ghoul-sfx-mine.js": "a247967bb2e665195e4957c7330222f0c03661b5780e964cb2282f45dbe7da0e",
"src/web-console/public/activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium-draw.js": "7b2e52dd4503bbc623feebdd2bb59f9cc9b103ce2981cb0f93e9ecfa369ba847",
"src/web-console/public/activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium.js": "9b5485d64cd1051cbae9e8a24dd62e408476be4bbd935904370adcf3560dd38f",
"src/web-console/public/activities/ghoul-rush/stages/sanatorium/ghoul-sfx-sanatorium.js": "c921e29f3cb52c0b549deebdf04a9d7021baf9713a4140e3b3847ae2aeb358c1",
"src/web-console/public/activities/ghoul-rush/stages/village/ghoul-sfx-village.js": "48e6d893184edf6bdf064a3b6900627574cbb220a7fa9ef7980343aaf7ce8b03",
"src/web-console/public/activities/ghoul-rush/stages/village/ghoul-village-draw.js": "6d27e23bc606ef81a3f86996e9ca8e8179b1e89e5b3ab0b9409fb69d1a7b984c",
"src/web-console/public/activities/ghoul-rush/stages/village/ghoul-village-wolf.js": "223568516573976f7927db41947888d4c7d4ce35f92776497c518368ee72fb1d",
"src/web-console/public/activities/ghoul-rush/stages/village/ghoul-village-world.js": "b7de2303a47d5fec0c38de47fb742fdfadf40fe8b5be09473e0614c879706971",
"src/web-console/public/activities/ghoul-rush/stages/village/ghoul-village.js": "0d27a65f07cf32d87e0a0294e0f5af4a1aafdbb47dc76283a2837c07ad56665c",
"src/web-console/public/activities/ghoul-rush/stages/wing/ghoul-bones-draw.js": "af7d2dbeed063386c8752252e605bf2e84fee65516935c32a3d155602c645c7b",
"src/web-console/public/activities/ghoul-rush/stages/wing/ghoul-bones.js": "e894d94d221d0ab013249a691d2e130d1a0c493233e6d0fe8a9a779f0928eb18",
"src/web-console/public/activities/ghoul-rush/story/ghoul-boss-intros.js": "a18d2b0f6afa231361c80292d9607ed4a360bc90c8ba598579976eba39961cd2",
"src/web-console/public/activities/ghoul-rush/story/ghoul-bossintro-draw.js": "8d3656f6e888020758c6ae76d8e8cfd9f896451544ea01f75e270c3e41cc44b7",
"src/web-console/public/activities/ghoul-rush/story/ghoul-ending-draw.js": "39267ecb23736cce9a78bfb1ab5861c13fcef2d1b9ec05725f5f55d4ade13859",
"src/web-console/public/activities/ghoul-rush/story/ghoul-ending.js": "6f29bc6527ed00498752c1c21f78a2bea2f96a9b1acb6608ea851f23789366bf",
"src/web-console/public/activities/ghoul-rush/story/ghoul-gameover-draw.js": "9c6857a1b09eb233d86deb09cb10bac5ce8106830c06082691a3da81ba62cc8a",
"src/web-console/public/activities/ghoul-rush/story/ghoul-intro-draw.js": "294b504cd1b6039456f249811dae7c15aadcaa2893953de70b0ecf39be8d0891",
"src/web-console/public/activities/ghoul-rush/story/ghoul-intros.js": "9e18399d14285c3b7364f784bf00f23136f5bdf422b4d6c5847e8fef5bbbd1c2",
"src/web-console/public/activities/ghoul-rush/story/ghoul-sfx-ending.js": "6a92b10b98cbb053cdf75f7f1fb10177a3f2ed1e9b5240f61a81d13a99c10817",
"src/web-console/public/activities/ghoul-rush/story/ghoul-sfx-story.js": "cea17b0b3a96fedc249839d598ae7d5a706475038714dba45ca933057bb1cb44",
"src/web-console/public/activities/ghoul-rush/story/ghoul-story-draw.js": "bec5146121c1ab1036c33d93063b94f2acf99157a9dc03e39c867a32ee9115e3",
"src/web-console/public/activities/ghoul-rush/story/ghoul-story.js": "65194e35fd3e61d05632cc8822642b302701086805400b42b7235ff7248db06e",
"src/web-console/public/activities/golf-course-candy.js": "0bd6026c0b744ce4fe327352e50d68d090c04e51b90a2d7bf66dcbd25d78430f",
"src/web-console/public/activities/golf-course-cave.js": "e6b4e6ecaf3893b2560e385dd3e720572e7a6e71ffd2c67487942b09c04fa346",
"src/web-console/public/activities/golf-course-dino.js": "3843ab92c094a68dbe1c2759c911762bf515a140a0465e8015df66ff5608aee9",
"src/web-console/public/activities/golf-course-frost.js": "e8eecae2ea1ad627aabfa6240377bb854d4c6875c5c56ab9e5b133c5c18d4d32",
"src/web-console/public/activities/golf-course-pirate.js": "4d451a3a7b734a5014a9dd465ae1de4e792f7fc68fcb28e5104401c2ebc2f1a9",
"src/web-console/public/activities/golf-course-space.js": "52d1674e887e7ce25213507b7aff5f603a28bf28a46f57c93fe0e836887cff2a",
"src/web-console/public/activities/golf-decor.js": "32e392c3cd50a78c7b04be67d38a3771abc3c50fe7c66df00187418b722dd90c",
"src/web-console/public/activities/golf-draw.js": "00b54c87f54d52ddae05bae608b9ca6d59be033b7b5c44bdaa560b5ee9d55652",
"src/web-console/public/activities/golf-holes.js": "113aa78b7cbee7ff6b48e84342d5d3c6a9d51902463c7ebc2ac5c8fab66d0729",
"src/web-console/public/activities/golf-kit.js": "992aaeff876b8045eb9c74fd5ebb5f36a2937d53be1b1088fe8158bdcbbe01ac",
"src/web-console/public/activities/golf-look-candy.js": "74b345a51cc4965c1ecb8951d2007709ce6f26aba25ec060427f7e5618b9b10b",
"src/web-console/public/activities/golf-look-dino.js": "e7f56f4c0cd7aa1e0dba9d5385be4831f4801a39b9f4a61b30822c46afee42b1",
"src/web-console/public/activities/golf-look-frost.js": "0a2bd622dde88b281b43824bcc68a111e69a83e668681fb3c6c7953ffc29547a",
"src/web-console/public/activities/golf-look-space.js": "c893b8eac841ef168d0623c83380e1da2f5abafacced1b311c6d9c93ed2595b1",
"src/web-console/public/activities/golf-looks.js": "58f79be4b7cc965096164e63663cbc53d2b8a2bd3e771a1fd53783b84827efb1",
"src/web-console/public/activities/golf-paint.js": "2592d193aa97076d27412b91c6c6018c4cfcb88f0ae98e9a366e98ec422f13d0",
"src/web-console/public/activities/golf-sfx.js": "870fa1f5cb1abffc7fe47fb98a64560043ef5ba53bf4338e3fa7b20b8685ee85",
"src/web-console/public/activities/golf.js": "d76448d4cdc4155f5773ff8394bd130b4f396ec87a93340f794e1464c4732115",
"src/web-console/public/activities/hop-draw.js": "d508bc5b61f1db34a0cecddbf5cc4abeb8f1dc41f535a47de6c58886f15c2847",
"src/web-console/public/activities/hop-sfx.js": "01a2d01598c8ccf7d08622e1b227e3271746429871a8dc050b9816998aa3e77e",
"src/web-console/public/activities/hop.js": "3d9d8503d42040a0a986a227b863cffbcb7f4b305653c68a43f9f9c88cbc6c77",
"src/web-console/public/activities/light-trails/1.mp3": "93975e32f3f1830a78e4b07b04ad43dd3533972728c6552a12afb288fa7556dd",
"src/web-console/public/activities/light-trails/2.mp3": "09b595a55dad3efeb64dbdec05b51eb8442b226ebe47655c5a24bac8c7e9b9e7",
"src/web-console/public/activities/light-trails/3.mp3": "68fa11146a34d1c35f447b6fbe618c72709cbf0f97ded4646075e6cc4a9a48e3",
"src/web-console/public/activities/light-trails/4.mp3": "e378239f15e79dff9b0f987d2d6c300d660c0c39adae21da8283b2a7550153fd",
"src/web-console/public/activities/light-trails/5.mp3": "730694ff29aedfc5550fd588ce7671c92041fc99edeffa3ed4e1a0eba60255cf",
"src/web-console/public/activities/pills.js": "6f833ae5555206fef459a8f631ae40469ccaa22a1e13642680c39750ce836141",
"src/web-console/public/activities/rapids-draw.js": "17eaf88cee0059fd0a0953c93fe7f8f2295cabe02a9079d1fee6812d4589e224",
"src/web-console/public/activities/rapids-sfx.js": "5b42b8c1ff53ee92a9c45aed8d6c27c38627a6cf26670d0ac7fab5eced503237",
"src/web-console/public/activities/rapids.js": "32df87b4ab4a355114ad683e92354ac45b823faf3f71e5d3798364122a654854",
"src/web-console/public/activities/snake-music.js": "2a1e8954992a7853f50d91c9982e5661cff15907cc0a025c0501e0e90b99717b",
"src/web-console/public/activities/snake-sfx.js": "e0c767221d0aca127d614c01e43260b62f314d0449e9dbfbc85d7ff6ff3c3582",
"src/web-console/public/activities/snake.js": "06b3327c84f78961a15d3786b80019295f641614096180b6a98c4c49c4ae756d",
"src/web-console/public/activities/stack-sfx.js": "f9cf9c65add82252bec3a11ea900694152c5914420210939d7b4896d8a8888ea",
"src/web-console/public/activities/stack.js": "46b2b02f336df75697a4d011064227a8af3e3bc9ececdd2f544aa39804ccbddd",
"src/web-console/public/activities/trails-sfx.js": "8011beeacbfaa7e690b95103a3f73c6dd9225b4a360765448d7cf09b175322b9",
"src/web-console/public/activities/trails.js": "35e4088fad5a065698d477ef8374cb6a1113e65e0289db280dadae36fa7c6feb",
"src/web-console/public/answers.js": "8a016be6bd9c30874b28d7930c6d69f693145acebe0d49125bb8fa3b75764b0d",
"src/web-console/public/app-bridge.js": "818ba79868e952d6b7bf3f6e5ce99bda64d79cc5ef4bd2817c4ceccac3abe93d",
"src/web-console/public/app.js": "b019c0c4d82422b168d98da8cbf029bc1b66173807eb171f7c321f89294528d4",
"src/web-console/public/boot.js": "37a9c5c46f1165f220a62833a2e80cd8de018f24f2d6694960791b7960aad000",
"src/web-console/public/bootup.mp3": "d1638e8ae22e5bc512f138e143fc1f21b59e2d02cc4d5792e65353922a1db213",
"src/web-console/public/card-rows.js": "a3a30b27328343757a436433f5de635d6ecb274dd6c800dadf0961d4d15d9757",
"src/web-console/public/chat.js": "641c3ca5f6ace134a735b695d25f22eef6eb52556259948a3d566b7655b0bc3b",
"src/web-console/public/continue-button.js": "d69f2b77b94e84b9766a1f8db1675b4ecb5531e2c4fe78dfa109545a4a9c72ae",
"src/web-console/public/diff-parse.js": "46d9b25e1c0db36076ee192cf2e1f41af2ce14d1a64d7407d6422f04578988d9",
"src/web-console/public/diff-view.js": "89a4be4aa9e70dfd8f3defff983fbd28c6a424d0b986bc2e7154c9fd15d46ea5",
"src/web-console/public/doc-files.js": "b8d9cf66abb271f872fbe034f4dd6501d8eea0f0bed2ca3a3d2bff6d6009d6ea",
"src/web-console/public/favicon.js": "41102eb0e79e9511fccd7c3f68ac2f9695aac06e471f2f0ac072b07b5f568953",
"src/web-console/public/favicon.png": "527ab3be16a39f9d43da47ffd65474f5a7f1e5af5e15c37336b8e14bbd05aa05",
"src/web-console/public/favicon.svg": "a7fff34a58e762c88c8bfbde9a2a932a127a0ddf7d0c19a01bf11494b73ed09d",
"src/web-console/public/git-board-view.js": "045478a838fa3b6777a371fa5faec66048a402eabac39c1ceb3573004c1d381e",
"src/web-console/public/git-board.js": "244cd3d83ca444b0a66f9d1093ecb11c7d4d745a6ddcc0ae15fc34216993f632",
"src/web-console/public/help.js": "5daec612ad1d86b421de3aa9d24ee0056343a141e8d467b0eaf9385fa1318fb1",
"src/web-console/public/hops.js": "49aef484aae5a910ff04d275f4a9a89752ba517713a586dfb6b76ba0410eeb47",
"src/web-console/public/index.html": "1c5e487880a888e72fb0a5d331c7ee7a561254217372abb89694bbf1b2d85252",
"src/web-console/public/labels.js": "0999a0d879403e1697ca5ece2998817769fd9177ac489bb7d61b1b6dd5e0c865",
"src/web-console/public/looks.js": "c99722c32a5a70f4af8d0150a72da49d13e2596581312e8c67ccc539b3c01bc9",
"src/web-console/public/loop-parts.js": "3324e9631dd2bb4c1fc33a856eb12c76209cbae6dfbcf8ee5e6db64454077012",
"src/web-console/public/md-field.css": "f8dc61d1686d0566c3e763ce05e36bbc47ea269556ca379558e0a579bd070aed",
"src/web-console/public/md-field.js": "154aa0a6c1d5bda78c4e7c81f32e40a44c59acb776ee20fb016dd51e45f626fd",
"src/web-console/public/mention-box.js": "17c7707a7ffa1b0f6bdb64629d5ec5b7a9eb3b45a7c972caacbcd94e58d5dcf4",
"src/web-console/public/mentions.js": "731c06c781a0b330eeda5741354b594b3801985d5c07abb8c10a0a2fdc003166",
"src/web-console/public/meter.js": "7b1ecb9caf57feb86dc484052687f8452194b8ac4cd5a99ad5484ccd90bbfbb0",
"src/web-console/public/music.js": "d63ad2387f8b9d413e54e32f456aeff3741990ce97c3137d1a34e488f9ae5400",
"src/web-console/public/net.js": "b19a78309d7d83fde1acbc7465174ee0ebd73bbe421ba8d352653722883f54f4",
"src/web-console/public/notepad-editor.css": "0fd6b8ec463ebddfab958a5819b741aef3d7dea1bcb79243ed95ddd8156b97a0",
"src/web-console/public/notepad-editor.js": "310163ffc597f27fe96b98caf0eb2b49e3d4a84063ed77818f5335e71ee4114e",
"src/web-console/public/notepad-tabs.js": "aa645b6e1e4d30a78d494efd05159613a77e76c00358a59f9af00440f91c315a",
"src/web-console/public/notepad.js": "32baf7d9926d874406dde58ddd00690536081bef125899e58b3821f03ed4af61",
"src/web-console/public/package.json": "3ca9d4afd21425087cf31893b8f9f63c81b0b8408db5e343ca76e5f8aa26ab9a",
"src/web-console/public/palette.js": "285554264e954924b4fe4ac629c8811cf0c78a99aa550daa6a72295fe4f380f8",
"src/web-console/public/pr-url.js": "178d7b5aa1765e32abb744de1fb002db882061a5f53ae48cbe93682f2341263f",
"src/web-console/public/prefs.js": "d46d8ec2c00d0d2e00f17dfc2a57316fb1bda5519dac26d39836e155c5d4856f",
"src/web-console/public/render.js": "d027e6a4177b93559c84ef00a831985b8df4be803a133cdd58aae8efe784505c",
"src/web-console/public/review-loop-end.js": "4deaae2f017c60cdb57590128fe88634d3b835541733a626ea693179468d898e",
"src/web-console/public/screens/activities.js": "27a6f2be3813e5bd57b82a2087cd656945cc30b95bc9cfe4500212013259cb1d",
"src/web-console/public/screens/agents-view.js": "4bf966bbfe4941982bdba15111aa83ecf06ad56ca37155e27078d0ad588a0634",
"src/web-console/public/screens/agents/agents-data.js": "8397846b62930ae0692f4f8d619a9f5a99dd0d3211d4428af2f15d18cd5b6fd0",
"src/web-console/public/screens/agents/agents-form.js": "dc5c7e4b0f74a4eb900d82c1a62148bb0c79b4e12da963425784a575f847c09c",
"src/web-console/public/screens/agents/agents-list-editor.js": "0d0ae6880c900f5af5113edf40cef5b84729c5d2bd9b3201b13a97f5c26582a6",
"src/web-console/public/screens/agents/agents-strengths.js": "3b5399ce98de9d043736b361447b8e84bb9773195213442867c843e05c105add",
"src/web-console/public/screens/agents/agents-summary.js": "5e77c6c4a186baa3a019171a6b72c68089e43c2906c7045ce818ba1c9716ebbe",
"src/web-console/public/screens/ask.js": "9ebe5d8451c18ce4f958633b47be01d8bf87f9c7333124eae4432bbc9e61ea69",
"src/web-console/public/screens/cards.js": "df60dabe524f128a5bae34040206a69682b25622b6fb5bbc3de621ec1f409674",
"src/web-console/public/screens/cleanup.js": "4afa85666fe3247e033a566592949c544cf574a28c7579b73f8ddf5ad30d1245",
"src/web-console/public/screens/core.js": "6186005e6bdb416080d299e8892f4d76bbcc1943622206ce0603df03be004568",
"src/web-console/public/screens/dashboard.js": "5530cec280374978066c7a3aaf508eff0b4374bb5875e58fa417b869e107a3cb",
"src/web-console/public/screens/docs.js": "c92c31e1e5d309f8fc3dc1583348635cfd6c0e0343fc00cabe1171f85b44c4f8",
"src/web-console/public/screens/ending.js": "3a34f00a1b60776e9b25dfcdb06711547bb003f2577c42131f1c3539f8dc6c61",
"src/web-console/public/screens/git-host.js": "f2de7539bc38598869e452d60a161c4a6563a95163fad60314cdb81e72fb3a2b",
"src/web-console/public/screens/help-dialog.js": "864c7a2d07d19d8a740811771060174c5b362ffe52db6d9319112f5edeacdca7",
"src/web-console/public/screens/learning-row.js": "dd3f4d7cda9fc3d4ec1e4e4ec6b4a4921ba4eda6829ad4838f7a7a09335b98a0",
"src/web-console/public/screens/looks.js": "0783c4337f67b06a1e6c43a3b83178b67a1fb83501d9b2c09fd69154fcc252fb",
"src/web-console/public/screens/loop-setup.js": "0c1419bf2aa870afb9028723755d5ed561c5d0056679337a42c0ab7ae352da17",
"src/web-console/public/screens/notepad.js": "86c4d96eeb4bbf5662d9def73149a40c464d76a274c8acaf230ffffc43a8dc4b",
"src/web-console/public/screens/prefs-dialog.js": "ac6dcbf7e30e2fea97464523af7530a1f325d612161e80303219fabc3e4c4dbd",
"src/web-console/public/screens/review-loop-setup.js": "cec92e6c3faa63e9c888d6dd40d6be04a88c16f6691ea7565f121e2830694164",
"src/web-console/public/screens/setup.js": "e268cba6edf0bdc78eafd10c206dc6048631f0d3a2ea07397f4d3038591a48ed",
"src/web-console/public/screens/starting.js": "f473aa825a19c5b5ba51bf88343e16713ce0a901ddeacdc61d3d53c5da764a29",
"src/web-console/public/screens/workspace.js": "3acef583a2bedd15c39430615bb1a356c4f7db68dad2d1318df774807e918767",
"src/web-console/public/selectors.js": "38b395ecb3b41af228b6278d9fefcb793e1f439ae0ec794a32dd374bc5d500cd",
"src/web-console/public/send-state.js": "cb743207b9bf391c879f7bebc1987bcf93475734dd9a8d180161ff411b3c878a",
"src/web-console/public/skills.js": "406a48cb3d3a1ac519c8954b43743b4ff8c8c84d85a73f2284db1a6369a26425",
"src/web-console/public/sleeping.mp3": "f5a3d12cac12d8592424b315053d8b5ebd97850ee1dd53807a065c5e05eb7047",
"src/web-console/public/sound.js": "f3e8e14313bdf00ad28ce5ad4fb587c05eb660096ea73ec392863523d93cb245",
"src/web-console/public/sounds/sound-01.mp3": "fa2d130ae2ea8cfad0863952e537e7350159422cb8552f2ee3a71c08eeb94621",
"src/web-console/public/sounds/sound-02.mp3": "d314d2886f802fe706dd4ac5ce465918ddd5aa6ecefca772b61eed0d121674ad",
"src/web-console/public/sounds/sound-03.mp3": "d3192c856fe76f02f5a9d088cba912035c7f6ce8356076e534411096a56f5630",
"src/web-console/public/sounds/sound-04.mp3": "adb998402e201f65305607d29442b45555fa23ad0f523e8d85d72573a87f249d",
"src/web-console/public/sounds/sound-05.mp3": "053a2fe627916e048af1ce04b356988f3844754f370ea169f16bdf8f72eb0d07",
"src/web-console/public/sounds/sound-06.mp3": "d9b387ef345d53a9020ffe0b963f3542a648fb3f9a4fe13e5ac924a5206db762",
"src/web-console/public/sounds/sound-07.mp3": "7832b6cf973ec406283b2a39601e1f35ad43f0748e11ce51c9096abd167b5d5e",
"src/web-console/public/sounds/sound-08.mp3": "ead034c72769fa4c696545d231e5d17a6973fd5b6517c27a016a1df7ae9070ea",
"src/web-console/public/sounds/sound-09.mp3": "42f6807a4ca04dac647ae192de5b0d04483af07fb510b6be72fa832c8e74cfa0",
"src/web-console/public/sounds/sound-10.mp3": "1431ec6e48e69d0be46b272cb32b81be59b831bfff9b5cd8af342a94089ff1ee",
"src/web-console/public/sounds/sound-11.mp3": "c13da61f3e5bcd79ce3e8785715970ef8d09b2edcd5f956febc6d83e6a759827",
"src/web-console/public/sounds/sound-12.mp3": "e6765615cf5b195b675df9cc065e67a2aa1155a8ac5546d1a963d9573cce1880",
"src/web-console/public/sounds/sound-13.mp3": "b1559967dedb7994a82371f10cec9f7f3992e6b147b4cd88d62112bcdc3f9ba3",
"src/web-console/public/sounds/sound-14.mp3": "e0c4ba748e31712a5f89bfc6ced5331877b67147e06c7f1f797871a417860f24",
"src/web-console/public/sounds/sound-15.mp3": "888e4fd4871a47bacbf10f7531f6f03beeef077a39eec7d2d0efbd5f621687fe",
"src/web-console/public/sounds/sound-16.mp3": "748e6d03a559ac909d04b9fa907fca3424c6bf00aa45bcad3f6a07238e58f6cb",
"src/web-console/public/sounds/sound-17.mp3": "d6a99e9d0721b7404b351ab5faff4ab3b79a061e3c383983640e007a81ae264f",
"src/web-console/public/sounds/sound-18.mp3": "416bef34427e51d60955fef04859ba73c6fee78ba2ce67d42e6b7f752aed6beb",
"src/web-console/public/sounds/sound-19.mp3": "eeba885a6fecaf9b0700b5aad6b31910c2d1a0d32fd3aa71a4a2e7233da3fb89",
"src/web-console/public/spec-states.js": "1529c472e0f2b3e9ff312941c9bf69caf6e3511ed2c3de930d7352c508ad92a2",
"src/web-console/public/starters.js": "a8c3d5fa8a9576da6929cdefe791879e47b63ece0a7a2c113e5f11729c875b4e",
"src/web-console/public/state.js": "c04f75ff18d3d86c346a3077e99f49b1f868de5890583d770236692f7f19e02e",
"src/web-console/public/strengths.js": "c7cb5b287df99eb0b3d849c2504f9ed439afdca5f31af0de935f3b4cda9e9c13",
"src/web-console/public/styles/activities.css": "c028932d0ea21a21f9c4299bbc500bc5df102fbc78111a9e48fa7facd0c6dd7c",
"src/web-console/public/styles/agents.css": "f2cb512a36a69834b0e675344645af59aa4447394b2c2bd80a0ad50c0e1f17a0",
"src/web-console/public/styles/ask.css": "5047adbd4be0249bca0f0e97ef668f9894806f9fb2f17248c6b5bb16fe6c0b17",
"src/web-console/public/styles/dashboard.css": "0dabce8ca3be297b7ea581a095aa87462f35d005c7a5833627d43ce4ed65fffa",
"src/web-console/public/styles/diff.css": "c1ce2f2862aba49ecdc39f822fe52850e5b773d686bb3aa4892d5bbee6538086",
"src/web-console/public/styles/docs.css": "ff02c2fe5b46e434c9809efa564a308c944b00248109740296a0b2aa5780a3ca",
"src/web-console/public/styles/ending.css": "e3cc86cf84dfc00011d43847e85afd9015d442d1a4308940332ad16f314fb4df",
"src/web-console/public/styles/git.css": "ebe477c34b00b7195ae7d91df98c1441bd46041e00e929d123ffdc76e8d56d98",
"src/web-console/public/styles/help.css": "0d42d001369ae55fe7f3fbc60ce0eb65199a5a0605693e4e40a05d3570f01d78",
"src/web-console/public/styles/learning.css": "e6cef12d22f005696a997e6dddc3fb3e5d5d2abd31c90ec192629a3828085a5e",
"src/web-console/public/styles/looks.css": "724c5670064b6093bd211ccbb8f63a7dfbb79f77c41ea61e861d87138d158cdf",
"src/web-console/public/styles/notepad.css": "af60a63ed251f79523186f1d403235e5b41da4ca68a6e9df2ace1d2837ba1dfd",
"src/web-console/public/styles/pieces.css": "81b3b21a404a64f9f1a36adefed3d6c29647194bb84f1dfcc2cbd4987c1b03c4",
"src/web-console/public/styles/planny.css": "dcdb9bdf79c4661d731b5c9ed60cf5f1d829d7e3bfd134b2e47ae71cb7e242be",
"src/web-console/public/styles/poses.css": "2dc0c86c96967b3f7860afcb75da9222b6c1f39a7044a2adfae6e779b9b64037",
"src/web-console/public/styles/prefs.css": "a9890aeb3e823cd0d05b655ae1e2a8163e302b692708f25e9ca738030f85be2f",
"src/web-console/public/styles/responsive.css": "7d918d478f8ccf8c7c573528853d4ecb39949d6086f0b9dd765c5a5515b86915",
"src/web-console/public/styles/shell.css": "26f9bdef3acb6c7957a4543be776c79157fa4519306d10f8404e22322838b4ef",
"src/web-console/public/styles/tokens.css": "3ac3615d151ee45f04774b543f00a48eff2a39ad221e049daa6992ff17ca3985",
"src/web-console/public/subagents.js": "62aeeaf0ba05164eb5a9b6cf178a3992a4ee0fb106710bdafdc8815aa2e4da09",
"src/web-console/public/tabs.js": "dbad09adac2b78abb6f89eabd1bb224c6425e5ea573a858ad80d3ad241de4007",
"src/web-console/public/tones.js": "d21d43ebc2888d60025d78b4da86b950e035fa340074ae7eb02c9e7d22651d91",
"src/web-console/public/uploads.js": "b0b5350f48b90942cf64a46fe8948bda13d0fc42fde3ac23fcc24091cb2c30ad",
"src/web-console/public/vendor/codemirror.esm.js": "3a8002b9cf34bf7731ea04775288ff93b66904477bad33ff38658dc9222c3032",
"src/web-console/public/vendor/marked.esm.js": "7a7d9a521ac9384e0c3a075120a7c486cbd0c3c32cc5601bbb79a23e97403690",
"src/web-console/public/workspace.js": "3e14446ea01b39f67e773d5d826ac9617881a5a41b1f575e739e9f0334a70c70",
"src/web-console/review-loop-setup.mjs": "d10fe48b3f683a983df6fe5ef5cb6a2930217f3d49fcf5cf9635577e4a935d01",
"src/web-console/routes.mjs": "f2d60c0c8927570fe974311d31bfa0c06a064135ab9189cbdf48d5a01d07593f",
"src/web-console/scan.mjs": "103735a448f048a5d3b39dcf58324b8f87a8e41fa65dbf7d0a3479fa0070e10f",
"src/web-console/server.mjs": "2c77e835e260cc701ed25a9b6d26b712f2928bb8dc0e42db74e378a680e4712c",
"src/web-console/sessions.mjs": "d8191783c8940ab3718fcf0ba131ae687fbafdc472bb6d70f05da2b6a165199f",
"src/web-console/settings.mjs": "252be82da12e5689b29233123b496236793c677997c63e24c4d0626b2428845f",
"src/web-console/spec-carry.mjs": "d7f812cc77989f22db2a8e1e3c7bb66dd60b6d48225d5d76a89166ea612d8550",
"src/web-console/spec-files.mjs": "e00cf9961dd78a2df9ac66027279b230b597131e505fbcf75d0019771d3e5254",
"src/web-console/static.mjs": "430141600d7800e474a32b840bf6cd6b9f9f9781e37d52a32c9ccb73869c9313",
"src/web-console/strengths.mjs": "4a94e7a8d2468909592c2cc995ab6abd75aa82f3507af25084ed043ecac1a7a5",
"src/web-console/update-check.mjs": "eec6edef80c97a5ca25252ea0338490d615594bcdc2418676a08126824111417",
"src/web-console/workspace.mjs": "a2efa4226cb64028d18289b8e3fae3318a806899cddaf7ab28ca7c6bed7408d8",
"version.json": "e7d6e7b17e25fc18b92d71954dafa02a6f593b2accf8687c6a480f60244af233"
}
}
-62
View File
@@ -1,62 +0,0 @@
# AGENTS.md
This file provides guidance to AI coding agents like Claude Code (claude.ai/code), Cursor AI, Codex, Gemini CLI, GitHub Copilot, Devin, Zed, and other AI coding assistants when 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 that can be installed globally or per-project for various AI coding tools (Claude Code, Cursor, Copilot, Continue, Windsurf, Codeium, Devin, Zed).
**Version:** Check `version.json` for current version
**Author:** Justin Parker
**License:** MIT
## 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 "Git Commit Messages" and "Project Overview" are fully inline here.
## Architecture
High-level directory structure, key files, workflow prompt inventory, and file naming conventions.
Details: [Architecture](./.agents-docs/AGENTS-architecture.md)
## Plan2Code Loop
Autonomous CLI tool (`plan2code-loop/`) that implements specs by looping through tasks. Covers loop architecture, modes (one-task vs one-phase), completion markers, and key source files.
Details: [Plan2Code Loop](./.agents-docs/AGENTS-plan2code-loop.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, project, branch, context usage, usage stats (rate limits or token counts), git diff stats, and duration. Reads data directly from Claude Code's stdin JSON — no API calls, no auth, no background processes. Included in `Install All + dev tools` (`A`); also available via `install.js` Custom → S (opt-in).
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line section)
## Development Commands
Build commands, installer menu options, how the installer generates platform-specific files, platform format table, and how to edit workflow prompts.
Details: [Development Commands](./.agents-docs/AGENTS-development-commands.md)
## Code Style & Gotchas
Language/toolchain conventions for `install.js` vs TypeScript packages, 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" - an ASCII art robot that appears in installer output and workflow prompts. Mascot variants are defined in `MASCOT` constant in `install.js` and appear in workflow markdown files.
```
╭───╮
│ ● │
│ ◡ │
╰───╯
```
-815
View File
@@ -1,815 +0,0 @@
# Changelog
All notable changes to Plan2Code will be documented in this file.
## v1.15.4
### ✨ Added
- **Status line: reasoning effort + context token count** — model segment now appends the current reasoning effort level (e.g. `Sonnet 5 | High`, hidden when the model doesn't support an effort parameter); context bar now shows raw input tokens used alongside the percentage (e.g. `42% (84k)`), independently toggleable via new `items.effort` / `items.contextTokens` config flags
## v1.15.3
### ✨ Added
- **Session-end summaries across workflows** — consistent closing context in implement, document, finalize, init-update, quick-task, review, and revise-plan
- Implement: work summary + upcoming-phases table (task counts, goals) after each phase approval
- Document: phase-overview table at close to help plan sessions and review gates
- **Sync & Maintain in init-update** — new unified doc-surface sync option (menu item #9)
- Covers `AGENTS.md`, `.agents-docs/`, active `specs/`, README, and human docs; tier-voice routing, never duplicates across tiers
- Adaptive to repo conventions — detects the human-docs tree, never assumes
- **Research steps in plan** — domain research (Phase 1), tech-options research (Phase 4), and an investigate-to-close-gaps rule on the 90% confidence gate
### 🔧 Changed
- **Spec auto-discovery hardened** — replaced Glob (silently fails on gitignored `specs/`) with explicit shell `ls` across document, implement, finalize, init-update, and revise-plan
- **Revision-mode guardrails** — `1b-revise-plan` edits restricted to `specs/` paths only; execution-shaped language removed; cleanup step added
- **Commit-message enforcement in implement** — subject ≤100 chars, exactly three `-m` flags, no body
- **Finalize documentation review expanded** — audits `AGENTS.md` + `.agents-docs/`, mandates corrections (not just additions), routes facts per tier voice
- **Quality language pass** — plan demands edge cases/failure modes and measurable criteria; document and finalize role statements sharpened
### 🐛 Fixed
- **Review workflow next-step guard** — Review mode no longer suggests `/plan2code-3-implement` when `overview.md` and `phase-*.md` files don't exist. If the document step hasn't been run yet, it now correctly directs users to `/plan2code-2-document` first.
## v1.15.2
### 🔧 Changed
- **Review workflow renamed** — `/plan2code-3b-review` → `/plan2code-review`
- Removed `3b` step-number prefix; review is now a standalone utility workflow (like `init` and `quick-task`)
- Source file: `src/plan2code-review.md` (was `plan2code-3b-review.md`)
- Reference directory: `src/plan2code-review-references/` (was `plan2code-3b-review-references/`)
- Updated all docs, installer config, architecture docs, and cross-references
## v1.15.1
### 🔧 Changed
- **Zed agent support** — Added Zed to all agent support documentation
- `README.md` Supported Platforms list
- `AGENTS.md` intro and Project Overview
- `.agents-docs/AGENTS-development-commands.md` Platform-Specific File Formats table
- `install.js` Agent Skills platform label
- `src/plan2code-init.md` AGENTS.md template text
## v1.15.0
### ✨ Added
- **Claude CLI status line** — Persistent three-line status bar for Claude Code, displaying model, project, git branch, uncommitted diff stats, session duration, context window usage bar, and plan/quota usage. Reads all data from Claude Code's stdin JSON — no API calls, no auth, no background processes.
- `src/statusline-claude/statusline.js` — self-contained: stdin parsing, config loader, ANSI formatting, orchestration
- `src/statusline-claude/statusline-config.json` — distributed default config
- `src/statusline-claude/README.md` — user docs: install, config, usage modes, troubleshooting
- **Planny mascot icons** on each line (`╭─╮`, `│★│`, `╰─╯`) in brand colors, with monochrome fallback
- **Context window bar** (12-cell `▰▱`) with configurable `autocompactBuffer` (default 33000 tokens) so the percentage reflects *usable* context, not the raw window
- **Adaptive plan usage segment** — auto-detects data shape:
- Pro/Max/Teams (rate_limits present) → `5h: NN% · 7d: NN%`
- Bedrock / Vertex / PAYG (no rate_limits) → `NNk in · NNk out` session tokens
- Segment hidden when neither is available
- **Real uncommitted diff stats** via `git diff HEAD --numstat` → `+NN -NN`
- **Color-coded thresholds** — green / yellow / red for context bar and rate limits
- **Separator line** rendered at fixed 55-character width for consistent alignment
- **Session cost display** — Estimated session cost shown next to duration (e.g. `49m ($4.62)`) via new `items.sessionCost` config (default on); reads `cost.total_cost_usd` from Claude Code stdin; hidden when zero or unavailable
- **Compact mode redesigned** — `"compact": true` now renders two content lines (no mascot icons, no separator) instead of one cramped single line. The single-line variant truncated in narrow terminals — the exact case compact mode was meant to help. Default remains `false`.
- **Silent failure** on all errors — never crashes, never blocks the CLI; 1.5s per-call timeouts on git operations; non-git workspaces short-circuit without spawning subprocesses
- **Installer integration** — Status line included in `Install All + dev tools` (`A`); also available via `Custom → S` (opt-in).
- Copies `statusline.js` verbatim to `~/.claude/plan2code-statusline.js` (single-file design, no bundling)
- Registers in `~/.claude/settings.json` under `statusLine` via atomic temp-file + rename write
- Preserves existing `statusline-config.json` on reinstall
- Detects non-plan2code custom `statusLine` configs — prompts before replacing; auto-backs up to `statusline-previous.json`
- Uninstall (`U`) removes bundled script + `settings.json` entry; preserves `statusline-config.json`. Only removes `settings.statusLine` if it points to the plan2code bundle — non-plan2code entries are left intact.
## v1.14.0
### ✨ Added
- **Review workflow (Step 3b)** — New `/plan2code-3b-review` command for comprehensive post-implementation code review
- 5-step process: scope detection, context analysis, 11-dimension review, spec/test assessment, summary with fix options
- Adaptive scope: focused (named files), branch (git diff), or full (subsystem) — auto-detected with user override
- 3 severity levels (Critical, Warning, Suggestion) with High-confidence-only findings
- Reference file architecture: orchestrator (≤11k chars) + 3 companion reference files loaded via Read directives
- Deep verification protocol with use-case tracing for architectural findings and adversarial self-check
- Detailed dimension checklists (8 non-obvious items per dimension with anti-patterns and "don't flag" guidance)
- False-positive catalog with detection shortcuts to prevent common false findings
- Finding verification gate — re-reads source at each cited line before presenting
- Mnemonic fix options: `H` (high-priority), `A` (all), `S` (specify by number)
- Post-fix Plan/Apply/Verify pipeline — enterprise-grade fix quality with full validation
- Doc review mode — >70% doc changes triggers editorial critique
- Graceful degradation for agents that can't read external files
- Spec-aware when `specs/` exists; works standalone for any codebase
- Context-aware session end with pipeline state detection
- Registered in installer for all 14+ platform destinations
- Installer copies reference directories for all 13+ platform targets
- Reference content inlined into TOML output (Gemini CLI) so platforms that cannot resolve runtime file reads still get full workflow depth
- Uninstall now removes orphaned `*-references/` directories even when prompt files were already removed manually
- Implement workflow session-end now suggests review after each phase
## v1.13.0
### 🔧 Changed
- **Simplified workflow naming convention** — All workflow and skill files unified to single-dash naming, eliminating double-dash (`--`) and triple-dash (`---`) conventions
- Renamed 8 source prompt files in `src/` (e.g., `plan2code---init.md` → `plan2code-init.md`, `plan2code-1--plan.md` → `plan2code-1-plan.md`)
- Updated `install.js` `SOURCE_PROMPTS` metadata and `generateFilename()` to emit single-dash names
- Updated all cross-references inside workflow prompt markdown content
- Updated documentation: `README.md`, `QUICK-REFERENCE.md`, `AGENTS.md`, `.agents-docs/AGENTS-architecture.md`
- Updated tooling references in `plan2code-loop/`, `plan2code-bot/`, and `plan2code-metrics/`
- Fixed pre-existing broken test assertion in `plan2code-bot` step-instructions test
- Repaired Windows-1252 / U+FFFD encoding artifacts (em-dashes) in `plan2code-loop` and `plan2code-bot` source files
### 🎁 Added
- **Devin platform support** — Added Devin to supported platforms list across `README.md`, `AGENTS.md`, `install.js` Agent Skills targets, `.agents-docs/AGENTS-development-commands.md`, and the `/plan2code-init` prompt
- **CLAUDE.md MANDATORY FIRST STEP template** — `/plan2code-init` and `/plan2code-init-update` now generate a CLAUDE.md template containing a `CRITICAL — MANDATORY FIRST STEP` directive that forces Claude Code to read AGENTS.md before responding to any user message
## v1.12.0
### 🔧 Changed
- **Resilient code references in workflow prompts** — Workflow prompts now explicitly guide AI agents to use semantic anchors (function names, class names, code patterns) instead of line numbers, which become stale as tasks modify files during implementation
- **Document mode** (`plan2code-2-document.md`) — New "Code references" block in Task Writing section lists four preferred anchor types with examples; line numbers allowed only as supplemental context
- **Revise-plan mode** (`plan2code-1b-revise-plan.md`) — Matching code reference rule added to Step 3 (Execute Revisions) so revised and new tasks follow the same convention
- **Implement mode** (`plan2code-3-implement.md`) — New "Verify locations" row in Code Consistency Rules table instructs agents to treat line numbers as approximate and locate by function/symbol name
## v1.11.1
### 🔧 Changed
- **Task complexity check in Document workflow** — Enhanced task writing guidance with lightweight cognitive complexity heuristics (inspired by PR #26)
- "Time-boxed" criterion now includes explicit split triggers: 5+ logic branches, 2+ integration points, or shared interface mutation
- New "Complexity check" prompt: before finalizing each task, LLM considers logic branches, distinct behaviors, integration points, shared interface impact, and error/edge cases
- Tasks complex on 3+ signals must be split; adjacent trivial tasks forming a cohesive unit should be combined
- Process step 7 updated to reinforce the complexity check during phase file authoring
## v1.11.0
### ✨ Added
- **plan2code-bot** — New autonomous workflow test runner (`plan2code-bot/`) that uses the Claude Agent SDK to simulate a human running the entire plan2code workflow end-to-end
- Two auto-detected modes: **new-project** (generates an app idea, creates a subdirectory, runs init through finalize) and **enhancement** (scans existing codebase, proposes a realistic enhancement)
- `--idea` flag to seed the idea generator with a specific concept
- `--resume` flag to continue incomplete runs from saved state — skips previously succeeded steps and restores idea, config, and implement pass counter
- State file (`.plan2code-bot-state.json`) saved after each step; automatically deleted on full success, preserved on failure for later resume
- Resume auto-detects state files in current directory (enhancement mode) or immediate subdirectories (new-project mode)
- Artifact validation after each step (aborts on missing expected outputs)
- **LLM-as-judge evaluation system** — Always-on quality assessment that transforms bot from "yes-man" to authentic QA agent
- **Intelligent decision making**: Uses LLM to answer `AskUserQuestion` prompts based on current observations (tools used, files created, errors) instead of hardcoded keyword matching
- **Post-step evaluation**: Comprehensive quality assessment after each step using step-specific criteria (score 0-100, strengths, weaknesses, suggestions, critical issues)
- **Observation tracking**: Full execution history captured (tools, files, messages, errors, questions with LLM reasoning)
- **Quality gate**: Blocks finalization if average score < 60, ensuring minimum quality standards
- **Evaluation artifacts**: Creates `BOT-EVALUATION.md` (quality assessments) and `BOT-NOTES.md` (execution observations) for metrics analysis
- **Color-coded output**: Green (≥85), yellow (70-84), red (<70) score display in console
- **Honest scoring**: Evaluation criteria emphasize realistic assessment (most work scores 70-85, not inflated)
- **Metrics-ready data**: Structured `EvaluationResult` and `ExecutionObservation` in state file for `plan2code-metrics` analysis
- Bot-friendly skill installation (copies plan2code skills with `disable-model-invocation` stripped)
- Implement step loops up to 10 passes until all phases are complete
- Installer integration: `C > B` menu option to install bot CLI only
## v1.10.0
### ✨ Added
- **Retry logic with escalating timeouts in loop controller** — Timed-out iterations now retry automatically instead of silently continuing
- Default base timeout reduced from 30 minutes to 3 minutes per attempt
- Up to 5 retry attempts per iteration (configurable via `maxRetries`)
- Each retry escalates timeout by +30 seconds (attempt 0 = base, attempt 1 = base + 30s, etc.)
- New `executeWithRetry()` method wraps `executeIteration()` with retry loop
- Fatal timeout (all attempts exhausted) stops the loop cleanly with a logged error
- Spinner displays elapsed seconds during each attempt; retries show attempt count
- `maxRetries` field added to `SessionConfig` and `DEFAULT_CONFIG`
### 🔧 Changed
- **Append-only scratchpad enforcement in loop prompt templates** — Both task-mode and phase-mode templates now explicitly prohibit editing or reorganizing existing scratchpad content
- Instruction changed from "append to scratchpad.md" to "add a new entry at the **bottom**"
- Added rule: "Never edit, reorganize, or insert into existing content — only append new entries to the end of the file"
- **AGENTS.md restructured into progressive discovery format** — AGENTS.md converted to a lightweight index with summaries and markdown links; full detail moved to `.agents-docs/` section files
- `.agents-docs/AGENTS-architecture.md` — Architecture overview and key design decisions
- `.agents-docs/AGENTS-code-style.md` — Code style conventions
- `.agents-docs/AGENTS-development-commands.md` — Development commands and setup
- `.agents-docs/AGENTS-plan2code-loop.md` — Loop CLI architecture and commands
- `.agents-docs/AGENTS-plan2code-metrics.md` — Metrics toolchain details
- `init-update` prompt updated with `.agents-docs/` detection in pre-flight check
- **Agents mode emoji updated** — Loop controller agents-mode indicator changed from wheel to hammer
## v1.9.1
### ✨ Added
- **Pi (pi.dev) platform support** — New target for the Pi terminal-based coding agent
- Local prompt templates installed to `.pi/prompts/` (flat `.md` with YAML `description` frontmatter)
- Global prompt templates installed to `~/.pi/agent/prompts/`
- Pi users already get skill support via existing `.agents/skills/` target; this adds native slash command access
- No new helper functions needed — Pi uses the same flat-file-with-YAML pattern as Windsurf, Copilot CLI, and Codeium
### 📚 Documentation
- `AGENTS.md` Platform-Specific File Formats table updated with Pi row
- `README.md` Supported Platforms list updated with Pi (pi.dev)
## v1.9.0
### ✨ Added
- **Progressive discovery for AGENTS.md** — Init and init-update prompts now generate AGENTS.md as a lightweight index with summaries and markdown links, plus `.agents-docs/` section files containing full detail
- **Init prompt** — New `## Progressive Discovery` section defines index format, always-inline sections (Project Overview, Git Commit Messages, How to Use This File), `.agents-docs/` directory setup, grouping heuristics, and opt-in restructure offer for existing single-file AGENTS.md
- **Init-update prompt** — `.agents-docs/` detection in pre-flight check, legacy migration offer, edit routing (inline sections → AGENTS.md, detailed sections → `.agents-docs/` files), section file lifecycle (create, delete, orphan cleanup), enhanced summary with file count, new update rule 9 (route edits to correct file)
- **Reference templates** updated in both prompts to include `.agents-docs/` in the bullet list
- **"How to Use This File"** added as a required content section in generated AGENTS.md files
## v1.8.2
### 🐛 Fixed
- **Inflated metrics task counts** — Metrics collector regex now matches only `**Task X.N:**` checkbox items instead of all checkboxes, fixing ~100-200% count inflation from prerequisite and acceptance criteria checkboxes
- `collectStep2` (`tasks_per_phase`) uses Task-pattern-only regex
- `collectStep3` (`phaseTotal`, `phaseCompleted`, `blockerCount`) all use Task-pattern-only regex
- Step 4 overview fallback left unchanged (correctly counts Phase Checklist checkboxes)
### 🔧 Changed
- **Document workflow** — Checkbox format `- [ ]` now restricted to Task items only; Prerequisites, Acceptance Criteria, and Success Criteria use plain bullet lists (no checkboxes)
- **Implement workflow** — Prerequisite verification changed from checkbox-based (`[x]`/`[?]`/`[!]`) to inline annotation approach (`VERIFIED`/`ASSUMED: [reason]`/`BLOCKED: [reason]`); added clarifying note that checkbox states apply to Task items and Phase Checklist only
- **Finalize workflow** — Task completion audit now specifies counting only `**Task X.N:**` checkbox items
- **Loop prompt templates** — Both task-mode and phase-mode templates updated: prerequisites use plain bullets with inline annotations instead of checkboxes; Checkbox States section scoped to "Task items only"
## v1.8.1
### ✨ Added
- **User feedback collection** — Optional 1-10 rating with reason, what went well, and what went poorly
- Finalize prompt (Step 5) asks for optional feedback before archival, writes structured table to `overview.md`
- Collector parses `## User Feedback` table from `overview.md` into `RunMetrics.user_feedback`
- Aggregator computes `avg_user_rating` and `feedback_count` per cohort
- CLI offers interactive feedback collection if none found during metrics collection
- Analysis and improvement prompts reference `avg_user_rating` metric target (≥ 7.0)
- `UserFeedback` type exported from public API
- **Pipe-safe feedback parsing** — User text containing `|` characters is escaped on write and correctly unescaped on parse using negative lookbehind regex
### 🐛 Fixed
- **Duplicate run files** — Interactive feedback no longer creates a second run JSON; the original is deleted before re-collecting
- **Finalize step ordering** — Feedback collection moved to Step 5 (before archival at Step 6), ensuring `overview.md` is written while still in the active spec directory
## v1.8.0
### ✨ Added
- **plan2code-metrics** — New recursive self-improvement toolchain for plan2code contributors (`plan2code-metrics/`)
- Fully interactive menu-driven CLI — no flags, all inputs collected via prompts
- **Collect** metrics from completed project specs (plan, document, implement, finalize steps)
- **Import** run data from other projects for cross-project aggregation
- **View** metrics status with health indicators and generation-over-generation deltas
- **Analyze** weak steps via AI-powered diagnosis (Claude Code or GitHub Copilot CLI)
- **Generate** surgical improvement proposals with automatic validation (char count limits, edit verification)
- **Review and apply** proposals with interactive diff review
- Cohort-based aggregation groups runs by prompt generation (SHA fingerprint of prompt files)
- Supports both Claude Code and GitHub Copilot CLI as AI backends
- Standalone TypeScript package with tsup build (ESM), installed via `npm link`
### 🔧 Changed
- **plan2code-4--finalize.md** — Added "Metrics Capture (Contributors)" note in Step 6 directing contributors to run `plan2code-metrics` after finalization
- **plan2code-loop index.ts** — Added dim hint "run plan2code-metrics" after session summary
## v1.7.0
### ✨ Added
- **4 new platform targets** — Gemini CLI, Crush, Amp, and OpenCode now supported
- Gemini CLI installs as TOML commands (`.gemini/commands/plan2code-*.toml`)
- Crush installs as skill subdirs (`~/.config/crush/skills/` on Unix, `%LOCALAPPDATA%\crush\skills\` on Windows)
- Amp and OpenCode covered via shared Agent Skills target (`.agents/skills/`)
- **Claude Code Skills format** — Migrated from flat `.claude/commands/*.md` to `.claude/skills/<skill-name>/SKILL.md` with `disable-model-invocation: true` frontmatter
- **Agent Skills cross-tool target** — Single `.agents/skills/` install covers Amp, Gemini CLI, and OpenCode simultaneously
- **Legacy cleanup** — Old `.claude/commands/plan2code-*.md` files automatically removed on install and uninstall
- **TOML generation** — New `generateTomlContent()` produces Gemini CLI command files using TOML literal multi-line strings
### 🔧 Changed
- `AGENTS.md` Platform-Specific File Formats table expanded to 5 columns with 4 new platform rows
- `docs/index.html` hero section updated with 4 new platform pills
- `README.md` Supported Platforms list updated with 4 new platforms
## v1.6.2
### 🔧 Changed
- **Installer menu simplified** — Replaced the 7-platform picker with a clean 4-option menu (I/U/C/Q)
- `I` — Install Plan2Code for all platforms + loop CLI
- `U` — Uninstall (with confirmation prompt)
- `C` — CUSTOM sub-menu: `L` (local install instructions), `O` (loop CLI only), `Q` (back)
- `Q` — Quit
- Any CLI arguments (e.g. `--dry-run`, `--platform`) are now silently ignored; installer always runs interactively
- **README installation section** — npx install method promoted to primary recommended install path; updated menu example
### 🗑️ Removed
- CLI flags `--dry-run`, `--platform`, `--local`, `--uninstall`, `--help`, `--loop`, `--uninstall-loop` (all removed; installer is always interactive)
- `displayHelp()` function removed from `install.js`
## v1.6.1
### ✨ Added
- **NPX installation support** - Team members can now install directly from GitHub without cloning
- Added `name`, `version`, and `bin` fields to `package.json` for npm compatibility
- Installation via `npx git+ssh://git@github.com/jparkerweb/plan2code.git` (SSH)
- Installation via `npx git+https://github.com/jparkerweb/plan2code.git` (HTTPS)
- Installer runs from temporary location and cleans up automatically
- Updated README.md with Quick Start section showing both authentication methods
- Added `.npmignore` file to suppress npm warnings during npx execution
## v1.6.0
### 🏎️ Improved
- **Reduced workflow file sizes** - All 4 over-target source prompts compressed to ≤ 11,000 characters for Windsurf IDE compatibility (12,000 char limit minus header buffer)
- `plan2code-3--implement.md` - 14,806 → 8,533 chars (42% reduction)
- `plan2code-1--plan.md` - 13,587 → 10,348 chars (24% reduction)
- `plan2code-4--finalize.md` - 12,012 → 8,586 chars (29% reduction)
- `plan2code-2--document.md` - 11,842 → 9,031 chars (24% reduction)
- All functional workflow behavior preserved
- Compression techniques: template-to-section-list specs, removed bad examples, consolidated redundant sections, simplified decorative boxes, imperative directives
### 🧪 Testing
- **Pre-commit character count validation** - Husky pre-commit hook prevents workflow files from exceeding 11,000 characters
- `scripts/validate-char-count.js` - Cross-platform Node.js validation script using only built-in modules
- `.husky/pre-commit` - Git hook trigger calling the validation script
- Root `package.json` with husky as sole devDependency (`private: true`)
- `.gitignore` updated with `node_modules/` and `package-lock.json`
## v1.5.4
### ✨ Added
- **AI Assisted commit attribution** - All git commit messages now include an `AI Assisted` footer for transparency
- **Init mode** - Generated AGENTS.md files include a Git Commit Messages section instructing agents to always append `AI Assisted`
- **Init-update mode** - New "Git Commit Messages" menu option (option 7) for adding or modifying commit message conventions
- **Loop task mode** - `createTaskCommit()` automatically appends `AI Assisted` footer to every commit
- **Loop phase mode** - Prompt template instructs LLM to include `-m "AI Assisted"` as final flag on every commit
- **Implement mode** - User-facing git commit suggestions after phase approval include `-m "AI Assisted"`
### 🔧 Changed
- **README loop install instructions** - Replaced inline text with formatted code block showing both install options
## v1.5.3
### ✨ Added
- **Loop mode selection** - Plan2Code Loop now asks users to choose between two loop modes:
- **One task per loop** (default) - Each agent invocation implements exactly one task. Node controller handles git commits after each task. Same behavior as before.
- **One phase per loop** - Each agent invocation implements all remaining tasks in the current phase. The LLM handles git commits after each task (with JIRA ticket ID). Ideal for related tasks and smart models with higher context windows.
- **Phase-mode prompt template** - New `LOOP_PROMPT_TEMPLATE_PHASE` instructs the LLM to complete all tasks in the current phase, create git commits per task, and output `TASK_COMPLETE` markers for each
- **Multi-marker completion detection** - New `checkForAllCompletions()` function parses all `TASK_COMPLETE`, `TASK_BLOCKED`, and `PREREQ_COMPLETE` markers from a single agent output
- **`PHASE_COMPLETE` marker** - New completion marker for phase mode indicating current phase is done (distinct from `LOOP_COMPLETE` which means all phases done)
- **`loopMode` config field** - New `SessionConfig.loopMode` field (`'task' | 'phase'`) persisted in session state for resume support
- **Documentation auto-discovery** - Documentation workflow now auto-discovers features to document
- Automatically finds `specs/*/PLAN-DRAFT-*.md` files
- If only one feature exists, uses it without prompting
- If multiple features exist, presents list and asks user to choose
- Automatically reads `PLAN-CONVERSATION-*.md` if present (optional, for context)
- **Documentation Verification Pass** - Documentation workflow now cross-references against PLAN-DRAFT before finalizing
- New Process Step 7 with sub-steps: 7A (re-read PLAN-DRAFT), 7B (cross-reference sections), 7C (fix gaps), 7D (output summary)
- New "Documentation Verification Pass" section with mapping table showing which PLAN-DRAFT sections to verify against which spec files
- Gap handling: Missing items added with `<!-- VERIFICATION: Added - FR-X from PLAN-DRAFT -->` markers
- Session end output now includes verification summary table showing Items in PLAN-DRAFT / Covered / Added per section
- Added reminders: "Always run verification pass before finalizing" and "PLAN-DRAFT is the source of truth"
- **Conversation Logging** - Planning workflow now saves the full planning conversation before creating PLAN-DRAFT
- New file: `specs/<feature-name>/PLAN-CONVERSATION-<YYYYMMDD>.md` created in Phase 7
- Contains full conversation transcript organized by phase with speaker attribution (`[AGENT]` vs `[USER RESPONSE]`)
- Decision summary tables with user quotes, confirmed requirements, approved technologies, and assumptions
- Serves as source of truth for plan verification
- **PLAN-DRAFT Verification Pass** - New STEP 7C verifies PLAN-DRAFT against conversation log
- Cross-references all requirements, tech decisions, risks, and assumptions
- Missing items added with `<!-- VERIFICATION: Added from Phase X -->` markers
- Outputs verification summary showing what was captured vs added
- **Conversation Log field in PLAN-DRAFT** - New header field links to the conversation log file
### 🔧 Changed
- **Installer default option** - Pressing Enter without selecting an option now defaults to `A` (Install to ALL platforms + loop CLI) instead of quitting
- **Planning output location changed** - PLAN-DRAFT and conversation log now created in feature subdirectory
- New location: `specs/<feature-name>/PLAN-DRAFT-<date>.md` and `specs/<feature-name>/PLAN-CONVERSATION-<date>.md`
- Date format: YYYYMMDD (e.g., `20250204`) instead of full timestamp
- Uppercase `PLAN-CONVERSATION` for consistency with `PLAN-DRAFT`
- Feature directory created during planning (Step 1) instead of documentation (Step 2)
- Documentation step no longer archives PLAN-DRAFT (already in correct location)
- **Planning Phase 7 restructured** - Now has three sub-steps:
- STEP 7A: Save Conversation Log (new)
- STEP 7B: Create PLAN-DRAFT (existing behavior, uses same timestamp)
- STEP 7C: Verification Pass (new)
- **Session End example updated** - Now shows both conversation log and PLAN-DRAFT files
- **Important Reminders expanded** - Added reminders about conversation log and verification pass
### 🐛 Fixed
- **`.gitignore` missing `specs/` entries in phase mode** - `ensureGitignore()` only ran inside `createTaskCommit()`, which is never called in phase mode. Moved `ensureGitRepo()` and `ensureGitignore()` to run once at startup in `Controller.run()` as a pre-flight step, ensuring `.gitignore` entries are set before the first iteration regardless of loop mode
## v1.5.2
### ✨ Added
- **AI Agent File Sync** - Init and Init-Update workflows now detect and sync other AI agent config files
- Detects 6 file types: CLAUDE.md, GEMINI.md, .cursorrules, .github/copilot-instructions.md, .cursor/rules/, .windsurf/rules/
- Offers to replace with references to AGENTS.md as single source of truth
- User confirmation required before any modifications
- Correct relative paths for each file location (./AGENTS.md, ../AGENTS.md, ../../AGENTS.md)
- **Knowledge Transfer** - Init mode now uses existing CLAUDE.md content as context when creating new AGENTS.md
- Preserves project knowledge during migration to AGENTS.md
## v1.5.1
### ✨ Added
- **Prerequisite verification workflow** - Agents now verify/complete prerequisites before starting phase tasks
- Implementation mode processes prerequisites in order: verify, complete, or mark assumed
- Loop prompt treats prerequisites as "Task 0.X" - one per iteration before tasks
- New completion markers: `PREREQ_COMPLETE` and `PREREQ_ASSUMED`
- **New checkbox state `[?]`** - "Assumed complete, couldn't verify" for prerequisites that can't be validated
- Use when prerequisite cannot be programmatically verified (e.g., "Design approved by stakeholder")
- Agents skip `[?]` items like `[x]` items
- **Re-opened phase handling in Revision mode** - Properly handle adding tasks to completed phases
- New "Re-opening" impact type (Medium-High risk) in impact assessment
- New tasks in completed phases get `🆕 ADDED` flag
- Phase checkbox changes from `[x]` to `[ ]` in overview.md when new tasks added
- "Phases Re-opened" section in revision summary
- Consistency check now verifies phase completion status matches task completion
### 🔧 Changed
- **Installer UI refresh** - Cleaner, narrower layout for better terminal compatibility
- Narrower menu boxes (65 characters instead of 76)
- Smaller mascot display at end of installation
- Added first-time user documentation link after successful install
- Updated menu descriptions to show "+ loop CLI" for relevant options
- **Planning workflow guardrails** - Prevent users from skipping the documentation step
- Added critical reminder after Phase 7 to direct to `/plan2code-2--document`
- Added workflow order reminder in Session End section: Plan → Document → Implement → Finalize
- Updated example closing message to emphasize documentation as next step
- Added workflow order to Important Reminders section
- **AGENTS.md pre-flight message** - Improved guidance for new projects
- Message now explains that new projects can continue without AGENTS.md
- Suggests creating basic AGENTS.md first with rules can still be valuable
## v1.5.0 - 2026-01-22
### ✨ Added
- **Plan2Code Loop** - New autonomous CLI tool for hands-off spec implementation
- Separate Node.js/TypeScript tool in `plan2code-loop/` directory
- LLM-driven task discovery - AI reads spec files and finds unchecked tasks
- Iterates through tasks one at a time, marking checkboxes as complete
- Structured completion markers: `TASK_COMPLETE: 1.1 - description`
- Session persistence with scratchpad and iteration logging
- Supports Claude Code and GitHub Copilot CLI agents
- **Installer integration** for loop CLI
- Option `A` now installs prompts to all platforms AND builds/links the loop CLI
- Option `O` builds and links plan2code-loop CLI only
- Option `U` uninstalls prompts AND unlinks the loop CLI
### 📝 Documentation
- Updated README.md with "Autonomous Loop" section explaining when to use loop vs manual Step 3
- Updated QUICK-REFERENCE.md with loop commands and decision tree
- Updated AGENTS.md with loop architecture, commands, and completion markers
## v1.4.0 - 2026-01-09
### ✨ Added
- **Parallel Phase Execution** - Run multiple implementation phases simultaneously in separate agent instances
- Documentation Mode auto-detects parallel-eligible phases based on file conflicts and dependencies
- Implementation Mode presents phase selection UI when parallel options are available
- New "Parallel Execution Groups" section in `overview.md` tracks which phases can run together
- Conflict detection criteria: file overlap, prerequisite dependencies, data/output dependencies, shared state
- Users can start multiple `/plan2code-3--implement` sessions to work on different parallel phases
- **In-Progress Phase Tracking** - Track which phases are actively being worked on
- New `[/]` checkbox status indicates a phase is in-progress (between `[ ]` pending and `[x]` complete)
- Phases marked `[/]` when an agent starts working, `[x]` when user approves completion
- Aborted phases stay `[/]` to enable resume - never reset back to `[ ]`
- Parallel selection UI shows `[IN PROGRESS]` vs `[AVAILABLE]` status for each phase
- Single in-progress phase prompts user to confirm resume (prevents accidental overlap)
- Supports multiple agent sessions on parallel phases with clear visibility of what's active
### 🔧 Changed
- **Documentation Mode process** - Added step 6 "Analyze phases for parallel execution eligibility"
- **Implementation Mode detection** - Now checks for parallel siblings before starting phase
- **Implementation Mode phase selection** - 4-case decision logic for parallel, resume, auto-start scenarios
- **Session end summaries** - Documentation Mode now reports parallel execution groups
- **Abort handling** - Phases remain `[/]` on abort with clear resume instructions
## v1.3.3 - 2025-12-30
### ✨ Added
- **Learning Capture Protocol** - Replaced simple "Session Hint" with structured learning capture
- Auto-capture triggers checklist (undocumented commands, gotchas, patterns, workarounds)
- Formatted capture template with category, learning, and context
- Inline `AGENTS.md` updates without requiring init-update mode switch
- Applied to Implementation (Step 3) and Finalize (Step 4) modes
### 🔧 Changed
- **Archive path includes timestamp** - Specs now archived to `specs--completed/<feature-name>-<timestamp>/`
- Prevents overwriting when re-implementing same feature
- Preserves history of multiple implementation attempts
- **Clearer session end instructions** - Planning mode (Step 1) now explicitly says "ALWAYS tell the user"
- **Simplified next command reference** - Removed "or equivalent" from next step instructions
## v1.3.2 - 2025-12-25
### 🔧 Changed
- **Phase file naming convention** - Changed from `Phase X.md` to `phase-X.md` (lowercase, hyphen instead of space)
- Affects generated spec files in `specs/<feature-name>/`
- Updated references in documentation, implementation, and finalization modes
- **PLAN-DRAFT auto-archiving** - Planning documents are now automatically archived without prompting
- Moves `specs/PLAN-DRAFT-<timestamp>.md` to `specs/<feature-name>/PLAN-DRAFT.md` after documentation step
- Removed user prompt asking to delete/archive/keep
### 📦 Updated
- Improved uniformity of Prompt files
## v1.3.1 - 2025-12-19
### ✨ Added
- **Init-update mode** (`/plan2code---init-update`) - Interactive workflow to update existing AGENTS.md files
- Detects recent work context and suggests relevant additions
- Menu-driven update options: Commands, Architecture, Gotchas, Testing, Environment, General Rules
- Review and prune options for existing content
- Confirms changes before applying
- Prefix: None (utility command)
- **Session hints** in Steps 2, 3, 4 - Prompts to run `/plan2code---init-update` after discovering project insights
- **AGENTS.md pre-flight check** in Quick Task and Planning modes
- Checks for `./AGENTS.md` at session start
- Offers to run `/plan2code---init` before continuing if not found
- **VS Code Copilot global support** - New platform for VS Code's custom prompts feature
- Files installed to platform-specific VS Code config directory:
- Windows: `%APPDATA%\Code\User\prompts\`
- macOS: `~/Library/Application Support/Code/User/prompts/`
- Linux: `~/.config/Code/User/prompts/`
- Uses VS Code custom prompt format with `agent: agent` header
- File extension: `.prompt.md`
- Platform ID: `vscode-copilot`
- **Dynamic path resolution in install.js** - Added helper functions for targets with platform-specific paths
- `getVSCodeCopilotDir()` - Returns correct VS Code config path per platform
- `resolveTargetDir()` - Handles both static and dynamic directory configurations
- `getDisplayPath()` - Returns human-readable path for display
### 🔧 Changed
- **install.js interactive menu** - Now shows 6 platforms (added VS Code Copilot)
- **Help text updated** - Valid platform IDs now include `vscode-copilot`
- **Merged `sync-prompts.js` into `install.js`** - Distribution files are now generated on-the-fly
- No longer need to run a separate sync script before installation
- `dist/` folder is now gitignored (generated dynamically)
- Removed `src/sync-prompts.js` (functionality merged into `install.js`)
- **Added `--local` option** - Show instructions for project-level (local) installation
- Generates `dist/local-commands/` and displays copy/paste instructions
- Available via `node install.js --local` or interactive menu option `L`
- **Updated interactive menu** - Added "L. LOCAL" option for local installation instructions
### 🗑️ Removed
- **`src/sync-prompts.js`** - No longer needed; functionality merged into `install.js`
- **`dist/` from version control** - Now generated dynamically during installation
## v1.3.0 - 2025-12-18
### ✨ Added
- **AGENTS.md Integration** - All workflow prompts now check for and follow project-specific agent instructions
- Added rule: "If a `./AGENTS.md` file exists, follow the rules, guidelines and documentation in it"
- Applied to Steps 1, 2, 3, and 4 (plan, document, implement, finalize)
- Enables project-specific customization while maintaining consistent workflow methodology
- **Init mode** (`/plan2code---init`) - New command to generate AGENTS.md files for projects
- Analyzes codebase structure and common development commands
- Extracts important details from existing docs (README, PROJECT.md, etc.)
- Creates focused, actionable guidance for AI agents (under 500 lines)
- Prefix: None (utility command)
### 🔧 Changed
- **Moved source prompts to `src/` directory** - Cleaner project structure separating source files from distribution
- All `plan2code-*.md` files now live in `src/`
- `sync-prompts.js` moved to `src/sync-prompts.js`
- Run with `node src/sync-prompts.js` (was `node sync-prompts.js`)
- `install.js` remains in project root
- **Sync script now cleans dist folders before syncing** - Ensures no orphaned files from previous syncs
- Deletes `dist/local-commands/` and `dist/global-commands/` before regenerating
- Prevents old/renamed files from lingering in distribution
- **Added `version.json`** - Centralized project metadata file
- Contains name, version, description, author, license, etc.
- Version displayed in install.js TUI header
- **Renamed Quick Task command** - `plan2code-0--quick-task` → `plan2code---quick-task`
- Removed number prefix for better categorization (utility/standalone mode)
- Maintains same functionality (lightweight planning for small tasks)
- **Renamed Revision command** - `plan2code-1b--revise` → `plan2code-1b--revise-plan`
- Clearer name indicating it revises planning specs
- Maintains same functionality (modify specs mid-implementation)
### 📚 Documentation
- Commands table updated to reflect new naming convention
- README.md updated with new command references and `src/` paths
- QUICK-REFERENCE.md updated with new command names
- CLAUDE.md updated with new development commands and file locations
- **Landing page updated** (`docs/index.html`)
- Added terminal UI screenshot showing the interactive installer
- Added code block with full installation steps (clone, cd, run)
## v1.2.1 - 2025-12-17
### 🔧 Changed
- **Reorganized distribution files into `dist/` folder** - Cleaner project structure separating source from generated files
- `local-commands/` → `dist/local-commands/`
- `global-commands/` → `dist/global-commands/`
- **Updated `sync-prompts.js`** - Now outputs to `dist/local-commands/` and `dist/global-commands/`
- **Updated `install.js`** - Now reads from `dist/global-commands/`
- **Simplified implement/finalize workflow** - Now only requires `overview.md` path instead of both `overview.md` and `Phase X.md`
- Auto-detects next uncompleted phase from Phase Checklist in overview.md
- Automatically reads corresponding `Phase X.md` file
- Reduces user friction when continuing between phases
- **Updated Next Steps sections** across all prompts to show simplified workflow
- Step 2 (Document): Now instructs to provide only `overview.md`
- Step 1b (Revise): Now instructs to provide only `overview.md`
- Step 3 (Implement): Session end boxes updated with auto-detect messaging
- Step 4 (Finalize): Incomplete implementation box updated
### 📚 Documentation
- Updated CLAUDE.md with new `dist/` paths for all references
- Updated README.md installation commands (30+ path references updated for both Unix and Windows)
- Updated QUICK-REFERENCE.md commands table (Steps 3 & 4 now show `overview.md` as input)
- Updated README.md workflow examples to show new `[Provide: overview.md]` pattern
- Updated README.md "What to Attach" table with simplified requirements
- Updated README.md troubleshooting section
## v1.2.0 - 2025-12-14
### ✨ Added
- **Quick Task mode** (`/plan2code-0--quick-task`) - Lightweight planning for small tasks that don't need the full 4-step workflow
- Standalone mode (doesn't create spec files)
- Conversational output with implementation plan
- **Scope validation** with thresholds (≤3 components, ≤2 integrations, ≤15 tasks, ≤8 files)
- **Escalation path** to full planning - creates PLAN-DRAFT and hands off to Step 1
- Prefix: `🚀`
- **Revision mode** (`/plan2code-1b--revise`) - Structured way to modify specs mid-implementation
- 5-step formal process: Change Analysis → Impact Assessment → Execute Revisions → Consistency Check → Summary
- Batch approval workflow
- Tracks revision history in overview.md
- Prefix: `🔄 [REVISION]`
- **Requirements Sign-Off gate** in Planning Phase 1 - User must explicitly approve requirements before Phase 2
- **Escalated PLAN-DRAFT recognition** - Planning mode detects and resumes from Quick Task escalations
- **Good/bad examples** added to Steps 1, 3, and 4 for clearer AI guidance
- **Clarification loop protocol** in Step 1 with max 3 rounds per phase
- **Devil's Advocate check** in Planning Phase 5 (Architecture Design)
- **Error recovery tables** in all prompts' Abort Handling sections
- **Quick Reference card** (`QUICK-REFERENCE.md`) for at-a-glance command reference
- **Revision reminders** in Step 3 completion messages
- **Copilot CLI global support** - Now installs to `~/.copilot/agents/` for global access
- **`install.js`** - New interactive installation script for global setup
- Interactive menu when run without arguments
- Select individual platforms (1-5), multiple (comma-separated), or ALL (A)
- Uninstall option (U) to remove installed files
- Non-interactive flags: `--platform X`, `--dry-run`, `--uninstall`
- **`local-commands/`** directory - Pre-formatted files for project installation
- **`global-commands/`** directory - Pre-formatted files for home directory installation
### 🔧 Changed
- **Standardized section headers** across all prompts:
- Role → Rules → Examples → Process → Templates → Session End → Abort Handling → Recovery → Important Reminders
- **Condensed templates** for token efficiency (~30% reduction in template verbosity)
- **`sync-prompts.js` restructured** - Now only writes to `local-commands/` and `global-commands/` (removed project root platform directories)
- **Removed platform directories from project root** - No longer syncs to `.claude/`, `.cursor/`, etc. in project root; users copy from `local-commands/` or `global-commands/` instead
- Updated README.md with Quick Reference section and new commands table
- Updated CLAUDE.md with new commands and response prefixes
### 📚 Documentation
- Added QUICK-REFERENCE.md with commands table, mode prefixes, file structure, and troubleshooting
- Expanded README.md workflow table to include Steps 0, 1b
- Updated all installation instructions to use `local-commands/` and `global-commands/`
- Added interactive mode documentation for `install.js`
- Documented Copilot CLI global installation at `~/.copilot/agents/`
## v1.1.1 - 2025-12-11
### 🔧 Changed
- **Phase approval prompt now uses ASCII box** - The "Reply approved" request during implementation sign-off now matches the visual style of other important prompts
- **Cursor: Switched from Rules to Commands** - Now uses `.cursor/commands/` (slash commands) instead of `.cursor/rules/` (MDC rules)
- Commands support global installation at `~/.cursor/commands/`
- Better aligns with how other tools handle workflows/slash commands
- **Archived specs folder renamed** - Changed from `specs/completed/` to `specs--completed/`
- Simplifies folder structure by avoiding nested directories
- Eliminates need for exclusion rules when searching `specs/`
### 📚 Documentation
- **Corrected global installation support** - Verified which tools actually support global installation:
- ✅ **Claude Code**: `~/.claude/commands/`
- ✅ **Cursor**: `~/.cursor/commands/` (commands, not rules)
- ✅ **Continue**: `~/.continue/prompts/`
- ✅ **Windsurf**: `~/.codeium/windsurf/global_workflows/`
- ❌ **GitHub Copilot**: Project-only (`.github/agents/` and `.github/prompts/`)
- ❌ **Antigravity**: Project-only (`.agent/workflows/`) - global path not well documented
- Updated Quick Start commands to only include tools that support global installation
- Added Windows-specific installation commands (PowerShell and Command Prompt)
- Added troubleshooting entry for unrecognized slash commands/workflows
## v1.1.0 - 2025-12-11
### ✨ Added
- **Testing Strategy support** - Optional testing preferences during planning phase
- Test types selection (Unit, Integration, E2E, or None)
- Phase testing option (run tests at end of each phase)
- Coverage target selection (Critical paths, Moderate, Comprehensive)
- Testing tasks automatically added to phase specs when enabled
- **User sign-off requirement** for implementation phases
- Phases marked "Ready for Sign-Off" instead of auto-completing
- User must reply "approved" before phase is marked complete
- Test failure handling: user chooses to fix, document, or investigate
- **Enhanced overview.md structure** - Now includes:
- Architecture Pattern and Component Overview sections
- Risks and Mitigations table
- Success Criteria checklist
- **Improved "Next Steps" formatting** - ASCII box format for clearer guidance at workflow transitions
### 🔧 Changed
- Implementation mode no longer auto-marks phases complete; requires explicit user approval
- Self-review checklist now includes test execution verification
- Completion report format updated to show test results table when applicable
- Spec auto-detection now explicitly excludes `specs--completed/` folder
### 📚 Documentation
- Added Testing Strategy section (2.4) to PLAN-DRAFT template
- Added Phase Testing task block template for phase specs
- Expanded special cases documentation for testing task generation
## v1.0.4 - 2025-12-07
### 📦 Updated
- Added explicit transition check to `Planning Phase 6` - when confidence >= 90%, the model now asks the user for confirmation before proceeding to create the PLAN-DRAFT document
## v1.0.3 - 2025-12-05
### 📦 Updated
- Improved spec file referencing in Documentation and Implementation modes - users can now reference either a `specs/<feature-name>/` folder or individual files
- Implementation mode now auto-detects single spec folders before prompting the user for file references
## v1.0.2 - 2025-12-05
### 🐛 Fixed
- Fixed pre-checked prerequisite checkbox in Phase template (`[x]` → `[ ]`) - generated phase documents no longer appear with prerequisites already complete
### 📦 Updated
- Added Session Start logic to Planning Mode - automatically detects and resumes from existing `PLAN-DRAFT-*.md` files
- Replaced vague scope indicators with measurable criteria (phases, requirements, components, integrations)
- Added Large Project checkpoint workflow - projects meeting Large thresholds now checkpoint at Phase 3 and resume in a new conversation
- Added output economy rule - keeps phase responses concise, reserving detailed schemas/APIs for final PLAN-DRAFT
- Updated PLAN-DRAFT template with new status options: `Draft | Phase 3 Complete - Resume at Phase 4 | Complete`
## v1.0.1 - 2025-12-05
### 📦 Updated
- Added Initial Context Check to `Planning Phase 1` - Model now asks about additional files, reference materials, and external integrations before
analyzing requirements
- Added user verification checklist and git checkpoint to `Implementation Phase 3` - Phase completion reports now guide users through verification and git checkpointing before starting the next phase
## v1.0.0 - 2025-12-04
### ✨ Added
- Initial 4-step workflow methodology for AI-assisted development
- Step 1: Planning mode with 90% confidence threshold
- Step 2: Documentation mode for structured implementation specs
- Step 3: Implementation mode with phase-by-phase execution
- Step 4: Finalization mode for validation and archiving
- Multi-platform support with pre-configured workflow files:
- Claude Code CLI (`.claude/commands/`)
- Cursor AI (`.cursor/rules/`)
- GitHub Copilot CLI (`.github/agents/`)
- VS Code Copilot (`.github/prompts/`)
- Windsurf IDE (`.windsurf/workflows/`)
- Google Antigravity (`.agent/workflows/`)
- Continue extension (`.continue/prompts/`)
- `sync-prompts.js` utility to propagate source prompts to all platform directories
+1
View File
@@ -0,0 +1 @@
Plan2Code, Copyright 2026 Justin Parker
-111
View File
@@ -1,111 +0,0 @@
# Plan2Code Quick Reference
## Commands
| Step | Command | Input | Output |
| ------ | ------------------------------- | --------------- | ----------------------------------- |
| Init | /plan2code-init | None | AGENTS.md file |
| Update | /plan2code-init-update | AGENTS.md | Updated AGENTS.md |
| 0 | /plan2code-quick-task | Requirements | Conversational plan |
| review | /plan2code-review | Scope guidance | Review findings + fixes |
| 1 | /plan2code-1-plan | Requirements | PLAN-CONVERSATION-<date>.md + PLAN-DRAFT-<date>.md |
| 1b | /plan2code-1b-revise-plan | Specs + changes | Updated specs |
| 2 | /plan2code-2-document | PLAN-DRAFT.md | overview.md + Phase files |
| 3 | /plan2code-3-implement | overview.md | Implemented code |
| 4 | /plan2code-4-finalize | overview.md | Archived specs |
## File Structure
```
specs/
└── <feature-name>/
├── PLAN-DRAFT-<date>.md # From Step 1 (verified plan)
├── PLAN-CONVERSATION-<date>.md # From Step 1 (conversation log)
├── overview.md # From Step 2
└── phase-X.md # From Step 2
specs--completed/ # After Step 4
└── <feature-name>/ # Archived specs
```
Note: `<date>` uses YYYYMMDD format (e.g., `20250204`)
## Key Rules
- Start NEW conversation for each step (and each implementation phase)
- ONE phase per conversation (but parallel phases can run in separate instances)
- Reply "approved" to complete phases
- 90% confidence required before planning completes
- Never look in `specs--completed/` (it's archived specs)
## Phase Status
| Checkbox | Status | Meaning |
|----------|--------|---------|
| `[ ]` | Pending | Not started |
| `[/]` | In Progress | Agent working (or paused) |
| `[x]` | Complete | Approved |
## Parallel Execution
When phases have no file conflicts or dependencies, they can run simultaneously:
1. Documentation Mode auto-detects parallel-eligible phases
2. Implementation Mode shows selection UI with status for each phase
3. Run multiple `/plan2code-3-implement` instances on different phases
4. `[/]` status shows which phases are actively being worked on
## Quick Troubleshooting
| Issue | Solution |
| ---------------------- | ------------------------------------------------- |
| Lost context mid-phase | Attach spec files, say "resume from Task X.Y" |
| Wrong phase started | Say "abort", start correct phase |
| Need to change plan | Use `/plan2code-1b-revise-plan` |
| Multiple spec folders | Specify which: "Continue with specs/user-auth/" |
| Need AGENTS.md file | Use `/plan2code-init` to generate one |
| Update AGENTS.md | Use `/plan2code-init-update` after sessions |
| Run phases in parallel | Check Parallel Execution Groups in overview.md |
## Workflow Decision
```
New to a project?
└── /plan2code-init → Generate AGENTS.md for project-specific guidance
Learned something during a session?
└── /plan2code-init-update → Add learnings to AGENTS.md
Is it a quick, small task?
├── Yes → /plan2code-quick-task (standalone)
└── No → /plan2code-1-plan (full workflow)
├── /plan2code-2-document
├── /plan2code-3-implement (repeat per phase)
│ └── OR: plan2code-loop (autonomous alternative)
└── /plan2code-4-finalize
Need to revise mid-implementation?
└── /plan2code-1b-revise-plan
```
## Autonomous Loop (Alternative)
The `plan2code-loop` CLI is an **alternative** to Step 3, not a replacement.
| Approach | Use When |
|----------|----------|
| `/plan2code-3-implement` | You want interactive control per phase |
| `plan2code-loop` | You want hands-off autonomous execution |
```bash
plan2code-loop # Fully interactive - auto-detects specs, prompts for options
```
### Loop Modes
| Mode | Description |
|------|-------------|
| **One task per loop** (default) | One task per agent invocation. Node handles git commits. |
| **One phase per loop** | All tasks in a phase per invocation. LLM handles git commits. Best for smart models with larger context. |
Session state stored per-spec in `specs/<feature>/.plan2code-loop/`
-553
View File
@@ -1,553 +0,0 @@
# Plan2Code: AI-Assisted Software Development Workflow
A structured 4-step workflow for developing features and projects with AI assistance. This methodology emphasizes thorough planning before implementation, ensuring well-documented, maintainable code.
<img src="docs/desk.jpg" alt="Plan2Code Workflow" height="275">
## Overview
```
🤔 📝 ⚡ 🧹
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Step 1 │ │ Step 2 │ │ Step 3 │ │ Step 4 │
│ PLAN │ --> │ DOCUMENT │ --> │ IMPLEMENT │ --> │ FINALIZE │
└─────────────────┘ └─────────────────┘ └─────────────────┘ └─────────────────┘
New Chat New Chat New Chat (per phase) New Chat
```
| Command | When to Use |
|----------------------------------|----------------------------------------------------------|
| `/plan2code-init` | Generate AGENTS.md file for new/existing projects |
| `/plan2code-init-update` | Update AGENTS.md with new learnings from coding sessions |
| `/plan2code-quick-task` | Small, quick tasks that don't need full workflow |
| `/plan2code-review` | Post-phase code review (after key features or milestones)|
| `/plan2code-1-plan` | Starting a new feature (full planning) |
| `/plan2code-1b-revise-plan` | Requirements change mid-implementation |
| `/plan2code-2-document` | After planning, create implementation specs |
| `/plan2code-3-implement` | Execute implementation (one phase per conversation) |
| `/plan2code-4-finalize` | All phases complete, ready to archive |
**Key Rules:**
- Start NEW conversation for each step (and each implementation phase)
- ONE phase per conversation
- Reply "approved" to complete phases
- 90% confidence required before planning completes
See [QUICK-REFERENCE.md](QUICK-REFERENCE.md) for full reference card.
---
## Installation
Plan2Code includes an interactive installer that generates and installs workflow files for all major AI coding assistants.
<img src="docs/install-script.jpg" width="600">
### Prerequisites
The install script requires **Node.js** (v14 or later). If you don't have Node.js installed:
1. Download from [nodejs.org](https://nodejs.org/) (recommended)
2. Or use a package manager:
- **macOS:** `brew install node`
- **Windows:** `winget install OpenJS.NodeJS` or `choco install nodejs`
- **Linux:** `sudo apt install nodejs` (Debian/Ubuntu) or `sudo dnf install nodejs` (Fedora)
### Supported Platforms
- Claude Code
- Cursor
- Windsurf
- Continue
- Codeium (IntelliJ)
- GitHub Copilot CLI
- VS Code GitHub Copilot
- Gemini CLI
- Crush
- Pi (pi.dev)
- Amp
- OpenCode
- Devin
- Zed
### Install via npx (Recommended — No Clone Required)
Run the interactive installer directly using `npx` with your preferred GitHub authentication method:
**If you use SSH keys:**
```bash
npx git+ssh://git@github.com/jparkerweb/plan2code.git
```
**If you use HTTPS authentication:**
```bash
npx git+https://github.com/jparkerweb/plan2code.git
```
This downloads the installer to a temporary location, runs it, installs the workflow files to your machine, and cleans up automatically. The installed workflows remain on your system and work independently. To update or reinstall, simply run the command again.
### Standard Installation (Clone Method)
#### No Clone Required
Run the interactive installer directly using `npx` with your preferred GitHub authentication method:
**If you use SSH keys:**
```bash
npx git+ssh://git@github.com/jparkerweb/plan2code.git
```
**If you use HTTPS authentication:**
```bash
npx git+https://github.com/jparkerweb/plan2code.git
```
This downloads the installer to a temporary location, runs it, installs the workflow files to your machine, and cleans up automatically. The installed workflows remain on your system and work independently. To update or reinstall, simply run the command again.
#### Standard Installation (Clone Method)
```bash
# Clone the repository
git clone https://github.com/jparkerweb/plan2code.git
cd plan2code
# Run the interactive installer
node install.js
# OPTIONAL: Install dev dependencies (ONLY if you plan to modify/contribute to Plan2Code)
npm install
```
The installer displays an interactive menu:
```
╔════════════════════════════════════════════════════════════════╗
║ INSTALL PLAN2CODE ║
╠════════════════════════════════════════════════════════════════╣
║ I. INSTALL Install Plan2Code for all platforms ║
║ U. UNINSTALL Remove Plan2Code files ║
║ C. CUSTOM Advanced options ║
║ Q. QUIT Exit ║
╚════════════════════════════════════════════════════════════════╝
SELECT OPTION (I, U, C, Q) [I]:
```
---
## Status Line — Claude CLI (Optional)
A persistent three-line status bar for Claude Code showing model, project, git branch, uncommitted diff stats, context usage, and plan quota. Included in `node install.js` → `A` (Install All + dev tools), or available individually via Custom → Status Line. See [src/statusline-claude/README.md](src/statusline-claude/README.md) for details.
---
## Important: Start Fresh Conversations
**Start a new conversation/chat session before each step.** This includes:
- Step 1: New conversation
- Step 2: New conversation
- Step 3: New conversation **for each phase** (Phase 1, Phase 2, etc.)
- Step 4: New conversation
Fresh conversations prevent context pollution and ensure the AI focuses on the current task with the relevant specifications.
---
## The Workflow Steps
### Step 1: Planning Mode 🤔
**Purpose:** Thoroughly analyze requirements and design the solution architecture before writing any code.
**AI Role:** Senior software architect and technical product manager
**Phases (completed one at a time):**
1. **Requirements Analysis** - Extract functional/non-functional requirements, identify ambiguities
2. **System Context Examination** - Review existing codebase, identify integration points
3. **Tech Stack** - Recommend and confirm all technologies (requires user sign-off)
4. **Architecture Design** - Propose patterns, define components, design interfaces/schemas
5. **Technical Specification** - Break down implementation phases, identify risks
6. **Transition Decision** - Finalize plan when confidence reaches 90%+
**Output:** `specs/<feature-name>/PLAN-DRAFT-<date>.md` and `specs/<feature-name>/PLAN-CONVERSATION-<date>.md` (date format: YYYYMMDD)
**Key Behaviors:**
- AI stops after each phase for clarification
- Must reach 90% confidence before finalizing
- All assumptions are documented
- User must approve tech stack decisions
---
### Step 2: Documentation Mode 📝
**Purpose:** Transform the planning output into structured, actionable implementation documents.
**Required Context:** Attach or reference the `specs/<feature-name>/PLAN-DRAFT-<date>.md` from Step 1 (or provide the planning conversation).
**Output Structure:**
```
specs/
└── <feature-name>/
├── overview.md # High-level overview with phase checkboxes and parallel groups
├── Phase 1.md # Detailed tasks for Phase 1
├── Phase 2.md # Detailed tasks for Phase 2
└── Phase N.md # ...additional phases
```
The `overview.md` includes a "Parallel Execution Groups" section that identifies which phases can be run simultaneously in separate agent instances.
**Document Format:**
- Each phase file contains detailed one-story-point tasks
- All tasks have checkboxes `[ ]` for progress tracking
- Each phase is self-contained (developer needs no prior context)
- Unit/E2E testing excluded unless explicitly requested
---
### Step 3: Implementation Mode ⚡
**Purpose:** Execute the implementation following the documented specifications.
**AI Role:** Senior software engineer
**Required Context:** Provide the path to `specs/<feature-name>/overview.md`. The command will auto-detect the next uncompleted phase and read the corresponding `Phase X.md` file automatically.
**Workflow:**
1. Identify the next uncompleted phase (unchecked in `overview.md`)
2. Check for parallel execution options (if phases can run simultaneously)
3. Implement ALL tasks in that phase exactly as specified
4. Update `Phase X.md` checkboxes as tasks complete `[x]`
5. Update `overview.md` phase checkbox when phase completes
6. Perform code review to ensure nothing was missed
7. Add completion summary to the phase document
**Parallel Execution:** If the next phase is part of a parallel-eligible group, you'll be prompted to choose which phase to implement. This allows running multiple agent instances simultaneously on different phases that don't conflict with each other.
**Key Rules:**
- **Start a new conversation for EACH phase**
- Work on ONE phase per conversation (unless told otherwise)
- Follow specifications EXACTLY as documented
- Keep checkboxes updated (enables progress tracking across sessions)
- Do NOT run tests unless specified in phase tasks
---
### Review Mode 🔬 (Optional)
**Purpose:** Comprehensive post-implementation code review with adaptive scope and spec compliance checking.
**AI Role:** Critical review specialist -- independent second opinion
**When to use:** After completing implementation phases, especially key features or milestones. Can be run after any phase, not just before finalization.
**What it does:**
1. Determines review scope — detects conversation context, user-specified scope, or gathers git changes as fallback
2. Understands context and determines review strategy
3. Analyzes across 11 dimensions (correctness, security, performance, spec compliance, etc.)
4. Generates findings ranked by severity (Critical, Warning, Suggestion)
5. Offers to fix issues, then provides commit guidance
**Key Behaviors:**
- Uses companion reference files for deep verification, detailed dimension checklists, and false-positive detection (loaded automatically during review)
- Reviews all changed files across 11 dimensions; prioritizes by risk when batches exceed 50 files
- Spec-aware when `specs/` exists; works standalone without specs
- Review phase is read-only; fixes only on user request with verification
---
### Step 4: Finalization Mode 🧹
**Purpose:** Validate implementation, create summaries, and archive documentation.
**Required Context:** Attach or reference the `specs/<feature-name>/` directory contents.
**Steps:**
1. **Validation** - Verify all tasks implemented correctly, check for issues
2. **Summary** - Document what was built and list all modified/created files
3. **Documentation Review** - Identify any needed README/CHANGELOG updates
4. **Spec Cleanup** - Move completed specs to `specs--completed/<implementation-name>/`
5. **Final Confirmation** - Confirm completion
---
## How to Use
After running `node install.js`, use the slash commands directly in your AI tool:
```
/plan2code-1-plan # Start planning a new feature
/plan2code-2-document # Create implementation docs from plan
/plan2code-3-implement # Begin/continue implementation
/plan2code-review # Post-phase code review (optional)
/plan2code-4-finalize # Wrap up after all phases complete
```
---
## Complete Workflow Example
### Starting a New Project
**Session 1 - Planning (New Chat):**
```
User: [Paste or invoke Step 1 prompt]
I want to build a REST API for a task management application.
AI: 🤔 [REQUIREMENTS ANALYSIS]
... asks clarifying questions, works through phases ...
AI: 🤔 [TRANSITION DECISION]
Confidence: 92%. Creating specs/task-api/PLAN-DRAFT-20250204.md...
```
**Session 2 - Documentation (New Chat):**
```
User: [Paste or invoke Step 2 prompt]
[Attach: specs/task-api/PLAN-DRAFT-20250204.md]
AI: 📝 [DOCUMENTATION]
Creating specs/task-api/overview.md...
Creating specs/task-api/Phase 1.md...
Creating specs/task-api/Phase 2.md...
...
```
**Session 3 - Implementation Phase 1 (New Chat):**
```
User: [Paste or invoke Step 3 prompt]
[Provide: specs/task-api/overview.md]
AI: ⚡ [PHASE 1: Project Setup]
(Auto-detected Phase 1 as next uncompleted phase)
Implementing tasks...
✓ Phase 1 complete. Updated checkboxes in Phase 1.md and overview.md.
```
**Session 4 - Implementation Phase 2 (New Chat):**
```
User: [Paste or invoke Step 3 prompt]
[Provide: specs/task-api/overview.md]
AI: ⚡ [PHASE 2: Database Models]
(Auto-detected Phase 2 as next uncompleted phase)
Implementing tasks...
✓ Phase 2 complete. Updated checkboxes in Phase 2.md and overview.md.
```
**Sessions 5-N - Continue Implementation (New Chat for each phase):**
```
... repeat for each remaining phase ...
```
**Final Session - Finalization (New Chat):**
```
User: [Paste or invoke Step 4 prompt]
[Provide: specs/task-api/overview.md]
AI: 🧹 [VALIDATION]
Verifying implementation...
AI: 🧹 [SPEC CLEANUP]
Moving to specs--completed/task-api/
Implementation complete!
```
---
## Progress Tracking
The checkbox system enables seamless progress tracking across multiple sessions:
**Phase Status (overview.md):**
| Checkbox | Status | Meaning |
|----------|--------|---------|
| `[ ]` | Pending | Not yet started |
| `[/]` | In Progress | Agent actively working (or paused/aborted) |
| `[x]` | Complete | Finished and approved |
```markdown
## Phases
- [x] Phase 1: Project Setup
- [x] Phase 2: Database Models
- [/] Phase 3: API Endpoints <- In progress (agent working)
- [ ] Phase 4: Authentication <- Next available
```
**Task Status (phase-X.md):**
```markdown
## Tasks
- [x] Create routes file
- [x] Implement GET /tasks
- [ ] Implement POST /tasks <- Current task
- [ ] Implement PUT /tasks/:id
- [ ] Implement DELETE /tasks/:id
```
The `[/]` status enables parallel execution - multiple agents can work on different phases simultaneously, and you can see which phases are actively being worked on.
---
## Best Practices
1. **Start fresh conversations** - New chat for each step and each implementation phase
2. **Always attach specs** - The AI needs the spec files to understand the current state
3. **Don't skip planning** - The upfront investment prevents costly rework later
4. **Confirm tech stack** - Ensure AI gets explicit approval before architecture design
5. **One phase at a time** - Keeps conversations focused and manageable
6. **Update checkboxes immediately** - Maintains accurate progress state
7. **Review phase output** - Verify each phase before moving to the next
8. **Keep spec files** - The completed folder serves as project documentation
---
## What to Attach at Each Step
| Step | Required Input |
| ------------------ | ---------------------------------------------------- |
| Step 1 (Plan) | None (describe your feature/project) |
| Step 2 (Document) | `specs/<feature>/PLAN-DRAFT-<date>.md` or planning conversation |
| Step 3 (Implement) | `specs/<feature>/overview.md` (auto-detects phase) |
| Review (Optional) | Scope guidance (e.g., "review last 2 phases", "just the auth module", "whole PR"). Auto-detects changes and specs if no scope given. |
| Step 4 (Finalize) | `specs/<feature>/overview.md` |
---
## Autonomous Loop (Alternative to Step 3)
For hands-off implementation, Plan2Code includes an optional autonomous loop CLI that iterates through your spec tasks automatically.
> **Note:** The loop is an **alternative** to `/plan2code-3-implement`, not a replacement. Use the manual Step 3 workflow when you want direct control over each phase, or use the loop when you prefer autonomous execution.
### When to Use Each
| Approach | Best For |
|----------|----------|
| `/plan2code-3-implement` | Interactive control, reviewing each phase, complex logic requiring human judgment |
| `plan2code-loop` | Straightforward implementations, batch processing, overnight runs |
### Installing the Loop
```bash
# From the plan2code root directory:
# Option 1: Install everything (recommended)
node install.js # Select I at the menu
# Option 2: Install loop only
node install.js # Select C, then O at the menu
```
### Using the Loop
```bash
# Run the loop - fully interactive
plan2code-loop
```
The CLI will:
1. Auto-detect specs in `./specs/` directory
2. Let you select a spec if multiple are found
3. Prompt to continue if an existing session is found
4. Ask for JIRA ticket ID, agent selection, loop mode, and max iterations
### Loop Modes
| Mode | Behavior | Git Commits | Best For |
|------|----------|-------------|----------|
| **One task per loop** (default) | Each agent call implements one task | Node controller commits after each task | Smaller models, cautious execution |
| **One phase per loop** | Each agent call implements all tasks in a phase | LLM commits after each task (with JIRA ID) | Smart models with larger context windows, related tasks |
Session state is stored per-spec in `specs/<feature>/.plan2code-loop/`, keeping each feature's progress isolated.
The loop will:
1. Read your `overview.md` and phase files
2. Find the first unchecked task (or phase, in phase mode)
3. Implement it and mark the checkbox complete
4. Repeat until all tasks are done or max iterations reached
See [plan2code-loop/](plan2code-loop/) for full documentation.
---
## File Structure After Complete Implementation
```
your-project/
├── specs/
│ └── another-feature/ # In-progress feature
│ ├── overview.md
│ └── Phase 1.md
├── specs--completed/
│ └── feature-name/
│ ├── overview.md # Archived with completion summary
│ ├── Phase 1.md # All checkboxes marked [x]
│ ├── Phase 2.md
│ └── ...
├── your project files...
└── README.md
```
---
## Customization
Feel free to modify these prompts to fit your workflow:
- **Add testing phases** - Uncomment/add testing requirements in Step 2
- **Adjust confidence threshold** - Change the 90% threshold in Step 1
- **Modify output structure** - Customize the specs folder organization
- **Add code review steps** - Enhance Step 3 with additional review gates
---
## Troubleshooting
**Slash commands/workflows not recognized:**
- Ensure you ran `node install.js` and selected the appropriate platform
- Restart your AI tool after installation
- For per-project installation, ensure the directory isn't in `.gitignore`
**AI jumps ahead to implementation during planning:**
- The prompts explicitly forbid this, but if it happens, remind the AI: "Stay in planning mode. Do not write code yet."
**AI doesn't know what to implement:**
- Make sure you provided the path to `overview.md`
- The AI will auto-detect the next phase and read the corresponding `Phase X.md` file
**Lost progress between sessions:**
- Check `overview.md` for phase status
- Review individual phase files for task completion status
**AI not following spec exactly:**
- Reference the specific phase document and ask it to re-read the requirements
**Too many/few phases:**
- Adjust during Step 2 (Documentation) - phases should represent logical groupings of work
-1
View File
@@ -1 +0,0 @@
plan2code.jparkerweb.com
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 185 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

-1227
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

+3350 -1520
View File
File diff suppressed because it is too large. Load diff
+19 -5
View File
@@ -1,15 +1,29 @@
{ {
"name": "plan2code", "name": "plan2code",
"version": "1.15.4", "version": "3.2.5",
"private": true, "private": true,
"license": "Apache-2.0",
"engines": {
"node": ">=18"
},
"bin": { "bin": {
"plan2code": "./install.js" "plan2code-install": "./install.js"
}, },
"scripts": { "scripts": {
"prepare": "husky", "setup:hooks": "husky",
"test": "node scripts/validate-char-count.js" "build:skills": "node install.js --build-skills",
"fix:eol": "node scripts/fix-line-endings.mjs",
"set-version": "node scripts/set-version.mjs",
"play": "node scripts/play.mjs",
"pretest": "node scripts/fix-line-endings.mjs",
"test:fast": "node scripts/test-fast.mjs",
"test:page": "node scripts/run-page-tests.mjs",
"test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-agent-lookup.mjs scripts/test-agents-file.mjs scripts/test-app-meter.mjs scripts/test-browser-helper.mjs scripts/test-check-console-openings.mjs scripts/test-check-doc-size.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-test-lanes.mjs scripts/test-check-versions.mjs scripts/test-console-stub.mjs scripts/test-console-wire-budgets.mjs scripts/test-getting-started.mjs scripts/test-git-repo.mjs scripts/test-install-bench.mjs scripts/test-install-e2e.mjs scripts/test-install-refs.mjs scripts/test-install-update.mjs scripts/test-launcher.mjs scripts/test-line-endings.mjs scripts/test-publish-install-refs.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-script-coverage.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-finalize.mjs scripts/test-script-git.mjs scripts/test-script-lessons.mjs scripts/test-script-pathfinder.mjs scripts/test-script-pr-prep.mjs scripts/test-script-run-check.mjs scripts/test-script-test-commands.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-xray.mjs scripts/test-set-version.mjs scripts/test-skill-scripts.mjs scripts/test-skill-test-runs.mjs scripts/test-spec-carry-page.mjs scripts/test-spec-carry.mjs scripts/test-standalone-check.mjs scripts/test-ui-prototype-page.mjs scripts/test-us-english.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-card-rows.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-git.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-notepad.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-review-loop.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-setup.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-shape.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-source.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-workspace.mjs",
"test:games": "node scripts/node-test.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-page-activities.mjs"
}, },
"devDependencies": { "devDependencies": {
"husky": "^9.0.0" "gpt-tokenizer": "2.9.0",
"husky": "^9.0.0",
"playwright-core": "1.64.1"
} }
} }
-49
View File
@@ -1,49 +0,0 @@
# Changelog
## 1.1.0
### Resume support
- Add `--resume` flag to continue incomplete runs from saved state
- Skip previously succeeded steps when resuming (init, plan, document, implement, finalize)
- Restore idea name, description, project directory, and implement pass counter from state
- Auto-detect state files in current directory (enhancement mode) or subdirectories (new-project mode)
- Delete state file automatically after a fully successful run
- Preserve state file on failure for later resume
- Add `deleteState()` and `findExistingState()` utilities to bot-state module
- Add bot-state unit tests (saveState, loadState, deleteState, findExistingState)
### Idea generation improvements
- Expand idea categories from binary CLI/web-app coin flip to 12 diverse categories (games, dashboards, browser extensions, desktop utilities, etc.)
- Add guidance to avoid defaulting to developer-centric tools (git analyzers, code formatters)
- Strengthen `--idea` seed clause so the LLM stays aligned with the user's theme instead of ignoring it
- Update system prompt to encourage creative, cross-domain ideas
### Init step overhaul (new projects)
- Init now creates a minimal AGENTS.md stub (name, description, status) instead of running the full `/plan2code-init` skill
- Prevents hallucinated architecture, commands, and `.agents-docs/` files before the plan step runs
- Init evaluation criteria updated to reward minimalism and penalize premature detail
### Implement step overhaul
- Implement step now works directly with Read/Write/Edit/Glob/Grep tools instead of delegating to Skill sub-session
- Inlined step-by-step process: find specs, pick phase, implement tasks, mark checkboxes
- Fixes issue where Skill sub-sessions did all work invisibly, causing zero tool observations
### Observation tracking fix
- Capture `tool_use` blocks from the assistant message stream in session-runner as a fallback when `canUseTool` callback doesn't fire
- Add deduplication in ObservationCollector to prevent double-counting from both sources
- Fixes all steps reporting 0 tools used / 0 files created in BOT-NOTES and evaluations
### Evaluator improvements
- Increase evaluator `maxTurns` from 3 to 30 so it has room for tool calls before producing the scored response
- Add warning log when evaluation parser can't find SCORE in output (was silently defaulting to 50)
## 1.0.0
- Initial release
- Two auto-detected modes: new-project and enhancement
- `--idea` flag to seed the idea generator
- Full workflow execution: init → plan → document → implement → finalize
- Artifact validation after each step
- State persistence to `.plan2code-bot-state.json`
- Auto-responder for autonomous Claude Agent SDK sessions
- Bot-friendly skill installation (strips `disable-model-invocation`)
-234
View File
@@ -1,234 +0,0 @@
# LLM-as-Judge Evaluation System
## Overview
The plan2code-bot now includes an **always-on LLM-as-judge evaluation system** that transforms it from a "yes-man" into an authentic QA agent. This provides realistic quality signals for `plan2code-metrics` to analyze and drive recursive self-improvement.
## Key Features
### 1. Intelligent Decision Making (Real-Time)
**What:** During execution, when `AskUserQuestion` is called, the bot uses an LLM to make thoughtful decisions based on current observations.
**How it works:**
- Collects observations up to the current point (tools used, files created, errors)
- Queries LLM with context: "Given what you've seen, should you approve this plan?"
- LLM inspects current artifacts using Read/Glob/Grep
- Returns evidence-based answer with reasoning
- All decisions are recorded for metrics analysis
**Example:**
```
Question: "Approve this plan?"
Observations: Created PLAN-DRAFT.md, 3 phases, 42s duration, no errors
LLM reads PLAN-DRAFT.md, evaluates quality
LLM decides: "Yes, approve - phases are well-scoped and realistic"
```
### 2. Post-Step Evaluation
**What:** After each step completes, the bot evaluates quality using step-specific criteria.
**How it works:**
- Collects complete execution observations
- Queries LLM with evaluation criteria for the step
- LLM inspects final artifacts
- Returns structured evaluation (score, strengths, weaknesses, suggestions)
- Writes `specs/<feature>/BOT-EVALUATION.md` and `specs/<feature>/BOT-NOTES.md` (falls back to project root if no spec folder exists yet, e.g. during `init`)
**Example output:**
```markdown
# Evaluation: plan Step
**Score:** 78/100
## Strengths
- Clear phase breakdown with realistic scope
- Tech stack choices appropriate
## Weaknesses
- Phase 3 description too vague
- No testing strategy mentioned
## Suggestions
- Expand Phase 3 with concrete tasks
- Add explicit testing phase
```
### 3. Quality Gate
**What:** Before finalize, checks that average quality score is acceptable.
**How it works:**
- Calculates average score across all evaluated steps
- If average < 60, blocks finalization
- Displays clear message about quality issues
- User must review `specs/<feature>/BOT-EVALUATION.md` and fix problems
## Files Created
### New Files
1. **`src/observation-collector.ts`**
- Tracks execution details (tools, files, messages, errors, questions)
- Provides snapshots for real-time decisions
- Captures complete history for evaluation
2. **`src/intelligent-responder.ts`**
- Replaces hardcoded auto-responder
- Uses LLM to answer AskUserQuestion prompts
- Provides reasoning for all decisions
- Falls back gracefully if LLM unavailable
3. **`src/prompts/evaluation-criteria.ts`**
- Step-specific evaluation criteria (init, plan, document, implement, finalize)
- Quality checks, common pitfalls, scoring guidance
- Emphasizes honest scoring (most work should score 70-85)
4. **`src/evaluator.ts`**
- Post-step evaluation using LLM-as-judge
- Queries LLM with observations and criteria
- Parses structured evaluation output
- Writes `specs/<feature>/BOT-EVALUATION.md` and `specs/<feature>/BOT-NOTES.md`
### Modified Files
1. **`src/types.ts`**
- Added interfaces: `ToolObservation`, `QuestionContext`, `ExecutionObservation`, `EvaluationResult`
- Extended `StepResult` with `evaluation` and `observations` fields
2. **`src/session-runner.ts`**
- Added `collector` parameter to `SessionOptions`
- Returns `observations` in `SessionResult`
- Records all messages for observation tracking
- Uses intelligent responder instead of auto-responder
3. **`src/cli.ts`**
- Creates `ObservationCollector` for each step
- Always runs evaluation after successful steps
- Displays scores with color coding (green/yellow/red)
- Implements quality gate before finalize
- Shows evaluation summary in step output
4. **`src/bin/plan2code-bot.ts`**
- Updated help text to mention LLM-as-judge evaluation
- No new CLI flags (evaluation is always on)
### Deleted Files
1. **`src/auto-responder.ts`** - Replaced by intelligent-responder.ts
2. **`src/auto-responder.test.ts`** - No longer needed
## Output Files (Created During Execution)
Both files are written to `specs/<feature>/` so they stay co-located with the feature they describe. If no spec folder exists yet (e.g. during `init`), they fall back to the project root.
### BOT-EVALUATION.md
Contains evaluation results for each step:
- Score (0-100)
- Strengths identified
- Weaknesses found
- Suggestions for improvement
- Critical issues (if any)
- Full reasoning from LLM
### BOT-NOTES.md
Contains execution observations:
- Duration, tool counts, file changes
- Questions asked and LLM reasoning for answers
- Tool usage timeline
- Files created/modified
- Assistant output summary
## Data Structure for Metrics
All evaluation data is structured in `StepResult`:
```typescript
{
step: 'plan',
success: true,
duration: 42000,
evaluation: {
score: 78,
strengths: ["Clear phases", "Realistic scope"],
weaknesses: ["Phase 3 too vague"],
suggestions: ["Add specific tasks to Phase 3"],
criticalIssues: [],
reasoning: "...",
timestamp: 1234567890,
evaluatorModel: 'claude-sonnet-4-5'
},
observations: {
tools: [{ toolName, input, output, timestamp }, ...],
questionsAsked: [
{
question: "Approve plan?",
selectedAnswer: "Yes, approve",
llmReasoning: "Phases are well-scoped...",
timestamp: 1234567890
}
],
filesCreated: [...],
filesModified: [...],
errors: []
}
}
```
## Benefits for Recursive Improvement
1. **Authentic Signals:** Real quality scores identify actual problem areas
2. **Detailed Context:** Observations + reasoning explain WHY failures happen
3. **Correlation Analysis:** Link patterns (tool usage, duration, errors) to quality
4. **Continuous Loop:** Better metrics → improved workflows → higher scores → repeat
## Usage
No special flags needed - evaluation is always on:
```bash
# New project
plan2code-bot --idea "todo app"
# Enhancement
cd my-project && plan2code-bot
# Resume with evaluation data preserved
plan2code-bot --resume
```
## Verification
After running the bot, check:
1. **`specs/<feature>/BOT-EVALUATION.md`** - Should show realistic scores (not all 100s)
2. **`specs/<feature>/BOT-NOTES.md`** - Should show LLM reasoning for decisions
3. **Console output** - Should display color-coded scores after each step
4. **State file** (`.plan2code-bot-state.json`) - Should include evaluation data
## Trade-offs
### Latency
- Adds ~2-3s per AskUserQuestion call (~15-20s total per run)
- Worth it for authentic evaluation
### Token Cost
- ~20-26K tokens per run (~$0.60 with Opus 4.6)
- Investment pays off through metrics-driven improvement
### Determinism
- LLM decisions vary between runs (non-deterministic)
- Realistic - humans vary too
- Metrics average over many runs
## Future Enhancements
Potential improvements:
- Model selection per step (use Haiku for simple decisions)
- Configurable quality gate threshold
- Historical score tracking across runs
- Comparison with previous evaluations
- More sophisticated scoring (weighted by step importance)
-111
View File
@@ -1,111 +0,0 @@
# plan2code-bot
Autonomous workflow test runner for plan2code. Uses the Claude Agent SDK to simulate a human running through the entire plan2code workflow (init, plan, document, implement, finalize) end-to-end.
## Two Modes (Auto-Detected)
1. **New Project Mode** — No `AGENTS.md` in cwd: generates an app idea, creates a subdirectory, writes IDEA.md, runs init, then all 4 steps.
2. **Enhancement Mode** — `AGENTS.md` exists in cwd: scans the existing codebase and proposes a realistic enhancement, writes IDEA.md, then runs plan through finalize.
## Installation
From the plan2code root:
```bash
node install.js
# Select C > B to install bot only, or I to install everything
```
Or manually:
```bash
cd plan2code-bot
npm install
npm run build
npm link
```
## Usage
```bash
# New project mode (run from an empty directory)
mkdir /tmp/test-bot && cd /tmp/test-bot
plan2code-bot
# Enhancement mode (run from an existing project with AGENTS.md)
cd my-project
plan2code-bot
# Seed the idea generator with a specific concept
plan2code-bot --idea "web app that displays the current weather as vector images"
# Resume a previous incomplete run
plan2code-bot --resume
```
### `--idea`
Pass a quoted string after `--idea` to seed the idea generator with a specific concept. The AI will use it as inspiration rather than generating a completely random idea. Wrap the value in double quotes so the shell treats it as a single argument.
```bash
# Specific app concept
plan2code-bot --idea "web app that displays the current weather as vector images"
# Short keyword to nudge the category
plan2code-bot --idea "markdown editor"
# Detailed constraint
plan2code-bot --idea "CLI tool that converts CSV files to SQLite databases with type inference"
# Works in enhancement mode too — guides what kind of enhancement to propose
cd my-existing-project
plan2code-bot --idea "add dark mode support"
```
Without `--idea`, the bot picks a random category (CLI tool or web app) and invents something on its own.
### `--resume`
Resume a previous incomplete run. The bot searches for a `.plan2code-bot-state.json` file in the current directory (enhancement mode) or in immediate subdirectories (new-project mode). If found, it restores the idea, config, and progress — skipping steps that already succeeded and continuing from where it left off.
```bash
# A run failed at the implement step — resume it
plan2code-bot --resume
# Can combine with --idea (idea is ignored when resuming since it's restored from state)
plan2code-bot --resume --idea "ignored when state exists"
```
If no state file is found, the bot starts a fresh run.
## How It Works
1. Detects mode based on presence of `AGENTS.md`
2. Generates an idea (new app or enhancement) via Claude, optionally guided by `--idea` seed
3. Writes `IDEA.md` to the project directory
4. Installs bot-friendly copies of plan2code skills (strips `disable-model-invocation` so sessions can invoke them)
5. Runs each workflow step as a separate Claude Agent SDK session:
- **init** — generates `AGENTS.md` (new-project mode only)
- **plan** — creates plan draft in `specs/<feature>/`
- **document** — produces `overview.md` and `phase-*.md` files
- **implement** — loops until all phases are complete (max 10 passes)
- **finalize** — validates and archives to `specs--completed/`
6. Validates expected artifacts after each step (aborts on missing artifacts)
7. Moves `IDEA.md` into `specs/<feature>/` after the plan step so it stays with its feature
8. Auto-responds to `AskUserQuestion` prompts (approvals, testing gates, name questions)
9. Saves state to `.plan2code-bot-state.json` after each step
## State File
After each step, the bot saves its state to `.plan2code-bot-state.json` in the project directory. This includes the config, all step results, and progress tracking.
- **On full success** — the state file is automatically deleted (clean finish)
- **On failure/incomplete** — the state file is preserved so you can `--resume` later
## Development
```bash
npm run build # Build with tsup
npm run dev # Watch mode
npm test # Run tests (vitest)
```
-36
View File
@@ -1,36 +0,0 @@
{
"name": "plan2code-bot",
"version": "1.1.0",
"description": "Plan2Code Bot - Autonomous workflow runner for testing plan2code end-to-end",
"type": "module",
"main": "dist/index.js",
"bin": {
"plan2code-bot": "./dist/bin/plan2code-bot.js"
},
"files": [
"dist"
],
"engines": {
"node": ">=18.0.0"
},
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"start": "node dist/bin/plan2code-bot.js",
"test": "vitest run",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.63",
"chalk": "^5.6.2",
"fs-extra": "^11.3.3",
"ora": "^9.0.0"
},
"devDependencies": {
"@types/fs-extra": "^11.0.4",
"@types/node": "^25.0.3",
"tsup": "^8.5.1",
"typescript": "^5.9.3",
"vitest": "^4.0.18"
}
}
-116
View File
@@ -1,116 +0,0 @@
import { runCLI } from '../cli.js';
function showHelp(): void {
console.log(`
+----------------------------------------------------------------+
— PLAN2CODEDE-BOT —
—----------------------------------------------------------------—
— Autonomous workflow test runner foplan2codede —
— Features LLM-as-judge for honest quality evaluation —
+----------------------------------------------------------------+
Usage:
plan2code-bot [options]
Options:
--help Show this help message
--idea <string> Seed the idea generator with a specific concept
Example: --idea "web app for weather"
Example: --idea="CLI tool for CSV conversion"
--resume Resume a previous incomplete run
Modes:
— New Project Mode - Run from empty directory
The bot generates an app idea, creates a subdirectory, writes
IDEA.md, runs init, then all 4 workflow steps.
— Enhancement Mode - Run from directory with AGENTS.md
The bot scans the existing codebase, proposes an enhancement,
writes IDEA.md, then runs plan through finalize.
Evaluation:
The bot acts as an authentic QA agent, using LLM-based decision
making during execution and providing honest quality assessments
after each step. Results are written to specs/<feature>/BOT-EVALUATION.md
and specs/<feature>/BOT-NOTES.md for metrics analysis.
Examples:
# New project (from empty directory)
plan2code-bot
# Enhancement (from existing project)
cd my-project && plan2code-bot
# With specific idea
plan2code-bot --idea "markdown editor with live preview"
# Resume incomplete run
plan2code-bot --resume
Documentation:
https://jparkerweb.github.io/plan2code
`);
}
function stripQuotes(str: string): string {
// Remove surrounding quotes if present (both single and double)
if ((str.startsWith('"') && str.endsWith('"')) ||
(str.startsWith("'") && str.endsWith("'"))) {
return str.slice(1, -1);
}
return str;
}
function parseArgs(): { idea?: string; resume?: boolean; help?: boolean } {
const args = process.argv.slice(2);
// Check for --help
if (args.includes('--help') || args.includes('-h')) {
return { help: true };
}
// Parse --idea (supports both --idea="value" and --idea "value")
let idea: string | undefined;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
// Format: --idea="value"
if (arg.startsWith('--idea=')) {
idea = stripQuotes(arg.substring('--idea='.length));
break;
}
// Format: --idea "value"
if (arg === '--idea' && i + 1 < args.length) {
idea = stripQuotes(args[i + 1]);
break;
}
}
// Parse --resume
const resume = args.includes('--resume');
return { idea, resume: resume || undefined };
}
async function main() {
try {
const { idea, resume, help } = parseArgs();
if (help) {
showHelp();
process.exit(0);
}
await runCLI({ idea, resume });
process.exit(0);
} catch (err) {
if (err instanceof Error && err.message.includes('User force closed')) {
process.exit(0);
}
console.error(err instanceof Error ? err.message : String(err));
process.exit(1);
}
}
main();
-121
View File
@@ -1,121 +0,0 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'fs-extra';
import path from 'path';
import os from 'os';
import { saveState, loadState, deleteState, findExistingState } from './bot-state.js';
import type { BotState } from './types.js';
function makeTmpDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'bot-state-test-'));
}
function makeState(projectDir: string): BotState {
return {
config: {
workDir: path.dirname(projectDir),
projectDir,
ideaName: 'test-idea',
ideaDescription: 'A test idea',
mode: 'new-project',
},
steps: [],
currentStep: null,
implementPasses: 0,
allPhasesComplete: false,
};
}
describe('bot-state', () => {
let tmpDir: string;
beforeEach(() => {
tmpDir = makeTmpDir();
});
afterEach(() => {
fs.removeSync(tmpDir);
});
describe('saveState', () => {
it('writes valid JSON', () => {
const projectDir = path.join(tmpDir, 'project');
fs.ensureDirSync(projectDir);
const state = makeState(projectDir);
saveState(state);
const filePath = path.join(projectDir, '.plan2code-bot-state.json');
expect(fs.existsSync(filePath)).toBe(true);
const parsed = fs.readJsonSync(filePath);
expect(parsed.config.ideaName).toBe('test-idea');
});
});
describe('loadState', () => {
it('returns state from file', () => {
const projectDir = path.join(tmpDir, 'project');
fs.ensureDirSync(projectDir);
const state = makeState(projectDir);
saveState(state);
const loaded = loadState(projectDir);
expect(loaded).not.toBeNull();
expect(loaded!.config.ideaName).toBe('test-idea');
expect(loaded!.implementPasses).toBe(0);
});
it('returns null when file does not exist', () => {
const result = loadState(path.join(tmpDir, 'nonexistent'));
expect(result).toBeNull();
});
});
describe('deleteState', () => {
it('removes the file', () => {
const projectDir = path.join(tmpDir, 'project');
fs.ensureDirSync(projectDir);
const state = makeState(projectDir);
saveState(state);
const filePath = path.join(projectDir, '.plan2code-bot-state.json');
expect(fs.existsSync(filePath)).toBe(true);
deleteState(projectDir);
expect(fs.existsSync(filePath)).toBe(false);
});
it('is a no-op when file does not exist', () => {
// Should not throw
deleteState(path.join(tmpDir, 'nonexistent'));
});
});
describe('findExistingState', () => {
it('finds state in workDir (enhancement mode)', () => {
const state = makeState(tmpDir);
state.config.projectDir = tmpDir;
state.config.mode = 'enhancement';
saveState(state);
const found = findExistingState(tmpDir);
expect(found).not.toBeNull();
expect(found!.config.ideaName).toBe('test-idea');
});
it('finds state in a subdirectory (new-project mode)', () => {
const projectDir = path.join(tmpDir, 'my-app');
fs.ensureDirSync(projectDir);
const state = makeState(projectDir);
saveState(state);
const found = findExistingState(tmpDir);
expect(found).not.toBeNull();
expect(found!.config.projectDir).toBe(projectDir);
});
it('returns null when no state exists', () => {
const found = findExistingState(tmpDir);
expect(found).toBeNull();
});
});
});
-48
View File
@@ -1,48 +0,0 @@
import fs from 'fs-extra';
import path from 'path';
import type { BotState } from './types.js';
const STATE_FILE = '.plan2code-bot-state.json';
export function saveState(state: BotState): void {
const filePath = path.join(state.config.projectDir, STATE_FILE);
fs.writeJsonSync(filePath, state, { spaces: 2 });
}
export function loadState(projectDir: string): BotState | null {
const filePath = path.join(projectDir, STATE_FILE);
if (!fs.existsSync(filePath)) {
return null;
}
return fs.readJsonSync(filePath) as BotState;
}
export function deleteState(projectDir: string): void {
const filePath = path.join(projectDir, STATE_FILE);
if (fs.existsSync(filePath)) {
fs.removeSync(filePath);
}
}
/**
* Search for an existing state file in workDir (enhancement mode)
* or in immediate subdirectories (new-project mode).
*/
export function findExistingState(workDir: string): BotState | null {
// Enhancement mode: state is in workDir directly
const direct = loadState(workDir);
if (direct) return direct;
// New-project mode: state is in a subdirectory
try {
for (const entry of fs.readdirSync(workDir, { withFileTypes: true })) {
if (entry.isDirectory()) {
const sub = loadState(path.join(workDir, entry.name));
if (sub) return sub;
}
}
} catch {
// workDir not readable — ignore
}
return null;
}
-195
View File
@@ -1,195 +0,0 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import { validateStepArtifacts, installSkillsForBot } from './cli.js';
let tmpDir: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'p2c-cli-test-'));
});
afterEach(() => {
fs.removeSync(tmpDir);
});
// ── validateStepArtifacts ───────────────────────────────────────────
describe('validateStepArtifacts', () => {
describe('init', () => {
it('valid when AGENTS.md exists', () => {
fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# Agents');
const result = validateStepArtifacts('init', tmpDir);
expect(result.valid).toBe(true);
expect(result.missing).toEqual([]);
});
it('missing when AGENTS.md does not exist', () => {
const result = validateStepArtifacts('init', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('AGENTS.md');
});
});
describe('plan', () => {
it('valid when specs/feature/PLAN-DRAFT-*.md exists', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(path.join(specDir, 'PLAN-DRAFT-v1.md'), '# Plan');
const result = validateStepArtifacts('plan', tmpDir);
expect(result.valid).toBe(true);
});
it('missing when specs/ is absent', () => {
const result = validateStepArtifacts('plan', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('specs/ directory');
});
it('missing when specs/ has dirs but no plan draft files', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(path.join(specDir, 'notes.md'), '# Notes');
const result = validateStepArtifacts('plan', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('specs/*/PLAN-DRAFT-*.md');
});
});
describe('document', () => {
it('valid when overview.md and phase-*.md exist', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(path.join(specDir, 'overview.md'), '# Overview');
fs.writeFileSync(path.join(specDir, 'phase-1.md'), '# Phase 1');
const result = validateStepArtifacts('document', tmpDir);
expect(result.valid).toBe(true);
});
it('missing overview.md when absent', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(path.join(specDir, 'phase-1.md'), '# Phase 1');
const result = validateStepArtifacts('document', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('specs/*/overview.md');
});
it('missing phase files when absent', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(path.join(specDir, 'overview.md'), '# Overview');
const result = validateStepArtifacts('document', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('specs/*/phase-*.md files');
});
it('accepts phase files inside phases/ subdirectory', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
const phasesDir = path.join(specDir, 'phases');
fs.ensureDirSync(phasesDir);
fs.writeFileSync(path.join(specDir, 'overview.md'), '# Overview');
fs.writeFileSync(path.join(phasesDir, 'phase-1.md'), '# Phase 1');
const result = validateStepArtifacts('document', tmpDir);
expect(result.valid).toBe(true);
});
});
describe('finalize', () => {
it('valid when specs--completed/ has a subdirectory', () => {
fs.ensureDirSync(path.join(tmpDir, 'specs--completed', 'my-feature'));
const result = validateStepArtifacts('finalize', tmpDir);
expect(result.valid).toBe(true);
});
it('missing when specs--completed/ is absent', () => {
const result = validateStepArtifacts('finalize', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('specs--completed/ directory');
});
it('missing when specs--completed/ is empty', () => {
fs.ensureDirSync(path.join(tmpDir, 'specs--completed'));
const result = validateStepArtifacts('finalize', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('archived spec in specs--completed/');
});
});
});
// ── installSkillsForBot ─────────────────────────────────────────────
describe('installSkillsForBot', () => {
let fakeHome: string;
let projectDir: string;
let origHome: string | undefined;
let origUserProfile: string | undefined;
beforeEach(() => {
fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'p2c-home-'));
projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'p2c-proj-'));
origHome = process.env.HOME;
origUserProfile = process.env.USERPROFILE;
process.env.HOME = fakeHome;
process.env.USERPROFILE = fakeHome;
});
afterEach(() => {
process.env.HOME = origHome;
process.env.USERPROFILE = origUserProfile;
fs.removeSync(fakeHome);
fs.removeSync(projectDir);
});
it('copies skills from user dir to project .claude/skills/', () => {
const srcDir = path.join(fakeHome, '.claude', 'skills', 'plan2code-init');
fs.ensureDirSync(srcDir);
fs.writeFileSync(path.join(srcDir, 'SKILL.md'), '---\nname: init\n---\nSome content');
installSkillsForBot(projectDir);
const dest = path.join(projectDir, '.claude', 'skills', 'plan2code-init', 'SKILL.md');
expect(fs.existsSync(dest)).toBe(true);
expect(fs.readFileSync(dest, 'utf-8')).toContain('Some content');
});
it('strips disable-model-invocation: true from copied SKILL.md', () => {
const srcDir = path.join(fakeHome, '.claude', 'skills', 'plan2code-1-plan');
fs.ensureDirSync(srcDir);
fs.writeFileSync(
path.join(srcDir, 'SKILL.md'),
'disable-model-invocation: true\n---\nname: plan\n---\nPlan content',
);
installSkillsForBot(projectDir);
const dest = path.join(projectDir, '.claude', 'skills', 'plan2code-1-plan', 'SKILL.md');
const content = fs.readFileSync(dest, 'utf-8');
expect(content).not.toContain('disable-model-invocation');
expect(content).toContain('Plan content');
});
it('preserves rest of skill content', () => {
const srcDir = path.join(fakeHome, '.claude', 'skills', 'plan2code-2-document');
fs.ensureDirSync(srcDir);
const original = 'disable-model-invocation: true\n---\nname: doc\n---\nLine 1\nLine 2\nLine 3';
fs.writeFileSync(path.join(srcDir, 'SKILL.md'), original);
installSkillsForBot(projectDir);
const dest = path.join(projectDir, '.claude', 'skills', 'plan2code-2-document', 'SKILL.md');
const content = fs.readFileSync(dest, 'utf-8');
expect(content).toContain('Line 1');
expect(content).toContain('Line 2');
expect(content).toContain('Line 3');
expect(content).toContain('name: doc');
});
it('skips gracefully when source skill does not exist', () => {
// No skills in fakeHome — should not throw
expect(() => installSkillsForBot(projectDir)).not.toThrow();
// No .claude/skills/ created in project
expect(fs.existsSync(path.join(projectDir, '.claude', 'skills'))).toBe(false);
});
});
-587
View File
@@ -1,587 +0,0 @@
import fs from 'fs-extra';
import path from 'path';
import chalk from 'chalk';
import ora from 'ora';
import { generateNewAppIdea, generateEnhancementIdea } from './idea-generator.js';
import { runSession } from './session-runner.js';
import { buildStepPrompt } from './prompts/step-instructions.js';
import { checkAllPhasesComplete } from './step-detector.js';
import { saveState, loadState, deleteState, findExistingState } from './bot-state.js';
import { ObservationCollector } from './observation-collector.js';
import { evaluateStep } from './evaluator.js';
import type { BotConfig, BotMode, BotState, StepName, StepResult } from './types.js';
const BANNER = `
╔══════════════════════════════════════╗
║ plan2code-bot v1.1.0 ║
║ Autonomous Workflow Test Runner ║
╚══════════════════════════════════════╝
`;
const MAX_IMPLEMENT_PASSES = 10;
/** Skill name mapping: bot step name → installed skill directory name */
const SKILL_MAP: Record<StepName, string> = {
init: 'plan2code-init',
plan: 'plan2code-1-plan',
document: 'plan2code-2-document',
implement: 'plan2code-3-implement',
finalize: 'plan2code-4-finalize',
};
/**
* Install bot-friendly copies of plan2code skills into the project's .claude/skills/.
* The global skills have `disable-model-invocation: true` which prevents the autonomous
* session from invoking them via the Skill tool. We copy them with that flag removed
* so the session can invoke the real workflow prompts instead of guessing.
*/
export function installSkillsForBot(projectDir: string): void {
const userSkillsDir = path.join(
process.env.HOME || process.env.USERPROFILE || '',
'.claude',
'skills',
);
const projectSkillsDir = path.join(projectDir, '.claude', 'skills');
for (const skillName of Object.values(SKILL_MAP)) {
const srcFile = path.join(userSkillsDir, skillName, 'SKILL.md');
if (!fs.existsSync(srcFile)) continue;
const content = fs.readFileSync(srcFile, 'utf-8');
// Remove the disable-model-invocation line so the bot session can invoke the skill
const patched = content.replace(/^disable-model-invocation:\s*true\n?/m, '');
const destDir = path.join(projectSkillsDir, skillName);
fs.ensureDirSync(destDir);
fs.writeFileSync(path.join(destDir, 'SKILL.md'), patched);
}
}
export function validateStepArtifacts(step: StepName, projectDir: string): { valid: boolean; missing: string[] } {
const missing: string[] = [];
switch (step) {
case 'init': {
const agentsPath = path.join(projectDir, 'AGENTS.md');
if (!fs.existsSync(agentsPath)) missing.push('AGENTS.md');
break;
}
case 'plan': {
const specsDir = path.join(projectDir, 'specs');
if (!fs.existsSync(specsDir)) {
missing.push('specs/ directory');
} else {
const entries = fs.readdirSync(specsDir, { withFileTypes: true });
const specDirs = entries.filter((e) => e.isDirectory());
const hasPlanDraft = specDirs.some((d) => {
const files = fs.readdirSync(path.join(specsDir, d.name));
return files.some((f) => /plan[-_]?draft/i.test(f));
});
if (!hasPlanDraft) missing.push('specs/*/PLAN-DRAFT-*.md');
}
break;
}
case 'document': {
const specsDir = path.join(projectDir, 'specs');
if (!fs.existsSync(specsDir)) {
missing.push('specs/ directory');
} else {
const entries = fs.readdirSync(specsDir, { withFileTypes: true });
const specDirs = entries.filter((e) => e.isDirectory());
let foundOverview = false;
let foundPhaseFile = false;
for (const d of specDirs) {
const specPath = path.join(specsDir, d.name);
const files = fs.readdirSync(specPath);
if (files.some((f) => f === 'overview.md')) foundOverview = true;
if (files.some((f) => /^phase[-_]?\d+.*\.md$/i.test(f))) foundPhaseFile = true;
// Also check phases/ subdirectory
const phasesSubdir = path.join(specPath, 'phases');
if (fs.existsSync(phasesSubdir)) {
const subFiles = fs.readdirSync(phasesSubdir);
if (subFiles.some((f) => /phase/i.test(f))) foundPhaseFile = true;
}
}
if (!foundOverview) missing.push('specs/*/overview.md');
if (!foundPhaseFile) missing.push('specs/*/phase-*.md files');
}
break;
}
case 'finalize': {
const completedDir = path.join(projectDir, 'specs--completed');
if (!fs.existsSync(completedDir)) {
missing.push('specs--completed/ directory');
} else {
const entries = fs.readdirSync(completedDir, { withFileTypes: true });
const specDirs = entries.filter((e) => e.isDirectory());
if (specDirs.length === 0) missing.push('archived spec in specs--completed/');
}
break;
}
}
return { valid: missing.length === 0, missing };
}
function detectMode(workDir: string): BotMode {
const agentsPath = path.join(workDir, 'AGENTS.md');
return fs.existsSync(agentsPath) ? 'enhancement' : 'new-project';
}
function formatDuration(ms: number): string {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
if (minutes > 0) {
return `${minutes}m ${remainingSeconds}s`;
}
return `${seconds}s`;
}
async function runStep(
step: StepName,
config: BotConfig,
state: BotState,
): Promise<StepResult> {
const spinner = ora({
text: chalk.cyan(`Running ${step} step...`),
spinner: 'dots',
}).start();
const prompt = buildStepPrompt(step, config);
try {
// Create observation collector
const collector = new ObservationCollector(step);
const result = await runSession({
prompt,
config,
step,
maxTurns: step === 'implement' ? 80 : 50,
collector,
});
if (result.success) {
spinner.succeed(
chalk.green(`${step} completed in ${formatDuration(result.duration)}`)
);
// Run evaluation
spinner.text = chalk.cyan('Evaluating step quality...');
spinner.start();
const evaluation = await evaluateStep(step, result.observations, config.projectDir);
spinner.succeed(
chalk.cyan(`Evaluation complete: ${formatScore(evaluation.score)}`)
);
// Display evaluation summary
console.log(chalk.dim(` Score: ${formatScore(evaluation.score)}`));
if (evaluation.strengths.length > 0) {
console.log(chalk.green(` ✓ ${evaluation.strengths[0]}`));
}
if (evaluation.weaknesses.length > 0) {
console.log(chalk.yellow(` ⚠ ${evaluation.weaknesses[0]}`));
}
const stepResult: StepResult = {
step,
success: result.success,
sessionId: result.sessionId,
duration: result.duration,
error: null,
evaluation,
observations: result.observations,
};
return stepResult;
} else {
spinner.fail(chalk.red(`${step} failed after ${formatDuration(result.duration)}`));
return {
step,
success: false,
sessionId: result.sessionId,
duration: result.duration,
error: 'Session failed',
observations: result.observations,
};
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
spinner.fail(chalk.red(`${step} error: ${errorMsg}`));
return {
step,
success: false,
sessionId: null,
duration: 0,
error: errorMsg,
};
}
}
function formatScore(score: number): string {
if (score >= 85) return chalk.green(`${score}/100`);
if (score >= 70) return chalk.yellow(`${score}/100`);
return chalk.red(`${score}/100`);
}
export interface CLIOptions {
idea?: string;
resume?: boolean;
}
/** Check if a step completed successfully in a saved state */
function stepSucceeded(state: BotState, step: StepName): boolean {
return state.steps.some((s) => s.step === step && s.success);
}
export async function runCLI(options: CLIOptions = {}): Promise<void> {
console.log(chalk.cyan(BANNER));
const workDir = process.cwd();
// Check for resumable state
let resuming = false;
let savedState: BotState | null = null;
if (options.resume) {
savedState = findExistingState(workDir);
if (savedState) {
resuming = true;
console.log(chalk.yellow('Resuming previous incomplete run...'));
} else {
console.log(chalk.dim('No previous state found, starting fresh.'));
}
}
const mode = resuming ? savedState!.config.mode : detectMode(workDir);
console.log(chalk.dim(`Working directory: ${workDir}`));
console.log(chalk.dim(`Mode: ${mode === 'new-project' ? 'New Project' : 'Enhancement'}`));
if (options.idea) {
console.log(chalk.dim(`Idea seed: ${options.idea}`));
}
console.log('');
let ideaName: string;
let ideaDescription: string;
let projectDir: string;
if (resuming) {
// Restore from saved state
ideaName = savedState!.config.ideaName;
ideaDescription = savedState!.config.ideaDescription;
projectDir = savedState!.config.projectDir;
console.log(chalk.green(`Restored idea: ${ideaName}`));
console.log(chalk.dim(` ${ideaDescription}`));
console.log('');
} else {
// Step 1: Generate idea
const ideaSpinner = ora({
text: chalk.cyan('Generating idea...'),
spinner: 'dots',
}).start();
try {
if (mode === 'new-project') {
const idea = await generateNewAppIdea(options.idea);
ideaName = idea.name;
ideaDescription = idea.description;
} else {
const idea = await generateEnhancementIdea(workDir, options.idea);
ideaName = idea.name;
ideaDescription = idea.description;
}
ideaSpinner.succeed(chalk.green(`Idea generated: ${ideaName}`));
} catch (error) {
ideaSpinner.fail(chalk.red('Failed to generate idea'));
throw error;
}
console.log(chalk.dim(` ${ideaDescription}`));
console.log('');
// Determine project directory
projectDir = mode === 'new-project'
? path.join(workDir, ideaName)
: workDir;
// Create project directory for new projects
if (mode === 'new-project') {
fs.ensureDirSync(projectDir);
}
}
// Install bot-friendly skills (without disable-model-invocation)
installSkillsForBot(projectDir);
console.log(chalk.dim('Installed plan2code skills for bot sessions'));
// Write IDEA.md (only if not resuming past plan step, since it gets moved)
if (!resuming || !stepSucceeded(savedState!, 'plan')) {
const ideaContent = `# ${ideaName}\n\n${ideaDescription}\n`;
fs.writeFileSync(path.join(projectDir, 'IDEA.md'), ideaContent);
console.log(chalk.dim(`Wrote IDEA.md to ${projectDir}`));
}
console.log('');
// Build config
const config: BotConfig = {
workDir,
projectDir,
ideaDescription,
ideaName,
mode,
};
// Initialize or restore state
const state: BotState = resuming
? { ...savedState!, config }
: {
config,
steps: [],
currentStep: null,
implementPasses: 0,
allPhasesComplete: false,
};
// Step 2: Run init (new project only)
if (mode === 'new-project') {
if (resuming && stepSucceeded(savedState!, 'init')) {
console.log(chalk.dim('--- Init (skipped — previously succeeded) ---'));
} else {
console.log(chalk.bold('--- Init ---'));
state.currentStep = 'init';
const initResult = await runStep('init', config, state);
state.steps.push(initResult);
saveState(state);
if (!initResult.success) {
console.log(chalk.red('\nInit failed. Aborting.'));
printSummary(state, workDir, false);
return;
}
const initValidation = validateStepArtifacts('init', projectDir);
if (!initValidation.valid) {
console.log(chalk.yellow(` ⚠ Missing artifacts: ${initValidation.missing.join(', ')}`));
initResult.success = false;
initResult.error = `Missing artifacts: ${initValidation.missing.join(', ')}`;
console.log(chalk.red('\nInit artifacts missing. Aborting.'));
printSummary(state, workDir, false);
return;
}
}
console.log('');
}
// Step 3: Plan
if (resuming && stepSucceeded(savedState!, 'plan')) {
console.log(chalk.dim('--- Plan (skipped — previously succeeded) ---'));
} else {
console.log(chalk.bold('--- Plan ---'));
state.currentStep = 'plan';
const planResult = await runStep('plan', config, state);
state.steps.push(planResult);
saveState(state);
if (!planResult.success) {
console.log(chalk.red('\nPlan step failed. Aborting.'));
printSummary(state, workDir, false);
return;
}
const planValidation = validateStepArtifacts('plan', projectDir);
if (!planValidation.valid) {
console.log(chalk.yellow(` ⚠ Missing artifacts: ${planValidation.missing.join(', ')}`));
planResult.success = false;
planResult.error = `Missing artifacts: ${planValidation.missing.join(', ')}`;
console.log(chalk.red('\nPlan artifacts missing. Aborting.'));
printSummary(state, workDir, false);
return;
}
// Move IDEA.md into the spec directory so it stays with its feature
const ideaPath = path.join(projectDir, 'IDEA.md');
if (fs.existsSync(ideaPath)) {
const specEntries = fs.readdirSync(path.join(projectDir, 'specs'), { withFileTypes: true });
const firstSpecDir = specEntries.find((e) => e.isDirectory());
if (firstSpecDir) {
const dest = path.join(projectDir, 'specs', firstSpecDir.name, 'IDEA.md');
fs.moveSync(ideaPath, dest, { overwrite: true });
console.log(chalk.dim(`Moved IDEA.md → specs/${firstSpecDir.name}/IDEA.md`));
}
}
}
console.log('');
// Step 4: Document
if (resuming && stepSucceeded(savedState!, 'document')) {
console.log(chalk.dim('--- Document (skipped — previously succeeded) ---'));
} else {
console.log(chalk.bold('--- Document ---'));
state.currentStep = 'document';
const docResult = await runStep('document', config, state);
state.steps.push(docResult);
saveState(state);
if (!docResult.success) {
console.log(chalk.red('\nDocument step failed. Aborting.'));
printSummary(state, workDir, false);
return;
}
const docValidation = validateStepArtifacts('document', projectDir);
if (!docValidation.valid) {
console.log(chalk.yellow(` ⚠ Missing artifacts: ${docValidation.missing.join(', ')}`));
docResult.success = false;
docResult.error = `Missing artifacts: ${docValidation.missing.join(', ')}`;
console.log(chalk.red('\nDocument artifacts missing. Aborting.'));
printSummary(state, workDir, false);
return;
}
}
console.log('');
// Step 5: Implement (loop until all phases complete)
if (resuming && savedState!.allPhasesComplete) {
console.log(chalk.dim('--- Implement (skipped — all phases already complete) ---'));
} else {
console.log(chalk.bold('--- Implement ---'));
while (state.implementPasses < MAX_IMPLEMENT_PASSES) {
state.implementPasses++;
state.currentStep = 'implement';
console.log(chalk.dim(` Pass ${state.implementPasses}/${MAX_IMPLEMENT_PASSES}`));
const implResult = await runStep('implement', config, state);
state.steps.push(implResult);
saveState(state);
if (!implResult.success) {
console.log(chalk.yellow(`\nImplement pass ${state.implementPasses} failed. Continuing...`));
}
// Check if all phases are complete
if (checkAllPhasesComplete(projectDir)) {
state.allPhasesComplete = true;
saveState(state);
console.log(chalk.green(' All phases complete!'));
break;
}
}
if (!state.allPhasesComplete && state.implementPasses >= MAX_IMPLEMENT_PASSES) {
console.log(chalk.yellow(`\nMax implement passes (${MAX_IMPLEMENT_PASSES}) reached.`));
}
}
console.log('');
// Step 6: Finalize
if (resuming && stepSucceeded(savedState!, 'finalize')) {
console.log(chalk.dim('--- Finalize (skipped — previously succeeded) ---'));
} else {
console.log(chalk.bold('--- Finalize ---'));
// Check quality gate: average score must be >= 60
const evaluatedSteps = state.steps.filter((s) => s.evaluation);
if (evaluatedSteps.length > 0) {
const avgScore =
evaluatedSteps.reduce((sum, s) => sum + (s.evaluation?.score ?? 0), 0) /
evaluatedSteps.length;
console.log(chalk.dim(` Average quality score: ${formatScore(Math.round(avgScore))}`));
if (avgScore < 60) {
console.log(
chalk.red(
'\n⚠ Quality gate failed: Average score is below 60. Please review and fix issues before finalizing.'
)
);
console.log(chalk.dim(' Check specs/<feature>/BOT-EVALUATION.md for detailed feedback.'));
printSummary(state, workDir, false);
return;
}
}
state.currentStep = 'finalize';
const finalizeResult = await runStep('finalize', config, state);
state.steps.push(finalizeResult);
saveState(state);
if (finalizeResult.success) {
const finalValidation = validateStepArtifacts('finalize', projectDir);
if (!finalValidation.valid) {
console.log(chalk.yellow(` ⚠ Missing artifacts: ${finalValidation.missing.join(', ')}`));
finalizeResult.success = false;
finalizeResult.error = `Missing artifacts: ${finalValidation.missing.join(', ')}`;
saveState(state);
}
}
}
console.log('');
// Determine overall success
const allSucceeded = state.steps.length > 0 && state.steps.every((s) => s.success);
printSummary(state, workDir, allSucceeded);
// Clean up state file on full success
if (allSucceeded) {
deleteState(projectDir);
console.log(chalk.dim('Cleaned up state file (run succeeded)'));
} else {
console.log(chalk.dim('State file preserved for resume (run incomplete)'));
}
console.log('');
}
function printSummary(state: BotState, workDir: string, allSucceeded: boolean): void {
const { ideaName, mode, projectDir } = state.config;
console.log(chalk.cyan('═══════════════════════════════════════'));
console.log(chalk.bold(' Bot Run Summary'));
console.log(chalk.cyan('═══════════════════════════════════════'));
console.log(chalk.dim(` Project: ${ideaName}`));
console.log(chalk.dim(` Mode: ${mode}`));
console.log(chalk.dim(` Directory: ${projectDir}`));
console.log('');
const totalDuration = state.steps.reduce((sum, s) => sum + s.duration, 0);
const successCount = state.steps.filter((s) => s.success).length;
for (const step of state.steps) {
const icon = step.success ? chalk.green('✓') : chalk.red('✗');
const scoreText = step.evaluation
? ` [${formatScore(step.evaluation.score)}]`
: '';
console.log(
` ${icon} ${step.step.padEnd(12)} ${formatDuration(step.duration)}${scoreText}`
);
}
console.log('');
// Display average quality score if available
const evaluatedSteps = state.steps.filter((s) => s.evaluation);
if (evaluatedSteps.length > 0) {
const avgScore =
evaluatedSteps.reduce((sum, s) => sum + (s.evaluation?.score ?? 0), 0) /
evaluatedSteps.length;
console.log(
chalk.dim(` Average quality: ${formatScore(Math.round(avgScore))}`)
);
}
console.log(
chalk.dim(
` Total: ${successCount}/${state.steps.length} steps succeeded in ${formatDuration(totalDuration)}`
)
);
console.log(chalk.dim(` Implement passes: ${state.implementPasses}`));
if (!allSucceeded) {
console.log(
chalk.dim(
` State saved to: ${path.relative(workDir, projectDir)}/.plan2code-bot-state.json`
)
);
}
console.log('');
}
-311
View File
@@ -1,311 +0,0 @@
import { query } from '@anthropic-ai/claude-agent-sdk';
import fs from 'fs-extra';
import path from 'path';
import type { EvaluationResult, ExecutionObservation, StepName } from './types.js';
import { getCriteriaForStep } from './prompts/evaluation-criteria.js';
/**
* Evaluates a completed step using LLM-as-judge.
* Returns honest quality assessment based on observations and artifacts.
*/
export async function evaluateStep(
step: StepName,
observations: ExecutionObservation,
projectDir: string
): Promise<EvaluationResult> {
const criteria = getCriteriaForStep(step);
const prompt = buildEvaluationPrompt(step, observations, criteria, projectDir);
try {
// Query LLM with ability to inspect artifacts
const session = query({
prompt,
options: {
maxTurns: 30,
cwd: projectDir,
permissionMode: 'bypassPermissions',
allowDangerouslySkipPermissions: true,
allowedTools: ['Read', 'Glob', 'Grep'],
systemPrompt:
'You are a QA engineer evaluating completed work. Be thorough, honest, and constructive.',
},
});
let output = '';
for await (const message of session) {
if (message.type === 'assistant') {
for (const block of message.message.content) {
if (block.type === 'text') output += block.text;
}
}
}
const evaluation = parseEvaluationOutput(output, step);
// Write evaluation files
await writeEvaluationFiles(evaluation, observations, projectDir);
return evaluation;
} catch (error) {
console.warn('Evaluation failed, using fallback:', error);
return createFallbackEvaluation(step, observations);
}
}
function buildEvaluationPrompt(
step: StepName,
observations: ExecutionObservation,
criteria: ReturnType<typeof getCriteriaForStep>,
projectDir: string
): string {
const duration = observations.endTime - observations.startTime;
const durationSec = Math.floor(duration / 1000);
const toolsSummary = observations.tools
.map((t) => `- ${t.toolName} (${new Date(t.timestamp).toISOString()})`)
.join('\n');
const filesSummary = [
...observations.filesCreated.map((f) => `CREATED: ${f}`),
...observations.filesModified.map((f) => `MODIFIED: ${f}`),
].join('\n');
const questionsSummary = observations.questionsAsked
.map(
(q) =>
`Q: ${q.question}\nA: ${q.selectedAnswer}\nReasoning: ${q.llmReasoning}`
)
.join('\n\n');
return `You are a QA engineer evaluating the quality of a completed workflow step.
## Step Information
- Step: ${step}
- Duration: ${durationSec}s
- Tools used: ${observations.tools.length}
- Files created: ${observations.filesCreated.length}
- Files modified: ${observations.filesModified.length}
- Errors: ${observations.errors.length}
## Execution Details
### Tools Used
${toolsSummary || '(none)'}
### Files Changed
${filesSummary || '(none)'}
${observations.questionsAsked.length > 0 ? `### Questions & Decisions\n${questionsSummary}` : ''}
${observations.errors.length > 0 ? `### Errors Encountered\n${observations.errors.join('\n')}` : ''}
## Evaluation Criteria
**Key Artifacts Expected:**
${criteria.keyArtifacts.map((a) => `- ${a}`).join('\n')}
**Quality Checks:**
${criteria.qualityChecks.map((c) => `- ${c}`).join('\n')}
**Common Pitfalls to Watch For:**
${criteria.commonPitfalls.map((p) => `- ${p}`).join('\n')}
**Scoring Guidance:**
${criteria.scoringGuidance}
## Your Task
Evaluate this step honestly and thoroughly:
1. **Inspect the artifacts** using Read, Glob, and Grep tools
2. **Check against quality criteria** listed above
3. **Identify strengths and weaknesses** based on actual evidence
4. **Provide constructive suggestions** for improvement
5. **Assign an honest score** (0-100) following the guidance
Be critical but fair. Most work scores 70-85. Don't inflate scores.
## Response Format
SCORE: <number 0-100>
STRENGTHS:
- <strength 1>
- <strength 2>
- <strength 3>
WEAKNESSES:
- <weakness 1>
- <weakness 2>
SUGGESTIONS:
- <suggestion 1>
- <suggestion 2>
CRITICAL_ISSUES:
- <critical issue 1 (or "None")>
REASONING:
<1-2 paragraphs explaining your evaluation, referencing specific files/evidence>
Provide honest, evidence-based evaluation.`;
}
function parseEvaluationOutput(
output: string,
step: StepName
): EvaluationResult {
// Extract score
const scoreMatch = output.match(/SCORE:\s*(\d+)/i);
if (!scoreMatch) {
console.warn(`Evaluation parser: no SCORE found in output (${output.length} chars). Defaulting to 50.`);
}
const score = scoreMatch ? parseInt(scoreMatch[1], 10) : 50;
// Extract sections
const strengthsMatch = output.match(
/STRENGTHS:\s*((?:- .+\n?)+)/i
);
const weaknessesMatch = output.match(
/WEAKNESSES:\s*((?:- .+\n?)+)/i
);
const suggestionsMatch = output.match(
/SUGGESTIONS:\s*((?:- .+\n?)+)/i
);
const criticalMatch = output.match(
/CRITICAL_ISSUES:\s*((?:- .+\n?)+)/i
);
const reasoningMatch = output.match(/REASONING:\s*(.+?)(?=\n\n|$)/is);
const parseList = (text: string | undefined): string[] => {
if (!text) return [];
return text
.split('\n')
.map((line) => line.replace(/^-\s*/, '').trim())
.filter((line) => line.length > 0 && !line.toLowerCase().includes('none'));
};
return {
step,
score: Math.max(0, Math.min(100, score)),
strengths: parseList(strengthsMatch?.[1]),
weaknesses: parseList(weaknessesMatch?.[1]),
suggestions: parseList(suggestionsMatch?.[1]),
criticalIssues: parseList(criticalMatch?.[1]),
timestamp: Date.now(),
evaluatorModel: 'claude-sonnet-4-5',
reasoning: reasoningMatch?.[1]?.trim() || 'No reasoning provided',
};
}
function createFallbackEvaluation(
step: StepName,
observations: ExecutionObservation
): EvaluationResult {
return {
step,
score: 50,
strengths: ['Step completed'],
weaknesses: ['Evaluation failed - using fallback'],
suggestions: ['Re-run with evaluation enabled'],
criticalIssues: ['Evaluation system unavailable'],
timestamp: Date.now(),
evaluatorModel: 'fallback',
reasoning: 'Evaluation failed, using fallback. Cannot provide detailed assessment.',
};
}
/**
* Resolves the active spec subdirectory (e.g. specs/<feature>/).
* Falls back to projectDir if no spec folder exists yet (e.g. during init).
*/
function resolveOutputDir(projectDir: string): string {
const specsDir = path.join(projectDir, 'specs');
if (fs.existsSync(specsDir)) {
const entries = fs.readdirSync(specsDir, { withFileTypes: true });
const firstSpec = entries.find((e) => e.isDirectory());
if (firstSpec) {
return path.join(specsDir, firstSpec.name);
}
}
return projectDir;
}
async function writeEvaluationFiles(
evaluation: EvaluationResult,
observations: ExecutionObservation,
projectDir: string
): Promise<void> {
const outputDir = resolveOutputDir(projectDir);
// Write BOT-EVALUATION.md
const evalContent = formatEvaluationMarkdown(evaluation);
const evalPath = path.join(outputDir, 'BOT-EVALUATION.md');
if (fs.existsSync(evalPath)) {
// Append to existing file
const existing = fs.readFileSync(evalPath, 'utf-8');
fs.writeFileSync(evalPath, existing + '\n\n---\n\n' + evalContent);
} else {
fs.writeFileSync(evalPath, evalContent);
}
// Write BOT-NOTES.md
const notesContent = formatObservationsMarkdown(observations);
const notesPath = path.join(outputDir, 'BOT-NOTES.md');
if (fs.existsSync(notesPath)) {
const existing = fs.readFileSync(notesPath, 'utf-8');
fs.writeFileSync(notesPath, existing + '\n\n---\n\n' + notesContent);
} else {
fs.writeFileSync(notesPath, notesContent);
}
}
function formatEvaluationMarkdown(evaluation: EvaluationResult): string {
return `# Evaluation: ${evaluation.step} Step
**Score:** ${evaluation.score}/100
**Timestamp:** ${new Date(evaluation.timestamp).toISOString()}
**Evaluator:** ${evaluation.evaluatorModel}
## Strengths
${evaluation.strengths.map((s) => `- ${s}`).join('\n') || '(none)'}
## Weaknesses
${evaluation.weaknesses.map((w) => `- ${w}`).join('\n') || '(none)'}
## Suggestions for Improvement
${evaluation.suggestions.map((s) => `- ${s}`).join('\n') || '(none)'}
${evaluation.criticalIssues.length > 0 ? `## Critical Issues\n${evaluation.criticalIssues.map((i) => `- ${i}`).join('\n')}\n` : ''}
## Reasoning
${evaluation.reasoning}`;
}
function formatObservationsMarkdown(observations: ExecutionObservation): string {
const duration = observations.endTime - observations.startTime;
const durationSec = Math.floor(duration / 1000);
return `# Observations: ${observations.step} Step
**Duration:** ${durationSec}s
**Tools Used:** ${observations.tools.length}
**Files Created:** ${observations.filesCreated.length}
**Files Modified:** ${observations.filesModified.length}
**Errors:** ${observations.errors.length}
${observations.questionsAsked.length > 0 ? `## Questions Asked & Answers\n\n${observations.questionsAsked.map((q) => `### Question: "${q.question}"\n**Selected:** "${q.selectedAnswer}"\n**Reasoning:** ${q.llmReasoning}`).join('\n\n')}\n` : ''}
## Tool Usage
${observations.tools.map((t) => `- ${t.toolName}`).join('\n')}
## Files Created
${observations.filesCreated.map((f) => `- ${f}`).join('\n') || '(none)'}
## Files Modified
${observations.filesModified.map((f) => `- ${f}`).join('\n') || '(none)'}
${observations.assistantMessages.length > 0 ? `## Assistant Output Summary\n${observations.assistantMessages.slice(0, 3).map((m) => `> ${m.substring(0, 100)}...`).join('\n')}\n` : ''}`;
}
-114
View File
@@ -1,114 +0,0 @@
import { query } from '@anthropic-ai/claude-agent-sdk';
interface IdeaResult {
name: string;
description: string;
}
function parseIdea(text: string): IdeaResult {
const nameMatch = text.match(/NAME:\s*(.+)/i);
const descMatch = text.match(/DESCRIPTION:\s*([\s\S]+?)(?:\n\n|$)/i);
const name = nameMatch?.[1]?.trim() ?? 'auto-project';
const description = descMatch?.[1]?.trim() ?? text.trim();
// Ensure kebab-case
const kebabName = name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
return { name: kebabName, description };
}
export async function generateNewAppIdea(seed?: string): Promise<IdeaResult> {
const categories = [
'CLI tool',
'single-page web app',
'REST API service',
'browser extension',
'interactive data visualization dashboard',
'terminal-based game',
'real-time web app (using WebSockets)',
'static site generator or theme',
'browser-based game',
'desktop utility (using Electron or Tauri)',
'chat bot or conversational tool',
'automation script or workflow tool',
];
const category = categories[Math.floor(Math.random() * categories.length)];
const seedClause = seed
? `\n\nThe user provided this seed for inspiration. Stay closely aligned with the theme and intent of the seed — build on it, don't ignore it:\n"${seed}"`
: '';
const prompt = `Generate a random, creative idea for a ${category}. The project should be achievable in a single coding session (1-2 hours) and should be interesting but not overly complex.
IMPORTANT: Be creative and diverse with your ideas. Avoid defaulting to developer-centric tools (git analyzers, code formatters, repo scanners, etc.) unless the category specifically calls for it. Think about ideas that would appeal to a broad audience — productivity, entertainment, education, health, finance, art, music, social, cooking, travel, fitness, etc.${seedClause}
Respond in EXACTLY this format (no other text):
NAME: <kebab-case-project-name>
DESCRIPTION: <2-3 sentence description of what the app does, its key features, and the tech stack to use>`;
const session = query({
prompt,
options: {
maxTurns: 1,
systemPrompt: 'You are a wildly creative project idea generator. You come up with surprising, fun, and diverse software project ideas spanning many domains — not just developer tools. Respond only in the exact format requested.',
},
});
let output = '';
for await (const message of session) {
if (message.type === 'assistant') {
for (const block of message.message.content) {
if (block.type === 'text') {
output += block.text;
}
}
}
}
return parseIdea(output);
}
export async function generateEnhancementIdea(projectDir: string, seed?: string): Promise<IdeaResult> {
const seedClause = seed
? `\n\nUse this as inspiration for the enhancement: "${seed}"`
: '';
const prompt = `You are in a project directory. Scan the existing codebase to understand what it does, then propose a realistic enhancement (new feature, refactor, improvement, or extension).
Use the Read, Glob, and Grep tools to explore the project. Look at:
- Package.json or similar config files for project info
- Source files for current functionality
- README or docs for context${seedClause}
Then respond in EXACTLY this format (no other text):
NAME: <kebab-case-enhancement-name>
DESCRIPTION: <2-3 sentence description of the enhancement, what it adds/changes, and why it would be valuable>`;
const session = query({
prompt,
options: {
maxTurns: 8,
cwd: projectDir,
tools: { type: 'preset', preset: 'claude_code' },
allowedTools: ['Read', 'Glob', 'Grep'],
systemPrompt: { type: 'preset', preset: 'claude_code' },
},
});
let output = '';
for await (const message of session) {
if (message.type === 'assistant') {
for (const block of message.message.content) {
if (block.type === 'text') {
output += block.text;
}
}
}
}
return parseIdea(output);
}
-2
View File
@@ -1,2 +0,0 @@
export { runCLI } from './cli.js';
export type { BotConfig, BotMode, BotState, StepName, StepResult } from './types.js';
-243
View File
@@ -1,243 +0,0 @@
import { query } from '@anthropic-ai/claude-agent-sdk';
import type { BotConfig, ExecutionObservation, StepName } from './types.js';
import type { ObservationCollector } from './observation-collector.js';
interface AskUserQuestionInput {
questions: Array<{
question: string;
options: Array<{ label: string; description: string }>;
multiSelect?: boolean;
}>;
}
interface IntelligentAnswers {
answers: Record<string, string>;
reasoning: Record<string, string>;
}
/**
* Creates an intelligent responder that uses LLM-as-judge for ALL decisions.
* Replaces the old hardcoded auto-responder logic.
*/
export function createIntelligentResponder(
config: BotConfig,
step: StepName,
collector: ObservationCollector
) {
return async (
toolName: string,
input: Record<string, unknown>
): Promise<{ behavior: 'allow'; updatedInput?: Record<string, unknown> } | { behavior: 'deny'; message: string }> => {
// Record every tool invocation for observations
collector.recordToolUse(toolName, input, undefined, true);
// Handle AskUserQuestion with LLM-generated answers
if (toolName === 'AskUserQuestion') {
const askInput = input as unknown as AskUserQuestionInput;
// Get current observations to provide context to LLM
const observations = collector.getSnapshot();
// Generate answers using LLM-as-judge
const answers = await generateIntelligentAnswers(
askInput,
observations,
config,
step
);
// Record each question/answer pair for metrics
for (const q of askInput.questions) {
const answer = answers.answers[q.question];
const reasoning = answers.reasoning[q.question] || 'No reasoning provided';
collector.recordQuestion(q.question, q.options, answer, reasoning);
}
return {
behavior: 'allow',
updatedInput: { ...input, answers: answers.answers },
};
}
// Allow all other tools
return { behavior: 'allow' };
};
}
async function generateIntelligentAnswers(
askInput: AskUserQuestionInput,
observations: ExecutionObservation,
config: BotConfig,
step: StepName
): Promise<IntelligentAnswers> {
const prompt = buildDecisionPrompt(askInput, observations, config, step);
try {
// Query LLM for decision (single turn, read-only tools)
const session = query({
prompt,
options: {
maxTurns: 1,
cwd: config.projectDir,
permissionMode: 'bypassPermissions',
allowDangerouslySkipPermissions: true,
allowedTools: ['Read', 'Glob', 'Grep'],
systemPrompt: 'You are a QA engineer reviewing work-in-progress. Be thoughtful and honest.',
},
});
let output = '';
for await (const message of session) {
if (message.type === 'assistant') {
for (const block of message.message.content) {
if (block.type === 'text') output += block.text;
}
}
}
return parseDecisionOutput(output, askInput);
} catch (error) {
console.warn('LLM decision failed, using fallback logic:', error);
// Fallback to reasonable defaults if LLM fails
return generateFallbackAnswers(askInput, step);
}
}
function buildDecisionPrompt(
askInput: AskUserQuestionInput,
observations: ExecutionObservation,
config: BotConfig,
step: StepName
): string {
const duration = observations.endTime - observations.startTime;
const toolSummary = observations.tools
.map((t) => `- ${t.toolName}`)
.join('\n');
const filesSummary = [
...observations.filesCreated.map((f) => `CREATED: ${f}`),
...observations.filesModified.map((f) => `MODIFIED: ${f}`),
].join('\n');
const questionsText = askInput.questions
.map((q, i) => {
const optionsText = q.options
.map((o, j) => ` ${j + 1}. ${o.label} - ${o.description}`)
.join('\n');
return `QUESTION ${i + 1}: ${q.question}\nOptions:\n${optionsText}`;
})
.join('\n\n');
return `You are a QA engineer reviewing a workflow step in progress.
## Context
- Step: ${step}
- Mode: ${config.mode}
- Duration so far: ${Math.floor(duration / 1000)}s
- Tools used: ${observations.tools.length}
- Errors encountered: ${observations.errors.length}
## What's Happened So Far
### Tools Used
${toolSummary || '(none yet)'}
### Files Changed
${filesSummary || '(none yet)'}
${observations.errors.length > 0 ? `### Errors\n${observations.errors.join('\n')}` : ''}
## Questions to Answer
${questionsText}
## Your Task
You need to answer these questions as a thoughtful QA engineer would:
1. Use Read, Glob, and Grep tools to inspect the current state of artifacts if needed
2. Consider what you've observed (tools used, files created, errors)
3. For each question, select the most appropriate answer
4. Provide brief reasoning for your choice
Respond in this format:
QUESTION 1:
ANSWER: <option label>
REASONING: <1-2 sentences explaining your choice>
QUESTION 2:
ANSWER: <option label>
REASONING: <1-2 sentences>
Be honest. If work looks incomplete or problematic, don't approve it.
If tests should be run but haven't been, don't skip them without good reason.
Act like a real developer who cares about quality.`;
}
function parseDecisionOutput(
output: string,
askInput: AskUserQuestionInput
): IntelligentAnswers {
const answers: Record<string, string> = {};
const reasoning: Record<string, string> = {};
// Parse structured output
const questionBlocks = output.split(/QUESTION \d+:/i).slice(1);
askInput.questions.forEach((q, i) => {
const block = questionBlocks[i] || '';
const answerMatch = block.match(/ANSWER:\s*(.+?)(?=\n|$)/i);
const reasoningMatch = block.match(/REASONING:\s*(.+?)(?=\n\n|$)/is);
const selectedLabel = answerMatch?.[1]?.trim() || '';
// Find matching option by label (case-insensitive partial match)
const matchedOption = q.options.find(
(opt) =>
opt.label.toLowerCase().includes(selectedLabel.toLowerCase()) ||
selectedLabel.toLowerCase().includes(opt.label.toLowerCase())
);
answers[q.question] = matchedOption?.label || q.options[0].label;
reasoning[q.question] = reasoningMatch?.[1]?.trim() || 'No reasoning provided';
});
return { answers, reasoning };
}
function generateFallbackAnswers(
askInput: AskUserQuestionInput,
step: StepName
): IntelligentAnswers {
// Simple fallback: pick first option for most questions
// For approval questions, approve; for testing, skip
const answers: Record<string, string> = {};
const reasoning: Record<string, string> = {};
for (const q of askInput.questions) {
const questionLower = q.question.toLowerCase();
if (questionLower.includes('approve') || questionLower.includes('proceed')) {
const approveOption = q.options.find(
(o) =>
o.label.toLowerCase().includes('approve') ||
o.label.toLowerCase().includes('yes')
);
answers[q.question] = approveOption?.label || q.options[0].label;
reasoning[q.question] = 'Fallback approval (LLM unavailable)';
} else if (questionLower.includes('test')) {
const skipOption = q.options.find(
(o) =>
o.label.toLowerCase().includes('skip') ||
o.label.toLowerCase().includes('none')
);
answers[q.question] = skipOption?.label || q.options[0].label;
reasoning[q.question] = 'Fallback skip (LLM unavailable)';
} else {
answers[q.question] = q.options[0].label;
reasoning[q.question] = 'Fallback first option (LLM unavailable)';
}
}
return { answers, reasoning };
}
-113
View File
@@ -1,113 +0,0 @@
import type { ExecutionObservation, StepName } from './types.js';
/**
* Collects detailed observations during step execution.
* Tracks tool usage, messages, errors, file changes, and questions asked.
*/
export class ObservationCollector {
private observations: ExecutionObservation;
private recentToolKeys: Set<string> = new Set();
constructor(step: StepName) {
this.observations = {
step,
startTime: Date.now(),
endTime: 0,
tools: [],
assistantMessages: [],
errors: [],
filesCreated: [],
filesModified: [],
questionsAsked: [],
};
}
/**
* Records a tool invocation with its input and output.
* Deduplicates if the same tool+input is recorded from both canUseTool and the message stream.
*/
recordToolUse(
toolName: string,
input: Record<string, unknown>,
output: unknown,
allowed: boolean
): void {
// Deduplicate based on tool name + serialized input (within a short time window)
const key = `${toolName}:${JSON.stringify(input)}`;
if (this.recentToolKeys.has(key)) {
return;
}
this.recentToolKeys.add(key);
// Clean up old keys periodically to avoid unbounded growth
if (this.recentToolKeys.size > 500) {
const entries = [...this.recentToolKeys];
this.recentToolKeys = new Set(entries.slice(entries.length - 250));
}
this.observations.tools.push({
toolName,
input,
output,
timestamp: Date.now(),
allowed,
autoAnswered: toolName === 'AskUserQuestion',
});
// Extract file paths from common tools
if (toolName === 'Write' && input.file_path) {
this.observations.filesCreated.push(input.file_path as string);
}
if (toolName === 'Edit' && input.file_path) {
this.observations.filesModified.push(input.file_path as string);
}
}
/**
* Records messages from the session (assistant text, errors).
*/
recordMessage(message: any): void {
if (message.type === 'assistant') {
for (const block of message.message.content) {
if (block.type === 'text') {
this.observations.assistantMessages.push(block.text);
}
}
}
if (message.type === 'error') {
this.observations.errors.push(message.error?.message ?? 'Unknown error');
}
}
/**
* Records a question that was asked and the LLM-generated answer.
*/
recordQuestion(
question: string,
options: Array<{ label: string; description: string }>,
selectedAnswer: string,
llmReasoning: string
): void {
this.observations.questionsAsked.push({
question,
options,
llmReasoning,
selectedAnswer,
timestamp: Date.now(),
});
}
/**
* Gets a snapshot of current observations (for real-time decision making).
*/
getSnapshot(): ExecutionObservation {
return { ...this.observations, endTime: Date.now() };
}
/**
* Finalizes observations and returns the complete record.
*/
finalize(): ExecutionObservation {
this.observations.endTime = Date.now();
return { ...this.observations };
}
}
@@ -1,158 +0,0 @@
import type { StepName } from '../types.js';
export interface StepEvaluationCriteria {
step: StepName;
keyArtifacts: string[];
qualityChecks: string[];
commonPitfalls: string[];
scoringGuidance: string;
}
export const EVALUATION_CRITERIA: Record<StepName, StepEvaluationCriteria> = {
init: {
step: 'init',
keyArtifacts: ['AGENTS.md', 'IDEA.md'],
qualityChecks: [
'AGENTS.md exists with project name and description',
'AGENTS.md includes a brief intro line and a Status section indicating the project is in planning phase',
'AGENTS.md does NOT contain hallucinated architecture, commands, file structures, or tech stack details',
'No .agents-docs/ directory was created (too early for detail files)',
'No project scaffolding (package.json, dependencies, src/) was created',
'IDEA.md exists with the project idea',
],
commonPitfalls: [
'Hallucinating architecture or tech stack details before the plan step',
'Creating .agents-docs/ detail files with invented content',
'Scaffolding project files or installing dependencies prematurely',
],
scoringGuidance: `
100 = Perfect: AGENTS.md stub with intro line, project name/description, and status section. IDEA.md present. Nothing else created.
85-95 = Good but minor extra content beyond the expected stub format (e.g., an extra placeholder heading)
70-84 = AGENTS.md exists but includes some hallucinated details (e.g., assumed tech stack or commands)
50-69 = Significant hallucination (e.g., .agents-docs/ created with invented content, project scaffolded)
<50 = Major problems (e.g., AGENTS.md missing, full project structure hallucinated)
The expected AGENTS.md format is: intro line, Project Overview (name + description), and a Status section. This is the target for a 100 score.
`,
},
plan: {
step: 'plan',
keyArtifacts: ['specs/*/PLAN-DRAFT-*.md', 'IDEA.md'],
qualityChecks: [
'Plan breaks work into clear, achievable phases',
'Each phase has specific goals and deliverables',
'Technical approach is appropriate',
'Scope is realistic for the idea',
'Dependencies between phases are identified',
],
commonPitfalls: [
'Phases too vague ("polish the app")',
'Missing specific tasks within phases',
'No testing strategy mentioned',
'Overly ambitious scope',
'Missing file paths or specific actions',
],
scoringGuidance: `
100 = Exceptional plan: detailed phases, realistic scope, clear tasks, testing included
85-95 = Good plan with minor improvements possible (e.g., one phase could be more specific)
70-84 = Acceptable but has vague sections or missing testing strategy
50-69 = Significant issues (e.g., multiple vague phases, unrealistic scope)
<50 = Major problems (e.g., no clear phases, plan doesn't match idea)
Most plans should score 70-85. Be critical of vague language.
`,
},
document: {
step: 'document',
keyArtifacts: ['specs/*/overview.md', 'specs/*/phase-*.md files'],
qualityChecks: [
'overview.md provides clear project summary',
'Each phase file has specific tasks with checkboxes',
'File paths are explicit (not generic)',
'Dependencies between tasks are identified',
'Technical details are specific',
'Acceptance criteria are clear',
],
commonPitfalls: [
'Tasks too generic ("implement feature X")',
'Missing file paths',
'No checkboxes or unclear task structure',
'Missing dependencies',
'Overly verbose or lacking specifics',
],
scoringGuidance: `
100 = Exceptional documentation: specific tasks, explicit file paths, clear dependencies
85-95 = Good documentation with minor vagueness in one or two tasks
70-84 = Acceptable but multiple tasks lack specifics or file paths
50-69 = Significant issues (e.g., many generic tasks, missing file paths)
<50 = Major problems (e.g., tasks don't match plan, fundamentally vague)
Most documentation should score 70-85. Penalize generic language heavily.
`,
},
implement: {
step: 'implement',
keyArtifacts: ['actual code files', 'checked-off tasks in phase files'],
qualityChecks: [
'Phase tasks are being completed',
'Code files are actually created/modified',
'Implementation follows the documented plan',
'No major errors blocking progress',
'Tests are written (if applicable)',
],
commonPitfalls: [
'Tasks marked complete but files not actually changed',
'Implementation deviates significantly from plan',
'Errors not addressed',
'Skipping tests without justification',
'Working on wrong phase',
],
scoringGuidance: `
100 = Exceptional implementation: all tasks complete, code works, tests pass
85-95 = Good implementation with minor issues or incomplete tests
70-84 = Acceptable but some tasks incomplete or code has issues
50-69 = Significant issues (e.g., many tasks incomplete, code doesn't work)
<50 = Major problems (e.g., wrong phase, no actual work done)
Implementation scoring depends heavily on actual progress. Be realistic.
`,
},
finalize: {
step: 'finalize',
keyArtifacts: ['specs--completed/', 'README or docs', 'final code state'],
qualityChecks: [
'All phases are marked complete',
'Spec moved to specs--completed/',
'Documentation is updated',
'Code is in working state',
'No obvious loose ends',
],
commonPitfalls: [
'Incomplete phases',
'Missing specs--completed/ move',
'Documentation not updated',
'Code broken or incomplete',
'Unrealistic self-assessment',
],
scoringGuidance: `
100 = Exceptional finalization: everything complete, polished, documented
85-95 = Good finalization with minor issues
70-84 = Acceptable but some loose ends or documentation gaps
50-69 = Significant issues (e.g., incomplete phases, broken code)
<50 = Major problems (e.g., work not actually done, fundamentally incomplete)
Finalize scores should reflect overall project quality. Be honest.
`,
},
};
/**
* Gets evaluation criteria for a specific step.
*/
export function getCriteriaForStep(step: StepName): StepEvaluationCriteria {
return EVALUATION_CRITERIA[step];
}
@@ -1,58 +0,0 @@
import { describe, it, expect } from 'vitest';
import { buildStepPrompt } from './step-instructions.js';
import type { BotConfig } from '../types.js';
const config: BotConfig = {
workDir: '/tmp/work',
projectDir: '/tmp/work/my-app',
ideaDescription: 'A todo app with drag-and-drop',
ideaName: 'drag-todo',
mode: 'new-project',
};
describe('buildStepPrompt', () => {
it('each step includes the autonomous preamble', () => {
const steps = ['init', 'plan', 'document', 'implement', 'finalize'] as const;
for (const step of steps) {
const prompt = buildStepPrompt(step, config);
expect(prompt).toContain('running autonomously');
}
});
it('init prompt includes /plan2code-init skill invocation', () => {
const prompt = buildStepPrompt('init', config);
expect(prompt).toContain('/plan2code-init');
});
it('plan prompt includes /plan2code-1-plan skill invocation', () => {
const prompt = buildStepPrompt('plan', config);
expect(prompt).toContain('/plan2code-1-plan');
});
it('document prompt includes /plan2code-2-document skill invocation', () => {
const prompt = buildStepPrompt('document', config);
expect(prompt).toContain('/plan2code-2-document');
});
it('implement prompt instructs direct tool usage without skill invocation', () => {
const prompt = buildStepPrompt('implement', config);
expect(prompt).toContain('Do NOT use the Skill tool');
});
it('finalize prompt includes /plan2code-4-finalize skill invocation', () => {
const prompt = buildStepPrompt('finalize', config);
expect(prompt).toContain('/plan2code-4-finalize');
});
it('plan prompt includes project name and description', () => {
const prompt = buildStepPrompt('plan', config);
expect(prompt).toContain('drag-todo');
expect(prompt).toContain('A todo app with drag-and-drop');
});
it('init prompt includes project name and description', () => {
const prompt = buildStepPrompt('init', config);
expect(prompt).toContain('drag-todo');
expect(prompt).toContain('A todo app with drag-and-drop');
});
});
@@ -1,131 +0,0 @@
import type { BotConfig, StepName } from '../types.js';
const AUTONOMOUS_PREAMBLE = `You are running autonomously as part of an automated test pipeline. Do NOT pause for human input. When you encounter questions or approval gates, make reasonable decisions and proceed. If asked for confirmation, approve. If asked to choose, pick the most reasonable option. Complete the entire step without stopping.`;
export function buildStepPrompt(step: StepName, config: BotConfig): string {
switch (step) {
case 'init':
return buildInitPrompt(config);
case 'plan':
return buildPlanPrompt(config);
case 'document':
return buildDocumentPrompt(config);
case 'implement':
return buildImplementPrompt(config);
case 'finalize':
return buildFinalizePrompt(config);
}
}
function buildInitPrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
This is a brand new project with no existing code. Create a minimal stub AGENTS.md file and an IDEA.md file. Do NOT run the /plan2code-init skill — there is no codebase to analyze yet.
The project idea is: ${config.ideaDescription}
The project name is: ${config.ideaName}
## What to create
### AGENTS.md
Create a minimal stub with ONLY the following — do NOT invent architecture, tech stack details, commands, or file structures:
\`\`\`markdown
# AGENTS.md
This file provides guidance to AI coding agents when working with code in this repository.
## Project Overview
**Name:** ${config.ideaName}
**Description:** ${config.ideaDescription}
## Status
This project is in the planning phase. Architecture, commands, and detailed documentation will be added after the plan and document steps are complete.
\`\`\`
### IDEA.md
If IDEA.md does not already exist, create it with the project name and description.
## Rules
- Do NOT create .agents-docs/ or any detail files — there is nothing to document yet
- Do NOT hallucinate architecture, dependencies, file structures, or tech stack choices
- Do NOT install dependencies or scaffold project files
- ONLY create the two files above`;
}
function buildPlanPrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
Run the /plan2code-1-plan skill to create a plan for this project.
Read the IDEA.md file first to understand the project. The project is: ${config.ideaDescription}
When making decisions during planning:
- Set confidence levels reasonably high (85-95%)
- Accept the generated tech stack without revision
- Do not request additional reference files
- Approve the plan when asked for sign-off
- Keep scope small and achievable (3-4 phases max)
- Use the project name: ${config.ideaName}`;
}
function buildDocumentPrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
Run the /plan2code-2-document skill to transform the plan into implementation specs.
Read the existing plan output in specs/ first to understand what was planned.
When making decisions:
- Accept all generated documentation
- Approve phase breakdowns and task lists
- Do not request changes to the generated docs`;
}
function buildImplementPrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
You are a senior software engineer implementing a project phase. Do NOT use the Skill tool — implement directly using Read, Write, Edit, Glob, and Grep tools.
## Process
1. **Find the spec**: Read \`specs/*/overview.md\` to find the phase checklist
2. **Pick the next phase**: Find the first phase marked \`[ ]\` (pending) or \`[/]\` (in-progress)
3. **Read the phase file**: Read the corresponding \`phase-X.md\` from the same directory
4. **Mark phase in-progress**: Update \`[ ]\` to \`[/]\` in overview.md
5. **Implement each task sequentially**:
- Read the task specification completely
- Write the code using Write or Edit tools — create real files, not code blocks
- Mark the task \`[x]\` in the phase file immediately after completing it
6. **Complete the phase**: After all tasks, fill in the "Phase Completion Summary" in the phase file
7. **Mark phase complete**: Update \`[/]\` to \`[x]\` in overview.md
## Rules
- Follow AGENTS.md if it exists
- Implement specs EXACTLY — no creative additions or unsolicited improvements
- Write task completion status (\`[x]\`) to disk immediately after each task — never batch
- Only create files mentioned in the spec tasks
- Use the specified file paths, function names, and structures from the spec
- No placeholder code — fully implement every function
- Match existing codebase conventions
- Do NOT run git commands
- Skip running tests unless explicitly listed as a phase task
## Project info
- Project: ${config.ideaName}
- Description: ${config.ideaDescription}
- Project directory: ${config.projectDir}`;
}
function buildFinalizePrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
Run the /plan2code-4-finalize skill to validate and archive the completed project.
When making decisions:
- Approve all documentation updates
- Accept the completion summary
- If asked for a rating or feedback, give 8/10 and positive feedback
- Complete the archival process fully`;
}
-82
View File
@@ -1,82 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
// Mock the SDK before importing session-runner
vi.mock('@anthropic-ai/claude-agent-sdk', () => ({
query: vi.fn(),
}));
import { query } from '@anthropic-ai/claude-agent-sdk';
import { runSession } from './session-runner.js';
import { ObservationCollector } from './observation-collector.js';
import type { BotConfig } from './types.js';
const config: BotConfig = {
workDir: '/tmp/work',
projectDir: '/tmp/work/my-app',
ideaDescription: 'test app',
ideaName: 'test-app',
mode: 'new-project',
};
describe('runSession', () => {
it('returns success: false when output is empty', async () => {
// Simulate a session that yields an assistant message with empty text
const mockQuery = vi.mocked(query);
mockQuery.mockReturnValue(
(async function* () {
yield {
type: 'assistant' as const,
session_id: 'sess-1',
message: { content: [{ type: 'text' as const, text: '' }] },
};
yield {
type: 'result' as const,
session_id: 'sess-1',
};
})() as any,
);
const collector = new ObservationCollector('init');
const result = await runSession({
prompt: 'do something',
config,
step: 'init',
collector,
});
expect(result.success).toBe(false);
expect(result.output.trim()).toBe('');
expect(result.observations).toBeDefined();
});
it('returns success: true when output has content', async () => {
const mockQuery = vi.mocked(query);
mockQuery.mockReturnValue(
(async function* () {
yield {
type: 'assistant' as const,
session_id: 'sess-2',
message: { content: [{ type: 'text' as const, text: 'AGENTS.md has been created successfully' }] },
};
yield {
type: 'result' as const,
session_id: 'sess-2',
};
})() as any,
);
const collector = new ObservationCollector('init');
const result = await runSession({
prompt: 'do something',
config,
step: 'init',
collector,
});
expect(result.success).toBe(true);
expect(result.output).toContain('AGENTS.md');
expect(result.sessionId).toBe('sess-2');
expect(result.observations).toBeDefined();
expect(result.observations.step).toBe('init');
});
});
-77
View File
@@ -1,77 +0,0 @@
import { query } from '@anthropic-ai/claude-agent-sdk';
import { createIntelligentResponder } from './intelligent-responder.js';
import type { BotConfig, ExecutionObservation, StepName } from './types.js';
import type { ObservationCollector } from './observation-collector.js';
export interface SessionOptions {
prompt: string;
config: BotConfig;
step: StepName;
maxTurns?: number;
collector: ObservationCollector;
}
export interface SessionResult {
sessionId: string | null;
output: string;
success: boolean;
duration: number;
observations: ExecutionObservation;
}
export async function runSession(options: SessionOptions): Promise<SessionResult> {
const { prompt, config, step, maxTurns = 50, collector } = options;
const startTime = Date.now();
let output = '';
let sessionId: string | null = null;
try {
const session = query({
prompt,
options: {
cwd: config.projectDir,
maxTurns,
permissionMode: 'bypassPermissions',
allowDangerouslySkipPermissions: true,
canUseTool: createIntelligentResponder(config, step, collector),
systemPrompt: { type: 'preset', preset: 'claude_code' },
settingSources: ['project'],
},
});
for await (const message of session) {
// Record all messages for observations
collector.recordMessage(message);
if (message.type === 'assistant') {
sessionId = message.session_id ?? sessionId;
for (const block of message.message.content) {
if (block.type === 'text') {
output += block.text + '\n';
} else if (block.type === 'tool_use') {
// Capture tool invocations from the message stream as a fallback
// in case canUseTool doesn't fire (e.g., Skill sub-sessions)
collector.recordToolUse(
block.name,
block.input as Record<string, unknown>,
undefined,
true
);
}
}
} else if (message.type === 'result') {
sessionId = message.session_id ?? sessionId;
}
}
const duration = Date.now() - startTime;
const hasOutput = output.trim().length > 0;
const observations = collector.finalize();
return { sessionId, output, success: hasOutput, duration, observations };
} catch (error) {
const duration = Date.now() - startTime;
const errorMsg = error instanceof Error ? error.message : String(error);
const observations = collector.finalize();
return { sessionId, output, success: false, duration, observations };
}
}
-164
View File
@@ -1,164 +0,0 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import { checkAllPhasesComplete, detectStepCompletion } from './step-detector.js';
let tmpDir: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'p2c-test-'));
});
afterEach(() => {
fs.removeSync(tmpDir);
});
// ── checkAllPhasesComplete ──────────────────────────────────────────
describe('checkAllPhasesComplete', () => {
it('returns false when no specs/ directory exists', () => {
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
it('returns false when specs/ has no subdirectories', () => {
fs.ensureDirSync(path.join(tmpDir, 'specs'));
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
it('returns false when spec dir exists but has no overview.md and no phase files', () => {
// This is the false-positive bug we fixed — an empty spec dir should NOT be "complete"
fs.ensureDirSync(path.join(tmpDir, 'specs', 'my-feature'));
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
it('returns true when overview.md has all phases checked [x]', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(
path.join(specDir, 'overview.md'),
`# Overview\n- [x] Phase 1: Setup\n- [x] Phase 2: Core\n- [x] Phase 3: Polish\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(true);
});
it('returns false when overview.md has unchecked [ ] phases', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(
path.join(specDir, 'overview.md'),
`# Overview\n- [x] Phase 1: Setup\n- [ ] Phase 2: Core\n- [ ] Phase 3: Polish\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
it('returns true via fallback: phase-*.md files with all checked, no overview.md', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(
path.join(specDir, 'phase-1.md'),
`# Phase 1\n- [x] Task A\n- [x] Task B\n`,
);
fs.writeFileSync(
path.join(specDir, 'phase-2.md'),
`# Phase 2\n- [x] Task C\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(true);
});
it('returns false via fallback: phase-*.md with unchecked items', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(
path.join(specDir, 'phase-1.md'),
`# Phase 1\n- [x] Task A\n- [ ] Task B\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
it('returns true via nested phases/ subdirectory fallback with all checked', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
const phasesDir = path.join(specDir, 'phases');
fs.ensureDirSync(phasesDir);
fs.writeFileSync(
path.join(phasesDir, 'phase-1.md'),
`# Phase 1\n- [x] Task A\n- [x] Task B\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(true);
});
it('returns false via nested phases/ with unchecked items', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
const phasesDir = path.join(specDir, 'phases');
fs.ensureDirSync(phasesDir);
fs.writeFileSync(
path.join(phasesDir, 'phase-1.md'),
`# Phase 1\n- [x] Task A\n- [ ] Task B\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
});
// ── detectStepCompletion ────────────────────────────────────────────
describe('detectStepCompletion', () => {
it('init: completed when output mentions agents.md created', () => {
const result = detectStepCompletion('AGENTS.md has been created successfully', 'init');
expect(result.completed).toBe(true);
expect(result.nextStep).toBe('plan');
});
it('init: not completed for unrelated output', () => {
const result = detectStepCompletion('Hello world, nothing happened', 'init');
expect(result.completed).toBe(false);
expect(result.nextStep).toBeNull();
});
it('plan: completed when plan is saved', () => {
const result = detectStepCompletion('The plan has been saved and finalized', 'plan');
expect(result.completed).toBe(true);
expect(result.nextStep).toBe('document');
});
it('plan: not completed for unrelated output', () => {
const result = detectStepCompletion('Reading the codebase...', 'plan');
expect(result.completed).toBe(false);
expect(result.nextStep).toBeNull();
});
it('document: completed when overview.md is mentioned', () => {
const result = detectStepCompletion('Created overview.md with all phases', 'document');
expect(result.completed).toBe(true);
expect(result.nextStep).toBe('implement');
});
it('document: not completed for unrelated output', () => {
const result = detectStepCompletion('Thinking about the design...', 'document');
expect(result.completed).toBe(false);
expect(result.nextStep).toBeNull();
});
it('implement: completed when phase is done', () => {
const result = detectStepCompletion('Phase 1 is now complete!', 'implement');
expect(result.completed).toBe(true);
expect(result.nextStep).toBe('finalize');
});
it('implement: not completed for unrelated output', () => {
const result = detectStepCompletion('Working on some files', 'implement');
expect(result.completed).toBe(false);
expect(result.nextStep).toBeNull();
});
it('finalize: completed when finalize is done', () => {
const result = detectStepCompletion('Finalize step is complete and archived', 'finalize');
expect(result.completed).toBe(true);
expect(result.nextStep).toBeNull(); // last step
});
it('finalize: not completed for unrelated output', () => {
const result = detectStepCompletion('Just starting...', 'finalize');
expect(result.completed).toBe(false);
expect(result.nextStep).toBeNull();
});
});
-151
View File
@@ -1,151 +0,0 @@
import fs from 'fs-extra';
import path from 'path';
import type { StepName } from './types.js';
export interface DetectionResult {
completed: boolean;
nextStep: StepName | null;
needsAnotherImplementPass: boolean;
}
const STEP_ORDER: StepName[] = ['init', 'plan', 'document', 'implement', 'finalize'];
export function detectStepCompletion(output: string, step: StepName): DetectionResult {
const lowerOutput = output.toLowerCase();
let completed = false;
switch (step) {
case 'init':
completed = lowerOutput.includes('agents.md') && (
lowerOutput.includes('created') ||
lowerOutput.includes('generated') ||
lowerOutput.includes('written')
);
break;
case 'plan':
completed = lowerOutput.includes('plan') && (
lowerOutput.includes('complete') ||
lowerOutput.includes('approved') ||
lowerOutput.includes('finalized') ||
lowerOutput.includes('saved')
);
break;
case 'document':
completed = lowerOutput.includes('overview.md') || (
lowerOutput.includes('document') && lowerOutput.includes('complete')
);
break;
case 'implement':
completed = lowerOutput.includes('phase') && (
lowerOutput.includes('complete') ||
lowerOutput.includes('done') ||
lowerOutput.includes('finished')
);
break;
case 'finalize':
completed = lowerOutput.includes('finalize') && (
lowerOutput.includes('complete') ||
lowerOutput.includes('archived') ||
lowerOutput.includes('done')
);
break;
}
// Determine next step
const currentIdx = STEP_ORDER.indexOf(step);
const nextStep = currentIdx < STEP_ORDER.length - 1 ? STEP_ORDER[currentIdx + 1] : null;
return {
completed,
nextStep: completed ? nextStep : null,
needsAnotherImplementPass: false,
};
}
export function checkAllPhasesComplete(projectDir: string): boolean {
const specsDir = path.join(projectDir, 'specs');
if (!fs.existsSync(specsDir)) {
return false;
}
const entries = fs.readdirSync(specsDir, { withFileTypes: true });
const specDirs = entries.filter((e) => e.isDirectory());
if (specDirs.length === 0) {
return false;
}
let foundPhaseTracking = false;
for (const dir of specDirs) {
const specPath = path.join(specsDir, dir.name);
// Try overview.md first
const overviewPath = path.join(specPath, 'overview.md');
if (fs.existsSync(overviewPath)) {
foundPhaseTracking = true;
if (hasUncheckedPhases(fs.readFileSync(overviewPath, 'utf-8'))) {
return false;
}
continue;
}
// Fallback: look for phase-*.md or PHASE-*.md in the spec dir
const phaseFiles = findPhaseFiles(specPath);
if (phaseFiles.length > 0) {
foundPhaseTracking = true;
for (const pf of phaseFiles) {
if (hasUncheckedPhases(fs.readFileSync(pf, 'utf-8'))) {
return false;
}
}
continue;
}
// Fallback: look inside a phases/ subdirectory
const phasesSubdir = path.join(specPath, 'phases');
if (fs.existsSync(phasesSubdir)) {
const subPhaseFiles = findPhaseFiles(phasesSubdir);
if (subPhaseFiles.length > 0) {
foundPhaseTracking = true;
for (const pf of subPhaseFiles) {
if (hasUncheckedPhases(fs.readFileSync(pf, 'utf-8'))) {
return false;
}
}
}
}
}
// Only return true if we positively confirmed all phases are checked off
return foundPhaseTracking;
}
function hasUncheckedPhases(content: string): boolean {
const lines = content.split('\n');
const phaseLines = lines.filter((line) =>
line.match(/^[-*]\s*\[[ x]\]/i) && line.toLowerCase().includes('phase')
);
if (phaseLines.length > 0) {
return phaseLines.some((line) => line.includes('[ ]'));
}
// No phase-specific checkboxes — check for any unchecked boxes
return lines.some((line) => /^[-*]\s*\[ \]/.test(line));
}
function findPhaseFiles(dir: string): string[] {
if (!fs.existsSync(dir)) return [];
const entries = fs.readdirSync(dir);
return entries
.filter((name) => /^phase[-_]?\d+.*\.md$/i.test(name))
.map((name) => path.join(dir, name));
}
-70
View File
@@ -1,70 +0,0 @@
export type BotMode = 'new-project' | 'enhancement';
export interface BotConfig {
workDir: string;
projectDir: string;
ideaDescription: string;
ideaName: string;
mode: BotMode;
}
export type StepName = 'init' | 'plan' | 'document' | 'implement' | 'finalize';
export interface ToolObservation {
toolName: string;
input: Record<string, unknown>;
output?: unknown;
timestamp: number;
allowed: boolean;
autoAnswered?: boolean;
}
export interface QuestionContext {
question: string;
options: Array<{ label: string; description: string }>;
llmReasoning: string;
selectedAnswer: string;
timestamp: number;
}
export interface ExecutionObservation {
step: StepName;
startTime: number;
endTime: number;
tools: ToolObservation[];
assistantMessages: string[];
errors: string[];
filesCreated: string[];
filesModified: string[];
questionsAsked: QuestionContext[];
}
export interface EvaluationResult {
step: StepName;
score: number;
strengths: string[];
weaknesses: string[];
suggestions: string[];
criticalIssues: string[];
timestamp: number;
evaluatorModel: string;
reasoning: string;
}
export interface StepResult {
step: StepName;
success: boolean;
sessionId: string | null;
duration: number;
error: string | null;
evaluation?: EvaluationResult;
observations?: ExecutionObservation;
}
export interface BotState {
config: BotConfig;
steps: StepResult[];
currentStep: StepName | null;
implementPasses: number;
allPhasesComplete: boolean;
}
-20
View File
@@ -1,20 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": ".",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
-15
View File
@@ -1,15 +0,0 @@
import { defineConfig } from 'tsup';
export default defineConfig({
entry: {
'bin/plan2code-bot': 'src/bin/plan2code-bot.ts',
index: 'src/index.ts',
},
format: ['esm'],
dts: false,
clean: true,
sourcemap: true,
banner: {
js: '#!/usr/bin/env node',
},
});
-7
View File
@@ -1,7 +0,0 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['src/**/*.test.ts'],
},
});
-210
View File
@@ -1,210 +0,0 @@
# Plan2Code Loop
An autonomous CLI tool that implements Plan2Code specs by looping through tasks automatically.
> **Note:** This is an **alternative** to `/plan2code-3-implement`, not a replacement. Use the manual Step 3 workflow when you want interactive control over each phase, or use this loop when you prefer hands-off autonomous execution.
## Installation
```bash
# From the plan2code root directory:
# Option 1: Install everything (recommended)
node install.js # Select option A
# Option 2: Install loop only
node install.js # Select option O
# Option 3: Manual build and link
cd plan2code-loop
npm install
npm run build
npm link
```
## Usage
Simply run the command - everything is interactive:
```bash
plan2code-loop
```
The CLI will:
1. Auto-detect specs in `./specs/` directory
2. Let you select a spec if multiple are found
3. Prompt to continue if an existing session is found
4. Ask for JIRA ticket ID, agent selection, loop mode, and max iterations
## How It Works
The loop uses an **LLM-driven discovery** approach:
1. **Spec Selection** - Interactive menu to select from discovered specs
2. **Task Discovery** - The AI reads `overview.md` and phase files to find unchecked tasks
3. **Implementation** - The AI implements tasks (one per iteration in task mode, or all in a phase in phase mode)
4. **Checkbox Update** - The AI marks tasks complete in the markdown file
5. **Scratchpad Update** - The AI appends notes to the per-spec scratchpad
6. **Completion Marker** - The AI outputs structured markers (e.g., `TASK_COMPLETE: 1.1 - description`)
7. **Loop** - Repeat until all tasks done or max iterations reached
### Loop Modes
The CLI asks you to choose a loop mode:
| Mode | Behavior | Git Commits | Best For |
|------|----------|-------------|----------|
| **One task per loop** (default) | Each agent invocation implements exactly one task | Node controller commits after each task | Smaller models, careful step-by-step execution |
| **One phase per loop** | Each agent invocation implements all remaining tasks in the current phase | LLM commits after each task (with JIRA ID if provided) | Smart models with larger context windows, keeping related tasks together |
### Why LLM-Driven?
The Node app does NOT parse markdown to find tasks. Instead, the AI reads the spec files directly and decides what to work on. This is:
- **More flexible** - Works with any reasonable markdown format
- **Smarter** - AI can handle edge cases and ambiguity
- **Simpler** - Node code is just orchestration, not parsing
## Completion Markers
The AI must output one of these markers at the end of each iteration:
```
TASK_COMPLETE: 1.1 - Initialize project structure
TASK_BLOCKED: 2.3 - Missing API credentials
PHASE_COMPLETE
LOOP_COMPLETE
```
| Marker | Meaning |
|--------|---------|
| `TASK_COMPLETE: X.X - desc` | Task implemented and marked complete |
| `TASK_BLOCKED: X.X - reason` | Cannot complete task (explains why) |
| `PHASE_COMPLETE` | Current phase finished (phase mode only) |
| `LOOP_COMPLETE` | All phases finished |
In **phase mode**, the AI outputs multiple `TASK_COMPLETE` markers (one per task) within a single iteration, followed by `PHASE_COMPLETE` or `LOOP_COMPLETE`.
## Session Files
Session state is stored **per-spec** inside the spec directory:
```
specs/my-feature/
├── overview.md
├── phase-1.md
├── phase-2.md
└── .plan2code-loop/ # Per-spec session state
├── config.json # Session configuration
├── scratchpad.md # LLM-managed progress notes
├── iteration.log # JSON log of each iteration
└── spec.hash # Hash for detecting spec changes
```
The scratchpad is managed by the LLM itself - after each task, the AI appends notes about what was done, decisions made, and files changed. This helps future iterations skip exploration.
## Supported Agents
| Agent | Status |
|-------|--------|
| Claude Code | Supported |
| GitHub Copilot CLI | Supported |
The loop uses your configured default model for each agent.
## Example Session
```
$ plan2code-loop
╭──────────────────────────────────────╮
│ │
│ 🔮 Plany's Loop │
│ Autonomous Implementation │
│ │
╰──────────────────────────────────────╯
Found spec: specs/todo-app
Feature: Todo App
Phases: 0/3
Tasks: 0/15
══════════════════════════════════════════════
Spec: Todo App
══════════════════════════════════════════════
Phases: 0/3
Tasks: 0/15
? JIRA Ticket ID (optional): PROJ-123
? Select AI agent: Claude Code
? Tasks per loop iteration: One task per loop (default)
? Maximum iterations: 100
Starting Plan2Code Loop
══════════════════════════════════════════════
Agent: Claude Code
Model: default
Spec: C:\projects\my-app\specs\todo-app
Loop mode: One task per loop
Max iterations: 100
Iteration 1/100
[1/100] Task 1.1: Initialize project with Vite (45s)
✓ Completed: Task 1.1: Initialize project with Vite
Iteration 2/100
[2/100] Task 1.2: Configure TypeScript (32s)
✓ Completed: Task 1.2: Configure TypeScript
...
Session Summary
══════════════════════════════════════════════
Total iterations: 12
Tasks completed: 12
Exit reason: all_complete
Session files saved to specs/todo-app/.plan2code-loop:
- config.json (session configuration)
- scratchpad.md (LLM-managed notes)
- iteration.log (history)
```
## Development
```bash
# Install dependencies
npm install
# Build
npm run build
# Link for global usage
npm link
# Unlink
npm unlink
```
## Architecture
```
src/
├── bin/plan2code-loop.ts # CLI entry point
├── index.ts # Main exports
├── controller.ts # Loop orchestration
├── cli.ts # Interactive prompts
├── agents/ # Agent implementations
│ ├── claude-code.ts
│ └── copilot-cli.ts
├── prompt/ # Prompt building
│ ├── templates.ts
│ └── builder.ts
├── state/ # Session state management
│ └── manager.ts
├── spec/ # Spec utilities (for CLI display)
│ └── utils.ts
└── utils/ # Utilities
├── completion.ts # Marker parsing
└── logger.ts
```
-46
View File
@@ -1,46 +0,0 @@
{
"name": "plan2code-loop",
"version": "1.6.2",
"description": "Plan2Code Loop - Autonomous spec-driven implementation CLI",
"type": "module",
"main": "dist/index.js",
"bin": {
"plan2code-loop": "./dist/bin/plan2code-loop.js"
},
"files": [
"dist"
],
"engines": {
"node": ">=18.0.0"
},
"keywords": [
"cli",
"ai",
"agent",
"automation",
"claude",
"copilot",
"spec-driven"
],
"license": "MIT",
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"start": "node dist/bin/plan2code-loop.js",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@inquirer/prompts": "^8.1.0",
"chalk": "^5.6.2",
"execa": "^9.6.1",
"fs-extra": "^11.3.3",
"ora": "^9.0.0"
},
"devDependencies": {
"@types/fs-extra": "^11.0.4",
"@types/node": "^25.0.3",
"tsup": "^8.5.1",
"typescript": "^5.9.3"
}
}
-82
View File
@@ -1,82 +0,0 @@
import type { Agent, AgentConfig, AgentExecutionOptions, AgentExecutionResult } from './types.js';
import { executeCommand } from '../utils/process.js';
import { writeFileSync, unlinkSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
const claudeCodeConfig: AgentConfig = {
name: 'claude-code',
displayName: 'Claude Code',
command: 'claude',
models: [
{ value: 'default', label: 'Default (use Claude config)' },
],
defaultModel: 'default',
flags: {
prompt: '--print',
model: '--model',
skipPermissions: '--dangerously-skip-permissions',
},
};
class ClaudeCodeAgent implements Agent {
readonly config = claudeCodeConfig;
async execute(options: AgentExecutionOptions): Promise<AgentExecutionResult> {
// Write prompt to temp file - more reliable than stdin on Windows
const tempFile = join(tmpdir(), `plan2code-prompt-${Date.now()}.txt`);
writeFileSync(tempFile, options.prompt, 'utf-8');
try {
// Build args: flags first, then read prompt from temp file via shell
const args: string[] = [
this.config.flags.prompt, // --print for non-interactive mode
this.config.flags.skipPermissions,
];
// Only add --model if not using default
if (options.model && options.model !== 'default') {
args.push(this.config.flags.model, options.model);
}
// Use stdin from the temp file
const result = await executeCommand({
command: this.config.command,
args,
cwd: options.cwd,
timeout: options.timeout,
signal: options.signal,
stdinFile: tempFile,
});
return {
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
timedOut: result.timedOut,
cancelled: result.cancelled,
duration: result.duration,
};
} finally {
// Clean up temp file
try {
unlinkSync(tempFile);
} catch {
// Ignore cleanup errors
}
}
}
async isAvailable(): Promise<boolean> {
// Run claude --version to verify it's actually installed and working
const result = await executeCommand({
command: this.config.command,
args: ['--version'],
cwd: process.cwd(),
timeout: 5000,
});
return result.exitCode === 0;
}
}
export const claudeCodeAgent = new ClaudeCodeAgent();
-70
View File
@@ -1,70 +0,0 @@
import type { Agent, AgentConfig, AgentExecutionOptions, AgentExecutionResult } from './types.js';
import { executeCommand } from '../utils/process.js';
const copilotCliConfig: AgentConfig = {
name: 'copilot-cli',
displayName: 'GitHub Copilot CLI',
command: 'copilot',
models: [
{ value: 'claude-sonnet-4', label: 'Claude Sonnet 4 (Default)' },
{ value: 'claude-sonnet-4.5', label: 'Claude Sonnet 4.5' },
{ value: 'claude-opus-4.5', label: 'Claude Opus 4.5' },
{ value: 'gpt-5', label: 'GPT-5' },
{ value: 'gpt-5-mini', label: 'GPT-5 Mini' },
{ value: 'gemini-3-pro-preview', label: 'Gemini 3 Pro' },
],
defaultModel: 'claude-sonnet-4',
flags: {
prompt: '-p',
model: '--model',
skipPermissions: '--allow-all-tools',
silent: '-s',
},
};
class CopilotCliAgent implements Agent {
readonly config = copilotCliConfig;
async execute(options: AgentExecutionOptions): Promise<AgentExecutionResult> {
// Use stdin for prompt to handle multi-line text properly
const args: string[] = [];
// Only add --model if not using default
if (options.model && options.model !== 'default') {
args.push(this.config.flags.model, options.model);
}
args.push(this.config.flags.skipPermissions, this.config.flags.silent!);
const result = await executeCommand({
command: this.config.command,
args,
cwd: options.cwd,
timeout: options.timeout,
signal: options.signal,
stdin: options.prompt,
});
return {
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
timedOut: result.timedOut,
cancelled: result.cancelled,
duration: result.duration,
};
}
async isAvailable(): Promise<boolean> {
// Run copilot --version to verify it's installed
const result = await executeCommand({
command: this.config.command,
args: ['--version'],
cwd: process.cwd(),
timeout: 5000,
});
return result.exitCode === 0;
}
}
export const copilotCliAgent = new CopilotCliAgent();
-19
View File
@@ -1,19 +0,0 @@
export type {
Agent,
AgentConfig,
AgentExecutionOptions,
AgentExecutionResult,
ModelOption,
} from './types.js';
export { agentRegistry } from './registry.js';
export { claudeCodeAgent } from './claude-code.js';
export { copilotCliAgent } from './copilot-cli.js';
// Register all agents
import { agentRegistry } from './registry.js';
import { claudeCodeAgent } from './claude-code.js';
import { copilotCliAgent } from './copilot-cli.js';
agentRegistry.register(claudeCodeAgent);
agentRegistry.register(copilotCliAgent);
-34
View File
@@ -1,34 +0,0 @@
import type { Agent } from './types.js';
class AgentRegistry {
private agents: Map<string, Agent> = new Map();
register(agent: Agent): void {
this.agents.set(agent.config.name, agent);
}
get(name: string): Agent | undefined {
return this.agents.get(name);
}
getAll(): Agent[] {
return Array.from(this.agents.values());
}
getAvailable(): Promise<Agent[]> {
return Promise.all(
this.getAll().map(async (agent) => ({
agent,
available: await agent.isAvailable(),
}))
).then((results) =>
results.filter((r) => r.available).map((r) => r.agent)
);
}
getNames(): string[] {
return Array.from(this.agents.keys());
}
}
export const agentRegistry = new AgentRegistry();
-42
View File
@@ -1,42 +0,0 @@
export interface ModelOption {
value: string;
label: string;
}
export interface AgentConfig {
name: string;
displayName: string;
command: string;
models: ModelOption[];
defaultModel: string;
flags: {
prompt: string;
model: string;
skipPermissions: string;
silent?: string;
};
}
export interface AgentExecutionOptions {
prompt: string;
model: string;
timeout: number; // milliseconds
verbose: boolean;
cwd: string;
signal?: AbortSignal; // For cancellation
}
export interface AgentExecutionResult {
stdout: string;
stderr: string;
exitCode: number;
timedOut: boolean;
cancelled: boolean;
duration: number; // milliseconds
}
export interface Agent {
config: AgentConfig;
execute(options: AgentExecutionOptions): Promise<AgentExecutionResult>;
isAvailable(): Promise<boolean>;
}
-34
View File
@@ -1,34 +0,0 @@
import { run } from '../index.js';
import { logger } from '../utils/index.js';
async function main() {
try {
const result = await run();
if (!result) {
process.exit(0);
}
// Exit codes per spec
switch (result.exitReason) {
case 'all_complete':
logger.success('Loop completed successfully - all tasks done!');
process.exit(0);
case 'max_iterations':
logger.warning('Loop ended: max iterations reached');
process.exit(1);
case 'interrupted':
logger.info('Loop interrupted by user');
process.exit(2);
case 'error':
logger.error('Loop ended with error');
process.exit(3);
}
} catch (error) {
logger.error(error instanceof Error ? error.message : String(error));
process.exit(3);
}
}
main();
-240
View File
@@ -1,240 +0,0 @@
import path from 'path';
import { confirm, input, select } from '@inquirer/prompts';
import { agentRegistry } from './agents/index.js';
import { StateManager, type SessionConfig, type LoopMode } from './state/index.js';
import { detectSpecDirectories, getSpecProgress } from './spec/utils.js';
import { logger } from './utils/index.js';
export interface SessionSetupResult {
config: SessionConfig;
isResume: boolean;
}
/**
* Detect and select a spec directory
*/
async function selectSpec(cwd: string = process.cwd()): Promise<string | null> {
// Auto-detect spec directories
const specDirs = await detectSpecDirectories(cwd);
if (specDirs.length === 0) {
logger.error('No spec directories found!');
logger.info('Expected: specs/<feature>/overview.md');
logger.info('');
logger.info('To get started:');
logger.info('');
logger.info('1. Create a spec using `plan2code-1-plan`');
logger.info(' command in our AI Agent');
logger.info('');
logger.info('2. Come back here and run `plan2code-loop`');
logger.info(' as an alternative to `plan2code-3-implement`');
logger.info('');
return null;
}
if (specDirs.length === 1) {
const spec = specDirs[0];
const progress = await getSpecProgress(spec);
logger.info(`Found spec: ${path.relative(cwd, spec)}`);
logger.dim(` Feature: ${progress.featureName}`);
logger.dim(` Phases: ${progress.totalPhases}`);
return spec;
}
// Multiple specs - let user choose
const choices = await Promise.all(
specDirs.map(async (spec) => {
const progress = await getSpecProgress(spec);
const relativePath = path.relative(cwd, spec);
return {
name: `${progress.featureName} (${progress.totalPhases} phases) - ${relativePath}`,
value: spec,
};
})
);
const selectedSpec = await select({
message: 'Select spec to implement:',
choices,
});
return selectedSpec;
}
/**
* Select AI agent
*/
async function selectAgent(): Promise<string> {
const allAgents = agentRegistry.getAll();
const agentName = await select({
message: 'Select AI agent:',
choices: allAgents.map((agent) => ({
name: agent.config.displayName,
value: agent.config.name,
})),
});
return agentName;
}
/**
* Prompt for JIRA ticket ID
*/
async function promptJiraTicketId(): Promise<string | undefined> {
const ticketId = await input({
message: 'JIRA Ticket ID (optional, for commit messages):',
});
return ticketId.trim() || undefined;
}
/**
* Select maximum iterations
*/
async function selectMaxIterations(): Promise<number> {
const choices = [15, 30, 50, 75, 100, 125, 150, 200];
const max = await select({
message: 'Maximum iterations:',
choices: choices.map((n) => ({
name: n.toString(),
value: n,
})),
default: 100,
});
return max;
}
/**
* Select loop mode: one task per loop or one phase per loop
*/
async function selectLoopMode(): Promise<LoopMode> {
const mode = await select<LoopMode>({
message: 'Tasks per loop iteration:',
choices: [
{
name: 'One task per loop (default)',
value: 'task' as LoopMode,
},
{
name: 'One phase per loop (related tasks together)',
value: 'phase' as LoopMode,
},
],
default: 'task',
});
return mode;
}
/**
* Handle existing session - returns action to take
*/
async function handleExistingSession(
stateManager: StateManager,
specPath: string
): Promise<'continue' | 'fresh' | 'new'> {
const state = await stateManager.detectSessionState(specPath);
if (state === 'new') {
return 'new';
}
if (state === 'continue') {
const config = await stateManager.readConfig();
const lastIter = config?.currentIteration ?? 0;
logger.info(`Found existing session at iteration ${lastIter}`);
const continueSession = await confirm({
message: 'Continue previous session?',
default: true,
});
return continueSession ? 'continue' : 'fresh';
}
if (state === 'changed') {
logger.warning('Spec has changed since last session.');
const startFresh = await confirm({
message: 'Start fresh? (This will clear previous progress)',
default: false,
});
return startFresh ? 'fresh' : 'continue';
}
return 'new';
}
/**
* Setup session via interactive prompts
*/
export async function setupSession(
stateManager: StateManager
): Promise<SessionSetupResult | null> {
// Show Planny welcome
logger.welcome();
// Select spec
const specPath = await selectSpec(process.cwd());
if (!specPath) {
return null;
}
// Set spec path on state manager for per-spec state directory
stateManager.setSpecPath(specPath);
// Show spec progress
const progress = await getSpecProgress(specPath);
console.log();
logger.header(`Spec: ${progress.featureName}`);
logger.info(`Phases: ${progress.totalPhases}`);
console.log();
// Check for existing session
const sessionAction = await handleExistingSession(stateManager, specPath);
if (sessionAction === 'continue') {
const existingConfig = await stateManager.readConfig();
if (existingConfig) {
const agent = await selectAgent();
existingConfig.agent = agent;
await stateManager.writeConfig(existingConfig);
logger.info('Resuming previous session...');
return { config: existingConfig, isResume: true };
}
}
if (sessionAction === 'fresh') {
await stateManager.clearState();
}
// Collect new session configuration
const jiraTicketId = await promptJiraTicketId();
const agent = await selectAgent();
const loopMode = await selectLoopMode();
const maxIterations = await selectMaxIterations();
const config: SessionConfig = {
agent,
model: 'default',
maxIterations,
specPath,
timeout: 3,
maxRetries: 5,
verbose: false,
startedAt: new Date().toISOString(),
currentIteration: 0,
jiraTicketId,
loopMode,
};
// Initialize session
await stateManager.initializeNewSession(config);
return { config, isResume: false };
}
-522
View File
@@ -1,522 +0,0 @@
import { agentRegistry, type Agent, type AgentExecutionResult } from './agents/index.js';
import { StateManager, type SessionConfig, type IterationLogEntry } from './state/index.js';
import { buildLoopPrompt } from './prompt/index.js';
import { checkForCompletion, checkForAllCompletions, logger, ensureGitRepo, ensureGitignore, type CompletionCheckResult } from './utils/index.js';
export interface TaskCompleteInfo {
marker: string;
taskId?: string;
taskName?: string;
}
export interface ControllerOptions {
config: SessionConfig;
stateManager: StateManager;
onIteration?: (iteration: number, max: number) => void;
onTaskComplete?: (info: TaskCompleteInfo) => void | Promise<void>;
onLoopComplete?: () => void;
}
export interface LoopResult {
completed: boolean;
iterations: number;
finalMarker?: string;
exitReason: 'all_complete' | 'max_iterations' | 'interrupted' | 'error';
tasksCompleted: number;
prereqsCompleted: number;
error?: Error;
}
export class Controller {
private readonly config: SessionConfig;
private readonly stateManager: StateManager;
private readonly agent: Agent;
private readonly onIteration?: (iteration: number, max: number) => void;
private readonly onTaskComplete?: (info: TaskCompleteInfo) => void | Promise<void>;
private readonly onLoopComplete?: () => void;
private interrupted = false;
private abortController: AbortController | null = null;
private tasksCompleted = 0;
private prereqsCompleted = 0;
constructor(options: ControllerOptions) {
this.config = options.config;
this.stateManager = options.stateManager;
this.onIteration = options.onIteration;
this.onTaskComplete = options.onTaskComplete;
this.onLoopComplete = options.onLoopComplete;
const agent = agentRegistry.get(this.config.agent);
if (!agent) {
throw new Error(`Agent not found: ${this.config.agent}`);
}
this.agent = agent;
}
private async buildPrompt(): Promise<string> {
return buildLoopPrompt({
specPath: this.config.specPath,
iteration: this.config.currentIteration + 1,
maxIterations: this.config.maxIterations,
stateManager: this.stateManager,
loopMode: this.config.loopMode || 'task',
jiraTicketId: this.config.jiraTicketId,
});
}
private computeTimeoutMs(attempt: number): number {
const baseMs = this.config.timeout * 60 * 1000;
return baseMs + (attempt * 30 * 1000);
}
private formatDuration(ms: number): string {
const totalSec = Math.round(ms / 1000);
const min = Math.floor(totalSec / 60);
const sec = totalSec % 60;
if (min === 0) return `${sec}s`;
if (sec === 0) return `${min}m`;
return `${min}m ${sec}s`;
}
private async executeWithRetry(prompt: string, iterNum: number): Promise<AgentExecutionResult | 'fatal_timeout'> {
const maxAttempts = (this.config.maxRetries ?? 5) + 1;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const timeoutMs = this.computeTimeoutMs(attempt);
if (attempt > 0) {
const prevTimeoutMs = this.computeTimeoutMs(attempt - 1);
logger.warning(
`Timed out after ${this.formatDuration(prevTimeoutMs)}, retrying (${attempt}/${maxAttempts - 1})...`
);
}
const spinnerBase = attempt > 0
? `Waiting for AI Agent response (retry ${attempt}/${maxAttempts - 1})`
: 'Waiting for AI Agent response (please be patient)';
const spinner = logger.spinner(spinnerBase);
const startTime = Date.now();
const elapsedInterval = setInterval(() => {
const elapsed = Math.round((Date.now() - startTime) / 1000);
spinner.text = `${spinnerBase} ... (${elapsed}s)`;
}, 1000);
const result = await this.executeIteration(prompt, timeoutMs);
clearInterval(elapsedInterval);
spinner.stop();
// Cancelled or interrupted — return immediately, don't retry
if (result.cancelled || this.interrupted) {
return result;
}
// Completed (success or error exit code) — return to caller
if (!result.timedOut) {
return result;
}
// Timed out — retry if attempts remain, otherwise fatal
if (attempt < maxAttempts - 1) {
continue;
}
// All attempts exhausted
logger.error(
`Iteration ${iterNum} timed out on all ${maxAttempts} attempt${maxAttempts === 1 ? '' : 's'}. Stopping loop.`
);
const entry: IterationLogEntry = {
iteration: iterNum,
timestamp: new Date().toISOString(),
duration: result.duration,
exitCode: -1,
status: 'timeout',
};
await this.stateManager.appendIterationLog(entry);
return 'fatal_timeout';
}
return 'fatal_timeout'; // unreachable, satisfies TS
}
private async executeIteration(prompt: string, timeoutMs: number): Promise<AgentExecutionResult> {
// Create new AbortController for this iteration
this.abortController = new AbortController();
const result = await this.agent.execute({
prompt,
model: this.config.model,
timeout: timeoutMs,
verbose: this.config.verbose,
cwd: process.cwd(),
signal: this.abortController.signal,
});
this.abortController = null;
return result;
}
private createLogEntry(
result: AgentExecutionResult,
status: IterationLogEntry['status'],
marker?: string
): IterationLogEntry {
return {
iteration: this.config.currentIteration + 1,
timestamp: new Date().toISOString(),
duration: result.duration,
exitCode: result.exitCode,
status,
completionMarker: marker,
};
}
private formatTaskDisplay(completion: CompletionCheckResult): string {
if (completion.taskId && completion.taskName) {
return `Task ${completion.taskId}: ${completion.taskName}`;
} else if (completion.taskId) {
return `Task ${completion.taskId}`;
}
return '';
}
private displayIterationResult(result: AgentExecutionResult, iterNum: number, completion: CompletionCheckResult): void {
const duration = Math.round(result.duration / 1000);
const taskDisplay = this.formatTaskDisplay(completion);
// Show iteration completion with task info if available
if (taskDisplay) {
logger.iteration(iterNum, this.config.maxIterations, `${taskDisplay} (${duration}s)`);
} else {
logger.iteration(iterNum, this.config.maxIterations, `completed in ${duration}s`);
}
// Verbose mode: show full output
if (this.config.verbose) {
console.log();
logger.dim('--- Agent Output ---');
console.log(result.stdout);
if (result.stderr) {
logger.dim('--- Agent Stderr ---');
console.log(result.stderr);
}
logger.dim('--- End Output ---');
console.log();
} else if (result.exitCode !== 0 && result.stderr.trim()) {
logger.error(` ${result.stderr.trim().split('\n')[0]}`);
}
}
async run(): Promise<LoopResult> {
// Pre-flight: verify agent CLI is available
const isAvailable = await this.agent.isAvailable();
if (!isAvailable) {
logger.error(`"${this.agent.config.displayName}" is not available!`);
logger.info(`Please ensure the "${this.agent.config.command}" command is installed and available in your PATH.`);
throw new Error(`Agent "${this.agent.config.displayName}" is not available. Please install it and try again.`);
}
// Ensure git repo and .gitignore are set up before any iterations
const gitReady = await ensureGitRepo(process.cwd());
if (!gitReady) {
throw new Error('Failed to initialize a git repository in the current working directory. Cannot start Plan2Code Loop.');
}
ensureGitignore(process.cwd());
const loopModeLabel = (this.config.loopMode || 'task') === 'phase' ? 'One phase per loop' : 'One task per loop';
logger.header('Starting Plan2Code Loop');
logger.info(`Agent: ${this.agent.config.displayName}`);
logger.info(`Model: ${this.config.model}`);
logger.info(`Spec: ${this.config.specPath}`);
logger.info(`Loop mode: ${loopModeLabel}`);
logger.info(`Max iterations: ${this.config.maxIterations}`);
console.log();
while (this.config.currentIteration < this.config.maxIterations) {
if (this.interrupted) {
return {
completed: false,
iterations: this.config.currentIteration,
exitReason: 'interrupted',
tasksCompleted: this.tasksCompleted,
prereqsCompleted: this.prereqsCompleted,
};
}
const iterNum = this.config.currentIteration + 1;
this.onIteration?.(iterNum, this.config.maxIterations);
console.log();
logger.info(`Iteration ${iterNum}/${this.config.maxIterations}`);
// Build prompt - simple, just spec path and iteration info
const prompt = await this.buildPrompt();
try {
const retryResult = await this.executeWithRetry(prompt, iterNum);
if (retryResult === 'fatal_timeout') {
return {
completed: false,
iterations: this.config.currentIteration,
exitReason: 'error',
tasksCompleted: this.tasksCompleted,
prereqsCompleted: this.prereqsCompleted,
error: new Error(`Iteration ${iterNum} failed after all retry attempts`),
};
}
const result = retryResult;
// Check if cancelled
if (result.cancelled || this.interrupted) {
logger.info('Agent process cancelled');
const entry: IterationLogEntry = {
iteration: iterNum,
timestamp: new Date().toISOString(),
duration: result.duration,
exitCode: -1,
status: 'interrupted',
};
await this.stateManager.appendIterationLog(entry);
return {
completed: false,
iterations: this.config.currentIteration,
exitReason: 'interrupted',
tasksCompleted: this.tasksCompleted,
prereqsCompleted: this.prereqsCompleted,
};
}
// Branch completion handling based on loop mode
const isPhaseMode = (this.config.loopMode || 'task') === 'phase';
if (isPhaseMode) {
// Phase mode: parse ALL completion markers from output
const allCompletions = checkForAllCompletions(result.stdout + result.stderr);
// Determine status
let status: IterationLogEntry['status'] = 'running';
if (allCompletions.tasks.length > 0 || allCompletions.loopComplete || allCompletions.phaseComplete) {
const hasBlocked = allCompletions.tasks.some(t => t.marker === 'TASK_BLOCKED');
const hasCompleted = allCompletions.tasks.some(t => t.marker === 'TASK_COMPLETE' || t.marker === 'PREREQ_COMPLETE' || t.marker === 'PREREQ_ASSUMED');
status = hasCompleted || allCompletions.phaseComplete || allCompletions.loopComplete ? 'completed' : hasBlocked ? 'blocked' : 'running';
} else if (result.timedOut) {
status = 'timeout';
} else if (result.exitCode !== 0) {
status = 'error';
}
// Log iteration with count of tasks
const markerSummary = allCompletions.tasks.map(t => `${t.marker}: ${t.taskId}`).join(', ');
const logEntry = this.createLogEntry(result, status, markerSummary || undefined);
await this.stateManager.appendIterationLog(logEntry);
// Display each completed task
const duration = Math.round(result.duration / 1000);
for (const task of allCompletions.tasks) {
if (task.marker === 'TASK_COMPLETE') {
this.tasksCompleted++;
const taskDisplay = this.formatTaskDisplay(task);
logger.success(taskDisplay ? `Completed: ${taskDisplay}` : 'Task completed!');
} else if (task.marker === 'PREREQ_COMPLETE') {
this.prereqsCompleted++;
const prereqDisplay = task.taskId && task.taskName
? `Prereq ${task.taskId}: ${task.taskName}`
: task.taskId ? `Prereq ${task.taskId}` : 'Prerequisite';
logger.success(`Verified: ${prereqDisplay}`);
} else if (task.marker === 'PREREQ_ASSUMED') {
this.prereqsCompleted++;
const prereqDisplay = task.taskId && task.taskName
? `Prereq ${task.taskId}: ${task.taskName}`
: task.taskId ? `Prereq ${task.taskId}` : 'Prerequisite';
logger.success(`Assumed: ${prereqDisplay}`);
} else if (task.marker === 'TASK_BLOCKED') {
const blockInfo = task.taskId
? `Task ${task.taskId} blocked: ${task.reason || 'Unknown reason'}`
: `Task blocked: ${task.reason || 'Unknown reason'}`;
logger.warning(blockInfo);
}
}
// Show phase-level summary
if (allCompletions.tasks.length > 0) {
const completedCount = allCompletions.tasks.filter(t => t.marker === 'TASK_COMPLETE').length;
const prereqCount = allCompletions.tasks.filter(t => t.marker === 'PREREQ_COMPLETE' || t.marker === 'PREREQ_ASSUMED').length;
const blockedCount = allCompletions.tasks.filter(t => t.marker === 'TASK_BLOCKED').length;
const parts: string[] = [];
if (completedCount > 0) parts.push(`${completedCount} task(s) completed`);
if (prereqCount > 0) parts.push(`${prereqCount} prereq(s) verified`);
if (blockedCount > 0) parts.push(`${blockedCount} blocked`);
logger.iteration(iterNum, this.config.maxIterations,
`Phase done: ${parts.join(', ')} (${duration}s)`);
} else {
logger.iteration(iterNum, this.config.maxIterations, `completed in ${duration}s`);
}
// Verbose output
if (this.config.verbose) {
console.log();
logger.dim('--- Agent Output ---');
console.log(result.stdout);
if (result.stderr) {
logger.dim('--- Agent Stderr ---');
console.log(result.stderr);
}
logger.dim('--- End Output ---');
console.log();
} else if (result.exitCode !== 0 && result.stderr.trim()) {
logger.error(` ${result.stderr.trim().split('\n')[0]}`);
}
// Handle LOOP_COMPLETE
if (allCompletions.loopComplete) {
this.onLoopComplete?.();
logger.success('All tasks complete!');
return {
completed: true,
iterations: iterNum,
finalMarker: 'LOOP_COMPLETE',
exitReason: 'all_complete',
tasksCompleted: this.tasksCompleted,
prereqsCompleted: this.prereqsCompleted,
};
}
} else {
// Task mode (default): existing single-marker logic
const completion = checkForCompletion(result.stdout + result.stderr);
// Determine status
let status: IterationLogEntry['status'] = 'running';
if (completion.completed) {
if (completion.marker === 'TASK_BLOCKED') {
status = 'blocked';
} else {
status = 'completed';
}
} else if (result.timedOut) {
status = 'timeout';
} else if (result.exitCode !== 0) {
status = 'error';
}
// Log iteration
const logEntry = this.createLogEntry(result, status, completion.marker);
await this.stateManager.appendIterationLog(logEntry);
// Display iteration result with task info from completion marker
this.displayIterationResult(result, iterNum, completion);
// Handle completion markers
if (completion.completed) {
const taskDisplay = this.formatTaskDisplay(completion);
if (completion.marker === 'TASK_COMPLETE') {
this.tasksCompleted++;
await this.onTaskComplete?.({
marker: completion.marker,
taskId: completion.taskId,
taskName: completion.taskName,
});
logger.success(taskDisplay ? `Completed: ${taskDisplay}` : 'Task completed!');
} else if (completion.marker === 'PREREQ_COMPLETE' || completion.marker === 'PREREQ_ASSUMED') {
this.prereqsCompleted++;
await this.onTaskComplete?.({
marker: completion.marker,
taskId: completion.taskId,
taskName: completion.taskName,
});
const prereqDisplay = completion.taskId && completion.taskName
? `Prereq ${completion.taskId}: ${completion.taskName}`
: completion.taskId ? `Prereq ${completion.taskId}` : 'Prerequisite';
const verb = completion.marker === 'PREREQ_COMPLETE' ? 'Verified' : 'Assumed';
logger.success(`${verb}: ${prereqDisplay}`);
} else if (completion.marker === 'TASK_BLOCKED') {
const blockInfo = completion.taskId
? `Task ${completion.taskId} blocked: ${completion.reason || 'Unknown reason'}`
: `Task blocked: ${completion.reason || 'Unknown reason'}`;
logger.warning(blockInfo);
} else if (completion.marker === 'LOOP_COMPLETE') {
// Commit any final changes before completing
this.tasksCompleted++;
await this.onTaskComplete?.({
marker: completion.marker,
taskId: completion.taskId,
taskName: completion.taskName || 'Final implementation complete',
});
this.onLoopComplete?.();
logger.success('All tasks complete!');
return {
completed: true,
iterations: iterNum,
finalMarker: 'LOOP_COMPLETE',
exitReason: 'all_complete',
tasksCompleted: this.tasksCompleted,
prereqsCompleted: this.prereqsCompleted,
};
}
}
}
// Increment iteration and update spec hash (so resume doesn't see false changes)
await this.stateManager.incrementIteration();
await this.stateManager.updateSpecHash(this.config.specPath);
this.config.currentIteration++;
// Handle error (but continue - LLM might recover)
if (result.exitCode !== 0) {
// In phase mode, check if any tasks completed despite error exit code
const hasCompletions = isPhaseMode
? checkForAllCompletions(result.stdout + result.stderr).tasks.length > 0
: checkForCompletion(result.stdout + result.stderr).completed;
if (!hasCompletions) {
logger.warning(`Iteration ${iterNum} exited with code ${result.exitCode}, continuing...`);
}
}
} catch (error) {
clearInterval(elapsedInterval);
spinner.stop();
logger.error(`Iteration ${iterNum} failed: ${error}`);
// Log the error
const entry: IterationLogEntry = {
iteration: iterNum,
timestamp: new Date().toISOString(),
duration: 0,
exitCode: -1,
status: 'error',
};
await this.stateManager.appendIterationLog(entry);
return {
completed: false,
iterations: this.config.currentIteration,
exitReason: 'error',
tasksCompleted: this.tasksCompleted,
prereqsCompleted: this.prereqsCompleted,
error: error instanceof Error ? error : new Error(String(error)),
};
}
}
// Max iterations reached
logger.warning('Max iterations reached');
return {
completed: false,
iterations: this.config.currentIteration,
exitReason: 'max_iterations',
tasksCompleted: this.tasksCompleted,
prereqsCompleted: this.prereqsCompleted,
};
}
interrupt(): void {
this.interrupted = true;
if (this.abortController) {
this.abortController.abort();
}
}
}
-96
View File
@@ -1,96 +0,0 @@
import path from 'path';
import { StateManager } from './state/index.js';
import { Controller, type LoopResult, type TaskCompleteInfo } from './controller.js';
import { setupSession } from './cli.js';
import { logger, createTaskCommit } from './utils/index.js';
export async function run(): Promise<LoopResult | null> {
// Ensure agents are registered
await import('./agents/index.js');
const stateManager = new StateManager();
const result = await setupSession(stateManager);
if (!result) {
return null;
}
const { config, isResume } = result;
if (isResume) {
logger.info(`Resuming from iteration ${config.currentIteration}`);
}
const controller = new Controller({
config,
stateManager,
onIteration: (iter, max) => {
// Could add git checkpoint logic here if needed
},
onTaskComplete: async (info: TaskCompleteInfo) => {
// Create git commit for completed task
const taskName = info.taskName || info.taskId || 'Task completed';
await createTaskCommit({
taskName,
jiraTicketId: config.jiraTicketId,
cwd: process.cwd(),
});
},
onLoopComplete: () => {
// All tasks completed callback
},
});
// Setup interrupt handler
const handleInterrupt = () => {
logger.warning('\nInterrupt received, saving state...');
controller.interrupt();
};
process.on('SIGINT', handleInterrupt);
process.on('SIGTERM', handleInterrupt);
try {
const loopResult = await controller.run();
// Display summary
console.log();
logger.header('Session Summary');
logger.info(`Total iterations: ${loopResult.iterations}`);
logger.info(`Tasks completed: ${loopResult.tasksCompleted}`);
if (loopResult.prereqsCompleted > 0) {
logger.info(`Prerequisites verified: ${loopResult.prereqsCompleted}`);
}
logger.info(`Exit reason: ${loopResult.exitReason}`);
if (loopResult.finalMarker) {
logger.info(`Completion marker: ${loopResult.finalMarker}`);
}
if (loopResult.error) {
logger.error(`Error: ${loopResult.error.message}`);
}
// Show completion celebration and finalize reminder when all phases complete
if (loopResult.exitReason === 'all_complete') {
logger.allPhasesComplete();
}
// Show state file locations (now per-spec)
console.log();
logger.dim(`Session files saved to ${path.relative(process.cwd(), stateManager.getStateDir())}:`);
logger.dim(' - config.json (session configuration)');
logger.dim(' - scratchpad.md (LLM-managed notes)');
logger.dim(' - iteration.log (history)');
return loopResult;
} finally {
process.off('SIGINT', handleInterrupt);
process.off('SIGTERM', handleInterrupt);
}
}
// Re-export types and classes
export { Controller, type ControllerOptions, type LoopResult, type TaskCompleteInfo } from './controller.js';
export { StateManager } from './state/index.js';
export { setupSession } from './cli.js';
export { agentRegistry, type Agent, type AgentConfig } from './agents/index.js';
export { detectSpecDirectories, getSpecProgress } from './spec/index.js';
-39
View File
@@ -1,39 +0,0 @@
import type { StateManager, LoopMode } from '../state/index.js';
import { LOOP_PROMPT_TEMPLATE, LOOP_PROMPT_TEMPLATE_PHASE } from './templates.js';
export interface PromptContext {
specPath: string;
iteration: number;
maxIterations: number;
stateManager: StateManager;
loopMode: LoopMode;
jiraTicketId?: string;
}
/**
* Build the prompt for the AI agent
* Selects template based on loop mode (task vs phase)
*/
export async function buildLoopPrompt(context: PromptContext): Promise<string> {
const { specPath, iteration, maxIterations, stateManager, loopMode, jiraTicketId } = context;
// Read scratchpad content for session continuity (LLM writes to this)
const scratchpadContent = await stateManager.readScratchpad();
// Project root is where plan2code-loop was invoked from
const projectRoot = process.cwd();
// Select template based on loop mode
const template = loopMode === 'phase' ? LOOP_PROMPT_TEMPLATE_PHASE : LOOP_PROMPT_TEMPLATE;
// Template substitution
const prompt = template
.replace(/{{projectRoot}}/g, projectRoot)
.replace(/{{specPath}}/g, specPath)
.replace(/{{iteration}}/g, iteration.toString())
.replace(/{{maxIterations}}/g, maxIterations.toString())
.replace(/{{scratchpadContent}}/g, scratchpadContent || '(First iteration - no previous progress)')
.replace(/{{jiraTicketId}}/g, jiraTicketId || '');
return prompt;
}
-6
View File
@@ -1,6 +0,0 @@
export {
buildLoopPrompt,
type PromptContext,
} from './builder.js';
export { LOOP_PROMPT_TEMPLATE, LOOP_PROMPT_TEMPLATE_PHASE } from './templates.js';
-200
View File
@@ -1,200 +0,0 @@
export const LOOP_PROMPT_TEMPLATE = `# PLAN2CODE-LOOP: Autonomous Task Implementation
## CRITICAL CONSTRAINT
**IMPLEMENT EXACTLY ONE TASK PER ITERATION.**
Do NOT implement multiple tasks. Do NOT complete an entire phase.
Find the FIRST unchecked task, implement ONLY that task, then STOP and report.
## Project Information
- **Project Root:** \`{{projectRoot}}\`
- **Spec Location:** \`{{specPath}}\`
- Read \`AGENTS.md\` for project-specific guidance if available
## IMPORTANT: File Locations
- Write ALL code files relative to the **project root** (\`{{projectRoot}}\`)
- The spec directory (\`{{specPath}}\`) is for documentation ONLY - never write code there
- Example: Create \`{{projectRoot}}/src/index.ts\`, NOT \`{{specPath}}/src/index.ts\`
## Iteration
{{iteration}} of {{maxIterations}}
## Task Discovery Process
1. Read \`{{specPath}}/overview.md\` to see all phases
2. Find the FIRST phase with an unchecked checkbox (\`- [ ]\` or \`- [/]\`)
3. Read that phase's file (e.g., \`phase-1.md\`)
4. Check the \`## Prerequisites\` section FIRST
5. Find the FIRST unverified prerequisite (no "VERIFIED" or "ASSUMED" annotation)
- If found, verify/complete it, then annotate "VERIFIED" or "ASSUMED: [reason]" inline
6. Only if ALL prerequisites are verified or assumed, find the FIRST unchecked task (\`- [ ]\`)
7. That is your ONE task - implement ONLY that task
## Checkbox States (Task items only)
- \`[ ]\` = incomplete/pending (do the FIRST one you find)
- \`[x]\` = complete (skip)
- \`[?]\` = assumed complete, couldn't verify (skip)
- \`[!]\` = blocked (skip)
Prerequisites use plain bullets with inline annotations, not checkboxes.
## Implementation Steps
1. Read and understand the single task
2. Implement it completely
3. Validate it works (run tests if applicable and double-check code)
4. Mark ONLY that task's checkbox as \`[x]\` in the phase file
5. If that was the LAST task in the phase, also mark the phase \`[x]\` in overview.md
6. Output your completion marker and STOP
## Git Policy
**DO NOT create git commits.** The orchestration system handles commits automatically after each task completion. Just implement the code and leave changes uncommitted.
## Completion Markers (REQUIRED FORMAT)
Output exactly ONE of these at the end, including the task ID and description:
**PREREQ_COMPLETE: [prereq_id] - [description]**
Example: \`PREREQ_COMPLETE: P1.1 - Verified Phase 1 complete\`
**PREREQ_ASSUMED: [prereq_id] - [description]**
Example: \`PREREQ_ASSUMED: P2.1 - Design approval (cannot verify)\`
**TASK_COMPLETE: [task_id] - [task_description]**
Example: \`TASK_COMPLETE: 1.1 - Initialize project structure\`
**TASK_BLOCKED: [task_id] - [reason]**
Example: \`TASK_BLOCKED: 2.3 - Missing API credentials\`
**LOOP_COMPLETE**
Use only when ALL phases in overview.md are marked complete.
## Scratchpad Management
After completing each task, add a new entry at the **bottom** of \`{{specPath}}/.plan2code-loop/scratchpad.md\`.
Never edit, reorganize, or insert into existing content — only append new entries to the end of the file.
Each entry should include:
- Task completed and Phase item reference
- Key decisions made and reasoning
- Files changed
- Any blockers or notes for next iteration
Keep entries concise. Sacrifice grammar for concision. This file helps future iterations skip exploration.
If key patterns or learnings were discovered, update \`./AGENTS.md\` if it exists.
## Previous Session Context
{{scratchpadContent}}
---
Remember: ONE TASK ONLY. Find it, implement it, mark it done, output TASK_COMPLETE with the task ID and description, then stop.
`;
export const LOOP_PROMPT_TEMPLATE_PHASE = `# PLAN2CODE-LOOP: Autonomous Phase Implementation
## CRITICAL CONSTRAINT
**IMPLEMENT ALL REMAINING TASKS IN THE CURRENT PHASE.**
Find the first incomplete phase, then implement every remaining task in that phase before stopping.
Complete each task fully before moving to the next task within the phase.
## Project Information
- **Project Root:** \`{{projectRoot}}\`
- **Spec Location:** \`{{specPath}}\`
- Read \`AGENTS.md\` for project-specific guidance if available
## IMPORTANT: File Locations
- Write ALL code files relative to the **project root** (\`{{projectRoot}}\`)
- The spec directory (\`{{specPath}}\`) is for documentation ONLY - never write code there
- Example: Create \`{{projectRoot}}/src/index.ts\`, NOT \`{{specPath}}/src/index.ts\`
## Iteration
{{iteration}} of {{maxIterations}}
## Phase Discovery Process
1. Read \`{{specPath}}/overview.md\` to see all phases
2. Find the FIRST phase with an unchecked checkbox (\`- [ ]\` or \`- [/]\`)
3. Read that phase's file (e.g., \`phase-1.md\`)
4. Check the \`## Prerequisites\` section FIRST
5. Verify ALL unverified prerequisites first, in order
- Annotate each "VERIFIED" or "ASSUMED: [reason]" inline
6. Once ALL prerequisites are verified, implement ALL unchecked tasks in order
7. Continue until every task in the phase is marked \`[x]\`
## Checkbox States (Task items only)
- \`[ ]\` = incomplete/pending
- \`[x]\` = complete (skip)
- \`[?]\` = assumed complete, couldn't verify (skip)
- \`[!]\` = blocked (skip, note in scratchpad)
Prerequisites use plain bullets with inline annotations, not checkboxes.
## Implementation Steps (repeat for EACH task in the phase)
1. Read and understand the task
2. Implement it completely
3. Validate it works (run tests if applicable and double-check code)
4. Mark that task's checkbox as \`[x]\` in the phase file
5. **Create a git commit** for this task (see Git Policy below)
6. Output a TASK_COMPLETE marker for this task
7. Move to the next unchecked task in the same phase
8. When ALL tasks in the phase are done, mark the phase \`[x]\` in overview.md
## Git Policy
**YOU are responsible for creating git commits after each task.** The orchestration system does NOT handle commits in phase mode.
After completing each task:
\`\`\`bash
git add -A
git commit -m "<commit message>"
\`\`\`
**Commit message format:**
\`\`\`
git add -A
git commit -m "Task X.Y: description" -m "{{jiraTicketId}}" -m "AI Assisted"
\`\`\`
- With JIRA ticket: three \`-m\` flags (description, ticket ID, AI Assisted)
- Without JIRA ticket: two \`-m\` flags (description, AI Assisted)
- ALWAYS include "AI Assisted" as the final \`-m\` flag
Replace X.Y with the actual task ID and description with a concise summary of what was implemented.
## Completion Markers (REQUIRED FORMAT)
Output one of these **after each task** you complete:
**PREREQ_COMPLETE: [prereq_id] - [description]**
Example: \`PREREQ_COMPLETE: P1.1 - Verified Phase 1 complete\`
**PREREQ_ASSUMED: [prereq_id] - [description]**
Example: \`PREREQ_ASSUMED: P2.1 - Design approval (cannot verify)\`
**TASK_COMPLETE: [task_id] - [task_description]**
Example: \`TASK_COMPLETE: 1.1 - Initialize project structure\`
**TASK_BLOCKED: [task_id] - [reason]**
Example: \`TASK_BLOCKED: 2.3 - Missing API credentials\`
If a task is blocked, skip it and continue to the next task.
After ALL tasks in the phase are complete (or blocked), output:
**PHASE_COMPLETE** - if only this phase is done
**LOOP_COMPLETE** - if ALL phases in overview.md are now marked complete
## Scratchpad Management
After completing each task, add a new entry at the **bottom** of \`{{specPath}}/.plan2code-loop/scratchpad.md\`.
Never edit, reorganize, or insert into existing content — only append new entries to the end of the file.
Each entry should include:
- Task completed and Phase item reference
- Key decisions made and reasoning
- Files changed
- Any blockers or notes for next iteration
Keep entries concise. Sacrifice grammar for concision. This file helps future iterations skip exploration.
If key patterns or learnings were discovered, update \`./AGENTS.md\` if it exists.
## Previous Session Context
{{scratchpadContent}}
---
Remember: Complete ALL tasks in the current phase. Implement each task, commit it, output TASK_COMPLETE, then continue to the next. Stop only when the phase is done.
`;
-4
View File
@@ -1,4 +0,0 @@
export {
detectSpecDirectories,
getSpecProgress,
} from './utils.js';
-70
View File
@@ -1,70 +0,0 @@
import path from 'path';
import fs from 'fs-extra';
/**
* Auto-detect spec directories in the project
* Looks for directories containing overview.md
*/
export async function detectSpecDirectories(cwd: string = process.cwd()): Promise<string[]> {
const specsDir = path.join(cwd, 'specs');
const specsDirs: string[] = [];
if (await fs.pathExists(specsDir)) {
// Look for overview.md files in subdirectories
const entries = await fs.readdir(specsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const overviewPath = path.join(specsDir, entry.name, 'overview.md');
if (await fs.pathExists(overviewPath)) {
specsDirs.push(path.join(specsDir, entry.name));
}
}
}
// Also check if specs/ itself contains overview.md
const rootOverview = path.join(specsDir, 'overview.md');
if (await fs.pathExists(rootOverview)) {
specsDirs.push(specsDir);
}
}
return specsDirs;
}
/**
* Simple progress stats by counting phase-*.md files
* Used for CLI display only - LLM handles actual task discovery
*/
export async function getSpecProgress(specPath: string): Promise<{
featureName: string;
totalPhases: number;
}> {
const overviewPath = path.join(specPath, 'overview.md');
// Extract feature name from overview.md
let featureName = path.basename(specPath);
try {
const overviewContent = await fs.readFile(overviewPath, 'utf8');
const h1Match = overviewContent.match(/^#\s+(.+)$/m);
if (h1Match) {
featureName = h1Match[1].trim();
}
} catch {
// Use directory name as fallback
}
// Count phase-*.md files
let totalPhases = 0;
try {
const entries = await fs.readdir(specPath);
totalPhases = entries.filter(name => /^phase-\d+\.md$/i.test(name)).length;
} catch {
// Directory read failed
}
return {
featureName,
totalPhases,
};
}
-35
View File
@@ -1,35 +0,0 @@
export type LoopMode = 'task' | 'phase';
export interface SessionConfig {
agent: string; // "claude-code" | "copilot-cli"
model: string; // Selected model
maxIterations: number; // 5-50
timeout: number; // Base timeout in minutes per iteration attempt
maxRetries: number; // Max retry attempts per iteration (timeout increments by 30s each retry)
verbose: boolean;
specPath: string; // Path to the spec directory
startedAt: string; // ISO timestamp
currentIteration: number;
jiraTicketId?: string; // JIRA ticket ID for commit messages
loopMode: LoopMode; // "task" = one task per loop, "phase" = one phase per loop
}
export interface IterationLogEntry {
iteration: number;
timestamp: string; // ISO timestamp
duration: number; // milliseconds
exitCode: number;
status: 'running' | 'completed' | 'error' | 'timeout' | 'interrupted' | 'blocked';
completionMarker?: string;
}
export type SessionState = 'new' | 'continue' | 'changed';
export const DEFAULT_CONFIG: Partial<SessionConfig> = {
maxIterations: 100,
timeout: 3,
maxRetries: 5,
verbose: false,
currentIteration: 0,
loopMode: 'task',
};
-9
View File
@@ -1,9 +0,0 @@
import { createHash } from 'crypto';
export function computeHash(content: string): string {
return createHash('sha256').update(content).digest('hex').slice(0, 16);
}
export function hashesMatch(a: string, b: string): boolean {
return a === b;
}
-10
View File
@@ -1,10 +0,0 @@
export {
type SessionConfig,
type IterationLogEntry,
type SessionState,
type LoopMode,
DEFAULT_CONFIG,
} from './config.js';
export { StateManager } from './manager.js';
export { computeHash, hashesMatch } from './hash.js';
-231
View File
@@ -1,231 +0,0 @@
import path from 'path';
import fs from 'fs-extra';
import type { SessionConfig, IterationLogEntry, SessionState } from './config.js';
import { DEFAULT_CONFIG } from './config.js';
import { computeHash, hashesMatch } from './hash.js';
const SCRATCHPAD_TEMPLATE = `# Scratchpad
Session notes appended by LLM during implementation.
---
`;
export class StateManager {
private readonly stateDir: string;
private readonly configPath: string;
private readonly scratchpadPath: string;
private readonly logPath: string;
private readonly hashPath: string;
private specPath: string | null = null;
constructor(cwd: string = process.cwd()) {
// Default to project root - will be updated when spec is selected
this.stateDir = path.join(cwd, '.plan2code-loop');
this.configPath = path.join(this.stateDir, 'config.json');
this.scratchpadPath = path.join(this.stateDir, 'scratchpad.md');
this.logPath = path.join(this.stateDir, 'iteration.log');
this.hashPath = path.join(this.stateDir, 'spec.hash');
}
/**
* Set the spec path and update all state paths to be inside the spec directory
*/
setSpecPath(specPath: string): void {
this.specPath = specPath;
const stateDir = path.join(specPath, '.plan2code-loop');
// Update all paths to be relative to spec directory
(this as any).stateDir = stateDir;
(this as any).configPath = path.join(stateDir, 'config.json');
(this as any).scratchpadPath = path.join(stateDir, 'scratchpad.md');
(this as any).logPath = path.join(stateDir, 'iteration.log');
(this as any).hashPath = path.join(stateDir, 'spec.hash');
}
// Directory operations
async ensureStateDir(): Promise<boolean> {
const existed = await fs.pathExists(this.stateDir);
await fs.ensureDir(this.stateDir);
return existed;
}
getStateDir(): string {
return this.stateDir;
}
// Config operations
async readConfig(): Promise<SessionConfig | null> {
try {
const content = await fs.readFile(this.configPath, 'utf8');
return JSON.parse(content) as SessionConfig;
} catch {
return null;
}
}
async writeConfig(config: SessionConfig): Promise<void> {
await fs.writeFile(
this.configPath,
JSON.stringify(config, null, 2),
'utf8'
);
}
async updateConfig(updates: Partial<SessionConfig>): Promise<SessionConfig> {
const existing = await this.readConfig();
const updated = { ...DEFAULT_CONFIG, ...existing, ...updates } as SessionConfig;
await this.writeConfig(updated);
return updated;
}
async incrementIteration(): Promise<number> {
const config = await this.readConfig();
if (!config) throw new Error('No session config found');
config.currentIteration++;
await this.writeConfig(config);
return config.currentIteration;
}
// Session state detection
async hasExistingSession(): Promise<boolean> {
const [configExists, scratchpadExists] = await Promise.all([
fs.pathExists(this.configPath),
fs.pathExists(this.scratchpadPath),
]);
return configExists || scratchpadExists;
}
async detectSessionState(specPath: string): Promise<SessionState> {
// Ensure we're using the correct spec path
this.setSpecPath(specPath);
const hasSession = await this.hasExistingSession();
if (!hasSession) {
return 'new';
}
// Check if the spec path has changed
const existingConfig = await this.readConfig();
if (existingConfig && existingConfig.specPath !== specPath) {
return 'changed';
}
// Check if spec content has changed (using hash of overview.md)
const specChanged = await this.hasSpecChanged(specPath);
return specChanged ? 'changed' : 'continue';
}
// Hash management for spec change detection
async computeSpecHash(specPath: string): Promise<string> {
const overviewPath = path.join(specPath, 'overview.md');
try {
const content = await fs.readFile(overviewPath, 'utf8');
return computeHash(content);
} catch {
return '';
}
}
async readStoredHash(): Promise<string | null> {
try {
return await fs.readFile(this.hashPath, 'utf8');
} catch {
return null;
}
}
async storeHash(hash: string): Promise<void> {
await fs.writeFile(this.hashPath, hash, 'utf8');
}
async hasSpecChanged(specPath: string): Promise<boolean> {
const stored = await this.readStoredHash();
if (!stored) return true;
const current = await this.computeSpecHash(specPath);
return !hashesMatch(stored, current);
}
async updateSpecHash(specPath: string): Promise<void> {
const hash = await this.computeSpecHash(specPath);
await this.storeHash(hash);
}
// Scratchpad operations
async initializeScratchpad(): Promise<void> {
await fs.writeFile(this.scratchpadPath, SCRATCHPAD_TEMPLATE, 'utf8');
}
async readScratchpad(): Promise<string> {
try {
return await fs.readFile(this.scratchpadPath, 'utf8');
} catch {
return '';
}
}
async writeScratchpad(content: string): Promise<void> {
await fs.writeFile(this.scratchpadPath, content, 'utf8');
}
// Iteration log operations
async appendIterationLog(entry: IterationLogEntry): Promise<void> {
const line = JSON.stringify(entry) + '\n';
await fs.appendFile(this.logPath, line, 'utf8');
}
async readIterationLog(): Promise<IterationLogEntry[]> {
try {
const content = await fs.readFile(this.logPath, 'utf8');
return content
.trim()
.split('\n')
.filter(Boolean)
.map((line) => JSON.parse(line) as IterationLogEntry);
} catch {
return [];
}
}
async getLastIteration(): Promise<IterationLogEntry | null> {
const log = await this.readIterationLog();
return log.length > 0 ? log[log.length - 1] : null;
}
// State clearing and initialization
async clearState(): Promise<void> {
const filesToDelete = [
this.scratchpadPath,
this.configPath,
this.logPath,
this.hashPath,
];
await Promise.all(
filesToDelete.map((file) => fs.remove(file).catch(() => {}))
);
}
async initializeNewSession(config: SessionConfig): Promise<void> {
// Ensure spec path is set before initializing
this.setSpecPath(config.specPath);
await this.clearState();
await this.ensureStateDir();
await this.initializeScratchpad();
await this.writeConfig({
...config,
startedAt: new Date().toISOString(),
currentIteration: 0,
});
const hash = await this.computeSpecHash(config.specPath);
await this.storeHash(hash);
}
}
-169
View File
@@ -1,169 +0,0 @@
// Completion markers for plan2code-loop
const COMPLETION_MARKERS = ['TASK_COMPLETE', 'TASK_BLOCKED', 'LOOP_COMPLETE', 'PREREQ_COMPLETE', 'PREREQ_ASSUMED'] as const;
export type CompletionMarker = (typeof COMPLETION_MARKERS)[number];
export interface CompletionCheckResult {
completed: boolean;
marker?: CompletionMarker;
taskId?: string; // e.g., "1.1", "2.3"
taskName?: string; // e.g., "Initialize project structure"
reason?: string; // For TASK_BLOCKED: reason
}
export function checkForCompletion(output: string): CompletionCheckResult {
// Check for LOOP_COMPLETE first (highest priority)
if (output.includes('LOOP_COMPLETE')) {
return { completed: true, marker: 'LOOP_COMPLETE' };
}
// Check for TASK_COMPLETE with task info
// Format: TASK_COMPLETE: 1.1 - Task description
// Or: TASK_COMPLETE: 1.1: Task description
// Or: TASK_COMPLETE[1.1]: Task description
const completeMatch = output.match(/TASK_COMPLETE[:\[\s]+(\d+\.\d+)[\]:\-\s]+(.+?)(?:\n|$)/i);
if (completeMatch) {
return {
completed: true,
marker: 'TASK_COMPLETE',
taskId: completeMatch[1],
taskName: completeMatch[2].trim(),
};
}
// Simple TASK_COMPLETE without structured info - try to extract task from context
if (output.includes('TASK_COMPLETE')) {
// Try to find task info nearby
const taskMatch = output.match(/(?:task|completed?)\s+(\d+\.\d+)[:\s]+([^\n]{5,80})/i);
return {
completed: true,
marker: 'TASK_COMPLETE',
taskId: taskMatch?.[1],
taskName: taskMatch?.[2]?.trim(),
};
}
// Check for PREREQ_COMPLETE with prereq info
// Format: PREREQ_COMPLETE: P1.1 - Verified Phase 1 complete
const prereqMatch = output.match(/PREREQ_COMPLETE[:\[\s]+([^\]:\-\s]+)[\]:\-\s]+(.+?)(?:\n|$)/i);
if (prereqMatch) {
return {
completed: true,
marker: 'PREREQ_COMPLETE',
taskId: prereqMatch[1],
taskName: prereqMatch[2].trim(),
};
}
// Check for PREREQ_ASSUMED with prereq info
// Format: PREREQ_ASSUMED: P2.1 - Design approval (cannot verify)
const assumedMatch = output.match(/PREREQ_ASSUMED[:\[\s]+([^\]:\-\s]+)[\]:\-\s]+(.+?)(?:\n|$)/i);
if (assumedMatch) {
return {
completed: true,
marker: 'PREREQ_ASSUMED',
taskId: assumedMatch[1],
taskName: assumedMatch[2].trim(),
};
}
// Check for TASK_BLOCKED with task info and reason
// Format: TASK_BLOCKED: 1.1 - Reason why blocked
const blockedWithTaskMatch = output.match(/TASK_BLOCKED[:\[\s]+(\d+\.\d+)[\]:\-\s]+(.+?)(?:\n|$)/i);
if (blockedWithTaskMatch) {
return {
completed: true,
marker: 'TASK_BLOCKED',
taskId: blockedWithTaskMatch[1],
reason: blockedWithTaskMatch[2].trim(),
};
}
// TASK_BLOCKED with just reason (no task ID)
const blockedMatch = output.match(/TASK_BLOCKED:\s*(.+?)(?:\n|$)/);
if (blockedMatch) {
return {
completed: true,
marker: 'TASK_BLOCKED',
reason: blockedMatch[1].trim()
};
}
// Simple TASK_BLOCKED without any info
if (output.includes('TASK_BLOCKED')) {
return { completed: true, marker: 'TASK_BLOCKED', reason: 'No reason provided' };
}
return { completed: false };
}
/**
* Extract ALL completion markers from output (for phase mode).
* Returns an array of all TASK_COMPLETE/TASK_BLOCKED markers found,
* plus whether LOOP_COMPLETE or PHASE_COMPLETE was present.
*/
export function checkForAllCompletions(output: string): {
tasks: CompletionCheckResult[];
loopComplete: boolean;
phaseComplete: boolean;
} {
const tasks: CompletionCheckResult[] = [];
let loopComplete = false;
let phaseComplete = false;
if (output.includes('LOOP_COMPLETE')) {
loopComplete = true;
}
if (output.includes('PHASE_COMPLETE')) {
phaseComplete = true;
}
// Find all TASK_COMPLETE markers with task info
// Format: TASK_COMPLETE: 1.1 - Task description
const completeRegex = /TASK_COMPLETE[:\[\s]+(\d+\.\d+)[\]:\-\s]+(.+?)(?:\n|$)/gi;
let match: RegExpExecArray | null;
while ((match = completeRegex.exec(output)) !== null) {
tasks.push({
completed: true,
marker: 'TASK_COMPLETE',
taskId: match[1],
taskName: match[2].trim(),
});
}
// Find all TASK_BLOCKED markers with task info
const blockedRegex = /TASK_BLOCKED[:\[\s]+(\d+\.\d+)[\]:\-\s]+(.+?)(?:\n|$)/gi;
while ((match = blockedRegex.exec(output)) !== null) {
tasks.push({
completed: true,
marker: 'TASK_BLOCKED',
taskId: match[1],
reason: match[2].trim(),
});
}
// Find PREREQ_COMPLETE markers
const prereqRegex = /PREREQ_COMPLETE[:\[\s]+([^\]:\-\s]+)[\]:\-\s]+(.+?)(?:\n|$)/gi;
while ((match = prereqRegex.exec(output)) !== null) {
tasks.push({
completed: true,
marker: 'PREREQ_COMPLETE',
taskId: match[1],
taskName: match[2].trim(),
});
}
// Find PREREQ_ASSUMED markers
const assumedRegex = /PREREQ_ASSUMED[:\[\s]+([^\]:\-\s]+)[\]:\-\s]+(.+?)(?:\n|$)/gi;
while ((match = assumedRegex.exec(output)) !== null) {
tasks.push({
completed: true,
marker: 'PREREQ_ASSUMED',
taskId: match[1],
taskName: match[2].trim(),
});
}
return { tasks, loopComplete, phaseComplete };
}
-136
View File
@@ -1,136 +0,0 @@
import { execa } from 'execa';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { join } from 'path';
import { logger } from './logger.js';
export interface GitCommitOptions {
taskName: string;
jiraTicketId?: string;
cwd?: string;
}
/**
* Check if directory is a git repository
*/
export async function isGitRepo(cwd: string): Promise<boolean> {
const result = await execa('git', ['rev-parse', '--git-dir'], { cwd, reject: false });
return result.exitCode === 0;
}
/**
* Initialize a git repository if one doesn't exist
*/
export async function ensureGitRepo(cwd: string): Promise<boolean> {
if (await isGitRepo(cwd)) {
return true;
}
logger.info('Initializing git repository...');
const result = await execa('git', ['init'], { cwd, reject: false });
if (result.exitCode !== 0) {
logger.error(`Failed to initialize git repo: ${result.stderr}`);
return false;
}
logger.success('Git repository initialized');
return true;
}
/**
* Required entries for the .gitignore file
*/
const REQUIRED_GITIGNORE_ENTRIES = ['specs/', 'specs--completed/', '.plan2code-loop', '.plan2code-metrics', 'nul', 'node_modules/'];
/**
* Ensure .gitignore exists with required entries
*/
export function ensureGitignore(cwd: string): void {
const gitignorePath = join(cwd, '.gitignore');
let content = '';
if (existsSync(gitignorePath)) {
content = readFileSync(gitignorePath, 'utf-8');
}
const lines = content.split('\n').map(line => line.trim());
const missingEntries = REQUIRED_GITIGNORE_ENTRIES.filter(entry => !lines.includes(entry));
if (missingEntries.length > 0) {
const needsNewline = content.length > 0 && !content.endsWith('\n');
const newContent = content + (needsNewline ? '\n' : '') + missingEntries.join('\n') + '\n';
writeFileSync(gitignorePath, newContent);
logger.dim(`Added to .gitignore: ${missingEntries.join(', ')}`);
}
}
/**
* Create a local git commit for a completed task
*/
export async function createTaskCommit(options: GitCommitOptions): Promise<boolean> {
const { taskName, jiraTicketId, cwd = process.cwd() } = options;
logger.dim(`Git commit check in: ${cwd}`);
try {
// Ensure we have a git repo
if (!await ensureGitRepo(cwd)) {
return false;
}
// Ensure .gitignore exists with required entries
ensureGitignore(cwd);
// Check if there are any changes to commit
const statusResult = await execa('git', ['status', '--porcelain'], { cwd, reject: false });
// Debug: show what git status returned
if (statusResult.stdout?.trim()) {
logger.dim(`Git status found changes:\n${statusResult.stdout.slice(0, 500)}`);
}
if (statusResult.exitCode !== 0) {
logger.error(`Git status failed: ${statusResult.stderr}`);
return false;
}
if (!statusResult.stdout?.trim()) {
logger.dim('No changes to commit');
return false;
}
// Stage all changes
const addResult = await execa('git', ['add', '-A'], { cwd, reject: false });
if (addResult.exitCode !== 0) {
logger.error(`Git add failed: ${addResult.stderr}`);
return false;
}
// Build commit message
let commitMessage = taskName;
if (jiraTicketId) {
commitMessage = `${taskName}\n\n${jiraTicketId}\nAI Assisted`;
} else {
commitMessage = `${taskName}\n\nAI Assisted`;
}
// Create the commit
const commitResult = await execa('git', ['commit', '-m', commitMessage], { cwd, reject: false });
if (commitResult.exitCode !== 0) {
// Check if it's just "nothing to commit" vs actual error
if (commitResult.stdout?.includes('nothing to commit') || commitResult.stderr?.includes('nothing to commit')) {
logger.dim('No changes to commit');
return false;
}
logger.error(`Git commit failed: ${commitResult.stderr || commitResult.stdout}`);
return false;
}
logger.success(`Created commit: ${taskName}${jiraTicketId ? ` (${jiraTicketId})` : ''}`);
return true;
} catch (error) {
logger.error(`Failed to create commit: ${error instanceof Error ? error.message : String(error)}`);
return false;
}
}
-19
View File
@@ -1,19 +0,0 @@
export { logger, MASCOT, type Logger } from './logger.js';
export {
checkForCompletion,
checkForAllCompletions,
type CompletionMarker,
type CompletionCheckResult
} from './completion.js';
export {
executeCommand,
type ExecuteOptions,
type ExecuteResult
} from './process.js';
export {
createTaskCommit,
isGitRepo,
ensureGitRepo,
ensureGitignore,
type GitCommitOptions
} from './git.js';
-126
View File
@@ -1,126 +0,0 @@
import chalk from 'chalk';
import ora, { type Ora } from 'ora';
// mascot - our friendly robot assistant
export const MASCOT = {
// Full mascot for headers
full: [
' ╭───╮ ',
' │ ● │ ',
' │ ◡ │ ',
' ╰───╯ ',
],
// Mini mascot for inline use
mini: '(◉‿◉)',
// Waving mascot for greetings
wave: [
' ╭───╮ ',
' │ ● │ ',
' │ ◡ │ ',
' ╰───╯ ',
],
// Celebration mascot for completion
celebrate: [
' ╭───╮ ',
' │ ★ │ ',
' │ ◡ │ ',
' ╰───╯ ',
],
};
export const logger = {
info: (message: string) => console.log(chalk.blue('i'), message),
success: (message: string) => console.log(chalk.green('+'), message),
warning: (message: string) => console.log(chalk.yellow('!'), message),
error: (message: string) => console.log(chalk.red('x'), message),
dim: (message: string) => console.log(chalk.dim(message)),
bold: (message: string) => console.log(chalk.bold(message)),
header: (message: string) => {
console.log();
console.log(chalk.cyan.bold(message));
console.log(chalk.cyan('-'.repeat(message.length)));
},
task: (phase: number, taskId: string, description: string) => {
console.log(
chalk.cyan(`[Phase ${phase}]`),
chalk.yellow(`Task ${taskId}:`),
chalk.white(description)
);
},
iteration: (num: number, max: number, status: string) => {
console.log(
chalk.cyan(`[${num}/${max}]`),
chalk.white(status)
);
},
specContent: (content: string) => {
console.log(chalk.dim('-'.repeat(50)));
console.log(chalk.white(content));
console.log(chalk.dim('-'.repeat(50)));
},
spinner: (text: string): Ora => ora({ text, color: 'cyan' }).start(),
// Display mascot with optional message
mascot: (variant: keyof typeof MASCOT = 'full', message?: string) => {
console.log();
const mascot = MASCOT[variant];
if (Array.isArray(mascot)) {
const mascotLines = [...mascot];
if (message) {
// Add message next to mascot (at the "mouth" line)
mascotLines[4] = mascotLines[4] + ' ' + chalk.cyan(message);
}
mascotLines.forEach((line) => console.log(chalk.yellow(line)));
} else {
// Mini variant
console.log(chalk.yellow(mascot), message ? chalk.cyan(message) : '');
}
console.log();
},
// Welcome banner with mascot
welcome: () => {
console.log();
console.log(chalk.cyan.bold('═'.repeat(50)));
MASCOT.wave.forEach((line, i) => {
if (i === 4) {
console.log(chalk.yellow(line) + ' ' + chalk.cyan.bold("Hi!"));
} else if (i === 5) {
console.log(chalk.yellow(line) + ' ' + chalk.dim('I\'m Your Plan2Code assistant'));
} else {
console.log(chalk.yellow(line));
}
});
console.log(chalk.cyan.bold('═'.repeat(50)));
console.log();
},
// Completion celebration with reminder
allPhasesComplete: () => {
console.log();
console.log(chalk.green.bold('═'.repeat(50)));
MASCOT.celebrate.forEach((line, i) => {
if (i === 4) {
console.log(chalk.yellow(line) + ' ' + chalk.green.bold('All phases complete!'));
} else if (i === 5) {
console.log(chalk.yellow(line) + ' ' + chalk.cyan('Great work!'));
} else {
console.log(chalk.yellow(line));
}
});
console.log(chalk.green.bold('═'.repeat(50)));
console.log();
console.log(chalk.cyan.bold('Next Step:'));
console.log(chalk.white(' Return to your AI Agent and run the'), chalk.yellow.bold('/plan2code-4-finalize'), chalk.white('step.'));
console.log(chalk.dim(' This will ensure quality, completeness, and proper documentation.'));
console.log();
},
};
export type Logger = typeof logger;
-81
View File
@@ -1,81 +0,0 @@
import { execa, type Options as ExecaOptions } from 'execa';
const MAX_OUTPUT_SIZE = 10 * 1024 * 1024; // 10MB
function truncateOutput(output: string, maxSize: number): string {
if (output.length > maxSize) {
return output.slice(0, maxSize) + '\n...[truncated]';
}
return output;
}
export interface ExecuteOptions {
command: string;
args: string[];
cwd: string;
timeout: number; // milliseconds
env?: Record<string, string>;
signal?: AbortSignal; // For cancellation
stdin?: string; // Input to pass via stdin as string
stdinFile?: string; // Path to file to pipe as stdin
}
export interface ExecuteResult {
stdout: string;
stderr: string;
exitCode: number;
timedOut: boolean;
cancelled: boolean;
duration: number; // milliseconds
}
export async function executeCommand(
options: ExecuteOptions
): Promise<ExecuteResult> {
const startTime = Date.now();
try {
const execaOptions: ExecaOptions = {
cwd: options.cwd,
timeout: options.timeout,
env: { ...process.env, ...options.env },
reject: false,
all: true,
};
// Add cancellation signal if provided
if (options.signal) {
(execaOptions as any).cancelSignal = options.signal;
}
// Add stdin input if provided (string or file)
if (options.stdin) {
(execaOptions as any).input = options.stdin;
} else if (options.stdinFile) {
(execaOptions as any).inputFile = options.stdinFile;
}
const result = await execa(options.command, options.args, execaOptions);
return {
stdout: truncateOutput(result.stdout || '', MAX_OUTPUT_SIZE),
stderr: truncateOutput(result.stderr || '', MAX_OUTPUT_SIZE),
exitCode: result.exitCode ?? 1,
timedOut: result.timedOut ?? false,
cancelled: result.isCanceled ?? false,
duration: Date.now() - startTime,
};
} catch (error: any) {
// Check if this was a cancellation
const isCancelled = error?.isCanceled || options.signal?.aborted;
return {
stdout: error?.stdout || '',
stderr: error?.stderr || (error instanceof Error ? error.message : String(error)),
exitCode: isCancelled ? -1 : 1,
timedOut: false,
cancelled: isCancelled,
duration: Date.now() - startTime,
};
}
}
-20
View File
@@ -1,20 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": ".",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
-15
View File
@@ -1,15 +0,0 @@
import { defineConfig } from 'tsup';
export default defineConfig({
entry: {
'bin/plan2code-loop': 'src/bin/plan2code-loop.ts',
index: 'src/index.ts',
},
format: ['esm'],
dts: false,
clean: true,
sourcemap: true,
banner: {
js: '#!/usr/bin/env node',
},
});
-289
View File
@@ -1,289 +0,0 @@
# plan2code-metrics
Recursive self-improvement toolchain for plan2code contributors. Collects metrics from completed project specs, aggregates them across runs and prompt generations, then uses AI to diagnose weak steps and propose targeted edits to the workflow prompts.
## Quick Reference
```bash
# Install (one-time, from the plan2code root)
node install.js # → "A" (Install All + dev tools) includes metrics
# → or "M" (Metrics only) under the CUSTOM sub-menu
# After finishing any project spec (steps 1-4):
cd your-project
plan2code-metrics # → "Collect metrics" → pick your spec dir → done (5 sec)
# When you're curious or have 3+ runs:
plan2code-metrics # → "View metrics status" to see the dashboard
# → "Run analysis" for AI diagnosis of weak spots
# → "Generate improvement proposal" for prompt edits
# → "Review and apply" to patch src/plan2code-*.md
```
**One habit:** collect after every finished spec. Everything else is on-demand.
### How Many Runs Do I Need?
| Runs | What You Get |
|------|-------------|
| **1** | Raw data and basic dashboard. Start here. |
| **3+** | AI analysis unlocks (warns below 3 that results may be unreliable). Pattern detection starts working. |
| **5-10+** | Averages stabilize. Generation-over-generation comparisons become meaningful. |
More is always better — each run adds a data point. You're looking for trends, not individual scores.
### The Feedback Loop
```
Use plan2code on a project (steps 1-4)
|
v
Collect metrics from the finished spec <-- do this every time
|
v
Aggregate across runs (automatic)
|
v
Analyze weak spots (AI-powered, 3+ runs)
|
v
Generate prompt improvements
|
v
Apply edits to src/plan2code-*.md
|
v
Prompts have new SHA hashes = new "generation"
|
v
Use improved prompts on next project
|
v
Collect again, compare generations <-- the loop closes
```
After applying edits, the prompt file SHA hashes change. The next collected run falls into a **new cohort** (generation). The dashboard then shows generation-over-generation deltas — "Did confidence go up? Did blockers decrease?" — so you can measure whether your edits actually helped.
---
## Installation
Requires Node.js >= 18.
### Via the plan2code installer (recommended)
From the plan2code repo root:
```bash
node install.js
```
Choose **A** (Install All + dev tools) to install prompts, loop CLI, bot, metrics, and status line together. Or choose **C** (Custom) then **M** (Metrics) to install just the metrics CLI.
The installer handles `npm install`, `npm run build`, and global linking automatically. After install, `plan2code-metrics` is available from any directory.
### Manual install
If you prefer to install manually or are developing on the metrics package:
```bash
cd plan2code-metrics
npm install
npm run build
npm link
```
To run without linking:
```bash
npm start
# or
node dist/bin/plan2code-metrics.js
```
## Usage
Run `plan2code-metrics` from inside (or near) a plan2code repository. The CLI is fully interactive — no flags, all inputs collected via prompts.
```
plan2code-metrics
```
### Main Menu
| Option | Description |
|--------|-------------|
| **Collect metrics** | Parse a completed project spec and extract step-by-step metrics into a run JSON |
| **Import run data** | Copy a run JSON from another project into the local metrics store |
| **View metrics status** | Show aggregated metrics with health indicators and generation deltas |
| **Run analysis** | AI-powered diagnosis of weak steps (requires Claude Code or Copilot CLI) |
| **Generate improvement proposal** | AI generates surgical prompt edits based on a diagnosis |
| **Review and apply** | Interactive diff review to accept/reject individual edits |
### Each Time You Finish a Spec
After completing Step 4 (finalize) on any project:
```bash
cd your-project
plan2code-metrics
```
Pick **"Collect metrics"** and point it at your spec directory (`specs/<feature>/` or `specs--completed/<feature>/`). It reads your artifacts, extracts ~30 metrics, and writes a run JSON. Takes about 5 seconds.
The data stays local to that project in `.plan2code-metrics/runs/`. To aggregate across multiple projects, use **"Import"** to copy run files into one central location.
### Cross-Project Aggregation
If you use plan2code across several repos, you can consolidate all run data in one place:
```bash
# From your central repo (e.g., the plan2code repo itself):
plan2code-metrics
# → "Import run data"
# → Paste path to: /path/to/other-project/.plan2code-metrics/runs/run-xxx.json
```
Imported runs are copied locally and included in all future aggregations, analyses, and comparisons.
## What It Measures
Each collection scrapes your spec files and extracts:
### Step 1 (Plan) — from `PLAN-DRAFT-*.md` and `PLAN-CONVERSATION-*.md`
- **Confidence score** — overall planning confidence percentage
- **Confidence breakdown** — requirements, feasibility, integration, risk sub-scores
- **Clarification rounds** — how many rounds of Q&A occurred
- **Verification gaps found** — missing requirements caught during verification
- **Functional/non-functional requirement counts** — FR- and NFR- headings
- **Risk count** — risk table entries
- **Phase count** — number of implementation phases planned
### Step 2 (Document) — from `overview.md` and `phase-*.md`
- **Total tasks** — checkbox count across all phases
- **Tasks per phase** — distribution of work
- **Phase count** — number of phase files
- **Parallel groups** — parallel execution groups identified
- **Requirement coverage** — coverage percentage if present
- **Verification items** — verification checklist items added
### Step 3 (Implement) — from `.plan2code-loop/` data (loop mode only)
- **Task completion rate** — completed / total tasks
- **Blocker count** — tasks marked TASK_BLOCKED
- **Blocker categories** — normalized reasons for blocks
- **Total iterations** — loop iteration count
- **Avg iteration duration** — mean time per iteration
- **Exit code distribution** — process exit codes
- **Completion marker success rate** — valid markers / total iterations
### Step 4 (Finalize) — from `overview.md` and directory structure
- **Completion rate at audit** — tasks done at finalization time
- **Verification failures** — tasks marked with `[!]`
- **Documentation updates needed** — TODO/FIXME/update markers
- **Archival success** — whether spec was moved to `specs--completed/`
### Health Targets
The dashboard compares key metrics against targets:
| Metric | Target | Direction |
|--------|--------|-----------|
| avg_confidence | 90 | >= |
| avg_clarification_rounds | 2.0 | <= |
| avg_verification_gaps_found | 2.0 | <= |
| avg_parallel_groups | 0.5 | >= |
| avg_task_completion_rate | 0.95 | >= |
| avg_blocker_count | 1.5 | <= |
| avg_completion_marker_success_rate | 0.95 | >= |
| avg_verification_failures_found | 1.0 | <= |
| archival_success_rate | 0.99 | >= |
Green checkmark = meeting target. Red X = below target (with the target shown).
## How It Works
### 1. Collect
Reads completed project artifacts from `specs/` or `specs--completed/` and extracts metrics for each workflow step. Output: `.plan2code-metrics/runs/run-<timestamp>.json`
### 2. Aggregate
Merges all run files into `aggregated.json`, grouped by **prompt generation** — a SHA fingerprint of the 8 workflow prompt files. Two runs that used identical prompt files belong to the same cohort.
### 3. Analyze
Sends aggregated metrics to an AI model with an analyst prompt. The AI produces a diagnosis identifying the weakest workflow steps and root causes. No edits are proposed at this stage.
Output: `.plan2code-metrics/proposals/<timestamp>-diagnosis.md`
### 4. Improve
Sends the diagnosis plus current prompt file contents to an AI model. The AI proposes surgical `old_text -> new_text` edits, each validated against:
- The `old_text` actually exists in the target file
- The edited file stays under the 11,000 character limit
Output: `.plan2code-metrics/proposals/prop-<timestamp>.json`
### 5. Apply
Interactive diff review for each proposed edit. Accept, reject, or skip individual changes. Applied edits are patched directly into `src/plan2code-*.md`.
## Data Directory
All metrics data lives in `.plan2code-metrics/` (add to `.gitignore` if desired):
```
.plan2code-metrics/
├── runs/ # Individual run JSONs
│ ├── run-20260215-120000-a1b2.json
│ └── run-20260220-090000-c3d4.json
├── aggregated.json # Merged cohort data
└── proposals/ # Diagnoses and improvement proposals
├── 20260220-diagnosis.md
└── prop-20260220.json
```
## AI Backends
The analysis and improvement steps require an AI agent. Two backends are supported:
| Backend | Command | Notes |
|---------|---------|-------|
| **Claude Code** | `claude` | Uses `--print` mode. Recommended. |
| **GitHub Copilot CLI** | `copilot` | Uses stdin piping with `--allow-all-tools -s`. |
Model selection is interactive — choose from available models when prompted.
## Architecture
```
src/
├── bin/plan2code-metrics.ts # Entry point
├── cli.ts # Interactive menu (main loop)
├── types.ts # RunMetrics, PromptProposal, CohortMetrics, etc.
├── collector.ts # Reads project artifacts → run JSON
├── aggregator.ts # Merges runs → aggregated.json (cohort grouping)
├── analyzer.ts # AI diagnosis via LLM invocation
├── improver.ts # AI improvement proposal + validation
├── applier.ts # Interactive diff review + file patching
├── invoke-llm.ts # Unified LLM invocation (Claude Code / Copilot CLI)
├── index.ts # Public API exports
└── prompts/
├── analyze.md # AI prompt template for diagnosis
└── improve.md # AI prompt template for improvement proposals
```
## Development
```bash
npm run dev # Watch mode (rebuilds on change)
npm run build # Production build
npm test # Run unit tests
npm run test:watch # Watch mode tests
npm start # Run the CLI
```
-46
View File
@@ -1,46 +0,0 @@
{
"name": "plan2code-metrics",
"version": "1.0.0",
"description": "Plan2Code Metrics - Recursive self-improvement toolchain for plan2code contributors",
"type": "module",
"main": "dist/index.js",
"bin": {
"plan2code-metrics": "./dist/bin/plan2code-metrics.js"
},
"files": [
"dist"
],
"engines": {
"node": ">=18.0.0"
},
"keywords": [
"cli",
"ai",
"metrics",
"plan2code",
"contributor-tooling"
],
"license": "MIT",
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"start": "node dist/bin/plan2code-metrics.js",
"test": "vitest run",
"test:watch": "vitest",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@inquirer/prompts": "^8.1.0",
"chalk": "^5.6.2",
"execa": "^9.6.1",
"fs-extra": "^11.3.3",
"ora": "^9.0.0"
},
"devDependencies": {
"@types/fs-extra": "^11.0.4",
"@types/node": "^25.0.3",
"tsup": "^8.5.1",
"typescript": "^5.9.3",
"vitest": "^3.1.1"
}
}
-154
View File
@@ -1,154 +0,0 @@
import { describe, it, expect } from 'vitest';
import { avg, rate, buildCohortKey, backfillPromptVersions } from './aggregator.js';
import type { PromptVersions } from './types.js';
// ── avg() ─────────────────────────────────────────────────────────────────────
describe('avg', () => {
it('returns null for empty array', () => {
expect(avg([])).toBeNull();
});
it('returns null for all-null/undefined values', () => {
expect(avg([null, undefined, null])).toBeNull();
});
it('computes correct average for valid numbers', () => {
expect(avg([10, 20, 30])).toBe(20);
});
it('filters out null/undefined/NaN from mixed arrays', () => {
expect(avg([10, null, 20, undefined, NaN, 30])).toBe(20);
});
});
// ── rate() ────────────────────────────────────────────────────────────────────
describe('rate', () => {
it('returns null for empty array', () => {
expect(rate([])).toBeNull();
});
it('returns null for all-null values', () => {
expect(rate([null, null])).toBeNull();
});
it('returns 1.0 for all-true', () => {
expect(rate([true, true, true])).toBe(1.0);
});
it('returns 0.0 for all-false', () => {
expect(rate([false, false, false])).toBe(0.0);
});
it('computes correct rate for mixed true/false', () => {
expect(rate([true, false, true, false])).toBe(0.5);
});
it('filters out null/undefined from mixed arrays', () => {
expect(rate([true, null, false, undefined])).toBe(0.5);
});
});
// ── backfillPromptVersions() ──────────────────────────────────────────────────
const FULL_VERSIONS: PromptVersions = {
plan: 'sha256:aaa',
revise_plan: 'sha256:bbb',
document: 'sha256:ccc',
implement: 'sha256:ddd',
finalize: 'sha256:eee',
init: 'sha256:fff',
init_update: 'sha256:ggg',
quick_task: 'sha256:hhh',
};
describe('backfillPromptVersions', () => {
it('returns all 8 fields with sentinels when given empty-ish object', () => {
const result = backfillPromptVersions({} as PromptVersions);
expect(Object.keys(result)).toHaveLength(8);
for (const val of Object.values(result)) {
expect(val).toBe('sha256:missing');
}
});
it('preserves existing values, fills missing with sha256:missing', () => {
const partial = { plan: 'sha256:aaa', implement: 'sha256:ddd' } as PromptVersions;
const result = backfillPromptVersions(partial);
expect(result.plan).toBe('sha256:aaa');
expect(result.implement).toBe('sha256:ddd');
expect(result.revise_plan).toBe('sha256:missing');
expect(result.document).toBe('sha256:missing');
expect(result.finalize).toBe('sha256:missing');
expect(result.init).toBe('sha256:missing');
expect(result.init_update).toBe('sha256:missing');
expect(result.quick_task).toBe('sha256:missing');
});
it('returns unchanged object when all 8 fields present', () => {
const result = backfillPromptVersions(FULL_VERSIONS);
expect(result).toEqual(FULL_VERSIONS);
});
});
// ── buildCohortKey() ──────────────────────────────────────────────────────────
describe('buildCohortKey', () => {
it('returns 12-char hex string', () => {
const key = buildCohortKey(FULL_VERSIONS);
expect(key).toMatch(/^[0-9a-f]{12}$/);
});
it('is deterministic (same input → same output)', () => {
const key1 = buildCohortKey(FULL_VERSIONS);
const key2 = buildCohortKey(FULL_VERSIONS);
expect(key1).toBe(key2);
});
it('old 4-field run with backfill sentinels produces same key as raw 4-field object', () => {
// Simulate an old run that only had 4 fields
const oldRun = {
plan: 'sha256:aaa',
implement: 'sha256:ddd',
document: 'sha256:ccc',
finalize: 'sha256:eee',
} as PromptVersions;
// After backfill, the missing fields get 'sha256:missing'
const backfilled = backfillPromptVersions(oldRun);
// buildCohortKey filters out 'sha256:missing', so both should match
const keyDirect = buildCohortKey(oldRun);
const keyBackfilled = buildCohortKey(backfilled);
expect(keyDirect).toBe(keyBackfilled);
});
it('different prompt versions → different keys', () => {
const altered = { ...FULL_VERSIONS, plan: 'sha256:zzz' };
expect(buildCohortKey(FULL_VERSIONS)).not.toBe(buildCohortKey(altered));
});
it('key is independent of field insertion order', () => {
const ordered: PromptVersions = {
plan: 'sha256:aaa',
revise_plan: 'sha256:bbb',
document: 'sha256:ccc',
implement: 'sha256:ddd',
finalize: 'sha256:eee',
init: 'sha256:fff',
init_update: 'sha256:ggg',
quick_task: 'sha256:hhh',
};
const reversed: PromptVersions = {
quick_task: 'sha256:hhh',
init_update: 'sha256:ggg',
init: 'sha256:fff',
finalize: 'sha256:eee',
implement: 'sha256:ddd',
document: 'sha256:ccc',
revise_plan: 'sha256:bbb',
plan: 'sha256:aaa',
};
expect(buildCohortKey(ordered)).toBe(buildCohortKey(reversed));
});
});
-219
View File
@@ -1,219 +0,0 @@
/**
* aggregator.ts
* Merges all run JSON files into aggregated.json, grouped by prompt generation (SHA fingerprint).
*/
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import type { RunMetrics, AggregatedMetrics, CohortMetrics, PromptVersions } from './types.js';
// ── Helpers ───────────────────────────────────────────────────────────────────
export function avg(values: (number | null | undefined)[]): number | null {
const valid = values.filter((v): v is number => v != null && !isNaN(v));
if (valid.length === 0) return null;
return valid.reduce((a, b) => a + b, 0) / valid.length;
}
export function rate(values: (boolean | null | undefined)[]): number | null {
const valid = values.filter((v): v is boolean => v != null);
if (valid.length === 0) return null;
return valid.filter(v => v).length / valid.length;
}
/**
* Build a stable cohort key from the sorted prompt_versions object.
* Two runs with identical prompt files get the same cohort key.
*/
export function buildCohortKey(promptVersions: PromptVersions): string {
// Filter out missing sentinels so old runs (4 fields) keep their original key
const entries = Object.entries(promptVersions)
.filter(([, v]) => v !== 'sha256:missing')
.sort(([a], [b]) => a.localeCompare(b));
const str = JSON.stringify(Object.fromEntries(entries));
return crypto.createHash('sha256').update(str).digest('hex').slice(0, 12);
}
/**
* Backfill missing PromptVersions fields for old run files (pre-v1.1).
*/
export function backfillPromptVersions(pv: PromptVersions): PromptVersions {
return {
plan: pv.plan ?? 'sha256:missing',
revise_plan: pv.revise_plan ?? 'sha256:missing',
document: pv.document ?? 'sha256:missing',
implement: pv.implement ?? 'sha256:missing',
finalize: pv.finalize ?? 'sha256:missing',
init: pv.init ?? 'sha256:missing',
init_update: pv.init_update ?? 'sha256:missing',
quick_task: pv.quick_task ?? 'sha256:missing',
};
}
// ── Load run files ────────────────────────────────────────────────────────────
export function loadRunFiles(runsDir: string): RunMetrics[] {
if (!fs.existsSync(runsDir)) return [];
const files = fs.readdirSync(runsDir)
.filter(f => f.endsWith('.json') && f.startsWith('run-'))
.sort();
const runs: RunMetrics[] = [];
for (const file of files) {
try {
const content = fs.readFileSync(path.join(runsDir, file), 'utf8');
const data = JSON.parse(content) as RunMetrics;
data.prompt_versions = backfillPromptVersions(data.prompt_versions);
runs.push(data);
} catch (err) {
console.warn(`Warning: could not parse ${file}: ${err}`);
}
}
return runs;
}
// ── Build cohort metrics ──────────────────────────────────────────────────────
function buildCohort(runs: RunMetrics[], cohortKey: string): CohortMetrics {
const runIds = runs.map(r => r.run_id);
const timestamps = runs
.flatMap(r => [r.project.started_at, r.project.completed_at])
.filter((t): t is string => t != null)
.sort();
// Step 1 averages
const avgConfidence = avg(runs.map(r => r.step1_plan.final_confidence));
const avgClarification = avg(runs.map(r => r.step1_plan.clarification_rounds));
const avgVerifGaps = avg(runs.map(r => r.step1_plan.verification_gaps_found));
const avgFRCount = avg(runs.map(r => r.step1_plan.functional_requirements_count));
const avgNFRCount = avg(runs.map(r => r.step1_plan.non_functional_requirements_count));
const avgRiskCount = avg(runs.map(r => r.step1_plan.risk_count));
const avgPhaseStep1 = avg(runs.map(r => r.step1_plan.phase_count));
// Step 2 averages
const avgTotalTasks = avg(runs.map(r => r.step2_document.total_tasks));
const avgPhaseStep2 = avg(runs.map(r => r.step2_document.phase_count));
const avgParallelGroups = avg(runs.map(r => r.step2_document.parallel_groups_identified));
const avgReqCoverage = avg(runs.map(r => r.step2_document.requirement_coverage_percent));
const avgVerifItems = avg(runs.map(r => r.step2_document.verification_items_added));
// Step 3 averages
const avgCompletionRate = avg(runs.map(r => r.step3_implement.task_completion_rate));
const avgBlockerCount = avg(runs.map(r => r.step3_implement.blocker_count));
// Step 4 averages
const avgCompletionAtAudit = avg(runs.map(r => r.step4_finalize.completion_rate_at_audit));
const avgVerifFailures = avg(runs.map(r => r.step4_finalize.verification_failures_found));
const avgDocUpdates = avg(runs.map(r => r.step4_finalize.documentation_updates_needed));
const archivalRate = rate(runs.map(r => r.step4_finalize.archival_succeeded));
// User feedback
const feedbackRuns = runs.filter(r => r.user_feedback != null);
const avgUserRating = avg(feedbackRuns.map(r => r.user_feedback!.overall_rating));
const feedbackCount = feedbackRuns.length;
return {
cohort_key: cohortKey,
prompt_versions: runs[0].prompt_versions,
run_count: runs.length,
run_ids: runIds,
first_seen: timestamps[0] ?? runs[0].run_id,
last_seen: timestamps[timestamps.length - 1] ?? runs[runs.length - 1].run_id,
avg_confidence: avgConfidence,
avg_clarification_rounds: avgClarification,
avg_verification_gaps_found: avgVerifGaps,
avg_functional_requirements_count: avgFRCount,
avg_non_functional_requirements_count: avgNFRCount,
avg_risk_count: avgRiskCount,
avg_phase_count_step1: avgPhaseStep1,
avg_total_tasks: avgTotalTasks,
avg_phase_count_step2: avgPhaseStep2,
avg_parallel_groups: avgParallelGroups,
avg_requirement_coverage_percent: avgReqCoverage,
avg_verification_items_added: avgVerifItems,
avg_task_completion_rate: avgCompletionRate,
avg_blocker_count: avgBlockerCount,
avg_completion_rate_at_audit: avgCompletionAtAudit,
avg_verification_failures_found: avgVerifFailures,
avg_documentation_updates_needed: avgDocUpdates,
archival_success_rate: archivalRate,
avg_user_rating: avgUserRating,
feedback_count: feedbackCount,
};
}
// ── Main aggregator ───────────────────────────────────────────────────────────
export function aggregate(runsDir: string, outputPath: string): AggregatedMetrics {
const runs = loadRunFiles(runsDir);
// Group by cohort key
const cohortMap = new Map<string, RunMetrics[]>();
for (const run of runs) {
const key = buildCohortKey(run.prompt_versions);
if (!cohortMap.has(key)) cohortMap.set(key, []);
cohortMap.get(key)!.push(run);
}
// Sort cohorts by first seen
const cohorts: CohortMetrics[] = [];
for (const [key, cohortRuns] of cohortMap) {
cohorts.push(buildCohort(cohortRuns, key));
}
cohorts.sort((a, b) => a.first_seen.localeCompare(b.first_seen));
// Determine current cohort (most recent)
const currentCohortKey = cohorts.length > 0
? cohorts[cohorts.length - 1].cohort_key
: null;
const aggregated: AggregatedMetrics = {
schema_version: '1.0',
last_updated: new Date().toISOString(),
total_runs: runs.length,
cohorts,
current_cohort_key: currentCohortKey,
};
// Write to output path
const dir = path.dirname(outputPath);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(outputPath, JSON.stringify(aggregated, null, 2), 'utf8');
return aggregated;
}
export function loadAggregated(outputPath: string): AggregatedMetrics | null {
try {
const content = fs.readFileSync(outputPath, 'utf8');
return JSON.parse(content) as AggregatedMetrics;
} catch {
return null;
}
}
/**
* Import a single run JSON from another project into the local runs dir.
* Returns true if imported, false if already present.
*/
export function importRun(runJsonPath: string, runsDir: string): boolean {
const content = fs.readFileSync(runJsonPath, 'utf8');
const run = JSON.parse(content) as RunMetrics;
run.prompt_versions = backfillPromptVersions(run.prompt_versions);
const destPath = path.join(runsDir, `${run.run_id}.json`);
if (fs.existsSync(destPath)) {
return false; // Already imported
}
fs.mkdirSync(runsDir, { recursive: true });
fs.writeFileSync(destPath, JSON.stringify(run, null, 2), 'utf8');
return true;
}
-128
View File
@@ -1,128 +0,0 @@
/**
* analyzer.ts
* Reads aggregated.json + prompt file contents, builds analysis prompt, invokes AI.
*/
import fs from 'fs';
import path from 'path';
import type { AggregatedMetrics } from './types.js';
import { invokeLLM, type AgentType } from './invoke-llm.js';
const ANALYZE_PROMPT_PATH = new URL('../src/prompts/analyze.md', import.meta.url).pathname
.replace(/^\/([A-Za-z]:)/, '$1'); // Fix Windows path
// ── Helpers ───────────────────────────────────────────────────────────────────
function readPromptFiles(plan2codeRoot: string): Record<string, string> {
const srcDir = path.join(plan2codeRoot, 'src');
const promptFiles = [
'plan2code-1-plan.md',
'plan2code-1b-revise-plan.md',
'plan2code-2-document.md',
'plan2code-3-implement.md',
'plan2code-4-finalize.md',
'plan2code-init.md',
'plan2code-init-update.md',
'plan2code-quick-task.md',
];
const contents: Record<string, string> = {};
for (const file of promptFiles) {
try {
contents[file] = fs.readFileSync(path.join(srcDir, file), 'utf8');
} catch {
contents[file] = '(file not found)';
}
}
return contents;
}
function interpolate(template: string, vars: Record<string, string>): string {
let result = template;
for (const [key, value] of Object.entries(vars)) {
result = result.replaceAll(`{{${key}}}`, value);
}
return result;
}
function generateDiagnosisId(): string {
const now = new Date();
const ts = now.toISOString().replace(/[-:T.Z]/g, '').slice(0, 14);
return `diag-${ts}`;
}
// ── Main analyzer ─────────────────────────────────────────────────────────────
export interface AnalyzerOptions {
aggregatedPath: string; // Path to aggregated.json
plan2codeRoot: string; // Path to plan2code repo root
proposalsDir: string; // Where to save diagnosis output
model?: string; // AI model to use (default: agent's default)
agent?: AgentType; // Agent to use (default: claude-code)
}
export async function runAnalysis(opts: AnalyzerOptions): Promise<string> {
const { aggregatedPath, plan2codeRoot, proposalsDir, model = 'default', agent = 'claude-code' } = opts;
// Load aggregated metrics
let aggregated: AggregatedMetrics | null = null;
try {
aggregated = JSON.parse(fs.readFileSync(aggregatedPath, 'utf8')) as AggregatedMetrics;
} catch {
throw new Error(`Could not read aggregated metrics at ${aggregatedPath}. Run "Collect metrics" and "Import run data" first.`);
}
if (aggregated.total_runs === 0) {
throw new Error('No runs in aggregated metrics. Collect and import some runs first.');
}
// Read prompt files
const promptContents = readPromptFiles(plan2codeRoot);
// Format for interpolation
const promptContentsStr = Object.entries(promptContents)
.map(([file, content]) => `## ${file}\n\n${content}`)
.join('\n\n---\n\n');
const aggregatedStr = JSON.stringify(aggregated, null, 2);
// Load analyze prompt template
let analyzeTemplate: string;
try {
analyzeTemplate = fs.readFileSync(ANALYZE_PROMPT_PATH, 'utf8');
} catch {
// Fallback: look relative to cwd
const altPath = path.join(process.cwd(), 'src', 'prompts', 'analyze.md');
analyzeTemplate = fs.readFileSync(altPath, 'utf8');
}
const fullPrompt = interpolate(analyzeTemplate, {
aggregatedMetrics: aggregatedStr,
promptContents: promptContentsStr,
});
// Invoke Claude
console.log(`\nInvoking AI analysis (agent: ${agent}, model: ${model === 'default' ? 'user default' : model})...`);
console.log('This may take a minute...\n');
let diagnosisContent: string;
try {
diagnosisContent = await invokeLLM({
prompt: fullPrompt,
model,
agent,
timeout: 300_000,
});
} catch (err) {
throw new Error(`AI invocation failed: ${err instanceof Error ? err.message : String(err)}\n\nMake sure the ${agent} CLI is installed and authenticated.`);
}
// Save diagnosis
const diagId = generateDiagnosisId();
fs.mkdirSync(proposalsDir, { recursive: true });
const diagPath = path.join(proposalsDir, `${diagId}-diagnosis.md`);
fs.writeFileSync(diagPath, diagnosisContent, 'utf8');
console.log(`Diagnosis saved to: ${diagPath}`);
return diagPath;
}
-201
View File
@@ -1,201 +0,0 @@
/**
* applier.ts
* Interactive review of a PromptProposal: display colored diff per edit,
* user approves/rejects each edit, apply approved edits to src files.
*/
import fs from 'fs';
import path from 'path';
import { confirm } from '@inquirer/prompts';
import chalk from 'chalk';
import type { PromptEdit, PromptProposal } from './types.js';
import { validateEdit } from './improver.js';
const CHAR_LIMIT = 11_000;
// ── Diff display ──────────────────────────────────────────────────────────────
function displayEditDiff(edit: PromptEdit, index: number, total: number): void {
console.log();
console.log(chalk.bold(`─── Edit ${index + 1} of ${total} ───────────────────────────────────`));
console.log(chalk.cyan(`File: ${edit.file}`));
console.log(chalk.gray(`Rationale: ${edit.rationale}`));
console.log(chalk.gray(`Expected impact: ${edit.expected_metric_impact}`));
console.log(chalk.gray(`Char impact: ${edit.char_count_before} → ${edit.char_count_after} (${edit.char_count_delta >= 0 ? '+' : ''}${edit.char_count_delta})`));
// Show char count status
if (edit.char_count_after > CHAR_LIMIT) {
console.log(chalk.red(`⚠ WARNING: Would exceed ${CHAR_LIMIT} char limit!`));
} else {
const headroom = CHAR_LIMIT - edit.char_count_after;
console.log(chalk.green(`✓ Char count OK (${headroom} chars headroom after edit)`));
}
console.log();
console.log(chalk.bold('── REMOVED (old_text) ──'));
// Show old text with line-level context
const oldLines = edit.old_text.split('\n');
for (const line of oldLines) {
console.log(chalk.red('- ') + chalk.red(line));
}
console.log();
console.log(chalk.bold('── ADDED (new_text) ──'));
const newLines = edit.new_text.split('\n');
for (const line of newLines) {
console.log(chalk.green('+ ') + chalk.green(line));
}
console.log();
}
// ── Apply edit to file ────────────────────────────────────────────────────────
function applyEdit(edit: PromptEdit, plan2codeRoot: string): boolean {
// Reject path traversal attempts
if (edit.file.includes('..') || path.isAbsolute(edit.file)) {
console.error(chalk.red(`✗ Rejected: "${edit.file}" contains path traversal or absolute path`));
return false;
}
const filePath = path.join(plan2codeRoot, 'src', edit.file);
try {
let content = fs.readFileSync(filePath, 'utf8');
if (!content.includes(edit.old_text)) {
console.error(chalk.red(`✗ Cannot apply: old_text not found in ${edit.file} (may have been modified by a previous edit)`));
return false;
}
content = content.replace(edit.old_text, edit.new_text);
// Post-apply char count check
if (content.length > CHAR_LIMIT) {
console.error(chalk.red(`✗ Cannot apply: would exceed ${CHAR_LIMIT} char limit (${content.length} chars)`));
return false;
}
fs.writeFileSync(filePath, content, 'utf8');
console.log(chalk.green(`✓ Applied edit to ${edit.file} (now ${content.length} chars)`));
return true;
} catch (err) {
console.error(chalk.red(`✗ Failed to apply edit: ${err instanceof Error ? err.message : String(err)}`));
return false;
}
}
// ── Main applier ──────────────────────────────────────────────────────────────
export interface ApplierOptions {
proposalPath: string;
plan2codeRoot: string;
proposalsDir: string;
}
export interface ApplierResult {
approved: number;
rejected: number;
applied: number;
failed: number;
}
export async function reviewAndApply(opts: ApplierOptions): Promise<ApplierResult> {
const { proposalPath, plan2codeRoot, proposalsDir } = opts;
// Load proposal
let proposal: PromptProposal;
try {
proposal = JSON.parse(fs.readFileSync(proposalPath, 'utf8')) as PromptProposal;
} catch {
throw new Error(`Could not read proposal at ${proposalPath}`);
}
if (proposal.proposals.length === 0) {
console.log(chalk.yellow('No edits in this proposal.'));
return { approved: 0, rejected: 0, applied: 0, failed: 0 };
}
console.log();
console.log(chalk.bold.cyan('=== Plan2Code Prompt Improvement Review ==='));
console.log(chalk.gray(`Proposal: ${proposal.proposal_id}`));
console.log(chalk.gray(`Created: ${proposal.created_at}`));
console.log(chalk.gray(`Based on: ${proposal.based_on_runs.length} run(s)`));
console.log(chalk.gray(`Edits: ${proposal.proposals.length}`));
// Re-validate all edits against current file state
const promptContents: Record<string, string> = {};
const srcDir = path.join(plan2codeRoot, 'src');
for (const edit of proposal.proposals) {
if (!promptContents[edit.file]) {
try {
promptContents[edit.file] = fs.readFileSync(path.join(srcDir, edit.file), 'utf8');
} catch {
promptContents[edit.file] = '';
}
}
}
let approved = 0;
let rejected = 0;
let applied = 0;
let failed = 0;
for (let i = 0; i < proposal.proposals.length; i++) {
const edit = proposal.proposals[i];
// Re-validate
const validation = validateEdit(edit, promptContents);
if (!validation.valid) {
console.log();
console.log(chalk.red(`✗ Edit ${i + 1} is no longer valid (files may have changed):`));
for (const err of validation.errors) {
console.log(chalk.red(` - ${err}`));
}
rejected++;
continue;
}
displayEditDiff(edit, i, proposal.proposals.length);
const approve = await confirm({
message: `Apply this edit to ${edit.file}?`,
default: true,
});
if (!approve) {
console.log(chalk.gray('Skipped.'));
rejected++;
continue;
}
approved++;
const success = applyEdit(edit, plan2codeRoot);
if (success) {
applied++;
// Update in-memory content to reflect the edit
promptContents[edit.file] = promptContents[edit.file].replace(edit.old_text, edit.new_text);
} else {
failed++;
}
}
// Update proposal status
proposal.status = applied > 0 ? 'applied' : 'rejected';
fs.writeFileSync(proposalPath, JSON.stringify(proposal, null, 2), 'utf8');
// Summary
console.log();
console.log(chalk.bold('─── Review Complete ──────────────────────────────────'));
console.log(`Approved: ${chalk.green(String(approved))} Rejected: ${chalk.red(String(rejected))} Applied: ${chalk.green(String(applied))} Failed: ${chalk.red(String(failed))}`);
if (applied > 0) {
console.log();
console.log(chalk.bold.cyan('Next steps — create a PR with your changes:'));
console.log(chalk.gray(' git add src/'));
console.log(chalk.gray(` git commit -m "metrics: apply prompt improvements (${proposal.proposal_id})"`));
console.log(chalk.gray(' git push -u origin HEAD'));
console.log(chalk.gray(' gh pr create --title "metrics: apply gen N improvements"'));
}
return { approved, rejected, applied, failed };
}
@@ -1,17 +0,0 @@
import { runCLI } from '../cli.js';
async function main() {
try {
await runCLI();
process.exit(0);
} catch (err) {
if (err instanceof Error && err.message.includes('User force closed')) {
// Ctrl+C — exit cleanly
process.exit(0);
}
console.error(err instanceof Error ? err.message : String(err));
process.exit(1);
}
}
main();
-841
View File
@@ -1,841 +0,0 @@
/**
* cli.ts
* 100% interactive menu-driven CLI for plan2code-metrics.
* No flags — all inputs collected via @inquirer/prompts.
*/
import fs from 'fs';
import os from 'os';
import path from 'path';
import { select, input, confirm } from '@inquirer/prompts';
import chalk from 'chalk';
import ora from 'ora';
import { collectRun } from './collector.js';
import { aggregate, loadAggregated, importRun, loadRunFiles } from './aggregator.js';
import { runAnalysis } from './analyzer.js';
import { generateImprovement } from './improver.js';
import { reviewAndApply } from './applier.js';
import type { AggregatedMetrics, CohortMetrics } from './types.js';
import { METRIC_TARGETS } from './types.js';
import { AGENTS, type AgentType } from './invoke-llm.js';
// ── Session state (set at startup via interactive prompts) ───────────────────
let resolvedPlan2CodeRoot = '';
let resolvedProjectRoot = '';
// ── Persisted user config (~/.plan2code-metrics.json) ──────────────────────
const USER_CONFIG_PATH = path.join(os.homedir(), '.plan2code-metrics.json');
interface UserConfig {
plan2codeRepoPath?: string;
}
function loadUserConfig(): UserConfig {
try {
return JSON.parse(fs.readFileSync(USER_CONFIG_PATH, 'utf8'));
} catch {
return {};
}
}
function saveUserConfig(config: UserConfig): void {
try {
fs.writeFileSync(USER_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
} catch { /* best-effort */ }
}
// ── Defaults ──────────────────────────────────────────────────────────────────
const DEFAULT_METRICS_DIR = '.plan2code-metrics';
const DEFAULT_RUNS_SUBDIR = 'runs';
const DEFAULT_AGGREGATED_FILE = 'aggregated.json';
const DEFAULT_PROPOSALS_SUBDIR = 'proposals';
function getMetricsDirs(baseDir = resolvedProjectRoot) {
const metricsDir = path.join(baseDir, DEFAULT_METRICS_DIR);
return {
metricsDir,
runsDir: path.join(metricsDir, DEFAULT_RUNS_SUBDIR),
aggregatedPath: path.join(metricsDir, DEFAULT_AGGREGATED_FILE),
proposalsDir: path.join(metricsDir, DEFAULT_PROPOSALS_SUBDIR),
};
}
// Detect plan2code root (either this directory or parent directories)
function detectPlan2CodeRoot(): string | null {
let dir = process.cwd();
for (let i = 0; i < 5; i++) {
const srcDir = path.join(dir, 'src');
if (
fs.existsSync(path.join(srcDir, 'plan2code-1-plan.md')) &&
fs.existsSync(path.join(srcDir, 'plan2code-2-document.md'))
) {
return dir;
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
// Detect plan2code version
function detectPlan2CodeVersion(plan2codeRoot: string): string {
try {
const versionPath = path.join(plan2codeRoot, 'version.json');
const content = JSON.parse(fs.readFileSync(versionPath, 'utf8'));
return content.version ?? '0.0.0';
} catch {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(plan2codeRoot, 'package.json'), 'utf8'));
return pkg.version ?? '0.0.0';
} catch {
return '0.0.0';
}
}
}
// ── Metric health helpers ─────────────────────────────────────────────────────
function metricStatus(key: string, value: number | null): string {
if (value == null) return chalk.gray('N/A');
const target = METRIC_TARGETS[key as keyof typeof METRIC_TARGETS];
if (!target) return chalk.white(String(Math.round(value * 100) / 100));
const ok = target.direction === 'gte' ? value >= target.target : value <= target.target;
const formatted = Number.isInteger(value) ? String(value) : value.toFixed(2);
return ok ? chalk.green(`✓ ${formatted}`) : chalk.red(`✗ ${formatted} (target: ${target.direction === 'gte' ? '≥' : '≤'}${target.target})`);
}
// ── Agent + model selection ───────────────────────────────────────────────────
async function selectAgentAndModel(): Promise<{ agent: AgentType; model: string }> {
const agentChoice = await select({
message: 'Which AI agent?',
choices: Object.values(AGENTS).map(a => ({ name: a.displayName, value: a.name })),
});
return { agent: agentChoice, model: AGENTS[agentChoice].defaultModel };
}
// ── Flow: Collect metrics ─────────────────────────────────────────────────────
async function flowCollect(): Promise<void> {
console.log();
console.log(chalk.bold.cyan('── Collect Metrics ──'));
const sourceChoice = await select({
message: 'Where is the completed project spec?',
choices: [
{ name: 'Archived spec (specs--completed/<feature-name>/)', value: 'archived' },
{ name: 'Active spec directory (specs/<feature-name>/)', value: 'active' },
{ name: 'Custom path', value: 'custom' },
],
});
let specDir: string;
let projectName: string;
if (sourceChoice === 'active' || sourceChoice === 'archived') {
const baseSubdir = sourceChoice === 'active' ? 'specs' : 'specs--completed';
const baseDir = path.join(resolvedProjectRoot, baseSubdir);
if (!fs.existsSync(baseDir)) {
console.log(chalk.red(`No ${baseSubdir}/ directory found in ${resolvedProjectRoot}`));
return;
}
const entries = fs.readdirSync(baseDir)
.filter(f => fs.statSync(path.join(baseDir, f)).isDirectory());
if (entries.length === 0) {
console.log(chalk.red(`No spec directories found in ${baseSubdir}/`));
return;
}
const chosen = await select({
message: 'Select spec directory:',
choices: entries.map(e => ({ name: e, value: e })),
});
specDir = path.join(baseDir, chosen);
projectName = chosen;
} else {
specDir = await input({
message: 'Enter full path to spec directory:',
validate: (v) => fs.existsSync(v) ? true : 'Directory not found',
});
projectName = await input({
message: 'Project name (for metrics label):',
default: path.basename(specDir),
});
}
// Detect plan2code root
const plan2codeRoot = resolvedPlan2CodeRoot;
const plan2codeVersion = detectPlan2CodeVersion(plan2codeRoot);
const { runsDir, aggregatedPath } = getMetricsDirs();
const spinner = ora('Collecting metrics from project artifacts...').start();
try {
const metrics = await collectRun({
specDir,
projectName,
plan2codeRoot,
plan2codeVersion,
outputDir: runsDir,
});
spinner.succeed(`Metrics collected: ${metrics.run_id}`);
console.log(chalk.gray(` Saved to: ${runsDir}/${metrics.run_id}.json`));
// Re-aggregate
aggregate(runsDir, aggregatedPath);
console.log(chalk.gray(' Aggregated metrics updated.'));
// Show summary
console.log();
console.log(chalk.bold('Collected:'));
console.log(` Step 1 (Plan): ${metrics.step1_plan.present ? chalk.green('✓') : chalk.gray('—')}`);
console.log(` Step 2 (Document): ${metrics.step2_document.present ? chalk.green('✓') : chalk.gray('—')}`);
console.log(` Step 3 (Implement): ${metrics.step3_implement.present ? chalk.green('✓') : chalk.gray('—')}`);
console.log(` Step 4 (Finalize): ${metrics.step4_finalize.present ? chalk.green('✓') : chalk.gray('—')}`);
console.log(` User Feedback: ${metrics.user_feedback ? chalk.green(`✓ (${metrics.user_feedback.overall_rating}/10)`) : chalk.gray('—')}`);
// Offer to collect feedback interactively if not present
if (!metrics.user_feedback) {
console.log();
const wantFeedback = await confirm({
message: 'No user feedback found in overview.md. Would you like to provide feedback now?',
default: false,
});
if (wantFeedback) {
const rating = await input({
message: 'Overall rating (1-10):',
validate: (v) => {
const n = parseInt(v, 10);
return (n >= 1 && n <= 10) ? true : 'Must be a number between 1 and 10';
},
});
const reason = await input({ message: 'Rating reason:' });
const wentWell = await input({ message: 'What went well?' });
const wentPoorly = await input({ message: 'What went poorly?' });
// Write the feedback table into overview.md
const overviewPath = path.join(specDir, 'overview.md');
let overviewContent = '';
try {
overviewContent = fs.readFileSync(overviewPath, 'utf8');
} catch { /* empty */ }
// Escape pipe characters in user text to prevent table parsing issues
const esc = (s: string) => s.replace(/\|/g, '\\|');
const feedbackTable = [
'',
'## User Feedback',
'| Field | Value |',
'|-------|-------|',
`| Rating | ${rating} |`,
`| Reason | ${esc(reason)} |`,
`| Went Well | ${esc(wentWell)} |`,
`| Went Poorly | ${esc(wentPoorly)} |`,
'',
].join('\n');
fs.writeFileSync(overviewPath, overviewContent + feedbackTable, 'utf8');
console.log(chalk.green('✓ Feedback written to overview.md'));
// Delete the original run (without feedback) before re-collecting
const originalRunPath = path.join(runsDir, `${metrics.run_id}.json`);
try { fs.unlinkSync(originalRunPath); } catch { /* ignore */ }
// Re-collect and re-aggregate
const reSpinner = ora('Re-collecting metrics with feedback...').start();
const updatedMetrics = await collectRun({
specDir,
projectName,
plan2codeRoot,
plan2codeVersion,
outputDir: runsDir,
});
aggregate(runsDir, aggregatedPath);
reSpinner.succeed(`Updated: ${updatedMetrics.run_id} (rating: ${updatedMetrics.user_feedback?.overall_rating}/10)`);
}
}
} catch (err) {
spinner.fail(`Collection failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
// ── Flow: Import run data ─────────────────────────────────────────────────────
async function flowImport(): Promise<void> {
console.log();
console.log(chalk.bold.cyan('── Import Run Data ──'));
console.log(chalk.gray('Copy a run JSON from another project into this repo for aggregation.'));
console.log();
const sourcePath = await input({
message: 'Path to run JSON file (e.g., /path/to/project/.plan2code-metrics/runs/run-xxx.json):',
validate: (v) => {
if (!fs.existsSync(v)) return 'File not found';
if (!v.endsWith('.json')) return 'Must be a .json file';
return true;
},
});
const { runsDir, aggregatedPath } = getMetricsDirs();
try {
const imported = importRun(sourcePath, runsDir);
if (!imported) {
console.log(chalk.yellow('Run already imported (same run_id exists).'));
} else {
console.log(chalk.green(`✓ Imported ${path.basename(sourcePath)}`));
}
const spinner = ora('Re-aggregating...').start();
const aggregated = aggregate(runsDir, aggregatedPath);
spinner.succeed(`Aggregated metrics updated (${aggregated.total_runs} total runs)`);
} catch (err) {
console.error(chalk.red(`Import failed: ${err instanceof Error ? err.message : String(err)}`));
}
}
// ── Flow: View metrics status ─────────────────────────────────────────────────
async function flowViewStatus(): Promise<void> {
console.log();
console.log(chalk.bold.cyan('── Metrics Status & History ──'));
const { runsDir, aggregatedPath } = getMetricsDirs();
const aggregated = loadAggregated(aggregatedPath);
if (!aggregated || aggregated.total_runs === 0) {
console.log(chalk.yellow('No metrics collected yet. Use "Collect metrics" to get started.'));
return;
}
console.log();
console.log(chalk.bold(`Total runs: ${aggregated.total_runs} | Generations: ${aggregated.cohorts.length}`));
console.log(chalk.gray(`Last updated: ${aggregated.last_updated}`));
for (let i = 0; i < aggregated.cohorts.length; i++) {
const cohort = aggregated.cohorts[i];
const isCurrent = cohort.cohort_key === aggregated.current_cohort_key;
const label = isCurrent ? chalk.bold.green('[CURRENT]') : '';
console.log();
console.log(chalk.bold(`Generation ${i + 1} (sha:${cohort.cohort_key}) — ${cohort.run_count} run(s) ${label}`));
console.log(chalk.gray(` Period: ${cohort.first_seen?.slice(0, 10)} → ${cohort.last_seen?.slice(0, 10)}`));
// Step 1 metrics
if (cohort.avg_confidence != null || cohort.avg_clarification_rounds != null) {
console.log(chalk.bold(' Step 1 (Plan):'));
if (cohort.avg_confidence != null)
console.log(` avg_confidence: ${metricStatus('avg_confidence', cohort.avg_confidence)}`);
if (cohort.avg_clarification_rounds != null)
console.log(` avg_clarification_rounds: ${metricStatus('avg_clarification_rounds', cohort.avg_clarification_rounds)}`);
if (cohort.avg_verification_gaps_found != null)
console.log(` avg_verification_gaps: ${metricStatus('avg_verification_gaps_found', cohort.avg_verification_gaps_found)}`);
}
// Step 2 metrics
if (cohort.avg_total_tasks != null || cohort.avg_parallel_groups != null) {
console.log(chalk.bold(' Step 2 (Document):'));
if (cohort.avg_total_tasks != null)
console.log(` avg_total_tasks: ${chalk.white(cohort.avg_total_tasks.toFixed(1))}`);
if (cohort.avg_parallel_groups != null)
console.log(` avg_parallel_groups: ${metricStatus('avg_parallel_groups', cohort.avg_parallel_groups)}`);
if (cohort.avg_verification_items_added != null)
console.log(` avg_verification_items: ${metricStatus('avg_verification_items_added', cohort.avg_verification_items_added)}`);
}
// Step 3 metrics
if (cohort.avg_task_completion_rate != null || cohort.avg_blocker_count != null) {
console.log(chalk.bold(' Step 3 (Implement):'));
if (cohort.avg_task_completion_rate != null)
console.log(` avg_task_completion_rate: ${metricStatus('avg_task_completion_rate', cohort.avg_task_completion_rate)}`);
if (cohort.avg_blocker_count != null)
console.log(` avg_blocker_count: ${metricStatus('avg_blocker_count', cohort.avg_blocker_count)}`);
}
// Step 4 metrics
if (cohort.avg_completion_rate_at_audit != null || cohort.archival_success_rate != null) {
console.log(chalk.bold(' Step 4 (Finalize):'));
if (cohort.avg_completion_rate_at_audit != null)
console.log(` avg_completion_at_audit: ${chalk.white(cohort.avg_completion_rate_at_audit.toFixed(2))}`);
if (cohort.avg_verification_failures_found != null)
console.log(` avg_verif_failures: ${metricStatus('avg_verification_failures_found', cohort.avg_verification_failures_found)}`);
if (cohort.archival_success_rate != null)
console.log(` archival_success_rate: ${metricStatus('archival_success_rate', cohort.archival_success_rate)}`);
}
// User feedback
if (cohort.feedback_count > 0) {
console.log(chalk.bold(' User Feedback:'));
console.log(` avg_user_rating: ${metricStatus('avg_user_rating', cohort.avg_user_rating)}`);
console.log(` feedback_count: ${chalk.white(String(cohort.feedback_count))}`);
}
// Compare with previous generation
if (i > 0) {
const prev = aggregated.cohorts[i - 1];
const deltas: string[] = [];
if (cohort.avg_confidence != null && prev.avg_confidence != null) {
const d = cohort.avg_confidence - prev.avg_confidence;
deltas.push(`confidence ${d >= 0 ? chalk.green(`▲${d.toFixed(1)}`) : chalk.red(`▼${Math.abs(d).toFixed(1)}`)}`);
}
if (cohort.avg_task_completion_rate != null && prev.avg_task_completion_rate != null) {
const d = cohort.avg_task_completion_rate - prev.avg_task_completion_rate;
deltas.push(`completion ${d >= 0 ? chalk.green(`▲${(d * 100).toFixed(1)}%`) : chalk.red(`▼${(Math.abs(d) * 100).toFixed(1)}%`)}`);
}
if (deltas.length > 0) {
console.log(chalk.gray(` vs Gen ${i}: ${deltas.join(' ')}`));
}
}
}
// Run list
const runs = loadRunFiles(runsDir);
if (runs.length > 0) {
console.log();
console.log(chalk.bold(`Run files (${runs.length}):`));
for (const run of runs.slice(-10)) {
console.log(chalk.gray(` ${run.run_id} ${run.project.name} v${run.plan2code_version}`));
}
if (runs.length > 10) {
console.log(chalk.gray(` ... and ${runs.length - 10} more`));
}
}
}
// ── Flow: Run analysis ────────────────────────────────────────────────────────
async function flowRunAnalysis(): Promise<string | null> {
console.log();
console.log(chalk.bold.cyan('── Run Analysis (Diagnose Weak Steps) ──'));
const { aggregatedPath, proposalsDir } = getMetricsDirs();
const plan2codeRoot = resolvedPlan2CodeRoot;
const aggregated = loadAggregated(aggregatedPath);
if (!aggregated || aggregated.total_runs === 0) {
console.log(chalk.yellow('No aggregated metrics found. Collect and import runs first.'));
return null;
}
if (aggregated.total_runs < 3) {
const proceed = await confirm({
message: `Only ${aggregated.total_runs} run(s) available (≥3 recommended for reliable analysis). Proceed anyway?`,
default: false,
});
if (!proceed) return null;
}
const { agent, model } = await selectAgentAndModel();
try {
const diagPath = await runAnalysis({
aggregatedPath,
plan2codeRoot,
proposalsDir,
model,
agent,
});
console.log();
console.log(chalk.green('✓ Analysis complete'));
console.log(chalk.gray(`Diagnosis: ${diagPath}`));
const viewNow = await confirm({
message: 'Open diagnosis in console?',
default: true,
});
if (viewNow) {
const content = fs.readFileSync(diagPath, 'utf8');
console.log();
console.log(chalk.dim('─'.repeat(60)));
console.log(content);
console.log(chalk.dim('─'.repeat(60)));
}
return diagPath;
} catch (err) {
console.error(chalk.red(`Analysis failed: ${err instanceof Error ? err.message : String(err)}`));
return null;
}
}
// ── Flow: Generate improvement proposal ──────────────────────────────────────
async function flowGenerateProposal(): Promise<void> {
console.log();
console.log(chalk.bold.cyan('── Generate Improvement Proposal ──'));
const { aggregatedPath, proposalsDir, runsDir } = getMetricsDirs();
const plan2codeRoot = resolvedPlan2CodeRoot;
// Find diagnosis files
let diagFiles: string[] = [];
if (fs.existsSync(proposalsDir)) {
diagFiles = fs.readdirSync(proposalsDir)
.filter(f => f.endsWith('-diagnosis.md'))
.sort()
.reverse(); // most recent first
}
let diagnosisPath: string;
if (diagFiles.length === 0) {
console.log(chalk.yellow('No diagnosis files found. Running analysis first...'));
const diagPath = await flowRunAnalysis();
if (!diagPath) return;
diagnosisPath = diagPath;
} else {
const choice = await select({
message: 'Select diagnosis to base proposal on:',
choices: [
...diagFiles.map(f => ({ name: f, value: path.join(proposalsDir, f) })),
{ name: '(run new analysis first)', value: '__new__' },
],
});
if (choice === '__new__') {
const diagPath = await flowRunAnalysis();
if (!diagPath) return;
diagnosisPath = diagPath;
} else {
diagnosisPath = choice;
}
}
const { agent, model } = await selectAgentAndModel();
try {
const result = await generateImprovement({
diagnosisPath,
plan2codeRoot,
proposalsDir,
runsDir,
model,
agent,
});
console.log();
console.log(chalk.green(`✓ Proposal generated: ${result.proposal.proposal_id}`));
console.log(chalk.gray(` Valid edits: ${result.validEditCount}`));
console.log(chalk.gray(` Invalid edits: ${result.invalidEditCount} (rejected)`));
console.log(chalk.gray(` Saved to: ${result.proposalPath}`));
if (result.validEditCount > 0) {
const reviewNow = await confirm({
message: 'Review and apply edits now?',
default: true,
});
if (reviewNow) {
await reviewAndApply({
proposalPath: result.proposalPath,
plan2codeRoot,
proposalsDir,
});
}
}
} catch (err) {
console.error(chalk.red(`Proposal generation failed: ${err instanceof Error ? err.message : String(err)}`));
}
}
// ── Flow: Review and apply proposal ──────────────────────────────────────────
async function flowReviewAndApply(): Promise<void> {
console.log();
console.log(chalk.bold.cyan('── Review and Apply a Proposal ──'));
const { proposalsDir } = getMetricsDirs();
const plan2codeRoot = resolvedPlan2CodeRoot;
if (!fs.existsSync(proposalsDir)) {
console.log(chalk.yellow('No proposals directory found. Generate a proposal first.'));
return;
}
const proposalFiles = fs.readdirSync(proposalsDir)
.filter(f => /^prop-\d+\.json$/.test(f))
.sort()
.reverse(); // most recent first
if (proposalFiles.length === 0) {
console.log(chalk.yellow('No proposal files found. Generate a proposal first.'));
return;
}
const chosen = await select({
message: 'Select proposal to review:',
choices: proposalFiles.map(f => {
try {
const p = JSON.parse(fs.readFileSync(path.join(proposalsDir, f), 'utf8'));
const label = `${f} [${p.status}] ${p.proposals?.length ?? 0} edits`;
return { name: label, value: path.join(proposalsDir, f) };
} catch {
return { name: f, value: path.join(proposalsDir, f) };
}
}),
});
await reviewAndApply({
proposalPath: chosen,
plan2codeRoot,
proposalsDir,
});
}
// ── Flow: Delete metrics data ─────────────────────────────────────────────────
async function flowDelete(): Promise<void> {
console.log();
console.log(chalk.bold.cyan('── Delete Metrics Data ──'));
const { metricsDir, runsDir, aggregatedPath, proposalsDir } = getMetricsDirs();
if (!fs.existsSync(metricsDir)) {
console.log(chalk.yellow('No metrics data found (.plan2code-metrics/ does not exist).'));
return;
}
const scope = await select({
message: 'What do you want to delete?',
choices: [
{ name: 'Delete specific run(s)', value: 'select' },
{ name: 'Delete all runs and aggregated data', value: 'runs' },
{ name: 'Delete everything (runs, aggregated data, proposals)', value: 'all' },
{ name: 'Cancel', value: 'cancel' },
],
});
if (scope === 'cancel') return;
if (scope === 'select') {
const runs = loadRunFiles(runsDir);
if (runs.length === 0) {
console.log(chalk.yellow('No run files found.'));
return;
}
const choices = runs.map(r => ({
name: `${r.run_id} ${r.project.name} v${r.plan2code_version}`,
value: r.run_id,
}));
// Select runs one at a time since @inquirer/prompts select is single-choice
const toDelete: string[] = [];
let selecting = true;
while (selecting) {
const remaining = choices.filter(c => !toDelete.includes(c.value));
if (remaining.length === 0) break;
const chosen = await select({
message: `Select a run to delete (${toDelete.length} selected so far):`,
choices: [
...remaining,
{ name: toDelete.length > 0 ? `Done selecting (delete ${toDelete.length})` : 'Cancel', value: '__done__' },
],
});
if (chosen === '__done__') {
selecting = false;
} else {
toDelete.push(chosen);
console.log(chalk.gray(` + ${chosen}`));
}
}
if (toDelete.length === 0) return;
const confirmed = await confirm({
message: `Delete ${toDelete.length} run(s)? This cannot be undone.`,
default: false,
});
if (!confirmed) return;
let deleted = 0;
for (const runId of toDelete) {
const filePath = path.join(runsDir, `${runId}.json`);
try {
fs.unlinkSync(filePath);
deleted++;
} catch {
console.log(chalk.yellow(` Could not delete ${runId}.json`));
}
}
console.log(chalk.green(`✓ Deleted ${deleted} run(s).`));
// Re-aggregate with remaining runs
const remainingRuns = loadRunFiles(runsDir);
if (remainingRuns.length > 0) {
aggregate(runsDir, aggregatedPath);
console.log(chalk.gray(` Aggregated metrics updated (${remainingRuns.length} runs remaining).`));
} else {
try { fs.unlinkSync(aggregatedPath); } catch { /* ignore */ }
console.log(chalk.gray(' No runs remaining — aggregated data removed.'));
}
return;
}
// scope === 'runs' or 'all'
const label = scope === 'all'
? 'ALL metrics data (runs, aggregated data, and proposals)'
: 'all runs and aggregated data';
const confirmed = await confirm({
message: `Delete ${label}? This cannot be undone.`,
default: false,
});
if (!confirmed) return;
// Delete run files
let runCount = 0;
if (fs.existsSync(runsDir)) {
const files = fs.readdirSync(runsDir).filter(f => f.endsWith('.json'));
for (const f of files) {
try { fs.unlinkSync(path.join(runsDir, f)); runCount++; } catch { /* ignore */ }
}
}
// Delete aggregated file
try { fs.unlinkSync(aggregatedPath); } catch { /* ignore */ }
console.log(chalk.green(`✓ Deleted ${runCount} run(s) and aggregated data.`));
if (scope === 'all') {
// Delete proposals
let proposalCount = 0;
if (fs.existsSync(proposalsDir)) {
const files = fs.readdirSync(proposalsDir);
for (const f of files) {
try { fs.unlinkSync(path.join(proposalsDir, f)); proposalCount++; } catch { /* ignore */ }
}
try { fs.rmdirSync(proposalsDir); } catch { /* ignore */ }
}
console.log(chalk.green(`✓ Deleted ${proposalCount} proposal file(s).`));
}
}
// ── Main menu ─────────────────────────────────────────────────────────────────
export async function runCLI(): Promise<void> {
console.log();
console.log(chalk.bold.white('plan2code-metrics'));
console.log(chalk.gray('Recursive self-improvement toolchain for plan2code contributors'));
console.log();
// ── Prompt for paths ────────────────────────────────────────────────────────
const userConfig = loadUserConfig();
const savedRoot = userConfig.plan2codeRepoPath && fs.existsSync(userConfig.plan2codeRepoPath)
? userConfig.plan2codeRepoPath
: null;
const detectedRoot = savedRoot ?? detectPlan2CodeRoot();
const s2cPath = await input({
message: 'Path to plan2code repo:',
default: detectedRoot ?? undefined,
validate: (v) => {
if (!v.trim()) return 'Path is required';
const resolved = path.resolve(v.trim());
if (!fs.existsSync(resolved)) return 'Directory not found';
return true;
},
});
resolvedPlan2CodeRoot = path.resolve(s2cPath.trim());
// Persist the path for next run
if (resolvedPlan2CodeRoot !== userConfig.plan2codeRepoPath) {
saveUserConfig({ ...userConfig, plan2codeRepoPath: resolvedPlan2CodeRoot });
}
// Warn if the path doesn't look like a plan2code repo
const hasSrcPrompts =
fs.existsSync(path.join(resolvedPlan2CodeRoot, 'src', 'plan2code-1-plan.md')) &&
fs.existsSync(path.join(resolvedPlan2CodeRoot, 'src', 'plan2code-2-document.md'));
if (!hasSrcPrompts) {
console.log(chalk.yellow('⚠ No src/plan2code-*.md prompts found at that path. Hashing and analysis may be limited.'));
}
const projPath = await input({
message: 'Path to project repo (metrics source):',
default: process.cwd(),
validate: (v) => {
if (!v.trim()) return 'Path is required';
const resolved = path.resolve(v.trim());
if (!fs.existsSync(resolved)) return 'Directory not found';
return true;
},
});
resolvedProjectRoot = path.resolve(projPath.trim());
// Display resolved paths
const version = detectPlan2CodeVersion(resolvedPlan2CodeRoot);
console.log();
console.log(chalk.gray(`plan2code repo: ${resolvedPlan2CodeRoot} (v${version})`));
console.log(chalk.gray(`project repo: ${resolvedProjectRoot}`));
console.log();
let continueLoop = true;
while (continueLoop) {
const action = await select({
message: 'What would you like to do?',
choices: [
{ name: 'Collect metrics for a completed project', value: 'collect' },
{ name: 'Import run data from another project', value: 'import' },
{ name: 'View metrics status and history', value: 'view' },
{ name: 'Run analysis (diagnose weak steps)', value: 'analyze' },
{ name: 'Generate improvement proposal', value: 'propose' },
{ name: 'Review and apply a proposal', value: 'apply' },
{ name: chalk.red('Delete metrics data'), value: 'delete' },
{ name: 'Exit', value: 'exit' },
],
});
switch (action) {
case 'collect':
await flowCollect();
break;
case 'import':
await flowImport();
break;
case 'view':
await flowViewStatus();
break;
case 'analyze':
await flowRunAnalysis();
break;
case 'propose':
await flowGenerateProposal();
break;
case 'apply':
await flowReviewAndApply();
break;
case 'delete':
await flowDelete();
break;
case 'exit':
continueLoop = false;
break;
}
if (continueLoop && action !== 'exit') {
console.log();
}
}
console.log(chalk.gray('Goodbye.'));
}
-633
View File
@@ -1,633 +0,0 @@
/**
* collector.ts
* Reads finished project artifacts and writes a RunMetrics JSON file.
* Zero dependency on plan2code-loop internals — reads files directly.
*/
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import type {
RunMetrics,
PromptVersions,
Step1PlanMetrics,
Step2DocumentMetrics,
Step3ImplementMetrics,
Step4FinalizeMetrics,
UserFeedback,
} from './types.js';
// ── Helpers ──────────────────────────────────────────────────────────────────
function sha256File(filePath: string): string {
try {
const content = fs.readFileSync(filePath, 'utf8');
return 'sha256:' + crypto.createHash('sha256').update(content).digest('hex');
} catch {
return 'sha256:missing';
}
}
function readFileSafe(filePath: string): string | null {
try {
return fs.readFileSync(filePath, 'utf8');
} catch {
return null;
}
}
/**
* Extract METRICS_JSON HTML comment blocks from a file.
* Format: <!-- METRICS_JSON {"key": value, ...} -->
* A file may contain multiple blocks (e.g., overview.md has document + finalize).
* If `stepFilter` is provided, returns only the block with matching "step" field.
* Returns parsed object or null if not found / invalid.
*/
function extractMetricsJson(content: string, stepFilter?: string): Record<string, unknown> | null {
const re = /<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/g;
let match: RegExpExecArray | null;
while ((match = re.exec(content)) !== null) {
try {
const parsed = JSON.parse(match[1]) as Record<string, unknown>;
if (!stepFilter || parsed['step'] === stepFilter) {
return parsed;
}
} catch {
// try next match
}
}
return null;
}
/** Strip the "## Success Criteria" section so its checkboxes aren't counted as tasks. */
function stripSuccessCriteriaSection(overview: string): string {
return overview.replace(/^## Success Criteria\s*\n[\s\S]*?(?=\n## |\n*$)/m, '');
}
/**
* Extract canonical task counts from the Completion Summary section.
* Supports two formats found in real specs:
* - Bold text: "**Completion Rate:** 100% (5/5 tasks)"
* - Table row: "| Total Tasks | 28 (28/28 complete — 100%) |"
* Returns null when no parseable counts are found.
*/
function parseCompletionSummaryTaskCount(overview: string): { completed: number; total: number } | null {
const summaryMatch = overview.match(/## Completion Summary\s*\n([\s\S]*?)(?=\n## |\n*$)/);
if (!summaryMatch) return null;
const summary = summaryMatch[1];
// "Completion Rate: X% (Y/Z tasks)" — handles bold markdown and various separators
const rateMatch = summary.match(/\**Completion(?:\s+Rate)?\**[:\s*]+\d{1,3}%\s*\((\d+)\/(\d+)\s*tasks?\)/i);
if (rateMatch) return { completed: parseInt(rateMatch[1], 10), total: parseInt(rateMatch[2], 10) };
// "Total Tasks | 28 (28/28 complete"
const tableMatch = summary.match(/Total Tasks\s*\|\s*(\d+)\s*\((\d+)\/(\d+)\s*complete/i);
if (tableMatch) return { completed: parseInt(tableMatch[2], 10), total: parseInt(tableMatch[3], 10) };
return null;
}
function generateRunId(): string {
const now = new Date();
const ts = now.toISOString().replace(/[-:T]/g, '').slice(0, 14);
const rand = crypto.randomBytes(2).toString('hex');
return `run-${ts.slice(0, 8)}-${ts.slice(8, 14)}-${rand}`;
}
// ── Prompt version hashing ────────────────────────────────────────────────────
export function collectPromptVersions(plan2codeRoot: string): PromptVersions {
const srcDir = path.join(plan2codeRoot, 'src');
return {
plan: sha256File(path.join(srcDir, 'plan2code-1-plan.md')),
revise_plan: sha256File(path.join(srcDir, 'plan2code-1b-revise-plan.md')),
document: sha256File(path.join(srcDir, 'plan2code-2-document.md')),
implement: sha256File(path.join(srcDir, 'plan2code-3-implement.md')),
finalize: sha256File(path.join(srcDir, 'plan2code-4-finalize.md')),
init: sha256File(path.join(srcDir, 'plan2code-init.md')),
init_update: sha256File(path.join(srcDir, 'plan2code-init-update.md')),
quick_task: sha256File(path.join(srcDir, 'plan2code-quick-task.md')),
};
}
// ── Step 1: Plan ──────────────────────────────────────────────────────────────
export function collectStep1(specDir: string): Step1PlanMetrics {
// Find PLAN-DRAFT-*.md files
let draftFiles: string[] = [];
let convFiles: string[] = [];
try {
const files = fs.readdirSync(specDir);
draftFiles = files
.filter(f => f.startsWith('PLAN-DRAFT-') && f.endsWith('.md'))
.map(f => path.join(specDir, f));
convFiles = files
.filter(f => f.startsWith('PLAN-CONVERSATION-') && f.endsWith('.md'))
.map(f => path.join(specDir, f));
} catch {
return { present: false, final_confidence: null, confidence_breakdown: null,
clarification_rounds: null, tech_stack_revision_rounds: null,
verification_gaps_found: null, functional_requirements_count: null,
non_functional_requirements_count: null, risk_count: null, phase_count: null };
}
if (draftFiles.length === 0) {
return { present: false, final_confidence: null, confidence_breakdown: null,
clarification_rounds: null, tech_stack_revision_rounds: null,
verification_gaps_found: null, functional_requirements_count: null,
non_functional_requirements_count: null, risk_count: null, phase_count: null };
}
// Use the latest draft file
draftFiles.sort();
const latestDraft = readFileSafe(draftFiles[draftFiles.length - 1]) ?? '';
// ── Primary source: METRICS_JSON HTML comment ──
// Format: <!-- METRICS_JSON {"confidence": 95, "clarification_rounds": 0, ...} -->
const metricsJson = extractMetricsJson(latestDraft);
if (metricsJson) {
const num = (key: string): number | null => {
const v = metricsJson[key];
return typeof v === 'number' ? v : null;
};
const bd = metricsJson['confidence_breakdown'] as Record<string, number> | undefined;
return {
present: true,
final_confidence: num('confidence'),
confidence_breakdown: bd ? {
requirements: bd.requirements ?? null,
feasibility: bd.feasibility ?? null,
integration: bd.integration ?? null,
risk: bd.risk ?? null,
} : null,
clarification_rounds: num('clarification_rounds'),
tech_stack_revision_rounds: num('tech_stack_revision_rounds'),
verification_gaps_found: num('verification_gaps_found'),
functional_requirements_count: num('functional_requirements_count'),
non_functional_requirements_count: num('non_functional_requirements_count'),
risk_count: num('risk_count'),
phase_count: num('phase_count'),
};
}
// ── Fallback: structured ## Planning Metrics appendix ──
// Handles both plain (confidence: 95) and bold (**confidence:** 95) field formats
// Planning Metrics is typically the last section, so we capture greedily to end,
// but stop at the next ## heading or --- if present.
const metricsSection = latestDraft.match(/^##\s+Planning\s+Metrics\s*\n([\s\S]+?)(?:\n##\s|\n---)/m)
?? latestDraft.match(/^##\s+Planning\s+Metrics\s*\n([\s\S]+)/m);
const metricsBlock = metricsSection?.[1] ?? '';
const parseMetricField = (field: string): number | null => {
// Match plain "field: N" or bold "**field:** N"
const m = metricsBlock.match(new RegExp(`^\\**${field}\\**[:\\s*]+?(\\d+)`, 'm'));
return m ? parseInt(m[1], 10) : null;
};
// ── Confidence ──
let finalConfidence = parseMetricField('confidence');
if (finalConfidence === null) {
// Fallback: prose scraping — handle bold markdown like **Confidence:** 95%
const confMatch = latestDraft.match(/(?:Overall|Final|Total)?\s*\**[Cc]onfidence\**[:\s*]+(\d{1,3})%/);
if (confMatch) {
finalConfidence = parseInt(confMatch[1], 10);
} else {
const tableMatch = latestDraft.match(/[|]\s*[Cc]onfidence\s*[|]\s*(\d{1,3})/);
if (tableMatch) finalConfidence = parseInt(tableMatch[1], 10);
}
}
// Confidence breakdown (requirements, feasibility, integration, risk)
let confidenceBreakdown: Step1PlanMetrics['confidence_breakdown'] = null;
const reqMatch = latestDraft.match(/[Rr]equirements?[:\s|]+(\d{1,2})/);
const feasMatch = latestDraft.match(/[Ff]easibility[:\s|]+(\d{1,2})/);
const intMatch = latestDraft.match(/[Ii]ntegration[:\s|]+(\d{1,2})/);
const riskMatch = latestDraft.match(/[Rr]isk[:\s|]+(\d{1,2})/);
if (reqMatch || feasMatch || intMatch || riskMatch) {
confidenceBreakdown = {
requirements: reqMatch ? parseInt(reqMatch[1], 10) : null,
feasibility: feasMatch ? parseInt(feasMatch[1], 10) : null,
integration: intMatch ? parseInt(intMatch[1], 10) : null,
risk: riskMatch ? parseInt(riskMatch[1], 10) : null,
};
}
// ── Clarification rounds ──
let clarificationRounds = parseMetricField('clarification_rounds');
// ── Verification gaps ──
let verificationGaps = parseMetricField('verification_gaps_found');
// ── Functional / non-functional requirements ──
let frCount = parseMetricField('functional_requirements_count');
if (frCount === null) {
frCount = (latestDraft.match(/###\s+FR-/g) ?? []).length || null;
}
let nfrCount = parseMetricField('non_functional_requirements_count');
if (nfrCount === null) {
nfrCount = (latestDraft.match(/###\s+NFR-/g) ?? []).length || null;
}
// ── Risk count ──
let riskCount = parseMetricField('risk_count');
if (riskCount === null) {
const riskRows = latestDraft.match(/^\s*[|][^|]*(?:High|Medium|Low|Critical)[^|]*[|]/gm) ?? [];
riskCount = riskRows.length || null;
}
// ── Phase count ──
let phaseCount = parseMetricField('phase_count');
if (phaseCount === null) {
phaseCount = (latestDraft.match(/^##\s+Phase\s+\d/gm) ?? []).length || null;
}
// ── Tech stack revision rounds (conversation file only) ──
let techStackRevisions: number | null = null;
// Fall back to conversation file scraping for fields not found in appendix
if (convFiles.length > 0) {
convFiles.sort();
const latestConv = readFileSafe(convFiles[convFiles.length - 1]) ?? '';
if (clarificationRounds === null) {
const clarRounds = (latestConv.match(/^##\s+(?:Clarification|Round)\s+\d/gm) ?? []).length;
clarificationRounds = clarRounds || null;
}
const techRounds = (latestConv.match(/^##\s+(?:Tech\s+Stack|Technology)\s+Revision/gmi) ?? []).length;
techStackRevisions = techRounds || null;
if (verificationGaps === null) {
const gapMatches = latestConv.match(/(?:verification\s+gap|gap\s+found|missing\s+requirement)/gi) ?? [];
verificationGaps = gapMatches.length || null;
}
}
return {
present: true,
final_confidence: finalConfidence,
confidence_breakdown: confidenceBreakdown,
clarification_rounds: clarificationRounds,
tech_stack_revision_rounds: techStackRevisions,
verification_gaps_found: verificationGaps,
functional_requirements_count: frCount,
non_functional_requirements_count: nfrCount,
risk_count: riskCount,
phase_count: phaseCount,
};
}
// ── Step 2: Document ──────────────────────────────────────────────────────────
export function collectStep2(specDir: string): Step2DocumentMetrics {
const overviewPath = path.join(specDir, 'overview.md');
const overview = readFileSafe(overviewPath);
if (!overview) {
return { present: false, total_tasks: null, tasks_per_phase: null,
phase_count: null, parallel_groups_identified: null,
requirement_coverage_percent: null, verification_items_added: null };
}
// ── Primary source: METRICS_JSON in overview.md ──
const step2Json = extractMetricsJson(overview, 'document');
if (step2Json) {
const num = (key: string): number | null => {
const v = step2Json[key];
return typeof v === 'number' ? v : null;
};
const tpp = step2Json['tasks_per_phase'];
return {
present: true,
total_tasks: num('total_tasks'),
tasks_per_phase: Array.isArray(tpp) ? tpp : null,
phase_count: num('phase_count'),
parallel_groups_identified: num('parallel_groups_identified') ?? 0,
requirement_coverage_percent: num('requirement_coverage_percent'),
verification_items_added: num('verification_items_added'),
};
}
// ── Fallback: regex scraping ──
// Detect Parallel Execution Groups table
const parallelGroups = (overview.match(/Parallel\s+Execution\s+Group/gi) ?? []).length;
// Count phase files (scanned first so we can use sum as a total_tasks fallback)
let phaseCount = 0;
let tasksPerPhase: number[] = [];
try {
const files = fs.readdirSync(specDir);
const phaseFiles = files
.filter(f => /^phase-\d+\.md$/i.test(f))
.sort();
phaseCount = phaseFiles.length;
for (const pf of phaseFiles) {
const content = readFileSafe(path.join(specDir, pf)) ?? '';
const count = (content.match(/^\s*-\s+\[[ x!/?]\]\s+\*\*Task\s+\d/gm) ?? []).length;
tasksPerPhase.push(count);
}
} catch {
// leave empty
}
// total_tasks priority:
// 1. Completion Summary canonical count
// 2. Sum of phase file task counts
// 3. Stripped overview checkboxes (excluding Success Criteria)
const summaryCount = parseCompletionSummaryTaskCount(overview);
const phaseSum = tasksPerPhase.length > 0 ? tasksPerPhase.reduce((a, b) => a + b, 0) : 0;
const strippedOverview = stripSuccessCriteriaSection(overview);
const strippedCheckboxCount = (strippedOverview.match(/^\s*-\s+\[[ x!/?]\]/gm) ?? []).length;
let totalTasks: number;
if (summaryCount) {
totalTasks = summaryCount.total;
} else if (phaseSum > 0) {
totalTasks = phaseSum;
} else {
totalTasks = strippedCheckboxCount;
}
// Requirement coverage: look for coverage percentage in overview
let reqCoverage: number | null = null;
const covMatch = overview.match(/[Cc]overage[:\s]+(\d{1,3})%/);
if (covMatch) reqCoverage = parseInt(covMatch[1], 10);
// Verification items added (look for verification checklist items)
const verifItems = (overview.match(/(?:verify|verification|test|check):\s*\[[ x]\]/gi) ?? []).length;
return {
present: true,
total_tasks: totalTasks || null,
tasks_per_phase: tasksPerPhase.length > 0 ? tasksPerPhase : null,
phase_count: phaseCount || null,
parallel_groups_identified: parallelGroups || 0,
requirement_coverage_percent: reqCoverage,
verification_items_added: verifItems || null,
};
}
// ── Step 3: Implement ──────────────────────────────────────────────────────────
export function collectStep3(specDir: string): Step3ImplementMetrics {
// Discover phase-*.md files
let phaseFiles: string[] = [];
try {
const files = fs.readdirSync(specDir);
phaseFiles = files
.filter(f => /^phase-\d+\.md$/i.test(f))
.sort();
} catch {
// leave empty
}
// Read overview.md for Completion Summary
const overviewPath = path.join(specDir, 'overview.md');
const overview = readFileSafe(overviewPath);
const summaryCount = overview ? parseCompletionSummaryTaskCount(overview) : null;
// ── Primary source: METRICS_JSON in overview.md (from finalize step) ──
if (overview) {
const step3Json = extractMetricsJson(overview, 'finalize');
if (step3Json) {
const num = (key: string): number | null => {
const v = step3Json[key];
return typeof v === 'number' ? v : null;
};
const total = num('tasks_total');
const completed = num('tasks_completed');
return {
present: true,
task_completion_rate: total && total > 0 && completed != null ? completed / total : null,
tasks_completed: completed,
tasks_total: total,
blocker_count: num('blocker_count') ?? 0,
};
}
}
// ── Fallback: regex scraping ──
// present = true if phase files exist OR overview has completion data
const present = phaseFiles.length > 0 || summaryCount != null;
if (!present) {
return { present: false, task_completion_rate: null, tasks_completed: null,
tasks_total: null, blocker_count: null };
}
// Count checkboxes in phase files
let phaseTotal = 0;
let phaseCompleted = 0;
let blockerCount = 0;
for (const pf of phaseFiles) {
const content = readFileSafe(path.join(specDir, pf)) ?? '';
phaseTotal += (content.match(/^\s*-\s+\[[ x!/?]\]\s+\*\*Task\s+\d/gm) ?? []).length;
phaseCompleted += (content.match(/^\s*-\s+\[x\]\s+\*\*Task\s+\d/gm) ?? []).length;
blockerCount += (content.match(/^\s*-\s+\[!\]\s+\*\*Task\s+\d/gm) ?? []).length;
}
// Count checkboxes in overview (stripped of Success Criteria)
let overviewTotal = 0;
let overviewCompleted = 0;
if (overview) {
const stripped = stripSuccessCriteriaSection(overview);
overviewTotal = (stripped.match(/^\s*-\s+\[[ x!/?]\]/gm) ?? []).length;
overviewCompleted = (stripped.match(/^\s*-\s+\[x\]/gm) ?? []).length;
}
// Task counts priority:
// 1. Completion Summary in overview.md
// 2. Checkbox counting in phase files
// 3. Checkbox counting in overview.md (stripped of Success Criteria)
let tasksTotal: number | null = null;
let tasksCompleted: number | null = null;
if (summaryCount) {
tasksTotal = summaryCount.total;
tasksCompleted = summaryCount.completed;
} else if (phaseTotal > 0) {
tasksTotal = phaseTotal;
tasksCompleted = phaseCompleted;
} else if (overviewTotal > 0) {
tasksTotal = overviewTotal;
tasksCompleted = overviewCompleted;
}
const taskCompletionRate = tasksTotal && tasksTotal > 0 && tasksCompleted != null
? tasksCompleted / tasksTotal
: null;
return {
present: true,
task_completion_rate: taskCompletionRate,
tasks_completed: tasksCompleted,
tasks_total: tasksTotal,
blocker_count: blockerCount,
};
}
// ── Step 4: Finalize ──────────────────────────────────────────────────────────
export function collectStep4(specDir: string): Step4FinalizeMetrics {
// Check if spec was archived (specs--completed exists at parent level)
const specDirName = path.basename(specDir);
const parentDir = path.dirname(specDir);
const completedPath = path.join(parentDir, '..', 'specs--completed', specDirName);
const archivalSucceeded = fs.existsSync(completedPath);
// Read overview for completion metrics
const overviewPath = path.join(specDir, 'overview.md');
// If archived, try from archived location
const effectiveOverviewPath = archivalSucceeded
? path.join(completedPath, 'overview.md')
: overviewPath;
const overview = readFileSafe(effectiveOverviewPath) ?? readFileSafe(overviewPath);
if (!overview) {
return { present: false, completion_rate_at_audit: null,
verification_failures_found: null, documentation_updates_needed: null,
archival_succeeded: archivalSucceeded };
}
// ── Primary source: METRICS_JSON in overview.md ──
const step4Json = extractMetricsJson(overview, 'finalize');
if (step4Json) {
const num = (key: string): number | null => {
const v = step4Json[key];
return typeof v === 'number' ? v : null;
};
return {
present: true,
completion_rate_at_audit: num('completion_rate_at_audit'),
verification_failures_found: num('verification_failures_found') ?? 0,
documentation_updates_needed: num('documentation_updates_needed'),
archival_succeeded: archivalSucceeded,
};
}
// ── Fallback: regex scraping ──
// Completion rate: prefer Completion Summary, fall back to stripped overview checkboxes
let completionRate: number | null = null;
const summaryCount = parseCompletionSummaryTaskCount(overview);
if (summaryCount) {
completionRate = summaryCount.total > 0 ? summaryCount.completed / summaryCount.total : null;
} else {
const stripped = stripSuccessCriteriaSection(overview);
const totalTasks = (stripped.match(/^\s*-\s+\[[ x!/?]\]/gm) ?? []).length;
const completedTasks = (stripped.match(/^\s*-\s+\[x\]/gm) ?? []).length;
completionRate = totalTasks > 0 ? completedTasks / totalTasks : null;
}
// Verification failures: look for [!] tasks or "verification failed" text
const blockedTasks = (overview.match(/^\s*-\s+\[!\]/gm) ?? []).length;
// Documentation updates needed (look for TODO or "update" markers)
const docUpdates = (overview.match(/(?:TODO|FIXME|update\s+(?:README|CHANGELOG|docs))/gi) ?? []).length;
return {
present: true,
completion_rate_at_audit: completionRate,
verification_failures_found: blockedTasks || 0,
documentation_updates_needed: docUpdates || null,
archival_succeeded: archivalSucceeded,
};
}
// ── User Feedback ─────────────────────────────────────────────────────────
export function collectUserFeedback(specDir: string): UserFeedback | null {
// Try both active and archived locations for overview.md
const overviewPath = path.join(specDir, 'overview.md');
const specDirName = path.basename(specDir);
const parentDir = path.dirname(specDir);
const completedPath = path.join(parentDir, '..', 'specs--completed', specDirName, 'overview.md');
const overview = readFileSafe(overviewPath) ?? readFileSafe(completedPath);
if (!overview) return null;
// Look for ## User Feedback section with a markdown table
const feedbackMatch = overview.match(
/## User Feedback\s*\n\s*\|[^\n]*\|\s*\n\s*\|[-| ]+\|\s*\n([\s\S]*?)(?=\n##\s|\n*$)/
);
if (!feedbackMatch) return null;
const tableBody = feedbackMatch[1];
// Parse table rows: | Field | Value |
// Use regex to split only on unescaped pipes, preserving whitespace in values
const rows = tableBody.split('\n').filter(l => l.trim().startsWith('|'));
const fields: Record<string, string> = {};
for (const row of rows) {
// Split on unescaped pipes (not preceded by backslash)
const cells = row.split(/(?<!\\)\|/).map(c => c.trim()).filter(c => c.length > 0);
if (cells.length >= 2) {
const value = cells.slice(1).join('|').replace(/\\\|/g, '|');
fields[cells[0].toLowerCase()] = value;
}
}
const rating = parseInt(fields['rating'] ?? '', 10);
if (isNaN(rating) || rating < 1 || rating > 10) return null;
return {
overall_rating: rating,
rating_reason: fields['reason'] ?? '',
what_went_well: fields['went well'] ?? '',
what_went_poorly: fields['went poorly'] ?? '',
};
}
// ── Main collector ────────────────────────────────────────────────────────────
export interface CollectorOptions {
specDir: string; // Path to the spec directory (specs/<feature-name>)
projectName: string; // Human-readable project name
plan2codeRoot: string; // Path to the plan2code repo (for prompt hashing)
plan2codeVersion: string; // e.g. "1.7.0"
outputDir: string; // Where to write <run-id>.json
}
export async function collectRun(opts: CollectorOptions): Promise<RunMetrics> {
const {
specDir,
projectName,
plan2codeRoot,
plan2codeVersion,
outputDir,
} = opts;
const runId = generateRunId();
// Get started_at / completed_at from spec directory mtime / iteration.log
let startedAt: string | null = null;
let completedAt: string | null = null;
try {
const stat = fs.statSync(specDir);
startedAt = stat.birthtime.toISOString();
completedAt = stat.mtime.toISOString();
} catch {
// leave null
}
const metrics: RunMetrics = {
schema_version: '1.0',
run_id: runId,
plan2code_version: plan2codeVersion,
prompt_versions: collectPromptVersions(plan2codeRoot),
project: {
name: projectName,
started_at: startedAt,
completed_at: completedAt,
},
step1_plan: collectStep1(specDir),
step2_document: collectStep2(specDir),
step3_implement: collectStep3(specDir),
step4_finalize: collectStep4(specDir),
user_feedback: collectUserFeedback(specDir),
};
// Write to output dir
fs.mkdirSync(outputDir, { recursive: true });
const outPath = path.join(outputDir, `${runId}.json`);
fs.writeFileSync(outPath, JSON.stringify(metrics, null, 2), 'utf8');
return metrics;
}
-139
View File
@@ -1,139 +0,0 @@
import { describe, it, expect } from 'vitest';
import { validateEdit, parseProposalFromResponse } from './improver.js';
import type { PromptEdit } from './types.js';
// ── Shared fixtures ───────────────────────────────────────────────────────────
const PROMPT_CONTENTS: Record<string, string> = {
'plan2code-1-plan.md': 'This is the plan prompt content. It has some text here.',
'plan2code-2-document.md': 'Document prompt with repeated text. repeated text. Done.',
'plan2code-3-implement.md': 'Implement prompt content.',
};
function makeEdit(overrides: Partial<PromptEdit> = {}): PromptEdit {
return {
file: 'plan2code-1-plan.md',
rationale: 'test rationale',
expected_metric_impact: 'test impact',
char_count_before: PROMPT_CONTENTS['plan2code-1-plan.md'].length,
char_count_after: PROMPT_CONTENTS['plan2code-1-plan.md'].length,
char_count_delta: 0,
old_text: 'some text',
new_text: 'better text',
...overrides,
};
}
// ── validateEdit() ────────────────────────────────────────────────────────────
describe('validateEdit', () => {
it('valid edit passes with no errors', () => {
const result = validateEdit(makeEdit(), PROMPT_CONTENTS);
expect(result.valid).toBe(true);
expect(result.errors).toHaveLength(0);
});
it('rejects path traversal (../ in file path)', () => {
const result = validateEdit(makeEdit({ file: '../etc/passwd' }), PROMPT_CONTENTS);
expect(result.valid).toBe(false);
expect(result.errors[0]).toMatch(/path traversal/i);
});
it('rejects absolute paths', () => {
const result = validateEdit(makeEdit({ file: '/etc/passwd' }), PROMPT_CONTENTS);
expect(result.valid).toBe(false);
expect(result.errors[0]).toMatch(/path traversal|absolute/i);
});
it('errors when file not found in promptContents', () => {
const result = validateEdit(makeEdit({ file: 'nonexistent.md' }), PROMPT_CONTENTS);
expect(result.valid).toBe(false);
expect(result.errors[0]).toMatch(/not found/i);
});
it('errors when old_text not found in file content', () => {
const result = validateEdit(makeEdit({ old_text: 'hallucinated text' }), PROMPT_CONTENTS);
expect(result.valid).toBe(false);
expect(result.errors[0]).toMatch(/not found verbatim/i);
});
it('warns when old_text appears multiple times', () => {
const edit = makeEdit({
file: 'plan2code-2-document.md',
old_text: 'repeated text',
char_count_before: PROMPT_CONTENTS['plan2code-2-document.md'].length,
char_count_after: PROMPT_CONTENTS['plan2code-2-document.md'].length,
});
const result = validateEdit(edit, PROMPT_CONTENTS);
expect(result.valid).toBe(true);
expect(result.warnings.some(w => /appears.*times/i.test(w))).toBe(true);
});
it('errors when edit would exceed 11,000 char limit', () => {
const bigText = 'x'.repeat(12_000);
const edit = makeEdit({ new_text: bigText });
const result = validateEdit(edit, PROMPT_CONTENTS);
expect(result.valid).toBe(false);
expect(result.errors.some(e => /exceed.*11.?000/i.test(e))).toBe(true);
});
it('warns when reported char counts diverge from actual (>10 chars off)', () => {
const edit = makeEdit({
char_count_before: 999,
char_count_after: 999,
});
const result = validateEdit(edit, PROMPT_CONTENTS);
expect(result.valid).toBe(true);
expect(result.warnings.some(w => /char_count_before.*differs/i.test(w))).toBe(true);
});
});
// ── parseProposalFromResponse() ───────────────────────────────────────────────
describe('parseProposalFromResponse', () => {
const sampleEdit = {
file: 'test.md',
rationale: 'r',
expected_metric_impact: 'e',
char_count_before: 100,
char_count_after: 110,
char_count_delta: 10,
old_text: 'old',
new_text: 'new',
};
it('parses JSON from markdown code block (```json ... ```)', () => {
const response = `Here is my proposal:\n\n\`\`\`json\n${JSON.stringify([sampleEdit])}\n\`\`\`\n\nDone.`;
const result = parseProposalFromResponse(response);
expect(result).toHaveLength(1);
expect(result![0].file).toBe('test.md');
});
it('parses JSON from bare code block (``` ... ```)', () => {
const response = `Proposal:\n\n\`\`\`\n${JSON.stringify([sampleEdit])}\n\`\`\``;
const result = parseProposalFromResponse(response);
expect(result).toHaveLength(1);
expect(result![0].old_text).toBe('old');
});
it('parses bare JSON array with old_text field', () => {
const response = `Some preamble\n${JSON.stringify([sampleEdit])}\nSome postamble`;
const result = parseProposalFromResponse(response);
expect(result).toHaveLength(1);
});
it('returns null for non-JSON response', () => {
const result = parseProposalFromResponse('No changes needed at this time.');
expect(result).toBeNull();
});
it('returns null for malformed JSON', () => {
const result = parseProposalFromResponse('```json\n{broken json]\n```');
expect(result).toBeNull();
});
it('returns null for empty response', () => {
const result = parseProposalFromResponse('');
expect(result).toBeNull();
});
});
-288
View File
@@ -1,288 +0,0 @@
/**
* improver.ts
* Reads diagnosis + prompt files, invokes AI, parses PromptEdit[] from response.
* Validates: old_text verbatim match, char count limits.
*/
import fs from 'fs';
import path from 'path';
import type { PromptEdit, PromptProposal } from './types.js';
import { invokeLLM, type AgentType } from './invoke-llm.js';
const CHAR_LIMIT = 11_000;
const IMPROVE_PROMPT_PATH = new URL('../src/prompts/improve.md', import.meta.url).pathname
.replace(/^\/([A-Za-z]:)/, '$1'); // Fix Windows path
// ── Helpers ───────────────────────────────────────────────────────────────────
function interpolate(template: string, vars: Record<string, string>): string {
let result = template;
for (const [key, value] of Object.entries(vars)) {
result = result.replaceAll(`{{${key}}}`, value);
}
return result;
}
function generateProposalId(): string {
const now = new Date();
const ts = now.toISOString().replace(/[-:T.Z]/g, '').slice(0, 14);
return `prop-${ts}`;
}
function readPromptFiles(plan2codeRoot: string): Record<string, string> {
const srcDir = path.join(plan2codeRoot, 'src');
const promptFiles = [
'plan2code-1-plan.md',
'plan2code-1b-revise-plan.md',
'plan2code-2-document.md',
'plan2code-3-implement.md',
'plan2code-4-finalize.md',
'plan2code-init.md',
'plan2code-init-update.md',
'plan2code-quick-task.md',
];
const contents: Record<string, string> = {};
for (const file of promptFiles) {
try {
contents[file] = fs.readFileSync(path.join(srcDir, file), 'utf8');
} catch {
contents[file] = '';
}
}
return contents;
}
// ── Edit validation ───────────────────────────────────────────────────────────
export interface ValidationResult {
valid: boolean;
errors: string[];
warnings: string[];
}
export function validateEdit(
edit: PromptEdit,
promptContents: Record<string, string>,
): ValidationResult {
const errors: string[] = [];
const warnings: string[] = [];
// Reject path traversal attempts
if (edit.file.includes('..') || path.isAbsolute(edit.file)) {
errors.push(`Rejected: "${edit.file}" contains path traversal or absolute path.`);
return { valid: false, errors, warnings };
}
// Check target file exists
const fileContent = promptContents[edit.file];
if (fileContent === undefined) {
errors.push(`Target file "${edit.file}" not found. Valid files: ${Object.keys(promptContents).join(', ')}`);
return { valid: false, errors, warnings };
}
// Check old_text exists verbatim in the file
if (!fileContent.includes(edit.old_text)) {
errors.push(`old_text not found verbatim in "${edit.file}". The AI may have hallucinated text.`);
} else {
// Warn if old_text appears more than once (ambiguous match)
const occurrences = fileContent.split(edit.old_text).length - 1;
if (occurrences > 1) {
warnings.push(`old_text appears ${occurrences} times in "${edit.file}". Only the first occurrence will be replaced.`);
}
}
// Check char count after edit
const afterContent = fileContent.replace(edit.old_text, edit.new_text);
if (afterContent.length > CHAR_LIMIT) {
errors.push(`Edit would cause "${edit.file}" to exceed ${CHAR_LIMIT} char limit (would be ${afterContent.length} chars).`);
}
// Verify reported char counts match reality
const actualBefore = fileContent.length;
const actualAfter = afterContent.length;
if (Math.abs(edit.char_count_before - actualBefore) > 10) {
warnings.push(`Reported char_count_before (${edit.char_count_before}) differs from actual (${actualBefore}).`);
}
if (Math.abs(edit.char_count_after - actualAfter) > 10) {
warnings.push(`Reported char_count_after (${edit.char_count_after}) differs from actual (${actualAfter}).`);
}
return { valid: errors.length === 0, errors, warnings };
}
// ── AI response parsing ───────────────────────────────────────────────────────
export function parseProposalFromResponse(response: string): PromptEdit[] | null {
// Look for JSON code block containing PromptEdit[]
const jsonBlockMatch = response.match(/```(?:json)?\s*(\[[\s\S]*?\])\s*```/);
if (!jsonBlockMatch) {
// Try bare JSON array
const bareMatch = response.match(/(\[[\s\S]*"old_text"[\s\S]*\])/);
if (!bareMatch) return null;
try {
return JSON.parse(bareMatch[1]) as PromptEdit[];
} catch {
return null;
}
}
try {
return JSON.parse(jsonBlockMatch[1]) as PromptEdit[];
} catch {
return null;
}
}
// ── Main improver ─────────────────────────────────────────────────────────────
export interface ImproverOptions {
diagnosisPath: string; // Path to diagnosis markdown file
plan2codeRoot: string; // Path to plan2code repo root
proposalsDir: string; // Where to save proposal JSON
runsDir: string; // For tracking which runs this is based on
model?: string;
agent?: AgentType; // Agent to use (default: claude-code)
}
export interface ImproverResult {
proposalPath: string;
proposal: PromptProposal;
validationResults: Array<{ edit: PromptEdit; result: ValidationResult }>;
validEditCount: number;
invalidEditCount: number;
}
export async function generateImprovement(opts: ImproverOptions): Promise<ImproverResult> {
const { diagnosisPath, plan2codeRoot, proposalsDir, runsDir, model = 'default', agent = 'claude-code' } = opts;
// Load diagnosis
let diagnosisContent: string;
try {
diagnosisContent = fs.readFileSync(diagnosisPath, 'utf8');
} catch {
throw new Error(`Could not read diagnosis file at ${diagnosisPath}`);
}
// Read prompt files
const promptContents = readPromptFiles(plan2codeRoot);
const srcDir = path.join(plan2codeRoot, 'src');
// Build char counts for each file
const charCounts = Object.entries(promptContents)
.map(([file, content]) => `| ${file} | ${content.length} | ${CHAR_LIMIT} | ${CHAR_LIMIT - content.length} headroom |`)
.join('\n');
const promptContentsStr = Object.entries(promptContents)
.map(([file, content]) => `## ${file} (${content.length} chars)\n\n${content}`)
.join('\n\n---\n\n');
// Load improve prompt template
let improveTemplate: string;
try {
improveTemplate = fs.readFileSync(IMPROVE_PROMPT_PATH, 'utf8');
} catch {
const altPath = path.join(process.cwd(), 'src', 'prompts', 'improve.md');
improveTemplate = fs.readFileSync(altPath, 'utf8');
}
const fullPrompt = interpolate(improveTemplate, {
diagnosisContent,
promptContents: promptContentsStr,
charCounts: `| File | Current Chars | Limit | Headroom |\n|------|--------------|-------|----------|\n${charCounts}`,
});
// Invoke Claude
console.log(`\nInvoking AI improvement proposal (agent: ${agent}, model: ${model === 'default' ? 'user default' : model})...`);
console.log('This may take a minute...\n');
let aiResponse: string;
try {
aiResponse = await invokeLLM({
prompt: fullPrompt,
model,
agent,
timeout: 300_000,
});
} catch (err) {
throw new Error(`AI invocation failed: ${err instanceof Error ? err.message : String(err)}`);
}
// Parse edits
const rawEdits = parseProposalFromResponse(aiResponse);
if (!rawEdits || rawEdits.length === 0) {
throw new Error('Could not parse PromptEdit[] from AI response. The AI may not have produced a valid JSON block.');
}
// Enforce max edits per cycle
const MAX_EDITS = 5;
if (rawEdits.length > MAX_EDITS) {
console.warn(`\n⚠ AI generated ${rawEdits.length} edits (max is ${MAX_EDITS}). Truncating to first ${MAX_EDITS}.`);
rawEdits.length = MAX_EDITS;
}
// Validate each edit
const validationResults: ImproverResult['validationResults'] = [];
const validEdits: PromptEdit[] = [];
for (const edit of rawEdits) {
const result = validateEdit(edit, promptContents);
validationResults.push({ edit, result });
if (result.valid) {
// Compute accurate char counts
const fileContent = promptContents[edit.file] ?? '';
const afterContent = fileContent.replace(edit.old_text, edit.new_text);
edit.char_count_before = fileContent.length;
edit.char_count_after = afterContent.length;
edit.char_count_delta = afterContent.length - fileContent.length;
validEdits.push(edit);
} else {
console.warn(`\n⚠ Edit rejected for "${edit.file}":`);
for (const err of result.errors) {
console.warn(` - ${err}`);
}
}
for (const warn of result.warnings) {
console.warn(` Warning: ${warn}`);
}
}
// Get run IDs that contributed to this analysis
const runIds: string[] = [];
try {
const files = fs.readdirSync(runsDir)
.filter(f => f.startsWith('run-') && f.endsWith('.json'));
runIds.push(...files.map(f => f.replace('.json', '')));
} catch { /* no runs dir */ }
// Build proposal
const proposalId = generateProposalId();
const proposal: PromptProposal = {
proposal_id: proposalId,
created_at: new Date().toISOString(),
based_on_runs: runIds,
analyst_model: model,
proposals: validEdits,
status: 'pending',
diagnosis_file: path.basename(diagnosisPath),
};
// Save proposal JSON
fs.mkdirSync(proposalsDir, { recursive: true });
const proposalPath = path.join(proposalsDir, `${proposalId}.json`);
fs.writeFileSync(proposalPath, JSON.stringify(proposal, null, 2), 'utf8');
// Also save raw AI response alongside
const rawPath = path.join(proposalsDir, `${proposalId}-raw.md`);
fs.writeFileSync(rawPath, aiResponse, 'utf8');
return {
proposalPath,
proposal,
validationResults,
validEditCount: validEdits.length,
invalidEditCount: rawEdits.length - validEdits.length,
};
}
-19
View File
@@ -1,19 +0,0 @@
// Public API for plan2code-metrics
export { collectRun, collectPromptVersions } from './collector.js';
export { aggregate, loadAggregated, loadRunFiles, importRun } from './aggregator.js';
export { runAnalysis } from './analyzer.js';
export { generateImprovement, validateEdit, parseProposalFromResponse } from './improver.js';
export { reviewAndApply } from './applier.js';
export { invokeLLM, AGENTS } from './invoke-llm.js';
export type { AgentType, InvokeLLMOptions } from './invoke-llm.js';
export { runCLI } from './cli.js';
export { METRIC_TARGETS } from './types.js';
export type {
RunMetrics,
UserFeedback,
PromptVersions,
PromptEdit,
PromptProposal,
AggregatedMetrics,
CohortMetrics,
} from './types.js';
-90
View File
@@ -1,90 +0,0 @@
/**
* invoke-llm.ts
* Unified LLM invocation for plan2code-metrics.
* Supports Claude Code (temp file → stdin) and Copilot CLI (stdin string).
* Mirrors the agent pattern from plan2code-loop.
*/
import { execa } from 'execa';
import { writeFileSync, unlinkSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
// ── Agent definitions ────────────────────────────────────────────────────────
export type AgentType = 'claude-code' | 'copilot-cli';
export interface AgentDef {
name: AgentType;
displayName: string;
command: string;
defaultModel: string;
}
export const AGENTS: Record<AgentType, AgentDef> = {
'claude-code': {
name: 'claude-code',
displayName: 'Claude Code',
command: 'claude',
defaultModel: 'default',
},
'copilot-cli': {
name: 'copilot-cli',
displayName: 'GitHub Copilot CLI',
command: 'copilot',
defaultModel: 'claude-sonnet-4',
},
};
// ── Invocation ───────────────────────────────────────────────────────────────
export interface InvokeLLMOptions {
prompt: string;
model: string;
agent: AgentType;
timeout?: number;
}
export async function invokeLLM(opts: InvokeLLMOptions): Promise<string> {
const { prompt, model, agent, timeout = 300_000 } = opts;
const def = AGENTS[agent];
if (agent === 'claude-code') {
// Write prompt to temp file — more reliable than stdin on Windows
const tempFile = join(tmpdir(), `plan2code-metrics-prompt-${Date.now()}.txt`);
writeFileSync(tempFile, prompt, 'utf-8');
try {
const args: string[] = [
'--print',
'--dangerously-skip-permissions',
];
// Only add --model if not using default
if (model && model !== 'default') {
args.push('--model', model);
}
const result = await execa(def.command, args, {
inputFile: tempFile,
timeout,
});
return result.stdout;
} finally {
try { unlinkSync(tempFile); } catch { /* ignore cleanup errors */ }
}
} else {
// Copilot CLI: pipe prompt via stdin string
const args: string[] = [];
// Only add --model if not using default
if (model && model !== 'default') {
args.push('--model', model);
}
args.push('--allow-all-tools', '-s');
const result = await execa(def.command, args, {
input: prompt,
timeout,
});
return result.stdout;
}
}
-100
View File
@@ -1,100 +0,0 @@
# PLAN2CODE METRICS ANALYSIS REQUEST
You are a senior AI systems analyst specializing in prompt engineering quality assessment. Your role is to diagnose weaknesses in the plan2code workflow prompts by examining aggregated run metrics.
**IMPORTANT:** Do NOT propose specific edits in this response. Diagnosis only. The improvement step is separate.
---
## Aggregated Run Metrics
The following JSON contains metrics aggregated from real plan2code project runs, grouped by prompt "generation" (a cohort is identified by the SHA fingerprint of the src/plan2code-*.md prompt files at collection time):
```json
{{aggregatedMetrics}}
```
---
## Current Prompt File Contents
The following are the current contents of the plan2code workflow prompt files being evaluated:
{{promptContents}}
---
## Metric Targets Reference
| Metric | Target | Direction |
|--------|--------|-----------|
| avg_confidence (Step 1) | ≥ 90 | higher is better |
| avg_clarification_rounds (Step 1) | ≤ 2.0 | lower is better |
| avg_verification_gaps_found (Step 1) | ≤ 2.0 | lower is better |
| avg_parallel_groups (Step 2) | ≥ 0.5 | higher is better |
| avg_verification_items_added (Step 2) | ≤ 1.5 | lower is better |
| avg_task_completion_rate (Step 3) | ≥ 0.95 | higher is better |
| avg_blocker_count (Step 3) | ≤ 1.5 | lower is better |
| avg_verification_failures_found (Step 4) | ≤ 1.0 | lower is better |
| archival_success_rate (Step 4) | ≥ 0.99 | higher is better |
| avg_user_rating (Feedback) | ≥ 7.0 | higher is better (1-10 scale, null if no feedback) |
---
## Analysis Instructions
1. Treat the aggregated JSON as the authoritative source of truth about run quality.
2. Compare each metric against its target. Calculate delta (actual − target).
3. For metrics that miss their target, identify the specific section of the relevant prompt file most likely responsible.
4. Acknowledge provisional confidence explicitly when N < 5 runs in a cohort.
5. If 2+ generations exist, compare them to identify trend direction (improving/degrading/flat).
6. Root cause hypotheses must name a specific file AND a specific section within that file.
7. Do not invent metrics not present in the JSON. If a metric is null, note it as "insufficient data."
---
## Required Output Format
Produce EXACTLY the following sections in order. Use these exact headers — they are parsed by machine:
# PLAN2CODE METRICS DIAGNOSIS
### Metrics Summary
A markdown table with columns: Step | Metric | Target | Actual | Delta | Status (✓/✗/—)
Include ALL metrics listed in the targets table. Use "—" for null values.
### Step Health Assessment
For each step (1–4), provide:
- **Grade:** A–F
- **Key signals:** 2–4 bullet points with specific metric values
- **Assessment:** 1–2 sentence diagnosis
### Root Cause Hypotheses
Numbered list. For each underperforming metric:
1. **Metric:** [metric name] | **Value:** [actual] | **Target:** [target]
- **File:** [plan2code-X-name.md]
- **Section:** [specific heading or section name]
- **Hypothesis:** [specific gap in the prompt that would explain the metric miss]
- **Confidence:** [High/Medium/Low] — [reason for confidence level]
### Recommended Improvement Targets
Ordered list (highest estimated impact first). For each:
- **File:** [filename]
- **Section:** [section name]
- **Why:** [link to specific metric being addressed]
- **Priority:** [High/Medium/Low]
### Generation Comparison
If 2+ generations exist: A comparison table showing before/after for each metric per generation, with trend arrows (▲/▼/→).
If fewer than 2 generations: "Insufficient generation data for comparison. Current generation: [cohort_key], [N] runs."
---
End of analysis request.
-92
View File
@@ -1,92 +0,0 @@
# PLAN2CODE PROMPT IMPROVEMENT REQUEST
You are a senior AI prompt engineer. Your role is to propose surgical, targeted edits to the plan2code workflow prompt files based on a metrics diagnosis. You make precise, minimal changes — NOT rewrites.
---
## Metrics Diagnosis
The following diagnosis was produced by the analysis step:
{{diagnosisContent}}
---
## Current Prompt File Contents (with char counts)
{{promptContents}}
---
## Character Count Status
{{charCounts}}
---
## Hard Constraints — ALL must be satisfied:
1. **Char limit:** Each target file MUST stay under 11,000 characters after your edit is applied. This is enforced by code — edits that violate it will be automatically rejected.
2. **Maximum 5 edits per cycle.** Focus on the highest-impact changes only.
3. **Each edit must cite a specific metric** in its `expected_metric_impact` field (e.g., "avg_task_completion_rate", "avg_blocker_count").
4. **`old_text` must be verbatim** from the file. Copy-paste exactly — include surrounding whitespace/newlines as they appear. Edits with mismatched old_text will be automatically rejected.
5. **Do NOT modify Role sections** (lines starting with "You are" at the top of each file) or step headings (lines starting with `#`).
6. **Each edit must be independently applicable** — no edit should depend on another edit being applied first.
7. **Prefer additive guidance over deletions.** Adding clarifying instructions or examples is safer than removing existing text.
8. **Do not change the overall structure** or flow of any prompt file.
---
## Edit Strategy Guidelines
- Target the specific sections identified in "Recommended Improvement Targets" from the diagnosis.
- For high `avg_clarification_rounds`: Add more upfront specification examples or decision criteria to Step 1.
- For high `avg_blocker_count`: Add blocker-recovery guidance or prerequisite check instructions.
- For low `avg_confidence`: Strengthen the confidence calculation instructions with clearer rubrics.
- For low `avg_parallel_groups`: Add explicit guidance for identifying parallel tasks in Step 2.
- For low `avg_user_rating`: Review user feedback themes (what_went_well, what_went_poorly) for systemic issues.
- Keep each `new_text` as short as possible while still addressing the root cause.
---
## Required Output Format
Produce EXACTLY the following sections. The JSON block is parsed by machine — it must be syntactically valid.
# PLAN2CODE PROMPT IMPROVEMENT PROPOSAL
### Improvement Rationale
2–3 paragraphs explaining:
1. Which metrics are being addressed and why they matter
2. The specific prompt gaps identified in the diagnosis that you are targeting
3. Why the proposed edits are expected to improve those metrics
### Proposed Edits
```json
[
{
"file": "plan2code-X-name.md",
"rationale": "One sentence explaining what this edit fixes",
"expected_metric_impact": "avg_metric_name: expected direction and magnitude",
"char_count_before": 0,
"char_count_after": 0,
"char_count_delta": 0,
"old_text": "exact verbatim text from the file to replace",
"new_text": "replacement text"
}
]
```
Set `char_count_before`, `char_count_after`, and `char_count_delta` to your best estimate (the system will verify and correct these automatically).
### Character Count Verification
A table with columns: File | Before | Projected After | Delta | Limit | Status (✓/✗)
Verify that NO file exceeds 11,000 characters after your proposed edits.
---
End of improvement request.
-163
View File
@@ -1,163 +0,0 @@
// All TypeScript interfaces for plan2code-metrics
export interface PromptVersions {
plan: string; // sha256:... plan2code-1-plan.md
revise_plan: string; // plan2code-1b-revise-plan.md
document: string; // plan2code-2-document.md
implement: string; // plan2code-3-implement.md
finalize: string; // plan2code-4-finalize.md
init: string; // plan2code-init.md
init_update: string; // plan2code-init-update.md
quick_task: string; // plan2code-quick-task.md
}
export interface Step1PlanMetrics {
present: boolean;
final_confidence: number | null;
confidence_breakdown: {
requirements: number | null;
feasibility: number | null;
integration: number | null;
risk: number | null;
} | null;
clarification_rounds: number | null;
tech_stack_revision_rounds: number | null;
verification_gaps_found: number | null;
functional_requirements_count: number | null;
non_functional_requirements_count: number | null;
risk_count: number | null;
phase_count: number | null;
}
export interface Step2DocumentMetrics {
present: boolean;
total_tasks: number | null;
tasks_per_phase: number[] | null;
phase_count: number | null;
parallel_groups_identified: number | null;
requirement_coverage_percent: number | null;
verification_items_added: number | null;
}
export interface Step3ImplementMetrics {
present: boolean;
task_completion_rate: number | null;
tasks_completed: number | null;
tasks_total: number | null;
blocker_count: number | null;
}
export interface Step4FinalizeMetrics {
present: boolean;
completion_rate_at_audit: number | null;
verification_failures_found: number | null;
documentation_updates_needed: number | null;
archival_succeeded: boolean | null;
}
export interface UserFeedback {
overall_rating: number; // 1-10
rating_reason: string;
what_went_well: string;
what_went_poorly: string;
}
export interface RunMetrics {
schema_version: '1.0';
run_id: string;
plan2code_version: string;
prompt_versions: PromptVersions;
project: {
name: string;
started_at: string | null;
completed_at: string | null;
};
step1_plan: Step1PlanMetrics;
step2_document: Step2DocumentMetrics;
step3_implement: Step3ImplementMetrics;
step4_finalize: Step4FinalizeMetrics;
user_feedback: UserFeedback | null;
}
export interface PromptEdit {
file: string;
rationale: string;
expected_metric_impact: string;
char_count_before: number;
char_count_after: number;
char_count_delta: number;
old_text: string;
new_text: string;
}
export interface PromptProposal {
proposal_id: string;
created_at: string;
based_on_runs: string[];
analyst_model: string;
proposals: PromptEdit[];
status: 'pending' | 'applied' | 'rejected';
diagnosis_file: string | null;
}
// Aggregated metrics schema
export interface CohortMetrics {
cohort_key: string; // hash of sorted prompt_versions
prompt_versions: PromptVersions;
run_count: number;
run_ids: string[];
first_seen: string;
last_seen: string;
// Step 1 averages
avg_confidence: number | null;
avg_clarification_rounds: number | null;
avg_verification_gaps_found: number | null;
avg_functional_requirements_count: number | null;
avg_non_functional_requirements_count: number | null;
avg_risk_count: number | null;
avg_phase_count_step1: number | null;
// Step 2 averages
avg_total_tasks: number | null;
avg_phase_count_step2: number | null;
avg_parallel_groups: number | null;
avg_requirement_coverage_percent: number | null;
avg_verification_items_added: number | null;
// Step 3 averages
avg_task_completion_rate: number | null;
avg_blocker_count: number | null;
// Step 4 averages
avg_completion_rate_at_audit: number | null;
avg_verification_failures_found: number | null;
avg_documentation_updates_needed: number | null;
archival_success_rate: number | null;
// User feedback
avg_user_rating: number | null;
feedback_count: number;
}
export interface AggregatedMetrics {
schema_version: '1.0';
last_updated: string;
total_runs: number;
cohorts: CohortMetrics[];
current_cohort_key: string | null;
}
// Metric targets for health assessment
export const METRIC_TARGETS = {
avg_confidence: { target: 90, direction: 'gte' as const },
avg_clarification_rounds: { target: 2.0, direction: 'lte' as const },
avg_verification_gaps_found: { target: 2.0, direction: 'lte' as const },
avg_parallel_groups: { target: 0.5, direction: 'gte' as const },
avg_verification_items_added: { target: 1.5, direction: 'lte' as const },
avg_task_completion_rate: { target: 0.95, direction: 'gte' as const },
avg_blocker_count: { target: 1.5, direction: 'lte' as const },
avg_verification_failures_found: { target: 1.0, direction: 'lte' as const },
archival_success_rate: { target: 0.99, direction: 'gte' as const },
avg_user_rating: { target: 7.0, direction: 'gte' as const },
} as const;
-20
View File
@@ -1,20 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": ".",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
-15
View File
@@ -1,15 +0,0 @@
import { defineConfig } from 'tsup';
export default defineConfig({
entry: {
'bin/plan2code-metrics': 'src/bin/plan2code-metrics.ts',
index: 'src/index.ts',
},
format: ['esm'],
dts: true,
clean: true,
sourcemap: true,
banner: {
js: '#!/usr/bin/env node',
},
});
-7
View File
@@ -1,7 +0,0 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['src/**/*.test.ts'],
},
});
-39
View File
@@ -1,39 +0,0 @@
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const CHAR_LIMIT = 11000;
const srcDir = path.join(__dirname, '..', 'src');
// Note: readdirSync is non-recursive, so files in subdirectories like
// plan2code-review-references/ are automatically excluded from
// the character limit check. Reference files have no char limit.
const files = fs.readdirSync(srcDir)
.filter(f => f.startsWith('plan2code-') && f.endsWith('.md'))
.sort();
const failures = [];
for (const file of files) {
const filePath = path.join(srcDir, file);
const content = fs.readFileSync(filePath, 'utf8');
const charCount = content.length;
if (charCount > CHAR_LIMIT) {
failures.push({ file: path.join('src', file), charCount });
}
}
if (failures.length > 0) {
console.error('Character limit exceeded:');
console.error('');
for (const { file, charCount } of failures) {
console.error(` ${file}: ${charCount} / ${CHAR_LIMIT} (+${charCount - CHAR_LIMIT} over)`);
}
console.error('');
console.error(`${failures.length} file(s) over the ${CHAR_LIMIT} character limit.`);
process.exit(1);
}
console.log(`All ${files.length} files under ${CHAR_LIMIT} characters \u2713`);
process.exit(0);
Loaded 100 of 572 files, more files were not shown because too many files have changed in this diff. Show more