mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
Remove the legacy plan2code-loop CLI
AI Assisted
This commit is contained in:
1 parent
d7abcd2ac6
commit
c8d12a3d99
89 files changed
+449
-3189
No files matched your search
@@ -29,9 +29,6 @@ plan2code/
|
||||
│ │ └── ai-agent-file-sync.md # Step 7: replace AI configs with AGENTS.md refs
|
||||
│ └── plan2code-4-finalize-references/ # Reference files for finalize skill
|
||||
│ └── community-feedback-submission.md # STEP 6.5 payload schema + submission tiers
|
||||
├── plan2code-loop/ # Autonomous loop CLI tool (Node.js/TypeScript)
|
||||
│ ├── src/ # TypeScript source
|
||||
│ └── dist/ # Built output (tsup)
|
||||
├── plan2code-bot/ # Autonomous end-to-end workflow test runner (TypeScript, tsup, Claude Agent SDK, vitest); user docs in .readme/test-bot.md
|
||||
├── plan2code-metrics/ # Recursive self-improvement toolchain
|
||||
│ ├── src/ # TypeScript source
|
||||
@@ -71,7 +68,7 @@ plan2code/
|
||||
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
|
||||
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/, plan2code-model-update/
|
||||
├── .github/ISSUE_TEMPLATE/ # bug.yml, idea.yml, config.yml (target of the console's feedback button)
|
||||
├── .readme/ # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, autonomous-loop.md, metrics.md, status-line.md, test-bot.md)
|
||||
├── .readme/ # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, metrics.md, status-line.md, test-bot.md)
|
||||
├── docs/ # Landing page `index.html` served at plan2code.jparkerweb.com (GitHub Pages, `CNAME`) and assets
|
||||
│ └── screenshots/ # Web console screenshots, <shot>-light.webp and <shot>-dark.webp (generated)
|
||||
├── specs/ # Feature specs (if any in-progress)
|
||||
@@ -284,6 +281,10 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/activities/ghoul-ride-scenes.js` | The dark ride's scene table as data (12 rooms, lengths, speeds, spawn rows in author coordinates), no imports |
|
||||
| `public/activities/ghoul-ride-core.js` | The ride's shared basics: the 96 by 54 field's constants, math helpers, the bound state `G` (a live import), `rnd`/`rand` (seeded) and `vrand` (visual) |
|
||||
| `public/activities/ghoul-ride-draw.js` | The ride's art entry (`rideArt(d, die)`: `field(ctx, v)` draws the whole field by phase, `tick` the cascade's sounds); `ghoul-draw.js` hands over to it when `round.gallery` is set. Parts: `ghoul-ride-gfx.js` (canvas helpers), `ghoul-ride-draw-kinds.js` (animatronics, mini-bosses, the Barker), `ghoul-ride-draw-sets.js` (the 12 sets, far walls, aisle, near layer), `ghoul-ride-draw-hud.js` (car and Planny, HUD, duck strip, reticle, title, end cascade) |
|
||||
| `public/activities/ghoul-ride-gfx.js` | The ride's drawing helpers: the bound 2D context and the short fill, stroke and shape calls the ride's art is written in |
|
||||
| `public/activities/ghoul-ride-draw-kinds.js` | The ride's drawn things: every figure, beast, lantern, blade, door, hand, head, mirror, web and boss, a port of the prototype's draw code (`prototypes/ghoul-rush-ride/gallery.html`) |
|
||||
| `public/activities/ghoul-ride-draw-sets.js` | The ride's rooms drawn: each room's far wall, set pieces front and back, aisle and the near pillars, a port of the prototype's world draw |
|
||||
| `public/activities/ghoul-ride-draw-hud.js` | The ride's car and the screen around it: Planny in his car, blood and sparks, the lens, the hearts, the progress bar, the room plaque, the aim, the title and the cleared card |
|
||||
| `public/activities/ghoul-ride-voices.js` | The ride's `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS` and `react` (every `ride<Name>` event plays tone `ghoulRide<Name>`) |
|
||||
| `public/activities/ghoul-sfx-ride.js` | The ride's synthesized sounds as `tones` (`ghoulRide<Kind>`) and its music `ghoulRideDrone` (`RIDE_SFX`, merged by `ghoul-sfx.js`) |
|
||||
| `public/activities/ghoul-frozen.js` | Ghoul Rush's Frozen Lake stage pack, its rules (imports only `burrow` from the Graveyard; draws no random number): uses `tick` (thin ice, the blizzard, the Widow's spikes, web and barrels), `place`, `unseen`, `solid`, `kill`, `target`, `land`, `weak`, `cause`, `guard`, `swoops` and `slides`. The generic slippery-ice rule (`iceRun`, room field `ice`) and thin-ice rule (`stepThin`, room field `thin`, `round.thin`), the under-ice hand, snow shade (unseen, footprints), Frozen Ghoul (slides, shatters into shards), Ice Wraith (its dive freezes), Hot Cocoa, the Frost Widow (veil, barrels, weak spot, blizzard, spikes, web, rage) and `FROZEN_ROOMS`. Every constant is exported and documented in its header |
|
||||
@@ -307,6 +308,9 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/activities/ghoul-powers.js` | Ghoul Rush's power-ups and pickups (no imports: `ghoul.js` hands its rules a kit, `POWER_KIT`, of `landing`, `MAX_LIVES` and the numbers they need): `POWERS` (each power-up's name, line, color, `ms` if timed, drop `weight`, and its rule, the Lantern's `dark`), `TIMED`, `PILL_WORDS`, `FLAP_CLEAR`, `HOURGLASS_MS`, `CANDY_POINTS`, `POWER_POINTS`, `CRYSTAL_POINTS`, `powerHere(round, kind)` (whether a power-up can turn up in the room as it is now; a new rule, such as a stage-only power-up, goes in `POWERS` and is checked here), `pickPower`, `applyPower(round, kind, kit)` (`ghoul.js` exports it bound to its kit as `applyPower(round, kind)`) and `pickups` (candy, placed and dropped power-ups, crystals up high and the key, taken by touch; drops fall and fade). Split from `ghoul.js` to keep it under the 3,000-line cap |
|
||||
| `public/activities/ghoul-arms.js` | Ghoul Rush's secondary weapons (imports only `ghoul-powers.js`; a pack in `PACKS`, `ARMS`): the double tap (`pressFire`, `releaseFire`, called from the game's `key()` and `release()`, never from `round.input.fire`, so bots never throw), the bag `round.arms` (`useArm`, `armOnTop`: a ride room skips what needs a floor), each weapon's rule (a shot with `arm` through `moveShots`, or a hazard), and `armBossDamage` (scaled to depth, capped at `ARM_BOSS_SHARE` of a boss's hp a fight). Weapons' names, bundles and caps are in `POWERS` (`arm: true`, weight 0), the stage's own in `STAGE_ARMS`, the kill drop band in `armDrop`, all in `ghoul-powers.js`. |
|
||||
| `public/activities/ghoul-arms-draw.js` | The weapons' art (`armsArt(d)`): their badges (`powers`), `hazards`, `shot` for one in flight, `pill` for the HUD's icon and count, `front` (stars over the dazed), `lights` and `react`. Dynamite's stick, blast and badge stay in `ghoul-mine-draw.js`. |
|
||||
| `public/activities/ghoul-rockets.js` | The Bottle Rocket's rules, the common weapon every stage sells: one use lights three rockets, one ahead, one up and one behind |
|
||||
| `public/activities/ghoul-rockets-draw.js` | The Bottle Rocket's drawing (`rocketArt(d)`): the muzzle's flash and smoke, the flared rocket on a stick with a glowing head, the fountain of sparks it sheds and the burst when it goes off |
|
||||
| `public/activities/ghoul-pans.js` | The Cast-Iron Skillet's rules, the East Wing's weapon: three pans that circle Planny, then spiral outward until they are off screen |
|
||||
| `public/activities/ghoul-sfx-arms.js` | The weapons' `tones` (`ARMS_SFX`), merged by `ghoul-sfx.js` like a stage's. A first pass, not yet picked by ear. |
|
||||
| `scripts/test-web-console-activities-ghoul-arms.mjs` | The weapons' suite: the double tap through the keys (repeats, feathering, hammering), the bag and its pill, each weapon, bosses (scale, cap, guards, the half-hp drop), placement in every room, the drop band's single draw, ride rooms, drawing and sounds. |
|
||||
| `public/activities/ghoul-run.js` | Ghoul Rush's run flow (no imports: `ghoul.js` hands its rules `RUN_KIT`, the room and stage tables, the timings and the helpers that set a room up, and binds them): `newRound`, `setupRoom`/`resetRoom`, the stage pick (`stagesLeft`, `nextRoom`, `steerPick`, `pickStage`), the stage select for testing (`openSelect`, `steerSelect`, `takeSelect`: a practice round, `round.practice`, that keeps no best score or record), `camera`, `respawn`, `lockArena`, `clearRoom`, and a room's monster supply (`spawners`, `horde`, `hurry`). `ghoul.js` re-exports `newRound`, `stagesLeft`, `steerPick`, `pickStage`, `steerSelect` and `takeSelect`, and its game answers `stageSelect()`. Split from `ghoul.js` to keep it under the 3,000-line cap, with the same random draws in the same order |
|
||||
@@ -461,7 +465,7 @@ Key design points:
|
||||
| `state.json` → `helpers` | `console.mjs post` | the helpers the agent reports, merged by `id`, checked by `checkHelpers()` plus the prose scan; dropped by `switchWorkflow()` on a dashboard hop |
|
||||
|
||||
`POST /subagents` (origin-checked; `400` `not-offered` / `bad` / `too-long` / `max`) saves the store and bumps the session setting. `consume()`, `cmdChat()`, `deliverChat()` and `open` append `blockFor()`'s lines last in `reply` and the `subagents` field; a change alone never ends a `wait` slice. The page's Subagents tab (before Ask) draws `state.helpers` through `helperRows()`. Helpers never reach the meter ledger. Contract: `console-subagents.md`.
|
||||
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or the loop's marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
|
||||
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or any marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
|
||||
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `routes.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `sessions.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
|
||||
- **Answers carry their terminal token.** Each item ships `fallbackText` and `token`, so a click resolves to the literal word the prompt already expects (`approved`, `a`, `skip`). No workflow needs a second code path, and declining the console degrades to prose with nothing lost.
|
||||
- **A build tells the page how long silence is normal.** The page calls a working agent stuck after two minutes without a post, which is right for a conversation and wrong for a twenty-minute build task. `agent.quietMinutes` (1 to 60, counted only while `working`) stretches the stuck, adrift and Send-grace thresholds; `quietLimitMs()` in `answers.js` is the one rule.
|
||||
@@ -530,7 +534,7 @@ The bracketed flags (each entry's `bypassArgs`; a custom agent's own `bypassArgs
|
||||
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it exits 127 and prints `SKILL_STEPS`: how to install an agent, `cd` into the project, and type `/plan2code` (`$plan2code` in Codex). An uninstalled `--cli` pick prints that CLI's own steps after its error (its install command, `cd` into the project, then `plan2code --cli <id>` or its prompt). `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. `plan2code update` is the one subcommand: it is never forwarded and opens no agent, it runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists. On every other start, before spawning the CLI, it prints one line when a newer release is out (`Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`), compared against `~/.plan2code/bin/version.json` and read from the console's cached release check (`~/.plan2code/console/update-check.json`); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
|
||||
|
||||
**Design constraints:**
|
||||
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. Beside it go `update-check.mjs` (the web console's release check, for the terminal notice) and a `version.json` (the installed version). (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. Beside it go `update-check.mjs` (the web console's release check, for the terminal notice) and a `version.json` (the installed version). (The metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||
- **npm-style shims** — written into npm's global bin (`npm config get prefix`; `<prefix>/bin` off Windows): an sh shim everywhere, plus `.cmd` and `.ps1` on Windows, so cmd.exe, PowerShell and Git Bash all resolve it. On macOS/Linux, when the npm bin isn't writable (system Node), it falls back to `~/.local/bin`.
|
||||
- **Marker-based ownership** — every shim contains `plan2code-launcher`; `uninstallLauncher()` removes only files carrying it, leaving any other `plan2code` bin alone.
|
||||
- **Resolving the CLI** — the launcher walks `PATH` (+ `PATHEXT` on Windows) itself. An `.exe` is spawned directly; a `.cmd`/`.bat` wrapper goes through `cmd.exe /d /s /c` with quoted args, since Node refuses to spawn batch files without a shell. The installer warns only when neither `claude` nor `devin` is on `PATH`.
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
## 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 & plan2code-bot:** TypeScript + ESM, built with tsup (target ES2022, moduleResolution: bundler)
|
||||
- External deps (loop, metrics): `@inquirer/prompts`, `chalk`, `execa`, `fs-extra`, `ora`
|
||||
- **plan2code-metrics & plan2code-bot:** TypeScript + ESM, built with tsup (target ES2022, moduleResolution: bundler)
|
||||
- External deps (metrics): `@inquirer/prompts`, `chalk`, `execa`, `fs-extra`, `ora`
|
||||
- External deps (bot): `@anthropic-ai/claude-agent-sdk`, `chalk`, `fs-extra`, `ora`
|
||||
- Interactive CLI via `@inquirer/prompts` (select, input, confirm)
|
||||
- **File operations:** Synchronous fs by default; the web console's fire-and-forget sweeps and `readOverview()` use `fs.promises`
|
||||
- **src/web-console:** ESM, Node built-ins only, no build step. It is bundled into every skill, so it must stay dependency-free and runnable as a plain `node console.mjs`. Anything added under `src/web-console/` ships to users — put tests in `scripts/` instead.
|
||||
- **US English everywhere:** docs, comments, prompts, UI text, test names and commit messages use US spelling: color, gray, behavior, center, canceled, labeled, judgment, license, defense, and -ize / -yze verbs (normalize, analyze, summarize). `scripts/test-us-english.mjs` (in `npm test`) fails on common UK spellings in tracked files. A few names keep the UK spelling because they are data contracts read in several places, and that test allow-lists them: the `greyed` field on `skills.js` entries, `{ cancelled: true }` from the folder picker and `/workspace/browse`, the `"cancelled"` event `routes.mjs` broadcasts, and the loop's `result.cancelled`. Rename one only together with every reader. `aria-labelledby` is HTML and stays; vendored files (`public/vendor/`) stay as shipped.
|
||||
- **US English everywhere:** docs, comments, prompts, UI text, test names and commit messages use US spelling: color, gray, behavior, center, canceled, labeled, judgment, license, defense, and -ize / -yze verbs (normalize, analyze, summarize). `scripts/test-us-english.mjs` (in `npm test`) fails on common UK spellings in tracked files. A few names keep the UK spelling because they are data contracts read in several places, and that test allow-lists them: the `greyed` field on `skills.js` entries, `{ cancelled: true }` from the folder picker and `/workspace/browse`, the `"cancelled"` event `routes.mjs` broadcasts. Rename one only together with every reader. `aria-labelledby` is HTML and stays; vendored files (`public/vendor/`) stay as shipped.
|
||||
|
||||
## Gotchas / Pitfalls
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
- **CHANGELOG house format is not Keep a Changelog:** version headings are `## vX.Y.Z` — with a `v` prefix and **no date**. The release date is recorded only in `version.json`'s `releaseDate`. Category headings carry emoji: `### ✨ Added`, `### 🔧 Changed`, `### 🐛 Fixed`, `### 💥 Breaking`, `### 🗑️ Removed`, `### 📚 Documentation`. Older entries contain one-off variants (`🎁 Added`, `📦 Updated`, `📝 Documentation`, `🏎️ Improved`, `🧪 Testing`) — do not introduce new ones. The `.claude/skills/plan2code-changelog/` skill automates version selection and formatting; use it rather than hand-rolling an entry.
|
||||
- **PowerShell mangles the CHANGELOG emoji:** `Get-Content` / `Select-String` render the `###` heading emoji as `?` under the default Windows console encoding, so a heading audit done that way reports garbage. Read `CHANGELOG.md` with a file-read or grep tool instead.
|
||||
- **`.claude/skills/` is tracked:** a new repo-local skill only needs `git add` (see Architecture → Repo-Local Skills). A correction that is a workflow belongs there as a skill, linked from AGENTS.md, not as a Failure log line.
|
||||
- **Loop `.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 (and the dashboard prompt `src/plan2code.md`) must be ≤ 20,000 characters (about 5k tokens, the usual Agent Skills guidance for a SKILL.md body). A husky pre-commit hook enforces this, and `plan2code-metrics` (`improver.ts`, `applier.ts`) applies the same number to proposed prompt edits, so change them together. History: 11,000 originally (headroom under Windsurf's old 12,000-char limit for platform-specific files, gone since 2.1.0's single-format build), 11,500 in 2.4.0, 20,000 in 2.4.1. The limit is now a prompt-size discipline only: the whole SKILL.md loads on every invocation while references load on demand, so situational detail still belongs in a reference file, and anything with one correct answer belongs in a script (see Skill scripts in the architecture doc).
|
||||
- **Keep LF line endings:** `.gitattributes` pins `eol=lf` because `validate-char-count.js` counts the characters on disk, and a CRLF checkout adds about one per line to every prompt. Measure with `node scripts/validate-char-count.js` before trusting a near-limit prompt. Git never writes CRLF here, but tools do (Python writing in text mode on Windows, some editors and generators), so `scripts/fix-line-endings.mjs` puts every text file git sees back to LF: `npm run fix:eol` by hand, `--check` to only list, and it runs by itself as npm's `pretest`, in the husky pre-commit before the char count, and after every Write or Edit through the PostToolUse hook in `.claude/settings.json`. In a Python script that writes repo files, open them with `newline="\n"` (or write bytes) anyway.
|
||||
- **The pre-commit hook runs only the char-count check:** `.husky/pre-commit` is `node scripts/validate-char-count.js` alone. `skills/` drift, parse errors and test failures are caught only by the tests, so run them before committing: the targeted suites for a change that stays in one area, the full `npm test` for shared code or before a PR (see "Targeted tests first" in [Development Commands](./AGENTS-development-commands.md)). Sub-package tests are separate; see [Development Commands](./AGENTS-development-commands.md).
|
||||
@@ -35,5 +34,5 @@
|
||||
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/styles/tokens.css`. No test ties them together.
|
||||
- **Reference file sizing guideline:** Files in `src/plan2code-*-references/` directories target ~100-200 lines each (soft guideline; evaluate splitting above 300). They are NOT subject to the 20,000 character limit. The pre-commit hook (`validate-char-count.js`) only checks `src/plan2code-*.md` flat files — subdirectory contents are automatically excluded.
|
||||
- **The splitting guideline has a hard ceiling — reference files cannot always be split:** each new reference costs the orchestrator a `Read references/<file>.md` line plus its fallback blockquote (~150-200 chars), which adds up across a prompt's 20,000-char budget. When a reference legitimately exceeds 300 lines (e.g. `plan2code-0-pathfinder-references/chart.md`), that is an accepted trade-off, not an oversight. Nested folders under `-references/` work: `references/` is the real path on every agent.
|
||||
- **Windows global bins for loop, metrics and bot are wrappers, not `npm link`:** on win32 the installer writes `<name>.cmd` and `<name>.ps1` into `npm config get prefix`, each running `node <package>/dist/bin/<name>.js` (`install.js:1302-1323` for the loop; the metrics and bot installers do the same). After a source change, `npm run build` in the package is enough; no reinstall.
|
||||
- **Windows global bins for metrics and bot are wrappers, not `npm link`:** on win32 the installer writes `<name>.cmd` and `<name>.ps1` into `npm config get prefix`, each running `node <package>/dist/bin/<name>.js` (the metrics and bot installers both do this). After a source change, `npm run build` in the package is enough; no reinstall.
|
||||
- **plan2code-metrics only runs from a repo checkout:** `analyzer.ts` and `improver.ts` load `src/prompts/analyze.md` / `improve.md` at runtime through `new URL('../src/prompts/...', import.meta.url)`, resolved relative to `dist/` (`analyzer.ts:11`, `improver.ts:13`). A packed or copied `dist/` without `src/prompts/` fails.
|
||||
@@ -42,10 +42,6 @@ node scripts/capture-screenshots.mjs --only dashboard # one screen (dashboard-u
|
||||
node scripts/css-snapshot.mjs --out before.json
|
||||
node scripts/css-snapshot.mjs --compare before.json
|
||||
|
||||
# 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
|
||||
@@ -80,7 +76,7 @@ The full `npm test` takes minutes and drives a browser per page suite. When a ch
|
||||
|
||||
Run the full `npm test` when the change touches something many suites lean on: `web-console-test-helpers.mjs` or `page-test-helpers.mjs`, `looks.js` / `prefs.js` / `static.mjs` (the `SERVABLE` list), `skills.js`, `install.js`, the server's shared modules (`console.mjs`, `routes.mjs`); after a sync merge or a version bump; before opening a PR or cutting a release; and whenever you cannot say which suites a change reaches.
|
||||
|
||||
The root `npm test` does not run the metrics or bot vitest suites; run them in their package. `npm run dev` in loop, metrics and bot is `tsup --watch`. The web console and launcher suites isolate themselves with `PLAN2CODE_CONSOLE_HOME`, `PLAN2CODE_MODELS_DIR` and `PLAN2CODE_NO_BROWSER=1` (`scripts/web-console-test-helpers.mjs`), so they never open a browser or touch your real console home. The web console suites are split by area so `node --test` runs them in parallel. `npm test` runs them through `scripts/node-test.mjs`, which caps the files run at once at one per spare core (8 at most): each page test file drives a browser, and more at once than the cores can carry fails page tests at random (a flat 8 did on 3 and 4 core CI runners). Page tests (`test-web-console-page-*.mjs`) read styles and set scrolls only through `styleOf()`, `stylesOf()` and `scrollCard()` from `page-test-helpers.mjs`, which retry until the element is still on the page; `test-web-console-shape.mjs` fails a raw `locator.evaluate` that does either.
|
||||
The root `npm test` does not run the metrics or bot vitest suites; run them in their package. `npm run dev` in metrics and bot is `tsup --watch`. The web console and launcher suites isolate themselves with `PLAN2CODE_CONSOLE_HOME`, `PLAN2CODE_MODELS_DIR` and `PLAN2CODE_NO_BROWSER=1` (`scripts/web-console-test-helpers.mjs`), so they never open a browser or touch your real console home. The web console suites are split by area so `node --test` runs them in parallel. `npm test` runs them through `scripts/node-test.mjs`, which caps the files run at once at one per spare core (8 at most): each page test file drives a browser, and more at once than the cores can carry fails page tests at random (a flat 8 did on 3 and 4 core CI runners). Page tests (`test-web-console-page-*.mjs`) read styles and set scrolls only through `styleOf()`, `stylesOf()` and `scrollCard()` from `page-test-helpers.mjs`, which retry until the element is still on the page; `test-web-console-shape.mjs` fails a raw `locator.evaluate` that does either.
|
||||
|
||||
## Test/Dev Env Vars
|
||||
|
||||
@@ -101,7 +97,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|
||||
| Option | Action |
|
||||
|--------|--------|
|
||||
| `I` | Install the Plan2Code skills globally via the `skills` CLI, plus the global `plan2code` command (opens the dashboard in Claude Code, Devin or Codex), then print the getting-started steps. No dev tools |
|
||||
| `U` | Uninstall Plan2Code: skills + `plan2code` command + `plan2code-loop` + `plan2code-metrics` + `plan2code-bot` + Claude Code status line (confirmation required) |
|
||||
| `U` | Uninstall Plan2Code: skills + `plan2code` command + `plan2code-metrics` + `plan2code-bot` + Claude Code status line (confirmation required) |
|
||||
| `A` | Open the ADVANCED sub-menu |
|
||||
| `Q` | Quit |
|
||||
|
||||
@@ -110,12 +106,11 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|
||||
| Option | Action |
|
||||
|--------|--------|
|
||||
| `L` | Install the skills into the current project instead of globally |
|
||||
| `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 |
|
||||
| `D` | Install the global `plan2code` command only |
|
||||
| `E` | Everything: the skills, the `plan2code` command and every dev tool (`plan2code-loop`, `plan2code-bot`, `plan2code-metrics`, the Claude Code status line) |
|
||||
| `E` | Everything: the skills, the `plan2code` command and every dev tool (`plan2code-bot`, `plan2code-metrics`, the Claude Code status line) |
|
||||
| `Q` | Return to main menu |
|
||||
|
||||
## Non-Interactive Flags
|
||||
@@ -126,7 +121,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|
||||
|------|--------|
|
||||
| `--build-skills` | Regenerate `skills/` from `src/`, pruning stale skills and reference files |
|
||||
| `--verify-skills` | Diff local `skills/` against `src/`; exits 1 on drift. Diagnostic only, the installer rebuilds anyway |
|
||||
| `--update` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, statusline, loop, metrics, bot), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx |
|
||||
| `--update` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, statusline, metrics, bot), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx |
|
||||
|
||||
## How the Installer Works
|
||||
|
||||
|
||||
@@ -1,54 +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
|
||||
|
||||
Run `plan2code-loop` in a project (fully interactive, no flags). Build commands: see [Development Commands](./AGENTS-development-commands.md).
|
||||
|
||||
The CLI auto-detects specs in `./specs/`, prompts for selection if multiple found, and handles session continuation interactively. Only `specs/<feature>/overview.md` is detected; archived specs in `specs--completed/` are ignored. Session state is stored per-spec in `specs/<feature>/.plan2code-loop/`.
|
||||
|
||||
Exit codes: 0 all complete, 1 max iterations, 2 interrupted (SIGINT/SIGTERM saves state), 3 error. The state dir holds `config.json`, `scratchpad.md` (LLM notes), `iteration.log` (NDJSON) and `spec.hash` (a mismatch prompts "Start fresh?"). Defaults: 100 max iterations, 3 min timeout, 5 retries.
|
||||
|
||||
## Supported Agents
|
||||
|
||||
Claude Code, GitHub Copilot CLI, Devin CLI, defined in `plan2code-loop/src/agents/` (one file each, registered in `agents/index.ts`).
|
||||
|
||||
## 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
|
||||
- `PREREQ_COMPLETE: P1.1 - Description` - Prerequisite verified
|
||||
- `PREREQ_ASSUMED: P2.1 - Description` - Prerequisite that cannot be verified, assumed met
|
||||
|
||||
Parsing is in `utils/completion.ts` and is lenient: `TASK_COMPLETE: 1.1: x` and `TASK_COMPLETE[1.1]: x` also match.
|
||||
|
||||
## 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 session setup (spec, agent, JIRA ID, loop mode, max iterations, resume/fresh) |
|
||||
| `plan2code-loop/src/utils/completion.ts` | Marker parsing (`checkForCompletion` task mode, `checkForAllCompletions` phase mode) |
|
||||
| `plan2code-loop/src/state/manager.ts` | Per-spec state dir, spec hash, iteration log |
|
||||
| `plan2code-loop/src/agents/` | Agent adapters (claude-code, copilot-cli, devin-cli) |
|
||||
@@ -19,7 +19,7 @@ A rule stated in six files is read six times and still skipped. The console sees
|
||||
- **Recommend sparingly.** "Which format survives Excel?" is the agent's to recommend; "Who is this for?" is not, because a recommendation there is an anchor people rubber-stamp.
|
||||
- **A placeholder is an offer.** The Autofill button drops it into the box as a real answer, so it must be a whole answer in the person's voice and satisfy any `pattern`.
|
||||
- **Titles in plain words.** Internal vocabulary (grill, frontier, fog) means nothing to a newcomer and the server refuses it. The metric words rule exists because the metrics collector scrapes `Requirements`, `Feasibility`, `Integration` and `Risk` followed by a number.
|
||||
- **Loop markers refused.** `TASK_COMPLETE`, `PHASE_COMPLETE` and the rest are read by the loop CLI as completion; one in page text would end a run.
|
||||
- **Completion markers refused.** `TASK_COMPLETE`, `PHASE_COMPLETE` and the rest are reserved signals; one in page text could read as a finished run.
|
||||
- **The page owns its stream.** The agent never writes timestamps, versions or `agent.status` for a turn: the server stamps them, and collecting a send already sets the page to working. A second source of truth for them would drift.
|
||||
- **Quoted heredoc.** Unquoted `<<EOF` lets the shell eat JSON backslashes. PowerShell has no heredoc and its pipe can mangle non-ASCII, so the patch goes through a file in the session folder, never in the project.
|
||||
- **No link in the app.** Inside the desktop app the page is already in the window; printing the link sends the person to a browser tab they do not need.
|
||||
|
||||
@@ -42,7 +42,7 @@ body:
|
||||
- Finalize
|
||||
- Handoff
|
||||
- Web console (page itself)
|
||||
- Loop (plan2code-loop)
|
||||
- Implementation Loop (desktop app)
|
||||
- Metrics
|
||||
- Status line
|
||||
- Installer
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
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
|
||||
|
||||
@@ -14,6 +14,3 @@ 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/
|
||||
@@ -1,65 +0,0 @@
|
||||
# Autonomous Loop
|
||||
|
||||
`plan2code-loop` is a CLI that works through your spec's tasks on its own, one agent call at a
|
||||
time. It is an **alternative to Step 3**, not a replacement — the four-step workflow and the specs it
|
||||
produces are unchanged.
|
||||
|
||||
← [Back to README](../README.md)
|
||||
|
||||
---
|
||||
|
||||
## When to use it instead of Step 3
|
||||
|
||||
| Approach | Best for |
|
||||
|----------|----------|
|
||||
| `/plan2code-3-implement` | Interactive control, reviewing each phase, logic that needs your judgment |
|
||||
| `/plan2code-3-implement-review` | The same interactive control, with a focused review and its fixes applied before you approve the phase |
|
||||
| `plan2code-loop` | Straightforward implementations, batch work, overnight runs |
|
||||
|
||||
The loop reads the same `overview.md` and phase files. You can start with the loop and finish by
|
||||
hand, or the reverse — the checkboxes are the only handoff.
|
||||
|
||||
---
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
# From the plan2code root directory
|
||||
node install.js # A → E (everything + dev tools) or A → O (loop only)
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
plan2code-loop # fully interactive
|
||||
```
|
||||
|
||||
It will:
|
||||
|
||||
1. Find specs in `./specs/`
|
||||
2. Let you pick one if there are several
|
||||
3. Offer to resume an existing session
|
||||
4. Ask for a JIRA ticket ID, which agent to drive, the loop mode, and a max iteration count
|
||||
|
||||
Then, per iteration: read `overview.md` and the phase files, find the first unchecked task (or
|
||||
phase), implement it, mark the checkbox, repeat — until everything is done or it hits the iteration
|
||||
cap.
|
||||
|
||||
---
|
||||
|
||||
## Loop modes
|
||||
|
||||
| Mode | Each agent call | Git commits | Best for |
|
||||
|------|-----------------|-------------|----------|
|
||||
| **One task per loop** (default) | Implements a single task | The Node controller commits after each task | Smaller models, cautious execution |
|
||||
| **One phase per loop** | Implements every task in a phase | The agent commits after each task, with the JIRA ID | Larger context windows, tightly related tasks |
|
||||
|
||||
Session state lives per-spec in `specs/<feature>/.plan2code-loop/`, so each feature's progress
|
||||
stays isolated.
|
||||
|
||||
---
|
||||
|
||||
## Full documentation
|
||||
|
||||
Architecture, completion markers, agent adapters, and configuration:
|
||||
[`plan2code-loop/README.md`](../plan2code-loop/README.md)
|
||||
@@ -77,7 +77,7 @@ The console carries all of these as opaque strings and never reformats them.
|
||||
### 2.5 Two regex landmines
|
||||
|
||||
- `plan2code-metrics` scrapes confidence with patterns like `/[Rr]equirements?[:\s|]+(\d{1,2})/` that **do not require a percent sign**. Nothing the console writes under `specs/` may contain bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number.
|
||||
- The loop parses `TASK_COMPLETE`, `PHASE_COMPLETE` and friends. Pathfinder already forbids these tokens under `specs/`.
|
||||
- `TASK_COMPLETE`, `PHASE_COMPLETE` and friends are reserved completion markers, refused outright. Pathfinder already forbids these tokens under `specs/`.
|
||||
|
||||
Both are cheap to enforce mechanically in the server's write path.
|
||||
|
||||
@@ -188,7 +188,7 @@ The filesystem is the database and the result transport.
|
||||
events.ndjson append-only, doubles as SSE Last-Event-ID replay
|
||||
```
|
||||
|
||||
Deliberately **not** under `specs/`: that keeps the console clear of the metrics scraper and the loop's marker parser, and survives a `git clean`.
|
||||
Deliberately **not** under `specs/`: that keeps the console clear of the metrics scraper and completion-marker parsers, and survives a `git clean`.
|
||||
|
||||
Draft persistence is the highest-value feature in the tool and among the cheapest. Twenty minutes of a product manager's structured answers must never be lost to a closed tab. Server-side debounced write plus a `localStorage` mirror keyed by `sid + rev`.
|
||||
|
||||
|
||||
@@ -22,12 +22,6 @@ High-level directory structure, key files, workflow prompt inventory, and file n
|
||||
|
||||
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.
|
||||
@@ -69,7 +63,7 @@ Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
|
||||
|
||||
## Mascot
|
||||
|
||||
The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` (and `plan2code-loop/src/utils/logger.ts`) and appear in workflow markdown files: arms down at rest, one arm waving when he is asking something, both arms up when he is celebrating. The eye is always the star.
|
||||
The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` and appear in workflow markdown files: arms down at rest, one arm waving when he is asking something, both arms up when he is celebrating. The eye is always the star.
|
||||
|
||||
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight color and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||
|
||||
|
||||
@@ -2,6 +2,14 @@
|
||||
|
||||
All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
## v4.0.0
|
||||
|
||||
### 💥 Breaking
|
||||
|
||||
- **the `plan2code-loop` CLI is no longer an install target, and the package is removed.** The `plan2code-loop/` directory is deleted, and with it the installer's `O. LOOP CLI` advanced option and the loop's install, update and uninstall wiring. Its docs (`.readme/autonomous-loop.md`, `.agents-docs/AGENTS-plan2code-loop.md`) are gone too, and every remaining mention across the docs, templates, metadata and comments is removed or reworded. The desktop app's **Implementation Loop**, which superseded the CLI, is a separate feature built into the app and is unchanged.
|
||||
|
||||
**Stale installs are still cleaned up.** `install.js` keeps a small `removeLegacyLoopShims()` step that removes the old global artifacts (`plan2code-loop`, `plan2code-loop.cmd`, `plan2code-loop.ps1` and `node_modules/plan2code-loop` under the npm prefix) when they are present. `update()` runs it once before reinstalling and quietly skips a stale `"loop"` entry in `~/.plan2code/install.json`; uninstall runs it too.
|
||||
|
||||
## v3.0.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
+1
-6
@@ -130,14 +130,9 @@ Is it a quick, small task?
|
||||
└── No → /plan2code-1-plan (full workflow)
|
||||
├── /plan2code-2-document
|
||||
├── /plan2code-3-implement (repeat per phase)
|
||||
│ ├── OR: /plan2code-3-implement-review (review gate before approval)
|
||||
│ └── OR: plan2code-loop (autonomous alternative)
|
||||
│ └── OR: /plan2code-3-implement-review (review gate before approval)
|
||||
└── /plan2code-4-finalize
|
||||
|
||||
Need to revise mid-implementation?
|
||||
└── /plan2code-1b-revise-plan
|
||||
```
|
||||
|
||||
## Autonomous Loop (Alternative)
|
||||
|
||||
`plan2code-loop` is a hands-off alternative to Step 3. See [.readme/autonomous-loop.md](.readme/autonomous-loop.md).
|
||||
@@ -13,7 +13,7 @@ the next engineer all start from the same specs.
|
||||
|
||||
One command opens it, every step is a card, and the terminal is always there if you prefer it.
|
||||
|
||||
Version 3.0.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
Version 4.0.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
|
||||
---
|
||||
|
||||
@@ -269,7 +269,7 @@ Each feature gets a folder under `specs/` (the plan, the overview and one file p
|
||||
moves it to `specs--completed/`. The layout and progress marks are on the
|
||||
[quick reference](QUICK-REFERENCE.md#file-structure).
|
||||
|
||||
Add `specs/` to your project's `.gitignore` (`plan2code-loop` adds it for you): it's your working
|
||||
Add `specs/` to your project's `.gitignore`: it's your working
|
||||
drawing, not a deliverable. Share a folder deliberately with `git add -f` when you want to.
|
||||
|
||||
Step 2 marks which phases don't share files. Open a second agent on one of those, and the `[/]` marks
|
||||
@@ -470,7 +470,6 @@ Core reference:
|
||||
|
||||
Optional tooling — none of it is required to use the workflow:
|
||||
|
||||
- **[.readme/autonomous-loop.md](.readme/autonomous-loop.md)** — `plan2code-loop`, a hands-off alternative to Step 3
|
||||
- **[.readme/status-line.md](.readme/status-line.md)** — three-line Claude Code status bar: model, context, quota, diff
|
||||
- **[.readme/metrics.md](.readme/metrics.md)** — `plan2code-metrics`, measuring and improving the prompts themselves
|
||||
- **[.readme/test-bot.md](.readme/test-bot.md)** — `plan2code-bot`, maintainer harness that runs the whole workflow unattended
|
||||
+32
-262
@@ -21,6 +21,7 @@ const path = require('path');
|
||||
const os = require('os');
|
||||
const readline = require('readline');
|
||||
const crypto = require('crypto');
|
||||
const { execSync, execFileSync } = require('child_process');
|
||||
|
||||
// Load project version metadata
|
||||
let projectVersion = { name: 'Plan2Code', version: 'unknown' };
|
||||
@@ -1247,13 +1248,13 @@ function runInteractive() {
|
||||
if (confirmInput === 'Y') {
|
||||
rl.close();
|
||||
const uninstallResult = uninstallSkills();
|
||||
const loopResult = uninstallPlan2CodeLoop();
|
||||
removeLegacyLoopShims();
|
||||
const metricsResult = uninstallPlan2CodeMetrics();
|
||||
const botResult = uninstallPlan2CodeBot();
|
||||
const statusLineResult = uninstallStatusLine();
|
||||
const launcherResult = uninstallLauncher();
|
||||
uninstallDesktopApp();
|
||||
const exitCode = uninstallResult !== 0 ? uninstallResult : loopResult !== 0 ? loopResult : metricsResult !== 0 ? metricsResult : botResult !== 0 ? botResult : statusLineResult !== 0 ? statusLineResult : launcherResult;
|
||||
const exitCode = uninstallResult !== 0 ? uninstallResult : metricsResult !== 0 ? metricsResult : botResult !== 0 ? botResult : statusLineResult !== 0 ? statusLineResult : launcherResult;
|
||||
process.exit(exitCode);
|
||||
} else {
|
||||
console.log(`\n${COLORS.YELLOW}${SYMBOLS.WARNING} CANCELED${COLORS.RESET}\n`);
|
||||
@@ -1269,7 +1270,6 @@ function runInteractive() {
|
||||
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}ADVANCED OPTIONS${COLORS.RESET}`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
|
||||
console.log(`${COLORS.CYAN}╠════════════════════════════════════════════════════════════════╣${COLORS.RESET}`);
|
||||
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}L.${COLORS.RESET} ${COLORS.BLUE}LOCAL${COLORS.RESET} Install skills into the current project only`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
|
||||
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}O.${COLORS.RESET} ${COLORS.GREEN}LOOP CLI${COLORS.RESET} Install plan2code-loop CLI only`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
|
||||
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}M.${COLORS.RESET} ${COLORS.GREEN}METRICS${COLORS.RESET} Install plan2code-metrics CLI only`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
|
||||
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}S.${COLORS.RESET} ${COLORS.GREEN}STATUS${COLORS.RESET} Install Claude Code status line`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
|
||||
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}B.${COLORS.RESET} ${COLORS.GREEN}BOT${COLORS.RESET} Install plan2code-bot CLI only`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
|
||||
@@ -1278,14 +1278,12 @@ function runInteractive() {
|
||||
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}Q.${COLORS.RESET} ${COLORS.DIM}BACK${COLORS.RESET} Return to main menu`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
|
||||
console.log(`${COLORS.CYAN}╚════════════════════════════════════════════════════════════════╝${COLORS.RESET}`);
|
||||
console.log('');
|
||||
const customAnswer = await question(`${COLORS.CYAN}${SYMBOLS.SELECT} SELECT OPTION${COLORS.RESET} (L, O, M, S, B, D, E, Q) [Q]: `);
|
||||
const customAnswer = await question(`${COLORS.CYAN}${SYMBOLS.SELECT} SELECT OPTION${COLORS.RESET} (L, M, S, B, D, E, Q) [Q]: `);
|
||||
const customInput = customAnswer.trim().toUpperCase() || 'Q';
|
||||
|
||||
// A > E: install everything (skills + loop + bot + metrics + Claude status line)
|
||||
// A > E: install everything (skills + bot + metrics + Claude status line)
|
||||
if (customInput === 'E') {
|
||||
rl.close();
|
||||
const loopResult = installPlan2CodeLoop();
|
||||
console.log('');
|
||||
const botResult = installPlan2CodeBot();
|
||||
console.log('');
|
||||
const metricsResult = installPlan2CodeMetrics();
|
||||
@@ -1293,7 +1291,7 @@ function runInteractive() {
|
||||
const statusLineResult = await installStatusLine();
|
||||
console.log('');
|
||||
const installResult = await install();
|
||||
const exitCode = loopResult !== 0 ? loopResult : botResult !== 0 ? botResult : metricsResult !== 0 ? metricsResult : statusLineResult !== 0 ? statusLineResult : installResult;
|
||||
const exitCode = botResult !== 0 ? botResult : metricsResult !== 0 ? metricsResult : statusLineResult !== 0 ? statusLineResult : installResult;
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
@@ -1303,13 +1301,6 @@ function runInteractive() {
|
||||
process.exit(installProjectSkills());
|
||||
}
|
||||
|
||||
// A > O: install loop CLI only
|
||||
if (customInput === 'O') {
|
||||
rl.close();
|
||||
const result = installPlan2CodeLoop();
|
||||
process.exit(result);
|
||||
}
|
||||
|
||||
// A > M: install metrics CLI only
|
||||
if (customInput === 'M') {
|
||||
rl.close();
|
||||
@@ -1361,268 +1352,46 @@ function runInteractive() {
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PLAN2CODE-LOOP INSTALLATION
|
||||
// LEGACY PLAN2CODE-LOOP SHIMS
|
||||
// ============================================================================
|
||||
|
||||
const { execSync, execFileSync } = require('child_process');
|
||||
|
||||
/**
|
||||
* Build plan2code-loop package
|
||||
* Remove stale plan2code-loop artifacts left behind by the retired CLI package:
|
||||
* the shims under the npm bin/prefix dir and the link under the npm root.
|
||||
* Silently does nothing when none are present.
|
||||
*/
|
||||
function buildPlan2CodeLoop() {
|
||||
const loopDir = path.join(__dirname, 'plan2code-loop');
|
||||
|
||||
// Check if directory exists
|
||||
if (!fs.existsSync(loopDir)) {
|
||||
console.log(`${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} plan2code-loop directory not found`);
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log(`${COLORS.CYAN}${SYMBOLS.ACTIVE} Building plan2code-loop...${COLORS.RESET}`);
|
||||
|
||||
function removeLegacyLoopShims() {
|
||||
let npmPrefix;
|
||||
try {
|
||||
// Install dependencies
|
||||
console.log(` ${COLORS.DIM}Installing dependencies...${COLORS.RESET}`);
|
||||
execSync('npm install', { cwd: loopDir, stdio: 'pipe' });
|
||||
|
||||
// Build
|
||||
console.log(` ${COLORS.DIM}Running build...${COLORS.RESET}`);
|
||||
execSync('npm run build', { cwd: loopDir, stdio: 'pipe' });
|
||||
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Build complete`);
|
||||
return true;
|
||||
npmPrefix = execSync('npm config get prefix', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
||||
} catch (error) {
|
||||
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Build failed: ${error.message}`);
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Clean up existing plan2code-loop symlinks/files before creating new ones
|
||||
* This prevents the Windows lstat error with stale symlinks
|
||||
*/
|
||||
function cleanupExistingSymlinks() {
|
||||
console.log(` ${COLORS.DIM}Cleaning up existing symlinks...${COLORS.RESET}`);
|
||||
|
||||
try {
|
||||
// Get npm global prefix - more reliable than npm bin -g on Windows
|
||||
const npmPrefix = execSync('npm config get prefix', { encoding: 'utf8' }).trim();
|
||||
// On Windows, bin files are directly in prefix; on Unix they are in prefix/bin
|
||||
const npmBinGlobal = process.platform === 'win32' ? npmPrefix : path.join(npmPrefix, 'bin');
|
||||
const npmRootGlobal = path.join(npmPrefix, 'node_modules');
|
||||
|
||||
// On Windows, bin files are directly in prefix; on Unix they're in prefix/bin
|
||||
const npmBinGlobal = process.platform === 'win32' ? npmPrefix : path.join(npmPrefix, 'bin');
|
||||
const npmRootGlobal = path.join(npmPrefix, 'node_modules');
|
||||
const artifacts = [
|
||||
{ path: path.join(npmBinGlobal, 'plan2code-loop'), name: 'plan2code-loop' },
|
||||
{ path: path.join(npmBinGlobal, 'plan2code-loop.cmd'), name: 'plan2code-loop.cmd' },
|
||||
{ path: path.join(npmBinGlobal, 'plan2code-loop.ps1'), name: 'plan2code-loop.ps1' },
|
||||
{ path: path.join(npmRootGlobal, 'plan2code-loop'), name: 'node_modules/plan2code-loop' }
|
||||
];
|
||||
|
||||
// Files/symlinks to clean up in npm bin directory
|
||||
const binFiles = [
|
||||
path.join(npmBinGlobal, 'plan2code-loop'),
|
||||
path.join(npmBinGlobal, 'plan2code-loop.cmd'),
|
||||
path.join(npmBinGlobal, 'plan2code-loop.ps1')
|
||||
];
|
||||
|
||||
// Symlink in node_modules - this is the main culprit for the lstat error
|
||||
const nodeModulesLink = path.join(npmRootGlobal, 'plan2code-loop');
|
||||
|
||||
// Remove bin files first
|
||||
for (const file of binFiles) {
|
||||
try {
|
||||
const stats = fs.lstatSync(file);
|
||||
if (stats) {
|
||||
fs.unlinkSync(file);
|
||||
console.log(` ${COLORS.DIM}Removed: ${path.basename(file)}${COLORS.RESET}`);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
// File exists but can't be removed normally, try rmSync
|
||||
try {
|
||||
fs.rmSync(file, { force: true, recursive: true });
|
||||
console.log(` ${COLORS.DIM}Removed: ${path.basename(file)}${COLORS.RESET}`);
|
||||
} catch (rmErr) {
|
||||
console.log(` ${COLORS.DIM}Could not remove: ${path.basename(file)}${COLORS.RESET}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove node_modules symlink - this is critical for fixing the lstat error
|
||||
for (const artifact of artifacts) {
|
||||
try {
|
||||
const stats = fs.lstatSync(nodeModulesLink);
|
||||
if (stats) {
|
||||
// On Windows, junction points need special handling
|
||||
if (process.platform === 'win32') {
|
||||
// Try using rmdir for junction points
|
||||
try {
|
||||
fs.rmdirSync(nodeModulesLink);
|
||||
console.log(` ${COLORS.DIM}Removed: node_modules/plan2code-loop (junction)${COLORS.RESET}`);
|
||||
} catch (rmdirErr) {
|
||||
// Fall back to rmSync
|
||||
fs.rmSync(nodeModulesLink, { force: true, recursive: true });
|
||||
console.log(` ${COLORS.DIM}Removed: node_modules/plan2code-loop${COLORS.RESET}`);
|
||||
}
|
||||
} else {
|
||||
fs.rmSync(nodeModulesLink, { force: true, recursive: true });
|
||||
console.log(` ${COLORS.DIM}Removed: node_modules/plan2code-loop${COLORS.RESET}`);
|
||||
}
|
||||
}
|
||||
fs.lstatSync(artifact.path);
|
||||
fs.rmSync(artifact.path, { force: true, recursive: true });
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Removed: ${artifact.name}`);
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
console.log(` ${COLORS.DIM}Could not remove node_modules symlink: ${err.message}${COLORS.RESET}`);
|
||||
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Failed to remove ${artifact.name}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
// Non-fatal - npm link might still work
|
||||
console.log(` ${COLORS.DIM}Cleanup skipped: ${error.message}${COLORS.RESET}`);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create global symlink for plan2code-loop
|
||||
*/
|
||||
function createGlobalSymlink() {
|
||||
const loopDir = path.join(__dirname, 'plan2code-loop');
|
||||
const distBin = path.join(loopDir, 'dist', 'bin', 'plan2code-loop.js');
|
||||
// Check if built binary exists
|
||||
if (!fs.existsSync(distBin)) {
|
||||
console.log(`${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} plan2code-loop binary not found. Run build first.`);
|
||||
return false;
|
||||
}
|
||||
console.log(`${COLORS.CYAN}${SYMBOLS.ACTIVE} Creating global symlink...${COLORS.RESET}`);
|
||||
|
||||
// Clean up existing symlinks first to prevent Windows lstat errors
|
||||
cleanupExistingSymlinks();
|
||||
|
||||
// On Windows, skip npm link entirely and create batch file directly
|
||||
// npm link has persistent issues with junctions and lstat errors on Windows
|
||||
if (process.platform === 'win32') {
|
||||
try {
|
||||
const npmPrefix = execSync('npm config get prefix', { encoding: 'utf8' }).trim();
|
||||
const symlinkCmd = path.join(npmPrefix, 'plan2code-loop.cmd');
|
||||
const symlinkPs1 = path.join(npmPrefix, 'plan2code-loop.ps1');
|
||||
|
||||
// Create batch file wrapper for cmd.exe
|
||||
const batchContent = `@echo off\r\nnode "${distBin}" %*\r\n`;
|
||||
fs.writeFileSync(symlinkCmd, batchContent);
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Created: plan2code-loop.cmd`);
|
||||
|
||||
// Create PowerShell wrapper for better shell support
|
||||
const ps1Content = `#!/usr/bin/env pwsh\r\nnode "${distBin}" $args\r\n`;
|
||||
fs.writeFileSync(symlinkPs1, ps1Content);
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Created: plan2code-loop.ps1`);
|
||||
|
||||
console.log(` ${COLORS.DIM}Run 'plan2code-loop --help' from any directory${COLORS.RESET}`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Failed to create wrappers: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// On Unix systems, use npm link as it works reliably
|
||||
try {
|
||||
execSync('npm link', { cwd: loopDir, stdio: 'pipe' });
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Global symlink created`);
|
||||
console.log(` ${COLORS.DIM}Run 'plan2code-loop --help' from any directory${COLORS.RESET}`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Symlink failed: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Remove global symlink for plan2code-loop
|
||||
*/
|
||||
function removeGlobalSymlink() {
|
||||
console.log(`${COLORS.CYAN}${SYMBOLS.ACTIVE} Removing global symlink...${COLORS.RESET}`);
|
||||
|
||||
let removedCount = 0;
|
||||
|
||||
try {
|
||||
// Get npm global prefix
|
||||
const npmPrefix = execSync('npm config get prefix', { encoding: 'utf8' }).trim();
|
||||
|
||||
// On Windows, bin files are directly in prefix; on Unix they're in prefix/bin
|
||||
const npmBinGlobal = process.platform === 'win32' ? npmPrefix : path.join(npmPrefix, 'bin');
|
||||
const npmRootGlobal = path.join(npmPrefix, 'node_modules');
|
||||
|
||||
// Files to remove
|
||||
const filesToRemove = [
|
||||
{ path: path.join(npmBinGlobal, 'plan2code-loop'), name: 'plan2code-loop' },
|
||||
{ path: path.join(npmBinGlobal, 'plan2code-loop.cmd'), name: 'plan2code-loop.cmd' },
|
||||
{ path: path.join(npmBinGlobal, 'plan2code-loop.ps1'), name: 'plan2code-loop.ps1' },
|
||||
{ path: path.join(npmRootGlobal, 'plan2code-loop'), name: 'node_modules/plan2code-loop' }
|
||||
];
|
||||
|
||||
for (const file of filesToRemove) {
|
||||
try {
|
||||
fs.lstatSync(file.path);
|
||||
fs.rmSync(file.path, { force: true, recursive: true });
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Removed: ${file.name}`);
|
||||
removedCount++;
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Failed to remove ${file.name}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (removedCount === 0) {
|
||||
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No files found to remove${COLORS.RESET}`);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Uninstall failed: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Install plan2code-loop (build + symlink)
|
||||
*/
|
||||
function installPlan2CodeLoop() {
|
||||
displaySectionHeader('PLAN2CODE-LOOP', '[ BUILD & INSTALL ]');
|
||||
|
||||
const buildSuccess = buildPlan2CodeLoop();
|
||||
if (!buildSuccess) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
const symlinkSuccess = createGlobalSymlink();
|
||||
if (!symlinkSuccess) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
console.log('');
|
||||
recordInstalled('loop');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-loop installed successfully!${COLORS.RESET}`);
|
||||
console.log('');
|
||||
console.log(`${COLORS.CYAN}Usage:${COLORS.RESET}`);
|
||||
console.log(` ${COLORS.BRIGHT}plan2code-loop${COLORS.RESET} Start the autonomous loop`);
|
||||
console.log(` ${COLORS.BRIGHT}plan2code-loop -c${COLORS.RESET} Resume previous session`);
|
||||
console.log(` ${COLORS.BRIGHT}plan2code-loop -v${COLORS.RESET} Verbose mode`);
|
||||
console.log(` ${COLORS.BRIGHT}plan2code-loop --help${COLORS.RESET} Show all options`);
|
||||
console.log('');
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstall plan2code-loop
|
||||
*/
|
||||
function uninstallPlan2CodeLoop() {
|
||||
displaySectionHeader('PLAN2CODE-LOOP', '[ UNINSTALL ]');
|
||||
|
||||
removeGlobalSymlink();
|
||||
forgetInstalled('loop');
|
||||
|
||||
console.log('');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-loop uninstalled${COLORS.RESET}`);
|
||||
console.log('');
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PLAN2CODE-METRICS INSTALLATION
|
||||
// ============================================================================
|
||||
@@ -2358,7 +2127,7 @@ const UPDATE_CHECK_DEST = path.join(path.dirname(LAUNCHER_DEST), 'update-check.m
|
||||
const LAUNCHER_VERSION_DEST = path.join(path.dirname(LAUNCHER_DEST), 'version.json');
|
||||
// What a global install put on this machine, so `plan2code update` reinstalls exactly that.
|
||||
const INSTALL_RECORD = path.join(os.homedir(), '.plan2code', 'install.json');
|
||||
const INSTALL_PIECES = ['skills', 'launcher', 'app', 'statusline', 'loop', 'metrics', 'bot'];
|
||||
const INSTALL_PIECES = ['skills', 'launcher', 'app', 'statusline', 'metrics', 'bot'];
|
||||
const LAUNCHER_PICK_FOLDER_FLAG = '--pick-folder';
|
||||
|
||||
/**
|
||||
@@ -3017,7 +2786,6 @@ const UPDATE_STEPS = {
|
||||
launcher: installLauncher,
|
||||
app: installDesktopApp,
|
||||
statusline: installStatusLine,
|
||||
loop: installPlan2CodeLoop,
|
||||
metrics: installPlan2CodeMetrics,
|
||||
bot: installPlan2CodeBot,
|
||||
};
|
||||
@@ -3026,7 +2794,7 @@ const UPDATE_STEPS = {
|
||||
* Reinstall whatever ~/.plan2code/install.json lists, without the menu or any prompt. Returns
|
||||
* the exit code: 0 when every piece updated, 1 naming the pieces that failed.
|
||||
*/
|
||||
async function update({ steps = UPDATE_STEPS } = {}) {
|
||||
async function update({ steps = UPDATE_STEPS, cleanShims = removeLegacyLoopShims } = {}) {
|
||||
displaySectionHeader(' UPDATING PLAN2CODE ');
|
||||
console.log(`${COLORS.BLUE}${COLORS.BRIGHT}Installing:${COLORS.RESET} ${projectVersion.name} ${projectVersion.version}`);
|
||||
console.log('');
|
||||
@@ -3038,6 +2806,8 @@ async function update({ steps = UPDATE_STEPS } = {}) {
|
||||
console.log('');
|
||||
}
|
||||
|
||||
cleanShims();
|
||||
|
||||
const results = {};
|
||||
for (const piece of INSTALL_PIECES) {
|
||||
if (!pieces.includes(piece) || piece in results) continue;
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code",
|
||||
"version": "3.0.0",
|
||||
"version": "4.0.0",
|
||||
"private": true,
|
||||
"bin": {
|
||||
"plan2code-install": "./install.js"
|
||||
@@ -11,7 +11,7 @@
|
||||
"fix:eol": "node scripts/fix-line-endings.mjs",
|
||||
"play": "node scripts/play.mjs",
|
||||
"pretest": "node scripts/fix-line-endings.mjs",
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"gpt-tokenizer": "2.9.0",
|
||||
|
||||
Generated
+1
-1
@@ -2371,7 +2371,7 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "plan2code-app"
|
||||
version = "3.0.0"
|
||||
version = "4.0.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"libc",
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "plan2code-app",
|
||||
"version": "3.0.0",
|
||||
"version": "4.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "plan2code-app",
|
||||
"version": "3.0.0",
|
||||
"version": "4.0.0",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "2.12.4",
|
||||
"@xterm/addon-fit": "0.11.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code-app",
|
||||
"version": "3.0.0",
|
||||
"version": "4.0.0",
|
||||
"private": true,
|
||||
"description": "Plan2Code desktop app (Tauri). Separate from the repo root so the root and the web console stay dependency-free.",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "plan2code-app"
|
||||
version = "3.0.0"
|
||||
version = "4.0.0"
|
||||
description = "Plan2Code desktop app"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Plan2Code",
|
||||
"version": "3.0.0",
|
||||
"version": "4.0.0",
|
||||
"identifier": "com.plan2code.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../ui",
|
||||
|
||||
@@ -1,212 +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 A (Advanced) → E (Everything)
|
||||
|
||||
# Option 2: Install loop only
|
||||
node install.js # Select A (Advanced) → O (Loop CLI)
|
||||
|
||||
# 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 |
|
||||
| Devin CLI | Supported |
|
||||
|
||||
The loop uses your configured default model for each agent.
|
||||
|
||||
## Example Session
|
||||
|
||||
```
|
||||
$ plan2code-loop
|
||||
|
||||
╭──────────────────────────────────────╮
|
||||
│ │
|
||||
│ 🔮 Planny'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
|
||||
│ └── devin-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
|
||||
```
|
||||
@@ -1,47 +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",
|
||||
"devin",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
@@ -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();
|
||||
@@ -1,81 +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 devinCliConfig: AgentConfig = {
|
||||
name: 'devin-cli',
|
||||
displayName: 'Devin CLI',
|
||||
command: 'devin',
|
||||
models: [
|
||||
{ value: 'default', label: 'Default (use Devin config)' },
|
||||
],
|
||||
defaultModel: 'default',
|
||||
flags: {
|
||||
prompt: '--print',
|
||||
promptFile: '--prompt-file',
|
||||
model: '--model',
|
||||
skipPermissions: '--permission-mode',
|
||||
},
|
||||
};
|
||||
|
||||
class DevinCliAgent implements Agent {
|
||||
readonly config = devinCliConfig;
|
||||
|
||||
async execute(options: AgentExecutionOptions): Promise<AgentExecutionResult> {
|
||||
// Devin CLI takes the prompt via --prompt-file rather than stdin
|
||||
const tempFile = join(tmpdir(), `plan2code-prompt-${Date.now()}.txt`);
|
||||
writeFileSync(tempFile, options.prompt, 'utf-8');
|
||||
|
||||
try {
|
||||
const args: string[] = [
|
||||
this.config.flags.prompt, // --print for non-interactive mode
|
||||
this.config.flags.promptFile!, tempFile, // --prompt-file <path>
|
||||
this.config.flags.skipPermissions, 'dangerous', // --permission-mode dangerous (auto-approve all tools)
|
||||
];
|
||||
|
||||
// Only add --model if not using default
|
||||
if (options.model && options.model !== 'default') {
|
||||
args.push(this.config.flags.model, options.model);
|
||||
}
|
||||
|
||||
const result = await executeCommand({
|
||||
command: this.config.command,
|
||||
args,
|
||||
cwd: options.cwd,
|
||||
timeout: options.timeout,
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
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 devin --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 devinCliAgent = new DevinCliAgent();
|
||||
@@ -1,22 +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';
|
||||
export { devinCliAgent } from './devin-cli.js';
|
||||
|
||||
// Register all agents
|
||||
import { agentRegistry } from './registry.js';
|
||||
import { claudeCodeAgent } from './claude-code.js';
|
||||
import { copilotCliAgent } from './copilot-cli.js';
|
||||
import { devinCliAgent } from './devin-cli.js';
|
||||
|
||||
agentRegistry.register(claudeCodeAgent);
|
||||
agentRegistry.register(copilotCliAgent);
|
||||
agentRegistry.register(devinCliAgent);
|
||||
@@ -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();
|
||||
@@ -1,43 +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;
|
||||
promptFile?: 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>;
|
||||
}
|
||||
@@ -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();
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
// Canceled 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 canceled
|
||||
if (result.cancelled || this.interrupted) {
|
||||
logger.info('Agent process canceled');
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
export {
|
||||
buildLoopPrompt,
|
||||
type PromptContext,
|
||||
} from './builder.js';
|
||||
|
||||
export { LOOP_PROMPT_TEMPLATE, LOOP_PROMPT_TEMPLATE_PHASE } from './templates.js';
|
||||
@@ -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 the tests the task or phase file lists, 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 the tests the task or phase file lists, 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.
|
||||
`;
|
||||
@@ -1,4 +0,0 @@
|
||||
export {
|
||||
detectSpecDirectories,
|
||||
getSpecProgress,
|
||||
} from './utils.js';
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
export type LoopMode = 'task' | 'phase';
|
||||
|
||||
export interface SessionConfig {
|
||||
agent: string; // "claude-code" | "copilot-cli" | "devin-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',
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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 --web'), chalk.white('step.'));
|
||||
console.log(chalk.dim(' This will ensure quality, completeness, and proper documentation.'));
|
||||
console.log();
|
||||
},
|
||||
};
|
||||
|
||||
export type Logger = typeof logger;
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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"]
|
||||
}
|
||||
@@ -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',
|
||||
},
|
||||
});
|
||||
@@ -78,7 +78,7 @@ From the plan2code repo root:
|
||||
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.
|
||||
Choose **A** (Advanced) then **E** (Everything) to install prompts, bot, metrics, and status line together. Or choose **A** 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.
|
||||
|
||||
@@ -170,15 +170,11 @@ Each collection scrapes your spec files and extracts:
|
||||
- **Requirement coverage** — coverage percentage if present
|
||||
- **Verification items** — verification checklist items added
|
||||
|
||||
### Step 3 (Implement) — from `.plan2code-loop/` data (loop mode only)
|
||||
### Step 3 (Implement) — from `phase-*.md` and `overview.md`
|
||||
|
||||
- **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
|
||||
- **Tasks completed / total** — task counts read from the METRICS_JSON block in `overview.md`, else the Completion Summary, else checkbox counts across the phase files
|
||||
- **Blocker count** — tasks marked `[!]`
|
||||
|
||||
### Step 4 (Finalize) — from `overview.md` and directory structure
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* collector.ts
|
||||
* Reads finished project artifacts and writes a RunMetrics JSON file.
|
||||
* Zero dependency on plan2code-loop internals — reads files directly.
|
||||
* Reads the spec files directly; no dependency on other plan2code packages.
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Unified LLM invocation for plan2code-metrics.
|
||||
* Supports Claude Code (temp file → stdin), Copilot CLI (stdin string), and
|
||||
* Devin CLI (temp prompt file).
|
||||
* Mirrors the agent pattern from plan2code-loop.
|
||||
* Each supported agent is one AgentDef: a presence check plus an invoke call.
|
||||
*/
|
||||
|
||||
import { execa } from 'execa';
|
||||
|
||||
@@ -65,7 +65,7 @@ async function runUpdate(steps) {
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
try {
|
||||
const code = await installer.update({ steps });
|
||||
const code = await installer.update({ steps, cleanShims: () => {} });
|
||||
return { code, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") };
|
||||
} finally {
|
||||
console.log = log;
|
||||
@@ -76,12 +76,12 @@ test("install record: recordInstalled and forgetInstalled round trip a sorted se
|
||||
clearRecord();
|
||||
assert.equal(installer.INSTALL_RECORD, RECORD);
|
||||
assert.equal(installer.readInstallRecord(), null);
|
||||
installer.recordInstalled("loop");
|
||||
installer.recordInstalled("metrics");
|
||||
installer.recordInstalled("skills");
|
||||
installer.recordInstalled("skills");
|
||||
installer.recordInstalled("not-a-piece");
|
||||
assert.deepEqual(installer.readInstallRecord(), { version: VERSION, scope: "global", pieces: ["loop", "skills"] });
|
||||
installer.forgetInstalled("loop");
|
||||
assert.deepEqual(installer.readInstallRecord(), { version: VERSION, scope: "global", pieces: ["metrics", "skills"] });
|
||||
installer.forgetInstalled("metrics");
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, ["skills"]);
|
||||
installer.forgetInstalled("skills");
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, []);
|
||||
@@ -112,26 +112,26 @@ test("update: with no record it says so and updates the skills and the plan2code
|
||||
});
|
||||
|
||||
test("update: a partial record runs only the listed pieces, in order, unattended", async () => {
|
||||
writeRecord(["loop", "statusline"]);
|
||||
writeRecord(["bot", "statusline"]);
|
||||
const fake = fakeSteps();
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.deepEqual(fake.ran(), ["statusline", "loop"]);
|
||||
assert.deepEqual(fake.ran(), ["statusline", "bot"]);
|
||||
for (const call of fake.calls) assert.equal(call.options.unattended, true, call.piece);
|
||||
assert.doesNotMatch(out, /No install record/);
|
||||
assert.doesNotMatch(out, /skills:/);
|
||||
});
|
||||
|
||||
test("update: a failing piece exits 1 naming it, and the others still run", async () => {
|
||||
writeRecord(["skills", "launcher", "loop", "metrics", "bot"]);
|
||||
const fake = fakeSteps({ codes: { loop: 1 }, throws: { metrics: "npm exploded" } });
|
||||
writeRecord(["skills", "launcher", "statusline", "metrics", "bot"]);
|
||||
const fake = fakeSteps({ codes: { statusline: 1 }, throws: { metrics: "npm exploded" } });
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 1, out);
|
||||
assert.deepEqual(fake.ran(), ["skills", "loop", "metrics", "bot"]);
|
||||
assert.match(out, /loop: failed: /);
|
||||
assert.deepEqual(fake.ran(), ["skills", "statusline", "metrics", "bot"]);
|
||||
assert.match(out, /statusline: failed: /);
|
||||
assert.match(out, /metrics: failed: npm exploded/);
|
||||
assert.match(out, /bot: updated/);
|
||||
assert.match(out, /Update failed for: loop, metrics/);
|
||||
assert.match(out, /Update failed for: statusline, metrics/);
|
||||
});
|
||||
|
||||
test("update: when the skills install leaves the command out, the launcher step runs on its own", async () => {
|
||||
@@ -351,7 +351,7 @@ test("app update: plan2code update replaces an older app and reports it", { skip
|
||||
const server = await releaseServer(goodRelease(bytes));
|
||||
try {
|
||||
// The real app step, in the real update loop; the record lists only the app.
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS }));
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.match(out, /app: updated/);
|
||||
assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes);
|
||||
@@ -366,7 +366,7 @@ test("app update: a checksum mismatch fails the update naming the app, nothing e
|
||||
writeRecord(["app"]);
|
||||
const server = await releaseServer(goodRelease(Buffer.from("tampered bytes"), "1".repeat(64)));
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS }));
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} }));
|
||||
assert.equal(result, 1);
|
||||
assert.match(out, /Update failed for: app/);
|
||||
} finally {
|
||||
@@ -382,7 +382,7 @@ test("app update: a release with no app file yet keeps the installed app and doe
|
||||
// main moves to a new version before the release's files are attached: every file is a 404.
|
||||
const server = await releaseServer({});
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS }));
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.match(out, /app: kept/);
|
||||
assert.doesNotMatch(out, /Update failed/);
|
||||
|
||||
@@ -100,12 +100,6 @@ test("Quick Task and Review name the tests covering the changed files", () => {
|
||||
assert.match(src("plan2code-review.md"), /\*\*Verify\*\* -- build and run the tests covering the fixed files \(per `references\/test-runs\.md`/);
|
||||
});
|
||||
|
||||
test("the loop prompt points at the tests the task or phase file lists", () => {
|
||||
const tpl = fs.readFileSync(path.join(ROOT, "plan2code-loop", "src", "prompt", "templates.ts"), "utf8");
|
||||
assert.equal(tpl.split("run the tests the task or phase file lists").length - 1, 2);
|
||||
assert.ok(!tpl.includes("if applicable"));
|
||||
});
|
||||
|
||||
test("Finalize offers the full suite, skips it for Never and records the four outcomes", () => {
|
||||
const fin = src("plan2code-4-finalize.md");
|
||||
assert.ok(fin.includes("Run the full suite now?"), "Finalize asks the question");
|
||||
|
||||
@@ -1603,3 +1603,35 @@ test("Ghoul Rush's weapons all draw and every sound they name exists", () => {
|
||||
}
|
||||
assert.ok(round.score >= 0);
|
||||
});
|
||||
|
||||
test("Ghoul Rush's Dynamite, Road Flare, Salt and Flash Powder are aimed: they land on the first monster ahead, or the middle of the group around it, and fly the old fixed throw with nothing ahead", () => {
|
||||
const landsAt = (kind, setup, tail) => {
|
||||
const round = roomOf("village", "inn");
|
||||
standAt(round, 40);
|
||||
give(round, kind, 3);
|
||||
setup(round);
|
||||
tapTap(round);
|
||||
const hz = round.hazards.find((h) => ["stick", "armRoadFlare", "armPod"].includes(h.kind));
|
||||
assert.ok(hz, `${kind} thrown`);
|
||||
for (let i = 0; i < 400 && round.hazards.includes(hz) && !hz.rest; i++) run(round, 16);
|
||||
return hz.x;
|
||||
};
|
||||
const still = (round, x) => put(round, "zombie", x, { stunMs: 1e9 });
|
||||
for (const kind of ["dyn", "flare", "salt", "flash"]) {
|
||||
const lone = landsAt(kind, (r) => still(r, 70));
|
||||
assert.ok(Math.abs(lone - 70) < (kind === "salt" || kind === "flash" ? 8 : 2), `${kind} lands on a lone monster (${lone})`);
|
||||
const group = landsAt(kind, (r) => { still(r, 62); still(r, 66); still(r, 70); still(r, 130); });
|
||||
assert.ok(Math.abs(group - 66) < (kind === "salt" || kind === "flash" ? 8 : 2), `${kind} lands in the middle of the group (${group})`);
|
||||
const behind = landsAt(kind, (r) => still(r, 10));
|
||||
const none = landsAt(kind, () => {});
|
||||
assert.ok(Math.abs(behind - none) < 0.5, `${kind} ignores what is behind`);
|
||||
}
|
||||
// The Creampie keeps its fixed lob.
|
||||
const pie = roomOf("village", "inn");
|
||||
standAt(pie, 40);
|
||||
give(pie, "pie", 3);
|
||||
put(pie, "zombie", 62, { stunMs: 1e9 });
|
||||
tapTap(pie);
|
||||
const lob = pie.hazards.find((h) => h.kind === "armPie");
|
||||
assert.ok(lob && Math.abs(lob.vx - arm.PIE_VX) < 1e-9, "the pie is not aimed");
|
||||
});
|
||||
@@ -614,7 +614,7 @@ test("Ghoul Rush's Mirror You fires a bolt for each bolt you fire, 500 ms late,
|
||||
};
|
||||
assert.equal(hit(false), "mirrorbolt", "a bolt on a standing you");
|
||||
assert.equal(hit(true), undefined, "a bolt over a ducked you");
|
||||
// Cancelling: your bolt and its bolt meet in the air.
|
||||
// Canceling: your bolt and its bolt meet in the air.
|
||||
const meet = carnivalRound("mirrors");
|
||||
standAt(meet, 50);
|
||||
meet.you.safeMs = 1e9;
|
||||
|
||||
@@ -96,7 +96,7 @@ Nothing decided in the range? Keep the file honest: "No decisions were recorded
|
||||
|
||||
- **Zero pathfinder machinery in the file.** No `NN` numbers, no markers, no `Type:`/`State:` tokens, no fog/frontier/grill vocabulary, no `Locked:`. Questions are referred to by name only, no links. The audience may never open a terminal.
|
||||
- **Scraper safety, same as the PLAN-DRAFT:** no `%`, no raw `NN/25` scores, and no bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number anywhere in the file. The plain-English confidence line is the only rendering permitted.
|
||||
- **Standing `specs/` rules apply:** no loop tokens, no `- [ ]` checkboxes, no `METRICS_JSON`.
|
||||
- **Standing `specs/` rules apply:** no completion-marker tokens, no `- [ ]` checkboxes, no `METRICS_JSON`.
|
||||
- **Rejections are one line each.** The brief summarizes; the question file argues. The closing pointer line covers readers who want the full reasoning.
|
||||
- **BRIEF mode does not count as question work.** It does not count toward the session's decision cadence; no claim is ever taken.
|
||||
- **Do not edit an old brief to "update" it.** Yesterday's brief reflects yesterday's map — write today's instead. Same-day overwrite only.
|
||||
@@ -116,7 +116,7 @@ Consequences of that being a literal string match:
|
||||
|
||||
**Discovery is shell-only.** `specs/` is gitignored, so Glob silently returns nothing and every downstream skill would report "no PLAN-DRAFT found". Use `ls specs/` and `ls specs/<idea>/` (Bash) or `Get-ChildItem specs/` (PowerShell) — the same rule 1-plan and `/plan2code-2-document` follow when they look for the file you are about to write.
|
||||
|
||||
**Do not append `## Planning Metrics` or any metrics comment.** Pathfinder is not a metered step. 1-plan's Phase 7 owns that block and will add it when it finishes the plan. Do not emit any of the loop's completion tokens listed in the skill's Rules anywhere under `specs/`.
|
||||
**Do not append `## Planning Metrics` or any metrics comment.** Pathfinder is not a metered step. 1-plan's Phase 7 owns that block and will add it when it finishes the plan. Do not emit any of the completion tokens listed in the skill's Rules anywhere under `specs/`.
|
||||
|
||||
## Map to PLAN-DRAFT mapping
|
||||
|
||||
|
||||
@@ -1033,7 +1033,7 @@ async function cmdLint(loc) {
|
||||
if (!/\.(md|txt|json|ya?ml|csv)$/i.test(f)) continue;
|
||||
const t = readText(f) || "";
|
||||
const m = t.match(LOOP_TOKENS);
|
||||
if (m) add("error", f, `contains the loop completion token ${m[0]} (the loop scans specs/ for these)`);
|
||||
if (m) add("error", f, `contains the loop completion token ${m[0]} (reserved; these never belong under specs/)`);
|
||||
}
|
||||
// Reserved names inside pathfinder/.
|
||||
for (const f of walk(loc.pf)) {
|
||||
|
||||
@@ -45,7 +45,7 @@ Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it
|
||||
- **Questions are ground truth; the map is a rebuildable index.** A filled `## Answer` beats any state marker; detail lives in one place.
|
||||
- **Never write implementation code** into the project. Sketches are throwaway, living only under `pathfinder/sketch-NN/`.
|
||||
- **Reserved names — never create inside `pathfinder/`:** `overview.md`, `phase-<N>.md`, `PLAN-DRAFT-*.md`, `PLAN-CONVERSATION-*.md`.
|
||||
- **Never emit the loop's completion tokens under `specs/`** — `TASK_COMPLETE`, `PHASE_COMPLETE`, `ALL_TASKS_COMPLETE`, `IMPLEMENTATION_COMPLETE`, `SPEC_COMPLETE`, `WORK_COMPLETE`. It scans for them.
|
||||
- **Never emit completion tokens under `specs/`** — `TASK_COMPLETE`, `PHASE_COMPLETE`, `ALL_TASKS_COMPLETE`, `IMPLEMENTATION_COMPLETE`, `SPEC_COMPLETE`, `WORK_COMPLETE`. They are reserved; a stray one would read as a finished run.
|
||||
- **No `- [ ]` checkboxes inside question files**, and no `METRICS_JSON` anywhere.
|
||||
- **Lint before every Session End** (on `github`, once a brief or PLAN-DRAFT is on local disk; it checks those): `lint` checks the rules above, the schema lines, `Blocked by:` targets and cycles, and metrics-scraper bait. Fix every error it lists (exit 4) before you stop.
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ No `specs/` activity this session? Skip this section entirely.
|
||||
## What to include
|
||||
|
||||
Keep it tight and high-signal. Prefer pointers over prose: this repo already
|
||||
records a lot (plan specs, the loop's NDJSON logs, git history, diffs), so
|
||||
records a lot (plan specs, the loop's reports, git history, diffs), so
|
||||
**reference those by path or URL instead of copying them in**. The reader can
|
||||
open a file; they can't open your memory.
|
||||
|
||||
@@ -96,7 +96,7 @@ them. Note anything half-applied or left uncommitted.>
|
||||
|
||||
## Key files & pointers
|
||||
<Bulleted paths the reader will need, each with a one-line "why". Include plan
|
||||
specs, the files you were editing, relevant logs (e.g. .plan2code-loop NDJSON),
|
||||
specs, the files you were editing, relevant logs (e.g. `specs/<feature>/LOOP-SUMMARY-<date>.md`, `~/.plan2code/console/loop-reports.json`),
|
||||
and any PR/issue URLs.>
|
||||
|
||||
## Gotchas & decisions
|
||||
|
||||
@@ -212,8 +212,8 @@ export function rel(root, p) {
|
||||
|
||||
/* ------------------------------------------------- planning-file patterns */
|
||||
|
||||
// The loop completion markers. The loop scans specs/ for them, so no planning
|
||||
// file may contain one. The one copy every skill script checks against.
|
||||
// The loop completion markers, reserved outright so nothing under specs/ can
|
||||
// fake a finished run. The one copy every skill script checks against.
|
||||
export const LOOP_TOKENS = /\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
|
||||
|
||||
// The metrics collector's own scrape patterns (plan2code-metrics/src/collector.ts).
|
||||
|
||||
@@ -773,7 +773,7 @@ const CONFIDENCE_HITS = ["overall confidence with %", "confidence table cell"];
|
||||
|
||||
function proseChecks(text, file, add, { allowConfidence = false } = {}) {
|
||||
const m = text.match(LOOP_TOKENS);
|
||||
if (m) add("error", file, "loop-token", `contains the loop completion token ${m[0]} (the loop scans specs/ for these)`);
|
||||
if (m) add("error", file, "loop-token", `contains the loop completion token ${m[0]} (reserved; these never belong under specs/)`);
|
||||
for (const h of scrapeHits(text.replace(METRICS_COMMENT_RE, ""))) {
|
||||
if (allowConfidence && CONFIDENCE_HITS.some((name) => h.startsWith(`${name}:`))) continue;
|
||||
add("error", file, "metric-word", `metrics-scraper bait (${h}); hyphenate the label or reword`);
|
||||
|
||||
@@ -80,7 +80,7 @@ Every note in an item's `thread` gets a reply: `{"id":"p4","thread":[{"who":"age
|
||||
- more than three open required questions at once (optional cards and notices do not count)
|
||||
- internal vocabulary in a title (grill, frontier, fog, HITL, AFK, durable, `Locked:`, `Blocked by:`, `State:`)
|
||||
- more than one recommended option on a question
|
||||
- loop completion markers (`TASK_COMPLETE`, `PHASE_COMPLETE` and the rest)
|
||||
- loop completion markers, reserved so agent text can never fake a done signal (`TASK_COMPLETE`, `PHASE_COMPLETE` and the rest)
|
||||
- a bare Requirements, Feasibility, Integration or Risk followed by a number (hyphenate or reword)
|
||||
- a doc `version` that goes back (leave `version` out)
|
||||
- a finish `command` with `<` or `>` in it
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
// session state ~/.plan2code/console/sessions/<sid>/
|
||||
// the request, the human's draft, the result, the event log.
|
||||
// Deliberately NOT under specs/: that keeps the console clear of
|
||||
// the metrics confidence scraper and the loop's completion-marker
|
||||
// parser, and it survives a `git clean`.
|
||||
// the metrics confidence scraper and completion-marker parsers,
|
||||
// and it survives a `git clean`.
|
||||
//
|
||||
// Node built-ins only. No build step.
|
||||
|
||||
|
||||
@@ -130,11 +130,14 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
// A whole new question under an answered card's id is not a typo fix: the
|
||||
// card would stay answered and nothing would be left for the person, who
|
||||
// sees a dead page. Refuse it so the agent picks a new id on the spot.
|
||||
// A change of kind is not this case: the merge below reopens it as a new
|
||||
// question on its own, so nothing stays answered.
|
||||
if (
|
||||
prev &&
|
||||
(prev.status === "answered" || prev.status === "skipped") &&
|
||||
!("status" in entry) &&
|
||||
!("answer" in entry) &&
|
||||
(!("kind" in entry) || entry.kind === prev.kind) &&
|
||||
"title" in entry &&
|
||||
entry.title !== prev.title &&
|
||||
(("body" in entry && entry.body !== prev.body) ||
|
||||
@@ -583,7 +586,7 @@ export function applyPatch(state, patch) {
|
||||
}
|
||||
if (settle !== undefined) next.items = settleItems(next.items || [], settle, patch.items, state.collected);
|
||||
// A question put to the person over a standing ending means the work went
|
||||
// on past it: the finish card would grey the form out, and the person has
|
||||
// on past it: the finish card would gray the form out, and the person has
|
||||
// no way to answer. The ending comes down unless this patch posts its own.
|
||||
if (next.finish && !Object.hasOwn(patch, "finish") && asksSomething(patch.items, state.items)) {
|
||||
delete next.finish;
|
||||
@@ -660,9 +663,10 @@ const JARGON = [
|
||||
/\bState:\s/,
|
||||
];
|
||||
|
||||
// The loop parses these out of agent output; pathfinder forbids them under specs/.
|
||||
// The other copy is LOOP_TOKENS in src/skill-scripts/common.mjs: the console is
|
||||
// not a skill script and cannot import it, so keep the two in step.
|
||||
// Completion markers refused outright, so agent text can never fake a done
|
||||
// signal; pathfinder forbids them under specs/. The other copy is LOOP_TOKENS
|
||||
// in src/skill-scripts/common.mjs: the console is not a skill script and
|
||||
// cannot import it, so keep the two in step.
|
||||
const FORBIDDEN_TOKENS =
|
||||
/\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
|
||||
|
||||
@@ -679,7 +683,7 @@ export function proseProblems(prose, subject = "text") {
|
||||
const marker = prose.match(FORBIDDEN_TOKENS);
|
||||
if (marker) {
|
||||
problems.push(
|
||||
rule("", subject, `contains a loop completion marker (${marker[0]}); the loop scans for these. Reword it`, marker[0].toLowerCase().replaceAll("_", " ")),
|
||||
rule("", subject, `contains a loop completion marker (${marker[0]}); these are reserved. Reword it`, marker[0].toLowerCase().replaceAll("_", " ")),
|
||||
);
|
||||
}
|
||||
const bait = prose.match(METRICS_BAIT);
|
||||
|
||||
@@ -254,13 +254,20 @@ export function armsArt(d) {
|
||||
ctx.translate(s.x, y);
|
||||
const heading = Math.atan2(-s.vy, s.vx);
|
||||
if (s.arm === "stake") {
|
||||
// A streak behind it, then the iron, its point leading.
|
||||
// A glow and a streak behind it, then a big iron stake, its point leading,
|
||||
// so it never reads as an ordinary bolt.
|
||||
ctx.rotate(heading);
|
||||
ctx.strokeStyle = "rgba(190, 210, 230, 0.4)";
|
||||
ctx.lineWidth = 0.6;
|
||||
line(ctx, -5, 0, -1.2, 0);
|
||||
ctx.scale(1.25, 1.25);
|
||||
stakeShape(ctx, "#d4e0ec");
|
||||
ctx.fillStyle = "rgba(190, 220, 255, 0.22)";
|
||||
circle(ctx, 0, 0, 3.6);
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = "rgba(190, 210, 230, 0.5)";
|
||||
ctx.lineWidth = 1.5;
|
||||
line(ctx, -11, 0, -3.6, 0);
|
||||
ctx.scale(3.2, 3.2);
|
||||
stakeShape(ctx, "#e4eef8");
|
||||
ctx.strokeStyle = "#3a4654";
|
||||
ctx.lineWidth = 0.07;
|
||||
ctx.stroke();
|
||||
} else if (s.arm === "sickle") {
|
||||
ctx.rotate(s.spin);
|
||||
ctx.scale(1.45, 1.45);
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
|
||||
import { ARM_POP_MS, POWERS, STAGE_ARMS, addArm } from "./ghoul-powers.js";
|
||||
import { stepPans, usePans } from "./ghoul-pans.js";
|
||||
import { stepFlareFly, stepRoadFire, useFlare } from "./ghoul-flare.js";
|
||||
import { FLARE_VX, FLARE_VY, stepFlareFly, stepRoadFire, useFlare } from "./ghoul-flare.js";
|
||||
import { stepBoom, stepMuzzle, stepRocket, useRockets } from "./ghoul-rockets.js";
|
||||
|
||||
const freeze = Object.freeze;
|
||||
@@ -77,8 +77,8 @@ export const BLAST_DAMAGE = 20;
|
||||
export const DYN_BOSS_DMG = 8;
|
||||
// The Iron Stake: pierces a whole line, chest high.
|
||||
export const STAKE_SPEED = 96;
|
||||
export const STAKE_DMG = 4;
|
||||
export const STAKE_BOSS = 4;
|
||||
export const STAKE_DMG = 12;
|
||||
export const STAKE_BOSS = 8;
|
||||
// The Bottle Rocket: three at once, ahead, up and behind (ghoul-rockets.js).
|
||||
export * from "./ghoul-rockets.js";
|
||||
// The Hedge Sickle: SICKLE_OUT out and back, SICKLE_DMG a pass.
|
||||
@@ -271,18 +271,51 @@ function armShot(round, k, arm, speed, over) {
|
||||
round.shots.push({ arm, x: at.x, y: at.y, vx: Math.cos(aim) * speed * you.face, vy: Math.sin(aim) * speed, gone: 0, t: 0, spin: 0, ...over });
|
||||
}
|
||||
|
||||
// Aimed lobs (Dynamite, the Road Flare): the first monster ahead in view, or, when others
|
||||
// stand within LOB_GROUP of it, the middle of that group, so one blast or fire
|
||||
// catches as many as it can. The sideways speed is solved so the throw lands there
|
||||
// (clamped to LOB_MIN_VX..LOB_MAX_VX); with nothing ahead it is the old fixed throw.
|
||||
export const LOB_GROUP = 9;
|
||||
const LOB_MIN_VX = 6;
|
||||
const LOB_MAX_VX = 70;
|
||||
|
||||
// `also` names kinds that count though they cannot be shot (the buried hands the salt is for).
|
||||
export function lobTarget(round, k, also = []) {
|
||||
const you = round.you;
|
||||
const lo = round.camX;
|
||||
const hi = round.camX + k.FIELD_W;
|
||||
const ahead = round.monsters
|
||||
.filter((m) => !m.dead && (k.solid(m) || k.stone(m) || also.includes(m.kind)) && (m.x - you.x) * you.face > 1 && m.x >= lo && m.x <= hi)
|
||||
.sort((a, b) => Math.abs(a.x - you.x) - Math.abs(b.x - you.x));
|
||||
if (!ahead.length) return null;
|
||||
const first = ahead[0];
|
||||
const group = ahead.filter((m) => Math.abs(m.x - first.x) <= LOB_GROUP);
|
||||
return group.reduce((sum, m) => sum + m.x, 0) / group.length;
|
||||
}
|
||||
|
||||
export function lobVx(round, k, vy, fixed, also) {
|
||||
const tx = lobTarget(round, k, also);
|
||||
if (tx === null) return round.you.face * fixed;
|
||||
const at = hand(round, k);
|
||||
const dy = k.groundAt(round.spec, tx) - at.y;
|
||||
const disc = vy * vy + 2 * k.BONE_G * dy;
|
||||
const t = disc > 0 ? (vy + Math.sqrt(disc)) / k.BONE_G : (2 * vy) / k.BONE_G;
|
||||
const vx = Math.min(LOB_MAX_VX, Math.max(LOB_MIN_VX, Math.abs(tx - at.x) / t));
|
||||
return round.you.face * vx;
|
||||
}
|
||||
|
||||
function lobStick(round, k) {
|
||||
const you = round.you;
|
||||
const at = hand(round, k);
|
||||
round.hazards.push({ kind: "stick", x: at.x, y: at.y, vx: you.face * DYN_VX, vy: DYN_VY, fuse: DYN_FUSE_MS, max: DYN_FUSE_MS, spin: 0, rest: false, w: 0.8, h: 0.8, live: 0, cause: "dynamite" });
|
||||
round.hazards.push({ kind: "stick", x: at.x, y: at.y, vx: lobVx(round, k, DYN_VY, DYN_VX), vy: DYN_VY, fuse: DYN_FUSE_MS, max: DYN_FUSE_MS, spin: 0, rest: false, w: 0.8, h: 0.8, live: 0, cause: "dynamite" });
|
||||
// The Mine's art plays Dynamite's own sound from this one.
|
||||
round.events.push({ type: "dynThrow", x: at.x, y: at.y, face: you.face });
|
||||
}
|
||||
|
||||
function lobPod(round, k, pay) {
|
||||
function lobPod(round, k, pay, aimed = false) {
|
||||
const you = round.you;
|
||||
const at = hand(round, k);
|
||||
round.hazards.push({ kind: "armPod", pay, x: at.x, y: at.y, vx: you.face * POD_VX, vy: POD_VY, spin: 0, w: 0.8, h: 0.8, live: 0, cause: "" });
|
||||
round.hazards.push({ kind: "armPod", pay, x: at.x, y: at.y, vx: aimed ? lobVx(round, k, POD_VY, POD_VX, ["hands"]) : you.face * POD_VX, vy: POD_VY, spin: 0, w: 0.8, h: 0.8, live: 0, cause: "" });
|
||||
}
|
||||
|
||||
function lobPie(round, k) {
|
||||
@@ -305,10 +338,10 @@ const USES = freeze({
|
||||
const you = round.you;
|
||||
round.hazards.push({ kind: "armRing", x: you.x, y: you.y + k.HIT_H / 2, r: 0, life: RING_MS, max: RING_MS, hit: [], hitPipe: [], hitBoss: false, w: 1, h: 1, live: 0, cause: "" });
|
||||
},
|
||||
salt: (round, k) => lobPod(round, k, "salt"),
|
||||
flash: (round, k) => lobPod(round, k, "flash"),
|
||||
salt: (round, k) => lobPod(round, k, "salt", true),
|
||||
flash: (round, k) => lobPod(round, k, "flash", true),
|
||||
pie: lobPie,
|
||||
flare: useFlare,
|
||||
flare: (round, k) => useFlare(round, k, lobVx(round, k, FLARE_VY, FLARE_VX)),
|
||||
trap: (round) => {
|
||||
const you = round.you;
|
||||
// Five at once, TRAP_GAP apart: two behind, one at his feet, two ahead.
|
||||
|
||||
@@ -278,7 +278,7 @@ function record(round, tw, ms) {
|
||||
tw.seq++;
|
||||
}
|
||||
|
||||
// Mirror You's bolts in flight: cancelling yours, or striking you.
|
||||
// Mirror You's bolts in flight: canceling yours, or striking you.
|
||||
function stepBolts(round, tw, ms, k) {
|
||||
const you = round.you;
|
||||
const dt = ms / 1000;
|
||||
|
||||
@@ -26,7 +26,7 @@ const PIPS = Object.freeze([
|
||||
|
||||
// The panel the big die rolls on, and the die in it.
|
||||
const PANEL_W = 44;
|
||||
const PANEL_H = 34;
|
||||
const PANEL_H = 40;
|
||||
const DIE_SIZE = 15;
|
||||
// Candidate spots for the panel's middle, tried in order: the field's middle
|
||||
// first, then to either side; a row high on the field and one low.
|
||||
@@ -108,7 +108,7 @@ export function diceArt(d) {
|
||||
ctx.strokeStyle = lucky ? GOLD : "rgba(255, 255, 255, 0.35)";
|
||||
ctx.lineWidth = lucky ? 0.6 : 0.3;
|
||||
ctx.stroke();
|
||||
const at = y - 3;
|
||||
const at = y - 6;
|
||||
let face;
|
||||
let size = DIE_SIZE;
|
||||
let angle = 0;
|
||||
@@ -141,7 +141,12 @@ export function diceArt(d) {
|
||||
text = r.heart ? `A ${r.face} on your last heart: +1 heart!` : wasted ? `A ${r.face}, and no lives left` : DICE_FACES[r.face].line;
|
||||
color = lucky ? GOLD : DICE_FACES[r.face].gift && !wasted ? "#ffffff" : DANGER;
|
||||
}
|
||||
label(ctx, text, x, y + 12, 2.7, color, "center", PANEL_W - 3);
|
||||
label(ctx, text, x, y + 9.5, 2.7, color, "center", PANEL_W - 3);
|
||||
// After the roll, what is left in hand (the roll has already taken its die).
|
||||
if (r.landed) {
|
||||
const n = v.round.dice;
|
||||
label(ctx, `You have ${n} Lucky ${n === 1 ? "Die" : "Dice"} left!`, x, y + 15, 2.3, "#8fd8ff", "center", PANEL_W - 3);
|
||||
}
|
||||
}
|
||||
|
||||
// What each step of the roll looks and sounds like (house tones for now);
|
||||
|
||||
@@ -35,7 +35,7 @@ export const DICE_FACES = Object.freeze({
|
||||
5: Object.freeze({ revive: true, give: Object.freeze(["life"]), line: "Back to life, +1 heart!", word: "+1 heart!" }),
|
||||
6: Object.freeze({ revive: true, give: Object.freeze(["life", "garlic"]), line: "Back to life, +1 heart + Garlic!", word: "+1 heart + Garlic!" }),
|
||||
});
|
||||
export const ROLL_MS = 1900;
|
||||
export const ROLL_MS = 3200;
|
||||
export const TUMBLE_MS = 600;
|
||||
// The clock a saved time-up gets back.
|
||||
export const SAVED_TIME_MS = 15000;
|
||||
|
||||
@@ -37,10 +37,11 @@ export const FLARE_SHOW_MS = 300;
|
||||
const inBox = (m, x0, x1, y0, y1) => m.x + m.w / 2 >= x0 && m.x - m.w / 2 <= x1 && m.y + m.h >= y0 && m.y <= y1;
|
||||
|
||||
// The throw: from his hand, ahead.
|
||||
export function useFlare(round, k) {
|
||||
// `vx` is the signed sideways speed (ghoul-arms.js aims it at the monsters ahead).
|
||||
export function useFlare(round, k, vx = round.you.face * FLARE_VX) {
|
||||
const you = round.you;
|
||||
const at = { x: you.x + you.face * 1.8, y: you.y + k.shotY(you) };
|
||||
round.hazards.push({ kind: "armRoadFlare", x: at.x, y: at.y, vx: you.face * FLARE_VX, vy: FLARE_VY, spin: 0, rest: false, t: 0, w: 0.8, h: 0.8, live: 0, cause: "" });
|
||||
round.hazards.push({ kind: "armRoadFlare", x: at.x, y: at.y, vx, vy: FLARE_VY, spin: 0, rest: false, t: 0, w: 0.8, h: 0.8, live: 0, cause: "" });
|
||||
round.events.push({ type: "flareThrow", x: at.x, y: at.y, face: you.face });
|
||||
}
|
||||
|
||||
|
||||
@@ -686,7 +686,7 @@ export function frozenWorld(d) {
|
||||
ctx.fillRect(x0, fy, w, 0.62);
|
||||
ctx.fillStyle = "rgba(255, 255, 255, 0.85)";
|
||||
ctx.fillRect(x0 + 0.2, fy + 0.06, w - 0.4, 0.14);
|
||||
// A green-grey tint as it weakens, and hairlines that lengthen with the weight on it.
|
||||
// A green-gray tint as it weakens, and hairlines that lengthen with the weight on it.
|
||||
ctx.fillStyle = rgba("#2a5a70", 0.2 + 0.4 * prog);
|
||||
ctx.fillRect(x0, fy + 0.62, w, 0.5);
|
||||
const lines = Math.ceil(prog * 7);
|
||||
|
||||
@@ -292,7 +292,7 @@ export function graveyardArt(d) {
|
||||
}
|
||||
}
|
||||
|
||||
// Grasping hands: under the dirt a trembling mound; then two grey arms
|
||||
// Grasping hands: under the dirt a trembling mound; then two gray arms
|
||||
// burst up and claw at the air, and sink again.
|
||||
function hands(ctx, v, m, x, y, t, flash) {
|
||||
if (m.act === "lurk" || m.act === "creep") return mound(ctx, x, y, t, m.act === "creep");
|
||||
@@ -429,7 +429,7 @@ export function graveyardArt(d) {
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
}
|
||||
// A long grey face under the hat, a grin of teeth.
|
||||
// A long gray face under the hat, a grin of teeth.
|
||||
ctx.fillStyle = flash ? FLASH : "#8a8e80";
|
||||
ellipse(ctx, d * 0.35, -4.4, 0.8, 0.85);
|
||||
ctx.fill();
|
||||
|
||||
@@ -428,7 +428,7 @@ export function groundsArt(d) {
|
||||
}
|
||||
}
|
||||
|
||||
// A long party table under a cloth gone grey, set for guests who never
|
||||
// A long party table under a cloth gone gray, set for guests who never
|
||||
// left: plates, a tipped glass, candle stubs and a cake gone to mold.
|
||||
function partyTable(ctx, x, fy, n) {
|
||||
const w = 11;
|
||||
@@ -840,7 +840,7 @@ export function groundsArt(d) {
|
||||
|
||||
// A shelf in the room's own terms, its top surface at screen y `y`: a
|
||||
// hanging block of hedge in the maze, an ivy-grown stone ledge in the
|
||||
// topiary garden, a table under a grey cloth or a shingled roof in the
|
||||
// topiary garden, a table under a gray cloth or a shingled roof in the
|
||||
// gazebo, a weathered plank on posts in the yard.
|
||||
function shelf(ctx, v, look, a, b, y) {
|
||||
const { spec, g } = v;
|
||||
@@ -916,7 +916,7 @@ export function groundsArt(d) {
|
||||
ellipse(ctx, lx, y + 5.4, 0.9, 1.1);
|
||||
ctx.fill();
|
||||
} else if (look.scene === "gazebo") {
|
||||
// A table: a grey cloth with a scalloped hem over dark legs.
|
||||
// A table: a gray cloth with a scalloped hem over dark legs.
|
||||
ctx.fillStyle = "#12100c";
|
||||
for (const s of [a + 1.2, b - 1.8]) ctx.fillRect(s, y + 1, 0.6, Math.max(1, fy - y - 1));
|
||||
ctx.fillStyle = "#c8c3ae";
|
||||
|
||||
@@ -192,7 +192,7 @@ export function mineArt(d) {
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
// A knocker imp: a wiry, hunched mine goblin, green-grey, with great ears swept
|
||||
// A knocker imp: a wiry, hunched mine goblin, green-gray, with great ears swept
|
||||
// back, a hooked nose, a grin and big amber eyes, a tiny pick in his fist. Running
|
||||
// (skitter, flee) his legs blur and he leans into it; with the stolen spark he
|
||||
// cups it in both hands, giggling; the decoy paces with the Tommyknocker's lantern
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
export const FROZEN_SFX = {
|
||||
tones: {
|
||||
// Frozen Lake picks, by ear (prototypes/sounds/ghoul-rush/frozen.html).
|
||||
// Under-Ice Hand: A grey hand that trails you under the ice, cracks thin ice open beneath you, or bursts up through the floor to grab.
|
||||
// Under-Ice Hand: A gray hand that trails you under the ice, cracks thin ice open beneath you, or bursts up through the floor to grab.
|
||||
// Slides in: Scrabbling fingernails.
|
||||
ghoulIceHandAppear: {
|
||||
layers: [
|
||||
|
||||
@@ -10,7 +10,7 @@ export const GRAVEYARD_SFX = {
|
||||
tones: {
|
||||
// The Graveyard's monsters and Mother Mourning, picked the same way
|
||||
// (prototypes/sounds/ghoul-rush/graveyard.html).
|
||||
// Grasping Hands: Grey arms that burst up out of the dirt and grab.
|
||||
// Grasping Hands: Gray arms that burst up out of the dirt and grab.
|
||||
// Stirs under the dirt: Low earth rumble.
|
||||
ghoulHandsAppear: {
|
||||
layers: [
|
||||
|
||||
@@ -402,7 +402,7 @@ export function villageArt(d) {
|
||||
/* --------------------------------------------------------- hanged man */
|
||||
|
||||
// A hanged man: a rope from the beam to a noose, the neck bent, the head
|
||||
// lolling, grey shirt and trousers, bare feet turning, arms limp; he swings on
|
||||
// lolling, gray shirt and trousers, bare feet turning, arms limp; he swings on
|
||||
// his rope, creaks before he drops, flings his arms up as he falls, bounces at the
|
||||
// rope's end and kicks as he is hauled up.
|
||||
function hanged(ctx, v, m, x, y, t, flash) {
|
||||
@@ -533,7 +533,7 @@ export function villageArt(d) {
|
||||
}
|
||||
}
|
||||
|
||||
// A ghoul in a window: gaunt grey, nightshirt, long black hair, a mouth full of
|
||||
// A ghoul in a window: gaunt gray, nightshirt, long black hair, a mouth full of
|
||||
// needles, eyes burning; when it lunges its neck and arms stretch out from the
|
||||
// window to where it reaches, hands clawed and grasping.
|
||||
function shutter(ctx, v, m, x, y, t, flash) {
|
||||
@@ -657,7 +657,7 @@ export function villageArt(d) {
|
||||
|
||||
/* ----------------------------------------------------------- moonhound */
|
||||
|
||||
// A moonhound: a gaunt wolfhound, ribs and spine showing, long legs, silver-grey
|
||||
// A moonhound: a gaunt wolfhound, ribs and spine showing, long legs, silver-gray
|
||||
// coat; trotting, coiled with its hackles up, stretched in its leap, panting after
|
||||
// it, or cowering from Wolfsbane (ears flat, tail between its legs, low). Grown,
|
||||
// it is half again as big with a mane that glows.
|
||||
|
||||
@@ -509,6 +509,7 @@ export const CLEAR_MS = 1200;
|
||||
// press takes one.
|
||||
export const OFFER_N = 2;
|
||||
export const PICK_HOLD_MS = 700;
|
||||
export const BANNER_STRETCH = 2;
|
||||
export const DOOR_REACH = 2.5;
|
||||
|
||||
// A banner fades to BANNER_SEE_THROUGH over BANNER_FADE_MS while something
|
||||
@@ -2441,7 +2442,9 @@ function create({ canvas, tone = () => {}, hum = () => {}, music = () => {}, onS
|
||||
// once that phase has passed; a full queue makes room for a more
|
||||
// important one (`rank`: "New best!") by dropping the least important one
|
||||
// waiting, and otherwise drops the newcomer.
|
||||
// Every banner is up BANNER_STRETCH times as long as its caller asks, so the words can be read.
|
||||
const banner = (title, sub, color, ms = 1800, { phase = "", rank = 0 } = {}) => {
|
||||
ms *= BANNER_STRETCH;
|
||||
if (fx.banners.some((b) => b.title === title)) return null;
|
||||
if (fx.banners.length >= 3) {
|
||||
let low = -1;
|
||||
@@ -2760,6 +2763,10 @@ function create({ canvas, tone = () => {}, hum = () => {}, music = () => {}, onS
|
||||
get state() {
|
||||
return state;
|
||||
},
|
||||
// The lost end screen animates, so the window keeps ticking it.
|
||||
get animating() {
|
||||
return state === "over" && !round.won;
|
||||
},
|
||||
// For the tests only: the window never reads it.
|
||||
get round() {
|
||||
return round;
|
||||
|
||||
@@ -334,6 +334,109 @@
|
||||
<aside class="aside" id="aside" aria-label="Notes and discussion"></aside>
|
||||
</div>
|
||||
|
||||
<!-- One small glyph per dashboard card, drawn before the card's title
|
||||
(dashboard.js) and beside it in Help's card list (help-dialog.js).
|
||||
A hidden sheet of <symbol>s in the same stroke style as help-icons:
|
||||
.dash-card-icon and .help-card-icon supply size and ink. -->
|
||||
<svg class="card-icons" aria-hidden="true" focusable="false">
|
||||
<!-- Set up this project: a map pin, "put this project on the map". -->
|
||||
<symbol id="ci-init" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M20 10c0 5-5.5 10.2-7.4 11.8a1 1 0 0 1-1.2 0C9.5 20.2 4 15 4 10a8 8 0 0 1 16 0z" />
|
||||
<circle cx="12" cy="10" r="2.8" />
|
||||
</symbol>
|
||||
<!-- Refresh AGENTS.md: circular refresh arrow. -->
|
||||
<symbol id="ci-init-update" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M21 12a9 9 0 1 1-9-9c2.5 0 4.9 1 6.7 2.7L21 8" />
|
||||
<path d="M21 3v5h-5" />
|
||||
</symbol>
|
||||
<!-- Pathfinder: a compass. -->
|
||||
<symbol id="ci-pathfinder" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="12" cy="12" r="9.2" />
|
||||
<path d="M16.2 7.8l-2.1 6.3-6.3 2.1 2.1-6.3z" />
|
||||
</symbol>
|
||||
<!-- Plan: a folded map. -->
|
||||
<symbol id="ci-plan" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M9 4 3 6v14l6-2 6 2 6-2V4l-6 2z" />
|
||||
<path d="M9 4v14" />
|
||||
<path d="M15 6v14" />
|
||||
</symbol>
|
||||
<!-- Revise the plan: a pencil. -->
|
||||
<symbol id="ci-revise-plan" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z" />
|
||||
<path d="m15 5 4 4" />
|
||||
</symbol>
|
||||
<!-- Document: a document with a check. -->
|
||||
<symbol id="ci-document" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z" />
|
||||
<path d="M14 2v4a2 2 0 0 0 2 2h4" />
|
||||
<path d="m9 15 2 2 4-4" />
|
||||
</symbol>
|
||||
<!-- Implement: code brackets. -->
|
||||
<symbol id="ci-implement" viewBox="0 0 24 24" fill="none">
|
||||
<path d="m16 18 6-6-6-6" />
|
||||
<path d="m8 6-6 6 6 6" />
|
||||
</symbol>
|
||||
<!-- Implementation Loop: repeat arrows. -->
|
||||
<symbol id="ci-loop" viewBox="0 0 24 24" fill="none">
|
||||
<path d="m17 2.5 4 4-4 4" />
|
||||
<path d="M3 11V9a4 4 0 0 1 4-4h14" />
|
||||
<path d="m7 21.5-4-4 4-4" />
|
||||
<path d="M21 13v2a4 4 0 0 1-4 4H3" />
|
||||
</symbol>
|
||||
<!-- Finalize: a finish flag. -->
|
||||
<symbol id="ci-finalize" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V4s-1 1-4 1-5-2-8-2-4 1-4 1z" />
|
||||
<path d="M4 21v-6" />
|
||||
</symbol>
|
||||
<!-- Quick task: a bolt. -->
|
||||
<symbol id="ci-quick-task" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M13 3 4.5 14h7.5l-1.5 7L19 10h-7.5z" />
|
||||
</symbol>
|
||||
<!-- Review: a magnifier. -->
|
||||
<symbol id="ci-review" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="11" cy="11" r="7.5" />
|
||||
<path d="m20.5 20.5-4.6-4.6" />
|
||||
</symbol>
|
||||
<!-- Codebase X-ray: a scan frame with its scan line. -->
|
||||
<symbol id="ci-xray" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M3 7V5a2 2 0 0 1 2-2h2" />
|
||||
<path d="M17 3h2a2 2 0 0 1 2 2v2" />
|
||||
<path d="M21 17v2a2 2 0 0 1-2 2h-2" />
|
||||
<path d="M7 21H5a2 2 0 0 1-2-2v-2" />
|
||||
<path d="M7 12h10" />
|
||||
</symbol>
|
||||
<!-- Diagnose a bug: a bug. -->
|
||||
<symbol id="ci-diagnose" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M12 20a6 6 0 0 0 6-6v-2.5a6 6 0 0 0-12 0V14a6 6 0 0 0 6 6z" />
|
||||
<path d="m9.5 6.5-2-3" />
|
||||
<path d="m14.5 6.5 2-3" />
|
||||
<path d="M12 11v6" />
|
||||
<path d="M6.5 13h-3" />
|
||||
<path d="M20.5 13h-3" />
|
||||
<path d="m6 17.5-2.5 1.5" />
|
||||
<path d="m18 17.5 2.5 1.5" />
|
||||
</symbol>
|
||||
<!-- Changelog: a version tag. -->
|
||||
<symbol id="ci-changelog" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M3 4a1 1 0 0 1 1-1h7.6a2 2 0 0 1 1.4.6l7.4 7.4a2 2 0 0 1 0 2.8l-5.6 5.6a2 2 0 0 1-2.8 0L4.6 12a2 2 0 0 1-.6-1.4z" />
|
||||
<path d="M7.5 7.5h.01" />
|
||||
</symbol>
|
||||
<!-- Git: a branch. -->
|
||||
<symbol id="ci-git" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="6" cy="6" r="2.5" />
|
||||
<circle cx="6" cy="18" r="2.5" />
|
||||
<circle cx="18" cy="6" r="2.5" />
|
||||
<path d="M6 8.5v7" />
|
||||
<path d="M18 8.5a9 9 0 0 1-9 7" />
|
||||
</symbol>
|
||||
<!-- Handoff: a package. -->
|
||||
<symbol id="ci-handoff" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
|
||||
<path d="m3.3 7 8.7 5 8.7-5" />
|
||||
<path d="M12 21.5V12" />
|
||||
</symbol>
|
||||
</svg>
|
||||
|
||||
<!-- Planny acting out each skill while it starts up and while it works.
|
||||
Inert until app.js clones one onto the starting or waiting screen
|
||||
(startStage), so it costs nothing on any other screen. Classes only,
|
||||
|
||||
@@ -580,13 +580,29 @@ function startLoop() {
|
||||
if (g.state !== "running") {
|
||||
hushTones();
|
||||
looping = false;
|
||||
return paintOverlay();
|
||||
paintOverlay();
|
||||
return overLoop(g, mine);
|
||||
}
|
||||
tickSource(frame);
|
||||
};
|
||||
tickSource(frame);
|
||||
}
|
||||
|
||||
// A game whose end screen moves (`animating`: Ghoul Rush's "G A M E - O V E R")
|
||||
// keeps being ticked and painted, with no countdown, until the screen is left.
|
||||
function overLoop(g, mine) {
|
||||
if (!g.animating) return;
|
||||
let last = null;
|
||||
const frame = (now) => {
|
||||
if (mine !== gen || looping || !$("activities-modal").open || g !== game() || g.state === "running" || !g.animating) return;
|
||||
const t = typeof now === "number" ? now : performance.now();
|
||||
if (last !== null) g.tick(Math.min(Math.max(0, t - last), MAX_FRAME_MS));
|
||||
last = t;
|
||||
tickSource(frame);
|
||||
};
|
||||
tickSource(frame);
|
||||
}
|
||||
|
||||
// After anything the person does: the timer follows the game's state.
|
||||
function follow() {
|
||||
const g = game();
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
loopDriving,
|
||||
} from "../selectors.js";
|
||||
import { hooks, page, redraw, saveNow } from "../state.js";
|
||||
import { el, approvalTip, mdInto, releasesLink, copyButton, lightDismiss } from "../render.js";
|
||||
import { el, approvalTip, mdInto, releasesLink, copyButton, lightDismiss, SVG_NS } from "../render.js";
|
||||
import { needsRoleNudge, ROLE_NOT_SET } from "../starters.js";
|
||||
import { looks, saveLooks } from "../looks.js";
|
||||
import { RED_BANNER, RED_BANNER_IN_APP } from "../meter.js";
|
||||
@@ -688,7 +688,18 @@ function dashCard(entry, menu) {
|
||||
head.appendChild(el("span", "dash-chip", entry.chip));
|
||||
if (presentation.recommended) head.appendChild(el("span", "pill suggested", "Suggested"));
|
||||
b.appendChild(head);
|
||||
b.appendChild(el("span", "dash-card-title", entry.title));
|
||||
const title = el("span", "dash-card-title");
|
||||
if (entry.icon) {
|
||||
const svg = document.createElementNS(SVG_NS, "svg");
|
||||
svg.setAttribute("class", "dash-card-icon");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
const use = document.createElementNS(SVG_NS, "use");
|
||||
use.setAttribute("href", "#ci-" + entry.icon);
|
||||
svg.appendChild(use);
|
||||
title.appendChild(svg);
|
||||
}
|
||||
title.appendChild(document.createTextNode(entry.title));
|
||||
b.appendChild(title);
|
||||
b.appendChild(el("span", "dash-card-blurb", entry.blurb));
|
||||
if (presentation.detail) b.appendChild(el("span", "dash-card-detail", presentation.detail));
|
||||
if (!presentation.on && presentation.reason) b.appendChild(el("span", "dash-card-off", presentation.reason));
|
||||
|
||||
@@ -254,7 +254,17 @@ function buildHelp() {
|
||||
const list = el("ul");
|
||||
for (const e of SKILL_CATALOG.filter((x) => x.group === g.id)) {
|
||||
const li = el("li");
|
||||
li.appendChild(el("strong", null, e.title + "."));
|
||||
const strong = el("strong", null, e.title + ".");
|
||||
if (e.icon) {
|
||||
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svg.setAttribute("class", "help-card-icon");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
|
||||
use.setAttribute("href", "#ci-" + e.icon);
|
||||
svg.appendChild(use);
|
||||
strong.prepend(svg);
|
||||
}
|
||||
li.appendChild(strong);
|
||||
li.appendChild(document.createTextNode(" " + (e.help || e.blurb)));
|
||||
list.appendChild(li);
|
||||
}
|
||||
|
||||
@@ -42,7 +42,8 @@
|
||||
// card the dashboard card (group, chip, title, blurb, about, and
|
||||
// `spec: true` when it takes the picked spec), or null; an
|
||||
// optional `help` is Help's line for the card when it differs
|
||||
// from `blurb`
|
||||
// from `blurb`, and `icon` names the `ci-*` symbol in
|
||||
// index.html's card-icons sheet drawn before the title
|
||||
// appOnly the entry is a card the desktop app alone offers (the
|
||||
// Implementation Loop): no workflow, no installed skill, and no
|
||||
// list derived from the workflows (WORKFLOWS, the meter, the
|
||||
@@ -82,6 +83,7 @@ export const SKILLS = Object.freeze([
|
||||
group: "setup",
|
||||
chip: "Set up",
|
||||
title: "Set up this project",
|
||||
icon: "init",
|
||||
blurb: "Reads your project and writes AGENTS.md, the guide every later step works from.",
|
||||
about:
|
||||
"Plan2Code reads the whole project: how it is organized, how it runs, and where the sharp edges are. Then it writes AGENTS.md, the guide every later step steers by. It asks a few questions as it goes, so nothing important gets guessed. Run this once per project, or again when the project has moved on.",
|
||||
@@ -102,6 +104,7 @@ export const SKILLS = Object.freeze([
|
||||
group: "setup",
|
||||
chip: "Set up",
|
||||
title: "Refresh AGENTS.md",
|
||||
icon: "init-update",
|
||||
blurb: "Brings AGENTS.md and its notes up to date with what the project has learned lately.",
|
||||
about:
|
||||
"The project moved on since AGENTS.md was written: new commands, new habits, new gotchas. This re-reads the project, asks what changed, and folds it into AGENTS.md and the notes beside it. Cheaper than a fresh setup, and whatever is still right is kept.",
|
||||
@@ -127,6 +130,7 @@ export const SKILLS = Object.freeze([
|
||||
chip: "Step 0",
|
||||
spec: true,
|
||||
title: "Pathfinder",
|
||||
icon: "pathfinder",
|
||||
blurb: "A foggy idea becomes a clear list of decisions, settled one question at a time.",
|
||||
about:
|
||||
"You have a rough idea and a lot of unknowns. Pathfinder asks one question at a time: who it is for, what it must do, what could go wrong. Each answer is written down in a spec folder. It ends with a list of decisions clear enough to plan from, and nothing gets built yet.",
|
||||
@@ -152,6 +156,7 @@ export const SKILLS = Object.freeze([
|
||||
chip: "Step 1",
|
||||
spec: true,
|
||||
title: "Plan",
|
||||
icon: "plan",
|
||||
blurb: "Requirements, technical design and your approval: the shape of what gets built.",
|
||||
about:
|
||||
"Turns what you bring into a real plan: a finished Pathfinder map, a folder of design notes, or just the idea in your head. You get requirements, a technical design, a phase-by-phase breakdown, and a final version to approve before anything is built. This is where 'what are we building' becomes 'how it gets built'.",
|
||||
@@ -173,6 +178,7 @@ export const SKILLS = Object.freeze([
|
||||
chip: "Step 1b",
|
||||
spec: true,
|
||||
title: "Revise the plan",
|
||||
icon: "revise-plan",
|
||||
blurb: "Requirements changed mid-build? Adjust the plan without starting over.",
|
||||
about:
|
||||
"Requirements moved mid-build: a feature added, a rule dropped, a deadline pulled in. This adjusts the existing spec for the change, shows you what it affects, and only rewrites what actually has to move. The approved plan stays the plan.",
|
||||
@@ -199,6 +205,7 @@ export const SKILLS = Object.freeze([
|
||||
chip: "Step 2",
|
||||
spec: true,
|
||||
title: "Document",
|
||||
icon: "document",
|
||||
blurb: "The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do.",
|
||||
about:
|
||||
"Writes the plan as numbered phase files. Each phase is a checklist of tasks small enough to just do, with the details a builder needs right there. This is the file the build step works from, and the thing a later session can pick up cold.",
|
||||
@@ -221,6 +228,7 @@ export const SKILLS = Object.freeze([
|
||||
chip: "Step 3",
|
||||
spec: true,
|
||||
title: "Implement",
|
||||
icon: "implement",
|
||||
blurb: "Builds the next phase, task by task, then reviews it, with your sign-off at the end.",
|
||||
about:
|
||||
"Builds the next phase of the spec. Tasks get checked off one by one, with progress and the occasional decision landing on this page as it goes. With Review ticked, a fresh pass then hunts for problems in exactly what changed and you pick what gets fixed. It ends with a report of what was built and a sign-off card you approve before the phase counts as done.",
|
||||
@@ -261,6 +269,7 @@ export const SKILLS = Object.freeze([
|
||||
chip: "Step 3",
|
||||
spec: true,
|
||||
title: "Implementation Loop",
|
||||
icon: "loop",
|
||||
blurb: "Build every remaining phase unattended, one fresh agent per phase.",
|
||||
about:
|
||||
"Builds every remaining phase of the spec without you at the keyboard. Each phase gets a fresh agent that builds it and reviews it. The app checks the result against the spec, runs your quick check, commits, and moves on. It stops at the first phase that goes wrong and tells you why. Desktop app only.",
|
||||
@@ -282,6 +291,7 @@ export const SKILLS = Object.freeze([
|
||||
chip: "Step 4",
|
||||
spec: true,
|
||||
title: "Finalize",
|
||||
icon: "finalize",
|
||||
blurb: "Checks the work, writes the summary, files the specs away and suggests the commit message.",
|
||||
about:
|
||||
"The closer. Checks every task against the spec, makes sure the build actually works, writes the summary into overview.md, updates the project docs, and suggests the commit message. Run it when the feature is done. It leaves the project tidy behind it.",
|
||||
@@ -302,6 +312,7 @@ export const SKILLS = Object.freeze([
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Quick task",
|
||||
icon: "quick-task",
|
||||
blurb: "Too small for the full process? A quick plan, then it just builds it.",
|
||||
about:
|
||||
"A fix, a tweak, a small feature. Not worth a spec folder. Describe it, confirm the one-line plan, and it builds it right there, with a report at the end. The fast lane for work the full process would over-plan.",
|
||||
@@ -322,6 +333,7 @@ export const SKILLS = Object.freeze([
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Review",
|
||||
icon: "review",
|
||||
blurb: "A second opinion on the changes. Problems ranked, and you pick what gets fixed.",
|
||||
about:
|
||||
"A fresh-eyes pass over what changed: bugs, gaps, and the things the builder was too close to see. Problems come back ranked with a suggestion each, you pick which ones get fixed, and it fixes them.",
|
||||
@@ -335,13 +347,14 @@ export const SKILLS = Object.freeze([
|
||||
pose: "xray",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "X-ray started", ran: "X-ray run", resume: null,
|
||||
subagents: null,
|
||||
subagents: "Use helpers for the reading both modes lean on: explain mode's area files and history leads, and rough-spots mode's top candidates, one helper per area or candidate. Keep the judgment, the citations, the ranking, the pick and every question with you. Lookups at light strength, low effort.",
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Codebase X-ray",
|
||||
icon: "xray",
|
||||
blurb: "Explain how and why an area works, or find the rough spots worth fixing.",
|
||||
about:
|
||||
"Two ways into code you did not write. Explain an area: how it works, step by step, and why it is that way, citing the files and the commits and pull requests behind it. Or find the rough spots: files that always change together, thin layers, tangled boundaries and busy code with no tests, ranked with a concrete example each. You tick the ones worth fixing and they become a brief for Pathfinder or Plan. It never changes code.",
|
||||
@@ -355,13 +368,14 @@ export const SKILLS = Object.freeze([
|
||||
pose: "diagnose",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Diagnose started", ran: "Diagnose run", resume: null,
|
||||
subagents: "Use helpers for the reading both modes lean on: explain mode's area files and history leads, and rough-spots mode's top candidates, one helper per area or candidate. Keep the judgment, the citations, the ranking, the pick and every question with you. Lookups at light strength, low effort.",
|
||||
subagents: "Use helpers for side lookups while you narrow: the code path a suspect change touches, a suspect function's callers, and the docs behind the failing behavior. Keep the reproduction, any bisect, the cause judgment and every question with you. Lookups at light strength, low effort.",
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Diagnose a bug",
|
||||
icon: "diagnose",
|
||||
blurb: "Find a bug's cause and write it up, without fixing it.",
|
||||
help: "Finds a bug's cause and writes it up without fixing it, ready to hand to Quick Task or Plan.",
|
||||
about:
|
||||
@@ -376,13 +390,14 @@ export const SKILLS = Object.freeze([
|
||||
pose: "changelog",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Changelog started", ran: "Changelog run", resume: null,
|
||||
subagents: "Use helpers for side lookups while you narrow: the code path a suspect change touches, a suspect function's callers, and the docs behind the failing behavior. Keep the reproduction, any bisect, the cause judgment and every question with you. Lookups at light strength, low effort.",
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Changelog",
|
||||
icon: "changelog",
|
||||
blurb: "Checks the CHANGELOG version against the main branch and suggests entries for what is new.",
|
||||
about:
|
||||
"Works out the right version from the default branch, then compares your branch with the latest CHANGELOG entry and suggests the entries it is missing. You edit them before anything is written, it keeps package.json in step, and it offers to commit the result in Git. If the newest version is not released or on another branch yet, it adds to that entry instead of starting a new one.",
|
||||
@@ -403,6 +418,7 @@ export const SKILLS = Object.freeze([
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Git",
|
||||
icon: "git",
|
||||
blurb: "Branches, pull, push and commits on one board that stays open while you work.",
|
||||
help: "Branches, pull, push and commits on one board, asking before anything leaves your machine. See \"The git board\".",
|
||||
about:
|
||||
@@ -424,6 +440,7 @@ export const SKILLS = Object.freeze([
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Handoff",
|
||||
icon: "handoff",
|
||||
blurb: "Pack the current session into a document a fresh session can pick up cold.",
|
||||
about:
|
||||
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
|
||||
|
||||
@@ -10,11 +10,12 @@
|
||||
attribute's own display. */
|
||||
#btn-activities[hidden] { display: none; }
|
||||
|
||||
/* The dialog: Notebook-sized, with the board taking whatever height the
|
||||
title, the banner, the picker, the note and the actions leave. */
|
||||
/* The dialog: as large as the viewport allows, a slim edge all round so it
|
||||
still reads as a window, with the board taking whatever height the title,
|
||||
the banner, the picker, the note and the actions leave. */
|
||||
.modal.activities {
|
||||
width: min(1200px, 90vw);
|
||||
height: min(900px, 85vh);
|
||||
width: calc(100vw - 32px);
|
||||
height: calc(100vh - 32px);
|
||||
max-width: none;
|
||||
max-height: none;
|
||||
flex-direction: column;
|
||||
@@ -184,11 +185,20 @@
|
||||
padding: 4px 2px 8px;
|
||||
}
|
||||
.activities-picker[hidden] { display: none; }
|
||||
/* Cards keep one width and wrap, and each row (a short last one too) sits in
|
||||
the middle, so a wide window is filled evenly and no corner is left bare. */
|
||||
.activities-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
gap: 16px;
|
||||
--card-w: 250px;
|
||||
--gap: 16px;
|
||||
/* At most six across: the width of six cards and the gaps between them. */
|
||||
max-width: calc(6 * var(--card-w) + 5 * var(--gap));
|
||||
margin-inline: auto;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: var(--gap);
|
||||
}
|
||||
.activities-cards > .activities-card { flex: 0 0 var(--card-w); max-width: 100%; }
|
||||
.activities-card {
|
||||
position: relative;
|
||||
display: flex;
|
||||
@@ -215,7 +225,7 @@
|
||||
/* A course dashboard: three across where it fits, so all six courses show
|
||||
at once. A course card's art is a hole drawn on a 4:3 canvas, cropped to a
|
||||
wide strip through its middle, where the play is. */
|
||||
.activities-courses { grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); }
|
||||
.activities-courses { --card-w: 290px; }
|
||||
.activities-cover canvas { display: block; width: 100%; height: auto; aspect-ratio: 16 / 9; object-fit: cover; }
|
||||
/* The covers' token colors (screens/activities.js names them), so a cover
|
||||
follows the theme and the highlight like the boards do. */
|
||||
|
||||
@@ -215,7 +215,21 @@
|
||||
}
|
||||
.dash-card.is-suggested .dash-chip { color: var(--accent); border-color: var(--accent-line); }
|
||||
|
||||
.dash-card-title { font-size: 15px; font-weight: 650; }
|
||||
/* The card icon sheet: present for <use href>, never drawn itself. */
|
||||
.card-icons { position: absolute; width: 0; height: 0; overflow: hidden; }
|
||||
|
||||
.dash-card-title { display: flex; align-items: center; gap: 7px; font-size: 15px; font-weight: 650; }
|
||||
.dash-card-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex: none;
|
||||
fill: none;
|
||||
stroke: currentColor;
|
||||
stroke-width: 1.8;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
.dash-card.is-suggested .dash-card-icon { stroke: var(--accent); }
|
||||
.dash-card-blurb { font-size: 13px; color: var(--ink-2); flex: 1; }
|
||||
.dash-card-detail { font-size: 12px; color: var(--accent); }
|
||||
|
||||
|
||||
@@ -119,6 +119,20 @@
|
||||
/* The icon sheet: present for <use href>, never drawn itself. */
|
||||
.help-icons { position: absolute; width: 0; height: 0; overflow: hidden; }
|
||||
|
||||
/* The card icons in the dashboard topic's card list: the same glyphs the
|
||||
cards wear, a touch quieter. */
|
||||
.help-card-icon {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
margin-right: 5px;
|
||||
vertical-align: -2px;
|
||||
fill: none;
|
||||
stroke: var(--ink-2);
|
||||
stroke-width: 1.8;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
|
||||
/* The diagrams. Colors only from variables, so each drawing follows the
|
||||
theme and the chosen highlight without a line of script. */
|
||||
.help-figure { margin: 4px 0 16px; }
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "3.0.0",
|
||||
"version": "4.0.0",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-25",
|
||||
"releaseDate": "2026-11-02",
|
||||
"mode": "utility"
|
||||
}
|
||||
Reference in new issue
Block a user