Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cedc3300ed | ||
|
|
8bace16e06 | ||
|
|
e87148ad10 | ||
|
|
23ac3a9c19 | ||
|
|
a0ac6eb655 | ||
|
|
958c0f4ccc | ||
|
|
959554d127 | ||
|
|
fc2921c848 | ||
|
|
e0b64e5895 | ||
|
|
7139d0340c | ||
|
|
e23ef8b3ec | ||
|
|
7336b7fcc5 | ||
|
|
4265eda68b | ||
|
|
15019dbc88 | ||
|
|
2e2edd538a | ||
|
|
807b6b038c | ||
|
|
8922d2e391 | ||
|
|
4352f3027d | ||
|
|
da6b738fc8 | ||
|
|
8ddf37911e | ||
|
|
17f98e62b5 | ||
|
|
2cb174ecf0 | ||
|
|
c52244bee1 | ||
|
|
0b6a376915 | ||
|
|
b17213322c | ||
|
|
30fd1134ea | ||
|
|
6376a68f85 | ||
|
|
e924cf5cde | ||
|
|
8491764273 | ||
|
|
7f95dabd00 | ||
|
|
81d14c8e78 | ||
|
|
e963513a8a | ||
|
|
9583b68a2e | ||
|
|
cc02631ab5 | ||
|
|
cc97161a23 | ||
|
|
bc2c7c6c41 | ||
|
|
f8a0a6bfc7 | ||
|
|
eb235dd91e | ||
|
|
7f1851fbb9 | ||
|
|
7509b09b81 | ||
|
|
bf23d7eeea | ||
|
|
ff1c793633 | ||
|
|
6cd7a7ff80 | ||
|
|
88c72dc2ce | ||
|
|
82298d256c | ||
|
|
aecc3afb4c | ||
|
|
e681d1f70d | ||
|
|
d716e3c3f5 | ||
|
|
903fbf5680 | ||
|
|
0454bdd19a | ||
|
|
899359806a | ||
|
|
a450604d8f | ||
|
|
bd5daa7972 | ||
|
|
d6be7f9240 | ||
|
|
8e1af1b15d | ||
|
|
1125cb2089 | ||
|
|
c02894ac2a | ||
|
|
61f27f81ab | ||
|
|
33f1783979 | ||
|
|
c122332657 | ||
|
|
1b9eb2e35b | ||
|
|
d016ba862a | ||
|
|
c1e32b8aca | ||
|
|
2acfd8907d | ||
|
|
c26759fd88 | ||
|
|
1eef797dc0 | ||
|
|
4704922286 | ||
|
|
26cb17f04a | ||
|
|
c8d12a3d99 | ||
|
|
d7abcd2ac6 | ||
|
|
ef4d86258b | ||
|
|
2d6c7078ae | ||
|
|
9c07ee5260 | ||
|
|
8e34bf1005 | ||
|
|
2468027a5a | ||
|
|
1f80fa6a7c | ||
|
|
8db8df5791 | ||
|
|
478ec28bc5 | ||
|
|
13532737e0 | ||
|
|
ed81c2b4fc | ||
|
|
5950abb0aa | ||
|
|
03f433043e | ||
|
|
dbd31611b7 | ||
|
|
720758a7ee | ||
|
|
7973bc093b | ||
|
|
528fcaaa8e | ||
|
|
d5d8278cfe | ||
|
|
77ddcc048d | ||
|
|
7d5e78179e | ||
|
|
46f1f17261 | ||
|
|
0d569954c4 | ||
|
|
2709252daa | ||
|
|
5043b424cf | ||
|
|
dd2ab86584 | ||
|
|
78153576a9 | ||
|
|
c3ee918b62 | ||
|
|
d4d64987fe | ||
|
|
10379e3870 | ||
|
|
899b3a48d8 | ||
|
|
e67aaabdce | ||
|
|
c602dfed57 | ||
|
|
765d2b3536 | ||
|
|
b99a1a701f | ||
|
|
a2b43d1188 | ||
|
|
94063fc0a9 | ||
|
|
3e22d53bf5 | ||
|
|
7a9f56a452 | ||
|
|
37f2735294 | ||
|
|
1d146cce6f | ||
|
|
5f91fb665f | ||
|
|
4d05b4f6f6 | ||
|
|
3155298fea | ||
|
|
a4644d533b | ||
|
|
b73a4cebe7 | ||
|
|
efc96e91c2 | ||
|
|
442904e6f2 | ||
|
|
c1f41e4a82 | ||
|
|
72043e20fc | ||
|
|
bdc4decbb4 | ||
|
|
cb6468577d | ||
|
|
0de630603b | ||
|
|
26013db54f | ||
|
|
e00769b56a | ||
|
|
a5a3a81c5f | ||
|
|
681c4a4b85 | ||
|
|
be31f6af89 | ||
|
|
7a4b7c6db8 | ||
|
|
086c735c65 | ||
|
|
d4adb53a3a | ||
|
|
50acdc8216 | ||
|
|
2075d235d8 | ||
|
|
452d8e3895 | ||
|
|
d32925cccf | ||
|
|
f8b54ef708 | ||
|
|
a19dc6c5df | ||
|
|
124beb46db | ||
|
|
1121157938 | ||
|
|
e3aba0a637 | ||
|
|
3edb4468a8 | ||
|
|
699a827cae | ||
|
|
765e374584 | ||
|
|
2ab57d9a7e | ||
|
|
17dffac1ea | ||
|
|
36843e4bc9 | ||
|
|
33a0dbd34a | ||
|
|
80ae3decdd | ||
|
|
caef9a0ee3 | ||
|
|
72c827dddf | ||
|
|
498e09bb15 | ||
|
|
68d1f82a2e | ||
|
|
fdf43b197f | ||
|
|
7e2c824d4f | ||
|
|
8890c3ad13 | ||
|
|
f328406bb5 |
No files matched your search
@@ -5,7 +5,7 @@
|
||||
|
||||
```
|
||||
plan2code/
|
||||
├── src/ # Source workflow prompts (14 markdown files)
|
||||
├── src/ # Source workflow prompts (19 markdown files)
|
||||
│ ├── plan2code-0-pathfinder-references/ # Reference files for pathfinder skill
|
||||
│ │ ├── brief.md # Dated plain-English decision briefs
|
||||
│ │ ├── chart.md # MODE A: destination + frontier grills, templates
|
||||
@@ -15,53 +15,67 @@ plan2code/
|
||||
│ │ ├── resolve.md # Per-type resolution + graduating the fog
|
||||
│ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff
|
||||
│ │ └── trail.md # Every-response map visual + pathed resume command
|
||||
│ ├── shared-references/ # Reference files shared across skills
|
||||
│ │ ├── building-habits.md # Find the cause, test first, pin behavior (quick-task, implement, implement-review, test)
|
||||
│ │ ├── helper-strength.md # How strong a model and how much effort each helper gets (init, init-update, pathfinder, plan, revise-plan, document, quick-task, implement, implement-review, review, finalize, xray, diagnose, pr-prep, test)
|
||||
│ │ └── test-runs.md # Choosing what tests to run: targeted per task and phase, full suite only where the plan puts it (document, implement, implement-review, quick-task, review, finalize, pr-prep, test)
|
||||
│ ├── plan2code-review-references/ # Reference files for review skill
|
||||
│ │ ├── verification-protocol.md # Deep verification + confidence calibration
|
||||
│ │ ├── dimensions.md # 11 dimensions with detailed checklists
|
||||
│ │ ├── false-positives.md # Known false-positive patterns
|
||||
│ │ ├── reviewer-brief.md # Fill-in brief for the one fresh helper that runs the analysis
|
||||
│ │ └── session-end.md # Next-step routing at review session end
|
||||
│ ├── plan2code-init-update-references/ # Reference files for init-update skill
|
||||
│ │ └── 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-4-finalize-references/ # Reference files for finalize skill
|
||||
│ │ └── community-feedback-submission.md # STEP 6.5 payload schema + submission tiers
|
||||
│ ├── skill-scripts/ # Scripts shared across skills: install.js copies the ones a skill lists into skills/<skill>/scripts/ (specs, commit-msg, review-scope, agents-md, agent-files, glob, test-map, test-match, test-commands, run-check, common)
|
||||
│ └── plan2code-<skill>-scripts/ # A skill's own scripts, same copy rule (pathfinder, finalize, changelog, git, xray, pr-prep and test each have one)
|
||||
├── 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
|
||||
│ │ └── prompts/ # Internal AI prompt templates (no char limit)
|
||||
│ └── dist/ # Built output (tsup)
|
||||
├── plan2code-app/ # Desktop app (Rust + Tauri): wraps the console in a window, agent-less setup screen; cargo fmt/clippy/test, see its README
|
||||
├── src/statusline-claude/ # Claude CLI status line (Node.js, zero deps, single file)
|
||||
│ ├── statusline.js # Self-contained: config, git, formatters, render
|
||||
│ └── statusline-config.json # Default config template
|
||||
├── src/launcher/ # Global `plan2code` command (Node.js, zero deps)
|
||||
│ ├── plan2code.js # Opens /plan2code in Claude Code or Devin in the cwd (or a picked folder)
|
||||
│ ├── agents.json # Shipped agent list (built-ins + starter templates with per-OS install data), copied to ~/.plan2code/bin/ on install
|
||||
│ ├── models.json # Curated model menu, copied to ~/.plan2code/bin/ on install
|
||||
│ └── plan2code.ico # Desktop shortcut icon (Windows)
|
||||
├── src/web-console/ # Local browser UI bundled into every skill (Node.js, zero deps, no build)
|
||||
│ ├── console.mjs # CLI the agent drives: open, post, wait, chat, keep, status, stop, help
|
||||
│ ├── server.mjs, lib.mjs, picker.mjs
|
||||
│ ├── console.md, building.md # Agent-facing contract
|
||||
│ ├── server.mjs, routes.mjs, static.mjs, cmd-*.mjs, picker.mjs, and the by-job files (files, sessions, patches, scan, inbox, workspace, settings, agents, agent-lookup, git-repo, handoffs, in-app, loop-setup, notepads, open-link, pointers, spec-files, update-check)
|
||||
│ ├── console.md, console-*.md, notes/, building*.md # Agent-facing contract (console.md read once, the rest on demand)
|
||||
│ └── public/ # Page assets served to the browser
|
||||
├── scripts/ # Development scripts
|
||||
│ ├── bench-web-console.mjs # Start-path timing
|
||||
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs puppeteer-core)
|
||||
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs a local Chrome or Edge, through `playwright-core`)
|
||||
│ ├── browser.mjs # The one place a browser is launched (Chrome, then Edge, through `playwright-core`; `PLAN2CODE_TEST_BROWSER` forces one); page tests, the screenshots and the bench use it
|
||||
│ ├── css-snapshot.mjs # Dev-only: every element's computed style on every screen, both themes; take one before a stylesheet move and `--compare` after
|
||||
│ ├── vendor-codemirror.mjs # Dev-only: bundles the pinned CodeMirror 6 packages with esbuild into `public/vendor/codemirror.esm.js` (installed in a temp folder from `vendor-codemirror-lock.json`, never in the repo)
|
||||
│ ├── check-skill-table.mjs # src/plan2code.md "What each skill reads and writes" table vs each skill's prompt and references
|
||||
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
|
||||
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
|
||||
│ ├── test-web-console.mjs, test-launcher.mjs, test-getting-started.mjs # node --test suites (the last keeps the newcomer docs in step)
|
||||
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, skill-script-helpers.mjs # Skill script suites and fixtures
|
||||
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area (the page tests are `-page-*`, the source shape `-shape`), and their shared setup
|
||||
│ ├── node-test.mjs, page-test-helpers.mjs # `npm test`'s `node --test`, files at once capped at one per spare core; the page tests' browser sessions and their redraw-safe `styleOf()`, `stylesOf()`, `scrollCard()`
|
||||
│ ├── test-launcher.mjs, test-getting-started.mjs # Launcher suite; newcomer docs kept in step
|
||||
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, test-git-repo.mjs, skill-script-helpers.mjs, fixture-helpers.mjs # Skill script suites and fixtures
|
||||
│ ├── check-versions.mjs, fix-line-endings.mjs, play.mjs # Six-file version sync; restores LF everywhere (also pretest + pre-commit); tries the games from src/
|
||||
│ ├── measure-console-wire.mjs, css-helpers.mjs, ghoul-test-helpers.mjs, fixtures/, console-wire-runs/ # Wire-size probe and its captured runs; shared CSS and Ghoul Rush test helpers; skill-script fixtures
|
||||
│ └── validate-char-count.js # Pre-commit character count validator
|
||||
├── skills/ # Generated, gitignored build output — one Agent Skill per src/ prompt
|
||||
│ └── plan2code-<name>/ # SKILL.md plus references/ and scripts/ where present
|
||||
│ # Generated by npm run build:skills; consumed by skills add
|
||||
├── .husky/ # Git hooks (husky)
|
||||
│ └── pre-commit # Runs character count validation
|
||||
│ └── pre-commit # Runs fix-line-endings, then character count validation
|
||||
├── .agents-docs/ # The detail files AGENTS.md links to (this file and its siblings)
|
||||
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
|
||||
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/, plan2code-model-update/
|
||||
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/, plan2code-launcher-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)
|
||||
@@ -85,7 +99,29 @@ plan2code/
|
||||
| `version.json` | Version metadata (name, version, description) |
|
||||
| `QUICK-REFERENCE.md` | User quick-reference card |
|
||||
| `src/statusline-claude/` | Claude CLI status bar (see Status Line below) |
|
||||
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`) |
|
||||
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`). When the desktop app is installed (`~/.plan2code/app/plan2code-app[.exe]`, or the file `PLAN2CODE_APP` names) and a display exists (Windows and macOS always; Linux needs `DISPLAY` or `WAYLAND_DISPLAY`), it opens the app after the agent and model questions with `--project <folder> --agent <id> [--model <id>]` and exits; `--classic` (never forwarded to the CLI) and a failed spawn keep the terminal flow. The app reads all three (`project::launch_choice`): the picker starts on `--agent`, and `--model` applies to that agent on every start and Restart (`AgentManager::set_model`); a model never applies to another agent. Its menu, lookup and no-agent flow come from `agents.json` through `agent-lookup.mjs`, loaded by dynamic `import()` from `~/.plan2code/bin/` (the launcher's one stated exception to its Node-built-ins-only rule; a missing copy falls back to the plain printed install steps) |
|
||||
| `plan2code-app/` | Tauri desktop app (Rust host, xterm panel, the console's dashboard in a frame; its own README). `RELEASE-CHECKLIST.md` lists the by-hand checks before each release. `src-tauri/src/versions.rs` compares the app's version (`tauri.conf.json`) with the installed skills' (`~/.plan2code/bin/version.json`) for the bar's **Update skills** line, which runs `node ~/.plan2code/bin/plan2code.js update` only when pressed |
|
||||
| `plan2code-app/src-tauri/src/attention.rs` | The taskbar signal's rules, pure and knowing nothing about Tauri: `Signal` (`busy`, `ready`, `attention`, `plain`), `badge_for(signal, os, enabled)` (Windows: green dot on `ready`, red on `attention`; macOS: red `!` on `attention` only; Linux: count 1 on `attention`), `should_flash(prev, next, focused, enabled)` (once, only on a change into `ready` or `attention` while unfocused) and `dot_rgba()` (the dot's pixels, in the favicon's colors, which a test checks against `public/favicon.js`). `main.rs` applies the result through `set_attention`, `set_taskbar_signal` and `clear_attention_cmd`; the page asks with the `attention` and `taskbar` messages (`public/app-bridge.js`) and the switch is `taskbarSignal` in the app's own `~/.plan2code/app.json`. |
|
||||
| `plan2code-app/src-tauri/src/quit_prompt.rs`, `task_dialog.rs` | The quit check shown while an agent runs. `quit_prompt(last_signal)` is pure: the page's last taskbar signal `ready` or `plain` is the waiting case ("Done for now?", Info icon), and `busy`, `attention` or none yet is the working case ("Leave while your agent is busy?", Warning icon). `task_dialog.rs` (Windows only) draws it with `TaskDialogIndirect` through `winapi`: a heading, Stay as the default, and the app's icon in the title bar, since the dialog plugin has no heading and Windows copies its icon into the title bar (the warning once showed twice). `confirm_quit` in `main.rs` runs it on its own thread; macOS and Linux use the plugin box with the same words, where Quit stays the default button (putting Stay first would make Esc quit). A page reload or an unanswered page clears the signal to none (`clear_attention`), so the box stays on the working words until the page reports again; `QUIT_OPEN` keeps a second box from stacking |
|
||||
| `plan2code-app/src-tauri/src/loop_driver.rs` | The Implementation Loop's driver. Its decisions are pure functions and carry the unit tests: `phase_prompt()` (the prompt each fresh phase session starts on), `judge_outcome()` (the skill's `loopOutcome` against the spec's marks and the setup), `expect_patch()` (the `loopExpect` judging criteria stamped into the session so the console refuses a bad report at post time), `silence_expired()`, `should_retry()` (one retry for a crash or silence, never for a real failure), `open_question()` and `stop_line()`. Around them sit the running record (app memory only), the watch thread and the stop and resume entry points. **The app, not the agent, marks a loop phase done and commits it**; the skill only builds and reports |
|
||||
| `plan2code-app/src-tauri/src/loop_commit.rs` | The loop's commit step, called by `handle_outcome` in a fixed order: prepare (subject, message), stage and check the staged names and sizes against a denylist (`.env*` except `.example`, `.sample`, `.template`; oversized files; a bad list unstages all and stops), save the phase file text, mark done, commit with its own limit, and on a failed commit restore the saved text only if the file still equals what the loop wrote (else stop with "marked, not committed", kept in the reports store). Stop now never commits; `judge_outcome` refuses missing task data and failed tests; the watcher runs under `catch_unwind` and counts unreadable sessions as silence; `loop_state` in `main.rs` redraws the strip after a reload |
|
||||
| `plan2code-app/src-tauri/src/loop_notify.rs` | The loop's notification: `NotifyKind` (query string, JSON body, Discord, Slack, Teams, Google Chat; its comment lists what a new service needs), `valid_url()`, `valid_param()` (mirrored in `loop-setup.mjs` and `screens/loop-setup.js`), `request_for()` (each kind's address and body) and `send()`, with a 10 second limit and errors that never hold the address. The driver writes the message and calls it from `observe()`, `stop_loop()` and `finish()`. |
|
||||
| `plan2code-app/src-tauri/src/loop_report.rs` | The loop's report on everything done for the person: one `LoopReport` per build, entries in order (passed, stopped, retried) with findings fixed, skipped and left open, assumptions read from the phase file, and reported decisions. Saved in the console's `loop-reports.json` after every entry, because a project file would dirty the tree Resume needs clean; `finish()` writes it to `LOOP-SUMMARY-<date>.md` and removes the entry. |
|
||||
| `plan2code-app/src-tauri/src/loop_tools.rs` | What the loop runs on its own, each call with a time limit and its output kept: the spec scripts (`specs.mjs status`, `mark --to done`), `commit-msg.mjs`, git (`add`, `commit`, `status`, the short head), the console's `post` and `open --resume`, and the person's quick check. No shell runs here except the quick check, whose text comes only from `loop-setup.json`, never from a page message |
|
||||
| `plan2code-app/src-tauri/src/agents.rs` | Agents in the app: `CustomAgent`, the `Agent` handle over built-ins and custom entries, `load_custom_agents`, reading the Agents file below; the shipped `agents.json` read at run time with the baked copy as fallback; `find_on_path`, the Rust twin of `agent-lookup.mjs`'s `findAgent` (PATH, PATHEXT, the saved PATH from `node_check::resolved_path()`, npm's global folder, the install folders), held to `scripts/fixtures/agent-lookup-cases.json`. The console side is `src/web-console/agents.mjs` |
|
||||
| Desktop app install (`install.js`) | `installDesktopApp()` downloads `plan2code-app-<version>-<windows\|macos\|linux>-<x64\|arm64>[.exe]` and `plan2code-app-<version>-SHA256SUMS.txt` from the GitHub release (`PLAN2CODE_RELEASE_BASE` replaces the URL; the tests serve a stand-in), checks the SHA-256 and places the file in `~/.plan2code/app/` (the old file is renamed aside first, since Windows cannot overwrite a running exe). `app` is an install piece (`INSTALL_PIECES`, after `launcher`), so `plan2code update` updates it with the rest. `install()` asks for it after the command (default yes; a no is kept as `skipped` in `install.json`); unattended it installs it unless it is already recorded or was declined. A failed app never fails the install. `.github/workflows/release-app.yml` builds one file per system (`tauri build --no-bundle`) and the checksum list on a published release, after `scripts/check-versions.mjs --tag` |
|
||||
|
||||
### Agents file
|
||||
|
||||
`~/.plan2code/agents.json` holds the person's custom agent CLIs. The web console is its only writer (User Preferences → Agents & models, through `POST /agents`); the `plan2code` launcher and the desktop app only read it. Each reader carries its own copy of the rules (`src/web-console/agents.mjs` for the console, a copy in `src/launcher/plan2code.js`, `agents.rs` in the app), and `scripts/fixtures/agents-cases.json` is the contract all three readers' tests load: file normalization with its warnings, `buildArgs` command lines and `makeId` ids. Change a rule in the fixture first.
|
||||
|
||||
`src/launcher/agents.json` is the shipped list: `kind: "builtin"` entries (Claude Code, Devin, Codex) with `installUrl`, per-OS `install` lines and `installDirs`, and `kind: "template"` entries other CLIs can be saved from. `install.js` copies it to `~/.plan2code/bin/agents.json` beside `agent-lookup.mjs`, which all JS readers share: `loadAgentList()` reads it, `findAgent()` gives a command its `found` / `outside` / `missing` state (PATH, the saved Windows PATH, npm's global bin, the entry's `installDirs`). The app reads the same JSON with `serde_json` at run time (`include_str!` of the repo file baked in as fallback) and `find_on_path` in `agents.rs` is its Rust twin: `scripts/fixtures/agent-lookup-cases.json`, loaded by `scripts/test-agent-lookup.mjs` and by `cargo test` through `include_str!`, is the contract both lookups are held to.
|
||||
|
||||
- **File:** `{ "schema": 1, "agents": [...] }`. Any other schema, text that is not JSON, or `agents` that is not a list gives no custom agents and one warning. A missing file is an empty list with no warning. More than 50 entries: the first 50 are used. Unknown keys, in the file and in an entry, are kept when the console saves.
|
||||
- **Entry:** `id`, `name` and `command` are required; `args` (default `[]`), `prompt` (default `"/plan2code"`, blank allowed), `bypassArgs` (`[]`), `modelArgs` (`["--model", "{model}"]`) and `models` (`[]`, each `{ id, label? }`) are optional. The three argument fields are lists of text, one list item per argument.
|
||||
- **Rules:** `id` matches `^[a-z0-9][a-z0-9-]{0,31}$`, is not `claude`, `devin` or `codex`, and is unique; `name` is at most 60 characters and unique ignoring case; `command` is not blank. `makeId(name, taken)` makes the id from the name in kebab case (`agent` when nothing is left), with `-2`, `-3` on a clash, at most 32 characters.
|
||||
- **Bad entries:** a bad entry is skipped with a warning naming it (`agents[i]`, 0-based) and the rest still load, in all three readers. `POST /agents` instead refuses the save with `{ error, index, field }`, and answers `409` while the file holds something `GET /agents` could not read, unless the body says `replace: true`.
|
||||
- **Command line:** `buildArgs` returns `args` with `{prompt}` filled (the prompt is appended when no argument holds it, and a blank prompt drops an argument that is exactly `{prompt}`), then `modelArgs` with `{model}` filled when a model is chosen, then `bypassArgs` when checks are off. Arguments travel as a list, never through a shell; the Windows `cmd` wrapper for a `.cmd` or `.bat` belongs to the launcher and the app.
|
||||
|
||||
## Workflow Prompts (in `src/`)
|
||||
|
||||
@@ -101,11 +137,15 @@ plan2code/
|
||||
| `plan2code-2-document.md` | 2 | Create implementation specs |
|
||||
| `plan2code-3-implement.md` | 3 | Execute implementation (phase by phase) |
|
||||
| `plan2code-3-implement-review.md` | 3 | Execute one phase, run focused review and fixes, then request approval |
|
||||
| `plan2code-review.md` | review | Post-implementation comprehensive review |
|
||||
| `plan2code-review.md` | review | Post-implementation comprehensive review, analyzed by one fresh helper when the tool has one (verified in session; the report says who reviewed) |
|
||||
| `plan2code-4-finalize.md` | 4 | Validate, summarize, feedback, archive (steps 1–7, +optional 6.5) |
|
||||
| `plan2code-handoff.md` | handoff | Compact the conversation into a self-contained handoff document for a fresh session |
|
||||
| `plan2code-changelog.md` | changelog | Check the CHANGELOG version against the default branch, suggest editable entries for new work, keep `package.json` aligned, offer Git commit |
|
||||
| `plan2code-git-commit.md` | git-commit | Commit with a clear message, suggested splits, a branch offer on the default branch, and an optional push |
|
||||
| `plan2code-xray.md` | xray | Explain how and why an area works (files, commits, PRs via `gh` when present), or rank the rough spots worth fixing into `ARCHITECTURE-BRIEF-<date>.md` for Pathfinder or Plan; never edits code |
|
||||
| `plan2code-diagnose.md` | diagnose | Find a bug's cause under the find-the-cause-first habit (`references/building-habits.md`) and write it up as `specs/<bug-name>/DIAGNOSIS-<YYYYMMDD>.md` without fixing it, then offer Quick Task to fix it, or Plan when the fix is big. The dashboard scan reports such a folder as spec state `diagnosed` ("Bug diagnosed"), which lights Quick Task (suggested) and Plan. Once Quick Task marks the diagnosis `Fixed` (nothing past it in the folder) the state is `fixed` ("Bug fixed"): no pipeline card lights, the picker never pre-selects it, and Quick Task offers to archive it with `specs.mjs archive` |
|
||||
| `plan2code-pr-prep.md` | pr-prep | Get a branch ready for review: pick the checks its changes need from the project's `## Test map` (or its config files), let the person trim the plan, run it, give Ready, Ready with notes or Not ready, and write a PR description to copy (following the repo's template) with the create-a-PR link; offers to save `PR-READINESS-<date>.md` into the branch's spec folder; never commits, pushes or opens the PR |
|
||||
| `plan2code-test.md` | test | Write missing tests: ask where to look, find source files no test covers (matching, plus real coverage when the project already has a coverage tool, offered first), show a plan opening with how this project writes tests, then write and run unit and integration tests; escalates past 8 source files, 8 new test files or 2 runners to a PLAN-DRAFT for Plan, hands a real bug to Diagnose, never changes source code |
|
||||
| `plan2code-changelog.md` | changelog | Check the CHANGELOG version against the default branch, suggest editable entries for new work, keep `package.json` aligned, offer to commit the result through Git |
|
||||
| `plan2code-git.md` | git | Branches, pull (with conflict help), push, publish and commits (clear message, suggested splits) on the web console's git board, or plain instructions in the terminal (`switch to main`, `commit and push`); asks before every push, publish and delete |
|
||||
|
||||
## Naming Convention
|
||||
|
||||
@@ -123,7 +163,7 @@ Examples:
|
||||
|
||||
Some workflows use companion reference files for depth that does not need to load on every invocation. The orchestrator (main workflow file) loads them via `Read` directives during execution.
|
||||
|
||||
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`)
|
||||
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`). A file several skills read lives in `src/shared-references/` instead and ships to each through `additionalReferences` (e.g., `building-habits.md` into Quick Task, Implement and Implement + Review).
|
||||
|
||||
**How the installer handles them:** the directory is copied verbatim to `skills/<skill-name>/references/`, so `Read references/<file>.md` resolves consistently for every agent. There is one output format, with no flat-file sibling directory or path rewrite.
|
||||
|
||||
@@ -142,20 +182,27 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
|
||||
|
||||
| Script | Skills | Does |
|
||||
|---|---|---|
|
||||
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/lib.mjs`, so the dashboard and the skills share one spec classifier |
|
||||
| `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update | The `<subject>` / `AI Assisted` commit command (two `-m` flags), with optional `git add` |
|
||||
| `review-scope.mjs` | review, implement(-review), quick-task | Review Mode's git fallback: files, lines, doc share, base branch |
|
||||
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff, diagnose | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/scan.mjs`, so the dashboard and the skills share one spec classifier |
|
||||
| `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update, git | The `<subject>` / `AI Assisted` commit command (two `-m` flags), with optional `git add` |
|
||||
| `review-scope.mjs` | review, implement(-review), quick-task, finalize, pr-prep, test | Review Mode's git fallback: files, lines, doc share, base branch |
|
||||
| `glob.mjs` | init, init-update, pr-prep, test | The glob subset (`**`, `*`, `?`, `{a,b}`) as a RegExp, and forward-slash path normalizing; imported by `test-map.mjs` and `test-match.mjs` |
|
||||
| `test-map.mjs` | init, init-update, pr-prep, test | `read` / `write` the project test map (one `\| Area \| Paths \| Run \| Shared \|` table under `## Test map` in `AGENTS.md`, or behind one link to `.agents-docs/`); every line outside the table stays byte-identical |
|
||||
| `test-match.mjs` | pr-prep, test | `covers` (changed files to the map rows and tests that cover them, plus shared-ground hints), `gaps` (source files no test covers, ranked by recent change) and `nearest` (existing tests to read for style) |
|
||||
| `test-commands.mjs` | init, init-update, pr-prep, test | `discover`: the whole-suite command, per-folder runners, lint/types/build checks, coverage commands already present and the language's built-in runner, from config files only |
|
||||
| `run-check.mjs` | pr-prep, test | Run one command with a timeout, kill its process tree on timeout, and classify it `passed`, `failed`, `timeout` or `not-started` with the output's tail |
|
||||
| `pr-prep.mjs` (own) | pr-prep | `template` (the PR template and its headings), `pr-url` (the create-a-PR link through `git-repo.mjs`) and `spec` (the branch's spec folder for the save offer). Read-only |
|
||||
| `coverage.mjs` (own) | test | `read --lcov` / `--go-func`: coverage output as per-file lines, hits and percent, plus the total. Read-only, runs no tool |
|
||||
| `agents-md.mjs` | init, init-update | AGENTS.md structure, budget, orphans, broken links, always-inline sections |
|
||||
| `agent-files.mjs` | init, init-update | Detect and replace other agents' config files with AGENTS.md pointers |
|
||||
| `pathfinder.mjs` (own) | 0-pathfinder | `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate`, `lint`, `brief-data` |
|
||||
| `feedback-payload.mjs` (own) | 4-finalize | STEP 6.5's payload (real sha256 prompt hashes) and the gh / browser / print submission tiers |
|
||||
| `handoff-path.mjs` (own) | handoff | Timestamped path, OS temp dir, git ignore check |
|
||||
| `xray.mjs` (own) | xray | `hotspots` (churn, files changed together, often-changed files with no test, from `git log` over a capped window) and `history <path>` (commits following renames, a blame summary, PR titles and first paragraphs through `gh` when signed in, and which sources were used). Read-only |
|
||||
| `changelog-state.mjs` (own) | changelog | `state`, `bump`, `set-package-version`: the default branch's version, whether the branch's entry can be extended (not released, not on another branch), the file's heading style, the gap since the entry was last touched; only `set-package-version` writes, and only the version field |
|
||||
| `git-state.mjs` (own) | git-commit | `state`, `branch-check`, `init-check`: the repo snapshot, branch-name check and git init safety check, read-only |
|
||||
| `git.mjs` (own) | git | `state`, `plan`, `branch-check`, `init-check`, `delete-check`, `cleanup-list`, `conflicts`, `pr-url`, `classify-error`: the repo snapshot, each action's exact command and confirm text (shared by the terminal and the board), branch-name, delete, cleanup and git init checks, a stopped rebase's conflicts, the pull-request link and git's errors sorted into kinds with a next step. Read-only: the agent runs every command it prints, and `guard()` refuses force push, hook skipping, amend, remote delete and blanket add |
|
||||
|
||||
**Conventions** (`common.mjs`): Node 18+ built-ins only; one JSON object on stdout (`ok: false` plus `error`, `message`, `next` on a handled failure, the same line on stderr); exit 0 ok, 1 crash, 2 bad arguments, 3 not found, 4 invalid or check failed, 5 refused; `--help` documents commands and exit codes; writes take `--dry-run`; `PLAN2CODE_NOW` pins the clock for tests. A SKILL.md names a script as `node "<S>/<name>.mjs"`, where `<S>` is `scripts/` beside it.
|
||||
|
||||
**Tests:** `scripts/test-skill-scripts.mjs` (installer plumbing and the shared scripts), `scripts/test-script-<skill>.mjs` (a skill's own), with fixtures from `scripts/skill-script-helpers.mjs`. They run the built `skills/` tree, and one test fails if any SKILL.md or shipped reference names a `<S>/<name>.mjs` that skill does not ship. The per-skill scripts import `./common.mjs`, which only sits beside them in the built tree, so run them from `skills/`, not `src/`.
|
||||
**Tests:** `scripts/test-skill-scripts.mjs` (installer plumbing and the shared scripts), `scripts/test-script-<skill>.mjs` (a skill's own, and the newer shared scripts: `test-script-test-map.mjs`, `test-script-test-match.mjs`, `test-script-test-commands.mjs`, `test-script-run-check.mjs`, `test-script-pr-prep.mjs`, `test-script-coverage.mjs`), with fixtures from `scripts/skill-script-helpers.mjs`. Importing that module rebuilds `skills/` unless `npm_lifecycle_event` is `test` (`npm test` has just built it). Git fixtures go through `copyFixture()` (`scripts/fixture-helpers.mjs`): built once per test file, copied per test, since every `git` process costs a few hundred milliseconds on Windows; a remote inside the fixture is added with `slashed()` so the copy's `.git/config` can be pointed at its own origin. They run the built `skills/` tree, and one test fails if any SKILL.md or shipped reference names a `<S>/<name>.mjs` that skill does not ship. The per-skill scripts import `./common.mjs`, which only sits beside them in the built tree, so run them from `skills/`, not `src/`.
|
||||
|
||||
## Repo-Local Skills (`.claude/skills/`)
|
||||
|
||||
@@ -163,94 +210,402 @@ Maintainer-only skills committed to the repo but deliberately excluded from the
|
||||
|
||||
- `plan2code-publish/` — publishes a GitHub Release after version files agree.
|
||||
- `plan2code-changelog/` — validates release classification and keeps version files synchronized.
|
||||
- `plan2code-model-update/` — refreshes the launcher's curated model menu (`src/launcher/models.json`) from `devin models list` and Claude Code's documented model aliases: shows a diff, applies only the changes the maintainer approves, validates the file and runs `npm test`. Terminal only, and it never commits.
|
||||
- `plan2code-launcher-update/`: refreshes the launcher's shipped data: the curated model menu (`src/launcher/models.json`) from `devin models list` and Claude Code's documented model aliases, and the agent list's install data (`src/launcher/agents.json`) re-checked against each vendor's docs, including a re-check of the agents left out as templates (Cursor CLI, Aider) against the template rule. Shows a diff, applies only the changes the maintainer approves, validates both files and runs `npm test`. Terminal only, and it never commits.
|
||||
- `sync-repo/` — decrypts the protected upstream-sync workflow in memory.
|
||||
|
||||
Do not run `skills add` against the repository root: recursive discovery also finds these maintainer skills. `install.js` targets `skills/` and passes explicit workflow names instead. Global install/uninstall cleanup removes `plan2code-*` workflow skills from user skill directories; it never operates on this repository's `.claude/skills/` directory, and `sync-repo` intentionally has no `plan2code-` prefix.
|
||||
|
||||
## Web Console
|
||||
|
||||
Optional local browser UI shipped with **every** skill. Source lives in `src/web-console/` and is fanned into each skill by an `additionalReferences: [{ source: 'web-console', target: 'web-console' }]` entry in `SOURCE_PROMPTS`, landing at `skills/<skill>/references/web-console/`. The bare `plan2code` skill is the hub: it opens the console as `--workflow dashboard`, the page draws the skill menu itself (from `SKILL_CATALOG` in `public/answers.js`, kept in sync with the install set by a test), and a card click reaches the agent as a `{ "i": "__launch", "skill": ..., "workflow": ... }` send — the dashboard then **resumes its own session** under the launched skill's workflow (`open --resume <sid> --workflow <w>` restates `workflow`/`title`/`specDir` on the live server) and runs that skill's file. `plan2code-review` now has a console of its own AND still runs inside builds on the page (a `review` verdict on Implementation's sign-off card, or the **Review it now** button on a finished quick task), so `plan2code-3-implement` and `plan2code-quick-task` also carry `review.md` and the review references, the same way `implement-review` does. The list of skills with a console is duplicated as `CONSOLE_WORKFLOWS` in `public/answers.js` (it decides whether a copied hand-off asks the next session for the console); a test fails if the two disagree.
|
||||
Optional local browser UI shipped with **every** skill. Source lives in `src/web-console/` and is fanned into each skill by an `additionalReferences: [{ source: 'web-console', target: 'web-console' }]` entry in `SOURCE_PROMPTS`, landing at `skills/<skill>/references/web-console/`. The bare `plan2code` skill is the hub: it opens the console as `--workflow dashboard`, the page draws the skill menu itself (from each `SKILLS` entry's `card` in `public/skills.js`, through `SKILL_CATALOG` in `public/answers.js`, kept in sync with the install set by a test), and a card click reaches the agent as a `{ "i": "__launch", "skill": ..., "workflow": ... }` send — the dashboard then **resumes its own session** under the launched skill's workflow (`open --resume <sid> --workflow <w>` restates `workflow`/`title`/`specDir` on the live server) and runs that skill's file. `plan2code-review` now has a console of its own AND still runs inside builds on the page (a `review` verdict on Implementation's sign-off card, the **Review it now** button on a finished quick task, or Finalize's Step 2.5 final review, offered on every run), so `plan2code-3-implement`, `plan2code-quick-task` and `plan2code-4-finalize` also carry `review.md`, the review references and `review-scope.mjs`, the same way `implement-review` does. `CONSOLE_WORKFLOWS` in `public/answers.js`, built from the same `SKILLS` list, decides whether a copied hand-off asks the next session for the console.
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`) |
|
||||
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `delete-spec`, `handoff new`, `delete-handoff` (both on `handoffs.mjs`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`; `help <topic>` prints one contract file, `help topics` lists them). `post --wait <N>` posts and waits in one command |
|
||||
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
|
||||
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()`; plus `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
|
||||
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `subagents.js`, `mentions.js`, `favicon.js`, `app.css`, `render.js`, `palette.js`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server, `console.mjs`, `lib.mjs` and the tests import several `public/*.js` modules) parses them as ES modules without a reparse warning |
|
||||
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (17 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
|
||||
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `console.mjs`, `lib.mjs` and the page |
|
||||
| `public/meter.js` | PURE, no imports: the session meter. `WEIGHTS` (the one place per-event points live; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
|
||||
| `public/` (other files) | `index.html`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server and the tests import the pure modules) parses them as ES modules without a reparse warning. The stylesheet is the files in `public/styles/`, joined by the server into the one `/app.css` the page asks for |
|
||||
| `cmd-chat.mjs` | the `chat` command: hand over Quick questions now, never waiting |
|
||||
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files; the usage's workflow list and its build sessions come from `WORKFLOWS` and `isBuild()` in `skills.js` |
|
||||
| `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser; refuses a `--workflow` that `isWorkflow()` does not know (exit 2, naming the valid ones), and asks `startsClean()` (`public/hops.js`) whether a resume blanks the page |
|
||||
| `in-app.mjs` | the desktop app's signal to `open`: `inAppSignal()` reads `PLAN2CODE_IN_APP`, `PLAN2CODE_CONSOLE_SID`, `PLAN2CODE_APP_ANNOUNCE` and `PLAN2CODE_APP_TOKEN`; `announcePage()` POSTs the page to that window's loopback endpoint. Under the app `open` never starts a browser, resumes the app's session and announces the page; with the variables unset nothing here runs. Imported by `cmd-open.mjs` |
|
||||
| `open-link.mjs` | the desktop app's webview opens no new windows, so the page there sends links off the console (`linkLeavesPage()` in `public/app-bridge.js`: http or https on another origin, caught in `wireChrome()`) to `POST /open-link`. `linkToOpen()` takes http and https only (400 otherwise); `openLink()` starts the default browser with the link as one argument, never through a shell (`rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `$BROWSER` or `xdg-open` elsewhere) and skips it under `PLAN2CODE_NO_BROWSER`. When that fails the page shows the link with a Copy button to paste into a browser |
|
||||
| `loop-setup.mjs` | the Implementation Loop's setup, remembered per project in `~/.plan2code/console/loop-setup.json` (one entry per folded project folder, schema 1): defaults, validation and the read and write the `/loop-setup` route uses. The app reads the same file itself for the quick check, so the page never carries that command |
|
||||
| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent |
|
||||
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does |
|
||||
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
|
||||
| `agents.mjs` | the rules of `~/.plan2code/agents.json` (see Agents file above), console side: `normalizeAgents()` reads the file into clean entries and warnings, never throwing; `validateForSave()` checks what User Preferences sends and names the first bad entry and field; `makeId()`, `buildArgs()` (the command line from an entry) and `resolveCommand()` (where a command runs from, never running it). Served by `GET` / `POST /agents` and `POST /agents/test` in `routes.mjs` |
|
||||
| `agent-lookup.mjs` | where an agent lives on this machine: `loadAgentList()` reads the shipped `bin/agents.json` (built-in agents and starter templates; `optional` keeps an absent file silent); `findAgent()` gives one command its `found` / `outside` / `missing` state, the path and which search found it (PATH, the Windows saved PATH, npm's global bin, the entry's `installDirs`), with `{bypass}` / `{model}` placeholders expanded to the user's picks. Used by `GET /agents`, `POST /agents/use-path`, the launcher's `chooseCli()` and the Windows picker |
|
||||
| `inbox.mjs` | the Quick question chat's inbox beside the card slot |
|
||||
| `console-docs.md` | the topic file for `docs` in a patch (tabs of blocks), named by the console at the first patch that carries `docs`; not read up front. Byte-budgeted with the card and the notes in `scripts/test-console-wire-budgets.mjs` |
|
||||
| `pointers.mjs` | which topic file the console names and when: once per session per topic, remembered in the session folder (`pointers.json`), reset by a resume |
|
||||
| `patches.mjs` | checking and merging an agent's patch into the session state: `validate()` (the house rules; allows `templates` only as `"idea"` on a `text` item, anything else exits 3), the patch merge, `resolveDocFiles()` and `applyPatch()` |
|
||||
| `routes.mjs` | every URL the page can call, in one ordered list (`ROUTES`, walked by `handle()`); `server.mjs` hands each request to it |
|
||||
| `scan.mjs` | what the dashboard knows about the repo: `scanProject()`, `classifySpec()` (a folder's files to a spec state), `TASK_LINE_RE` (re-exported from `spec-files.mjs`) and `removeSpec()` |
|
||||
| `sessions.mjs` | a session's roots and handle files (`repoRoots()`, `healthOk()`, `attachmentName()`: the kept-file name `<slug>-<id8>.<ext>`, the same upload always gets the same name, `readOverview()`) and the console folder's housekeeping: the three sweeps `open` runs fire-and-forget after it prints (`sweepUploads()`, `staleSessions()` / `removeSessions()`, `staleScratch()` / `removeScratch()`) and `cleanupFindings()` / `removeCleanup()` for User Preferences → System → Cleanup |
|
||||
| `settings.mjs` | the person's saved console settings: Subagents and pull-request hosts |
|
||||
| `spec-files.mjs` | no imports: how a spec's markdown files are read, `MARKERS`, `TASK_LINE_RE`, `TASK_ID_RE`, `CHECKBOX_RE`, `STATUS_RE`, `statusOf()` and `countTasks()`; shared by `scan.mjs`, `patches.mjs` and `src/skill-scripts/specs.mjs` (through `consoleModule()`) |
|
||||
| `static.mjs` | serving the page's own files: `SERVABLE` (the allow-list), `TYPES`, caching and ETags, the accent colors, and `CSS_ORDER` + `joinedStyles()`, the one place the cascade order is stated |
|
||||
| `workspace.mjs` | the session's extra folders, and the folders remembered per project and spec |
|
||||
| `public/activities.js` | the list of activities (`ACTIVITIES`: each game's id, title, picker card line `blurb` and module path) an optional `courses` list (Mini golf's six course ids, which open a course dashboard), `bestKey(id, course?)`, the flat looks.json key for its best score (`activityBestSnake`, one per golf course `activityBestGolfPirate` to `activityBestGolfFrost`, `activityBestTrails`, `activityBestBugs`, `activityBestDrive`, `activityBestStack`, `activityBestBumper`, `activityBestRapids`, `activityBestFuse`, `activityBestHop`, `activityBestBounce`, `activityBestGhoul`, `activityBestFlock`); lists Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, `bestKeys(entry)`, every best key a game keeps, and documents the game contract including the course parts (`courses` and `preview()` on the export, `setCourse()` and `course` on the game), the optional `pointer(type, x, y)`, `release(name)` (a game key let go) and `lowerIsBetter`; data only, imported by the page and by Node |
|
||||
| `public/activities/snake.js` | Snake: its rules as plain exported functions and the game contract (`create({ canvas, tone, onScore })` returning `start`, `pause`, `resume`, `key`, `tick`, `resize`, `score`, `state`); it never runs a timer or listens for keys, so the Activities window drives it; it also holds the music's rules: `MUSIC_TRACKS`, `dealMusic(random, last)` (a round's shuffle of the ten tracks, never opening on the last round's opener), `trackFor(deck, level)` and `heat(round)` (the snake's speed as 0.3 to 1, so the lead and drums are in from the first step) |
|
||||
| `public/activities/trails.js` | Light Trails: its rules as plain exported functions (`newRound`, `newHeat`, `turn`, `boost`, `advance` in 8 ms slices (where your crash is held for `GRACE_MS`, a turn in that time riding out of it; rivals get no grace), `choose` and `room` for the rivals' flood-fill steering, `applyPower` (a Mystery becoming another pad), `pickPower` (by each pad's `from` arena, a Heart only under `MAX_LIVES`), `fireLaser`, `hyperjump`, `awardLives` (a life every `LIFE_SCORE` points, the mark moving on at the cap), `spawnItem`, `closeRing`), the `ARENAS` (rivals, sharpness and what each adds), the `POWERS` pads (Boost, Phase, Eraser, Slow-mo, Coin, Heart, Shield held across heats until a crash in your grace pops it, Laser with `LASER_SHOTS`, Score x2 through one `gain()` every score goes through, Wide Trail with its side cells in `rider.wide`, Coin Rain whose `rain` coins never hold back a pad, Hyperjump, Mystery) and the game contract; `START_LIVES` is 5; memo is the furthest arena reached; a read-only `round` getter for the tests only; it also holds the music's rules: `MUSIC_TRACKS` (its five songs) and `dealMusic(random, last)` (a shuffle of them, never opening on `last`); a run plays the deal one song after another, each in full from the top (asking with `{ restart: true }` until the music takes it), moves on when `music()` answers `"ended"`, deals again after the last, and a new run deals afresh, never opening on the song the last run was playing; its tones and hums play `SFX_LOUDER` times as loud through tones.js's `louder`, all but the engine drones (`DRONES`), kept low under the songs |
|
||||
| `public/activities/bugs.js` | Bug Hunt: its rules as plain exported functions (`newRound`, `spawnWave`, `slotPos`, `advance` in 8 ms slices over `round.input`, which `key()` and `release()` set, `hurtBug`, `hurtBoss`, `hitShip`, `applyPower`, `ghostly`, `tentacleTip`, `bossRadius`), the `BUGS` by first wave, the `BOSSES` every `BOSS_EVERY` waves, the `POWERS`, the `SECTORS` scenery and the game contract with `release()`; memo is the tally of `DISCOVERIES` as bits; a read-only `round` getter for the tests only |
|
||||
| `public/activities/drive.js` | Sunset Drive: its rules as plain exported functions (`newRound`, `buildStage`, which appends a stage of road and returns its `forkAt`, `gateAt` and `fork`, `segAt`, `advance` in 8 ms slices over `round.input`, which `key()` and `release()` set, `boost`, `usePower` (the oldest queued power-up, which space fires ahead of `boost`), `hopHeight`, `checkTime`), the `POWERS` in `POWER_ORDER`, the `REGIONS` (roads with their bonus, bends, hills, traffic, colors and props) in `REGION_ORDER`, the projection and drawing (sky, road far to near, props, traffic, Planny's car) and the game contract with `release()`; the next road is built only when the fork is chosen, and `FORK_LEN` must stay at least `DRAW` so it is built before it comes into view; memo is the roads found as bits; a read-only `round` getter for the tests only |
|
||||
| `public/activities/stack.js` | Stack Deploy: its rules as plain exported functions (`newRound`, `spawnBlock`, `advance` in 8 ms slices that slides the block between the walls, `drop`, which drops it where it was last drawn and returns `{ kept, sliced, perfect, miss }`, `isPerfect` and `zoneOf` (3% of the block's width, the slide in `PERFECT_MS`, or `round.minZone`, the `MIN_ZONE_PX` floor the game sets at each resize, whichever is most, but never more than half the block's width, so a drop off the tower is never perfect), `grow`, `speedAt`, `twistsAt`, `styleAt`, `comboPitch`), the `TWISTS` by floor (speed ramp, either side and turning back, lag spikes, wind, rush hour, faster) and the `STYLES` of the tower, the drawing (sky by height, blocks per style, Planny riding the top, the dashed marker of the highest floor) and the game contract with `pointer()` (a press on the board drops) and `release()` (a held up drops once, not at every key repeat, and `key(name, repeat)` ignores a repeat the window marks, so up held through the countdown never drops at its first repeat); a press waits for the first tick after a start or a play-on, so an arrow that resumes never also drops; a miss holds the round running for `OUTRO_MS` while the camera pulls back over the whole tower; memo is the highest floor ever reached, saved on a pause and at the end; a read-only `round` getter for the tests only |
|
||||
| `public/activities/bumper.js` | Bumper Ring: its rules and physics as plain exported functions (`newRound`, `newHeat`, `advance` on a fixed 4 ms sub-step over `round.input`, which `key()` and `release()` set, `push` (accel toward the held direction, capped at the top speed that way, drag easing a car to the floor's own speed), `collide` (circle bounce with restitution `BOUNCE`; the faster car rams and gives `SHOVE_BONUS` more, takes that much less back; under `IMPACT_SPEED` it is a lean, no bounce and no shove, so a pushing match goes to the stronger push), `dash`, `edgeGap` and `outOfRing` (a car is out when its center is past the edge or over an open hole; round or, in the Hall of Mirrors, square), `shrinkAt` and `nextShrinkIn` (whole for `SHRINK_START_MS`, `SHRINK_STEP` a step to `MIN_RING`, then after `SUDDEN_MS` sudden death to `LAST_RING`, under one car's radius, so every heat ends), `aim` (a rival's push, dash and target per personality, with panic near the edge and a sharpness-scaled chance to misjudge), `applyPower`, `spawnPad`, `creditKo` (the last toucher within `CREDIT_MS`, your hit carried through a rival counting as yours, and a rival you rammed into another keeping your credit, the carry lasting `CAROM_MS` from your hit; the combo, the double and the bait bonus), `rivalPower` and `arenaFor` (each built once per arena, since the rules ask every slice), `holeState`), the `ARENAS` (rivals, sharpness, shrink pace, then endless Finals past the ninth), the `RIVALS` personalities and the `POWERS` pads, and the game contract with `release()`; a rival winds a dash up for `WINDUP_MS` (shorter when sharper) before it goes, which is the player's moment to step aside; a big hit holds the action for `HIT_STOP_MS`; memo is the furthest arena reached, which can pass 9; a read-only `round` getter for the tests only. Hand-tuned from the brief's starting numbers (the changes are listed under "As built" in `game-ideas/bumper-ring.md`), aiming for heats of 20 to 60 s from arena 2 on |
|
||||
| `public/activities/bumper-draw.js` | Bumper Ring's drawing: `drawScene(ctx, view)` from a plain view `bumper.js` builds (the round, the board geometry, the effects, the pill numbers), each arena's ring in its fixed palette (`themeFor`), the floor (ice, oil, holes, bumpers, the magnet, the warning bands), the cars (Planny upright at the wheel of a car in `--accent`, star eye and stick arms; rivals with a face each), the pills (laid out by `hudLayout`, which starts a row below rather than run into the ring's countdown or off the board), banners and the start and end strip, and `readColors(canvas)`; decides nothing |
|
||||
| `public/activities/rapids.js` | Rapids Run: its rules as plain exported functions over a round on a river scrolling down a 64 unit wide field, 84 units of it on the board (`newRound(seed)`, `newRiver(seed)`, `buildStretch(river, n, random)` (a stretch's rows from its own seed, each row a center, width and island width: a calm opening, then drifts, narrows and islands, every bank slanting at most `SLOPE` a unit, every channel at least `MIN_CHANNEL` wide, then a `BASIN_W` basin on a boss stretch and the narrowing to the `DAM_W` dam; and its plan of foes, buoys and crates, none in the first `SAFE_START` (where you start again) or by the dam), `ensureRiver`, `riverAt` (a row's banks and island eased from the row before's, so they slant as drawn), `channelsAt`, `channelAt`, `isWater`, `onLand` (the hull sampled at seven points), `placeAt` (the start of a stretch, its dam whole and its plan loaded afresh), `advance` in 4 ms slices over `round.input`, which `key()` and `release()` set: steering eased in, the whirlpools' tug, the speed held (up, down or neither, times the stretch's `pace`), the battery drained (`DRAIN` a second cruising, more at speed), distance points, the guns (`FIRE_MS`, Spread's fan), shots against foes, the boss, the dam and buoys, the foes (skiffs and darters drift and turn at the banks, a darter swerves into your lane, gulls take off as you near and swoop across, sentries fire at you), the boss (`spawnBoss` holds the river and the battery; its volleys by kind), bolts, pickups (a buoy `BUOY_CHARGE`, the magnet's pull, crates), crashes (`lose`: a shield takes any crash but a flat battery and slides you off a bank; blinking for `GRACE_MS` after a restart), skims (`SKIM_POINTS` each `SKIM_MS` closer than `SKIM_GAP` at speed), the dam (`hitDam`, then past it the next stretch, with `FLAWLESS_POINTS` times it for no life lost), `hurtFoe` (the combo, up to `MAX_COMBO`), `hurtBoss` (a life back and a crate), `applyPower`, `stretchFor` (built once a stretch; past the eighth, Night Water 2, 3 and on), `underBanner`, `screenY`, `seeded`), the `FOES`, `BOSSES`, `POWERS` and `STRETCHES`, and the game contract with `release()` (held arrows steer, speed and slow, held space fires; a pause lets go of every key); memo is the furthest dam blasted, which can pass 8; a read-only `round` getter for the tests only. Tuned by a scratch sim: a careful bot clears a stretch in 20 to 35 seconds, and the battery runs flat for one that grabs too few buoys |
|
||||
| `public/activities/rapids-draw.js` | Rapids Run's drawing: `drawScene(ctx, view)` from one view object `rapids.js` refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run off the board and centers its rows in the strip), the river a look at a time (`LOOKS`: meadow, autumn, canyon, marsh, dusk and night, each in fixed colors, the look changing at each dam): banded banks, the water between them with shore lines and flow streaks carried downstream by the view's clock, pointed islands, trees or rocks; the dam ahead (hazard stripes, a crack for every share knocked out, a trickle once it is close to going) and the broken one behind; charge buoys, crates with their glyphs, whirlpools, skiffs, darters, mines, bank sentries aiming at you and gull drones with their shadows; the mini-boss and its health bar; Planny's jet-skimmer in your highlight with a white trim (so a blue highlight still shows on blue water), his wake, jets, arms to the bars (up when a dam or a boss goes), his box and his star eye in your highlight, bobbing with the star spinning after a crash; shots, bolts, sparks, rings, floating words (kept on the field by `labelSpot`), the combo's big number, the battery gauge beside the field (green, amber, then red and blinking under the low mark), banners, and the start and end strip with the big final score and a dot per named stretch whose dam you have blasted; `readColors(canvas)`, `lookColor`, `inkOn`, `contrast`; decides nothing |
|
||||
| `public/activities/flock.js` | Flock Dash: its rules as plain exported functions over a round scrolling right to left over a 96 by 54 unit field (`newRound(seed)`, `steer` (the leader eased up and down inside the `BAND_MIN` to `BAND_MAX` band at the left), `recordPath`, `placeFlock`, `screenX`, `collect` and `spawnStrays` (a stray joins the flock, the combo up to `MAX_COMBO` within `COMBO_MS`), `buildStage(seed, n)` (a stage's hazards by distance from its own seed, a clear `SAFE_START` and `SAFE_END`, and `clearGap` keeping a way through), `moveHazards`, `hazardHits`, `snapAt` (a snap drops the birds behind the one hit, `scattered` for `SCATTER_MS` so they can be picked up again), `hitLeader` (a life, or a shield; `GRACE_MS` after), `reachPortal` (the jet stream portal, the V of `V_POINTS` a bird when the flock has `min`, `FLAWLESS_POINTS` for no snap or life lost, and the final portal that sways), `applyPower` (crates: tailwind, shield up to `MAX_SHIELDS`, magnet), `banner`, `bannerRow`, `underBanner`, `advance` in `SLICE_MS` slices, `teaser`, `seeded`, `dealMusic`), the `STAGES` table (eight stages, each with its speed, length, stray gap, portal `min`, hazard weights and gap; the place to tune the difficulty), the `HAZARDS` (balloon, gust, stream, cluster, storm, kite, each from its own stage) and `POWERS`, and the game contract with `release()` (held arrows steer, a pause lets go of every key); the round also carries `events` (what the draw and the sounds react to) and `warned` (one gust or storm warning each); memo is the furthest stage reached. The flock is a recorded path with running arc length: follower k sits `k * SPACING` behind the leader along it, so it copies every turn at any speed. `MUSIC_TRACKS` names the five songs, dealt afresh each round |
|
||||
| `public/activities/flock-draw.js` | Flock Dash's drawing: `drawScene(ctx, view)` and `hudLayout` from one view object `flock.js` refills each frame, in field units: the sunset sky (`SKIES`, one palette per stage: the sun sinking, clouds, a rim light from stage 6 and stars on the last), the hazards (balloons and bunches, the head-wind's warning band and gust, slipstreams, thunderheads with their flash and bolt, kites on their strings), the strays and scattered birds, the flock, Planny as the lead bird with a star for an eye, crates and the magnet ring, the tailwind streaks, the portal and the V, the pills (laid out by `hudLayout`, which shrinks them to fit the board), banners, and the end strip with the final score, the best and the teaser; `readColors(canvas)`; decides nothing |
|
||||
| `public/activities/fuse.js` | Hot Potato: its rules as plain exported functions over a round on a 104 by 70 arena (`newRound`, `newMatch(round, venue)`, which lights each bomb on a rival, never you, in a match's first fuse, `advance` in 8 ms slices over `round.input`, which `key()` and `release()` set, `move` (speed eased toward the held direction at `GRIP`, a dash holding its line, belts and ice from the floor), `dash` (a holder's dash is a numbered lunge), `tag` (a holder touching a runner with no bomb passes it, never inside `NO_TAGBACK_MS` of the bomb changing hands, nor back to the one who just passed it within `TAGBACK_MS` while three or more are left, `tagBack`, with `tagSafe` saying who is safe that way for the drawing; a fuse under `PASS_FLOOR_MS`, `NO_TAGBACK_MS` plus `PASS_REACT_MS`, is raised to it on any pass, once a fuse for each runner (`bomb.lifted`); your pass scores, a hot one under `HOT_MS` as passed steps the streak), `burn` (Freeze takes its share first), `blast` (the holder out, everyone near knocked back, the match over when that was you or one is left), `nextFuse` (a survivor with no bomb, the next shorter fuse from `fuseFor`, never more bombs than one for every two left), `think` (a holder chases by its own flood-fill path, weighted toward a boxed-in or dashless target; a runner without a bomb scores candidate spots by the holders' path distance against its own and flees to the best; personalities bend both), `applyPower`, `spawnPickup`, `speedOf`, `clearLine`, `rivalPower` and `venueFor` (each built once per venue), `rivalColors(you)`), the `VENUES`, `LAYOUTS`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` never dashes on a repeat); a rival holder winds up (`WINDUP_MS`, shorter when sharp) or, a Trickster, feints (`FAKE_MS`) before a lunge, and a runner a lunge comes at dodges once a lunge at its venue's odds after its reaction time; the fuse ticks quicker and higher as it burns down, on one clock however many bombs burn (yours, else the shortest); a bomb whose fuse has run out passes to nobody; memo is the furthest venue reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/hot-potato.md`) |
|
||||
| `public/activities/fuse-draw.js` | Hot Potato's drawing: `drawScene(ctx, view)` from one view object `fuse.js` refills each frame, in arena units: the strip above the arena in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run into the fuse and centers its rows in the strip), each venue's floor in its fixed palette (`themeFor`, `venueColor`), ice, running belts, the Rooftop's open edge, the things to run round, pickups, the runners (Planny on his feet with his star eye and stick arms, flailing while he holds a bomb, and still Planny when charred; arms and feet on the floor in `limbInk(level)`, the ink that stands out from that venue's tiles; rivals with a mark per personality; a white ring with a dark edge at the feet of a runner safe from a tag-back; the charred waddle to the nearest wall and the fall from the roof), the bomb over its holder (a red ball with a `<<<` band, growing and glowing as it burns, flashing white while it cannot be passed, its fuse a shortening curl with a spark, the last seconds in big numbers (under the holder's feet when there is no room above, `countY`), a hop across on a pass), blast clouds, the Blackout's dark worked out once a frame in cells, the red edge pulse in a fuse's last second, banners and the start and end strip with the big final score, and `readColors(canvas)`; decides nothing |
|
||||
| `public/activities/hop.js` | Crossing Rush: its rules as plain exported functions over a round on a strip `COLS` (11) cells wide of 30 to 40 lanes, `VIEW_ROWS` (14) on the board at once (`newRound`, `newHeat(round, zone)`, which builds the heat's lanes from the round's seed, kept when a heat runs again, `buildLanes(zone, seed)` (groups of road, highway, ice, river, turtle, rapids or rail lanes with a grass row between each two, the zone's new thing first; the same seed builds the same lanes), `advance` in 8 ms slices (lanes flow, riders drift with their log, rivals choose, everyone is checked where they stand before any hop moves on, then hops and flights; hoppers home in the same slice finish by the moment each landed, a dead heat to you), `hop(round, hopper, dir)` (one cell, two with a Spring; a hopper counts in the cell it leaves for the first half and the one it lands on for the second; an icy lane slides it a cell more), `laneAt`, `occupied(round, row, col, atMs)` (a car or a train on it, or in a river no float or the edge, `atMs` ahead through `shiftAt`, which follows a lane's flips, surges and a Horn exactly), `sendBack` (to the last grass row, `safeBelow`, crediting a shove within `SHOVE_CREDIT_MS`), `shove(round, from, to)` (a cell the way `from` faces, only on a hopper `inReach` and never on one past the half of its hop home, once every `SHOVE_MS`), `plan(round, hopper, random, power)` (a look ahead of `LOOKAHEAD` to `LOOKAHEAD_SHARP` hops over the lanes as they will move, each hop followed by the hopper's wait where it lands; never a hop where it would be hit or fall in at full sharpness; a sloppy rival now and then hops on regardless), `applyPower`, `zoneFor` and `rivalPower` (each built once per zone), `rivalColors(you)`, `standings`), the `ZONES`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` hops once a press: never on a repeat, never again until the arrow is let go, never with the press that plays on, and with one hop queued behind the one in the air; a pause drops what is held and the queue); rivals wait `REACT_MS` down to a sharp rival's after each landing, a Bruiser shoves anyone beside it into a lane, a Tagalong follows a row behind you and shoves near the top, and a rival that lets a shove go weighs the next one only after `SHOVE_LOOK_MS`; memo is the furthest zone reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/crossing-rush.md`) |
|
||||
| `public/activities/hop-draw.js` | Crossing Rush's drawing: `drawScene(ctx, view)` from one view object `hop.js` refills each frame, in board units: the strip above the field in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run into your place and centers its rows in the strip), the lanes in fixed colors (`LANES`, `lookOf`; pavement, grass with tufts, bushes and rocks, the checkered finish, roads with dashes and surge chevrons, icy roads, rivers with ripples and Rapids arrows, tracks with a signal that flashes while a train is coming), cars, vans, trucks, logs, turtles that sink and dive, the train, pickups, the hoppers (Planny on his stick feet with his star eye in every state: stretching mid-hop, spinning as he flies back, cheering, slumped when beaten; rival critters with a Hopper's ears, a Daredevil's goggles, a Bruiser's brow and a Tagalong's beak; arms and feet, and each rival's body edge, in `limbInk(look)`, the ink that stands out from that lane), a Shield's ring and a Spring's coil, staggered stars, arrows at the edge for hoppers out of view, the Night Market's dark (soft lights cut from a layer the size of the field with one gradient made with the layer, or in steps with no second canvas), the race bar in the page's colors, banners, and the start and end strip with the big final score; every word kept on the field by `labelSpot`, and `readColors(canvas)`, `zoneColor`; decides nothing |
|
||||
| `public/activities/bounce.js` | Bounce Road: the cars, the hazards against them, the scoring and the round, as plain exported functions over a round on a road scrolling up a 72 unit wide field, 90 units of it on the board (it re-exports every rule of `bounce-road.js` and `bounce-rivals.js`, so the suite imports one module): `newRound(seed, random)`, `advance` in 4 ms slices over `round.input`, which `key()` and `release()` set (a jump press first, then your `move`, the rivals' `think` and `move`, the pads (a boost strip pushes you to `NITRO_TOP` for `BOOST_MS` even off the throttle, and the brake cuts it; a ramp launches any car crossing its lip quick enough `RAMP_AIR` the usual jump; a slick eases the steering at `SLICK_EASE` and makes a knock last for `SLICK_MS`), the bumps (`collide`: boxes pushed apart along the shallower overlap, side on a knock split by mass and harder for the car that did not steer in, end on speed passed forward, into a `HEAVY` truck's back at `CRASH_CLOSE` a crash; with Mega wheels a touch flattens; a close shave, `NEAR_GAP` or less between the boxes at speed and no touch, scores once), the barriers (a cone or a tire knocked flying slows you to `CONE_SLOW`; a block, pot or bucket nose first is a crash, from the side a push out), the hazards placed by the round's clock (a train hits a car on its track, a ball knocks a car by `BALL_KICK`, a sprinkler's jet pushes at `SPRAY_PUSH`, a drop falls `DROP_FALL_MS` after you come within `DROP_TRIGGER`, aimed at your line, and lies there after, a gust pushes at `WIND_PUSH`), then the ground (water or a hole under your middle a life, a flowerbed nose first a crash, a rival off the road out and yours within `CREDIT_MS`)), `jump`, `land` (on a car: flattened for its `points` times the chain up to `MAX_CHAIN`, a truck's roof `HAUL_POINTS`, the Monster a stomp, `STOMP_POINTS`, and on its last of `BOSS_HP` `BOSS_POINTS` times the lap and a life; on the road the chain ends, and the holes, trains, balls and barriers flown over and a ramp's big air score), `stunt` (a stunt's points times `comboOf(streak)`: every `COMBO_STEP` stunts within `STREAK_MS` of each other one more, up to `MAX_COMBO`), `lose` (a Bubble throws you clear instead), `applyPower`, `underBanner(round, y, cam)` (a rival, a coming train, a ball or a thing still falling in the strip) and `BANNER_Y`, `rivalColors(you)`), the `POWERS` (Spring, Bubble, Nitro, Mega wheels) and the game contract with `release()` (`key(name, repeat)`: held arrows drive and steer, space jumps once a press, never on a repeat or with the press that plays on, and a press up to `JUMP_BUFFER_MS` before a landing jumps on it; a pause lets go of every key and drops a press). A stage line scores `STAGE_POINTS` times the stage, `TIME_POINTS` a second under its par and, flawless, `FLAWLESS_POINTS` and a life back up to `MAX_LIVES`. Memo is the furthest stage reached, which can pass 10. A read-only `round` getter is for the tests only. Tuned by scratch bots: a careful bot clears all ten stages with no rivals on every seed tried (23 to 42 s a stage), and a bot with 150 ms reactions and 80 ms jump timing error reaches a median of stage 5 with the rivals out, stage 10 without |
|
||||
| `public/activities/bounce-draw.js` | Bounce Road's drawing: `drawScene(ctx, view)` from one view object `bounce.js` refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by `hudLayout`: stage, lives, Spring, Bubble, Nitro and Mega with their timers, the chain and the combo with its timer; a pill that would run off the board starts a second row), the road a chunk of `CHUNK_ROWS` rows at a time, drawn off screen once per road and scale, a few kept and copied each frame (rows from `bounce-scenery.js`), the layers over it (`bounce-scenery.js`), the landing rings (yours in your highlight, a rival's in red, the Monster's its own size), the cars through `bounce-cars.js` (every shadow first, upright, then every body with its tumble: Planny in your highlight with his box in the page's panel color and his star eye, arms to the wheel, up in the air or cheering, down at the end; each rival kind in its own style and color, the Cop's siren while it chases, the Monster's dents and a star per life left above it, headlights at Night Lights), sparks, rings, the dark of Night Lights, the chain's big number, the stage bar beside the field, banners, and the start and end strip with the big final score and a dot per stage reached; every word kept on the field by `labelSpot`, and `readColors(canvas)`, `limbInk`, `inkOn`; decides nothing |
|
||||
| `public/activities/bounce-cars.js` | Bounce Road's cars, drawing only and no imports: `drawCarBody(ctx, style, opts)` draws one top-down toy car about the origin, nose up, filling `w` by `h` field units exactly (tires on the box's corners), in one of `CAR_STYLES` (`STYLE_NAMES`: Planny's convertible with his star eye and arms to the wheel, hatch, sedan, coupe, muscle, pickup, van, box truck, police, racer, taxi, jeep, monster) with flat-fill shading worked out from `color` and `accent` (`shade`, `rgbOf`), and options for roll (`tilt`), a jump (`air`: it draws the shadow and the lift itself), a pancake (`squash`), night beams, a siren bar, damage, a boost flame and brake lights, all moving parts on `opts.clock`; `drawCarShadow` and `shadow: false` for a shadows-first pass in screen space; `carLength(style, w)` for a style's natural length and `carReach(style, opts)` (with `MARGINS`) for what reaches outside the box |
|
||||
| `public/activities/bounce-scenery.js` | Bounce Road's scenery, drawing only: each stage's look in fixed colors (`LOOKS`: patio slabs, lawn stripes, kitchen tiles, garden, sand, a toy room's rug, a pond with lily pads, roof shingles, the night lawn with lamps and the Monster's dirt; `lookOf`, `stageColor`, `contrast`, `better`), `drawRow` (one row of the road in three passes over a chunk: the yard, the road's surface, the details: edges slanting from row to row, rivers, plank bridges with jagged broken ends, cracks, flowerbeds, rails across a crossing, cracked road over a pit, checkered stage lines, verge decor), and the layers drawn fresh each frame from the round's clock: `drawTimed` (a drawbridge lifting with its red lights, a swaying bridge where it is now, crumbled road gone to the pit), `drawPads` (running boost chevrons, ramps, slicks), `drawBlocks` (cones, toy blocks, pots, buckets, acorns and tires, knocked ones tumbling off), `drawStars`, `drawSigns` (a mark per hazard), `drawItems`, `drawHazardsLow` (crossing lights, the train, a rolling ball, a falling thing's growing shadow, a sprinkler's head), `drawHazardsHigh` (the jet, gust streaks, the thing still falling), `drawNight` and `drawFireflies`; decides nothing |
|
||||
| `public/activities/bounce-road.js` | Bounce Road's road, rules only: the jump math every hole is sized by (`airMs(v)`, `reach(v)`, `LONGEST_JUMP`, `JUMP_FAIR`, `TOP_SPEED`, `MAX_SPEED`), `stageFor(n)` (built once a stage: the ten of `bounce-roads.js`, then laps from `LAP_FROM`, quicker, keener, busier, the Monster at every Monster Mash) and `stageName`, `newRoad(seed)` and `buildStage(road, n, random)` (a stage's rows from its own seed, by the stage's piece weights: straights, cracks, rivers on bridges with one or two broken spans or a drawbridge, splits round flowerbeds, ramps before a crack with stars beyond, cone or block chicanes, crumbling road, train crossings, swaying bridges, boost strips, slicks, balls, sprinklers, drops and gusts; every hole after a `RUNUP` with a sign and no longer than `MAX_HOLE`, the bridge between two breaks long enough to land `LONGEST_JUMP` on), `ensureRoad`, `groundAt(road, x, d, t)` (a row's edges eased from the row before's; a drawbridge water while lifted, a swaying bridge shifted, crumbled road a hole), `rowGone`, `spanAt`, `holesIn`, `firstAt`, `plainRow`, `safeSpot` (no hole, water, timed part or rails for `RESPAWN_RUN` ahead), and where each timed thing is at a moment: `swayOff`, `drawLift`, `crumbleAt` (falling away `CRUMBLE_DELAY` after you reach it, at `CRUMBLE_SPEED`, under a fair speed), `trainAt` (on, and lit `TRAIN_WARN_MS` before), `ballX`, `sprayAt`, `gustAt`; plus `seeded`, `GROUND`, `MARK`, `SPAN` |
|
||||
| `public/activities/bounce-rivals.js` | Bounce Road's rivals, rules only: `RIVALS` (the Zigzag, Brick, Frog, Nudge, Hauler, Sneak, Bruiser, Racer, Cop and Monster: box, mass, speed, points, how readily each dodges, how often each comes, its car style and whether it comes from behind), `makeCar`, `think(round, car, ms, random)` (each kind's choice of speed and line: the Zigzag's weave, into your path when you follow; the Brick holding your lane and brake-checking from in front, then resting `BRAKE_REST_MS` or more; the Frog's hops toward you; the Nudge's chase and up to 1 + 2 times the stage's `sharp` swipes; the Hauler drifting to block; the Sneak dropping up to `SNEAK_DROPS` cones while you follow; the Bruiser slamming you within `BRUISER_RANGE`; the Racer passing then fleeing; the Cop sitting on your roomier side and leaning in to push you to the near edge for `COP_MS`, never on a bridge or by the water (`nearWater`), nor the Bruiser; the Monster keeping `BOSS_AHEAD` in front, hopping every `BOSS_HOP_MS` to come down where you will be and dropping tires; every rival rubber-banded to stay near you, swerving from under your landing as sharply as its stage allows, keeping to the narrowest road just ahead and the band a swaying bridge always covers, holding a slower car's speed, and hopping any hole, drawbridge, barrier or coming train, or flying off a ramp), `spawnRival`, `pickKind` (one of each special kind at a time), `HEAVY`, `RIVAL_MIN_SPEED` |
|
||||
| `public/activities/bounce-roads.js` | Bounce Road's ten stages as data (no imports): `FIELD_W`, `FIELD_H`, `ROW`, `MAX_HOLE`, `LAP_FROM`, and per stage its length, par time, road widths, piece weights (straights, holes, rivers, splits, ramps, chicanes, crumbling road, trains, swaying bridges, boost strips, slicks, balls, sprinklers, drops, gusts), crack and broken span lengths, bridge widths and shares of broken, double and drawbridge spans, flowerbed sizes, barrier and drop kinds, the rivals' count, kinds, pace and sharpness, power-ups, stars, and whether the Monster comes |
|
||||
| `public/md-field.js` | A Markdown answer field on CodeMirror 6: every multiline box the person types into renders its Markdown live. |
|
||||
| `public/md-field.css` | The frame a Markdown field wears inside its shadow root, linked beside `notepad-editor.css`. |
|
||||
| `public/activities/ghoul-rush/ghoul.js` | Ghoul Rush's public face and nothing else: it re-exports the parts below, so the page and the tests import from one place. Everything lives under `ghoul-rush/`: `core/` (the rules, rooms, run flow, power-ups, dice, bonus rounds), `arms/` (secondary weapons), `draw/` (shared drawing), `story/` (the intro story, stage and boss cards, game over), `sfx/` (shared sounds), `stages/<stage>/` and `rides/<ride>/` (each with its rules, art and sounds). |
|
||||
| `public/activities/ghoul-rush/core/ghoul-tables.js` | Ghoul Rush's numbers and tables: the shared timings and sizes, `PACKS` with every pack's monsters, bosses and hooks joined in, the seeded dice, and `roomFor`. Loads first and imports none of the other parts. |
|
||||
| `public/activities/ghoul-rush/core/ghoul-kit.js` | `KIT`, the helpers handed to the stage packs: one object `ghoul-play.js` fills as it loads, so a part that only passes it on has no load-order tie to the play loop. |
|
||||
| `public/activities/ghoul-rush/core/ghoul-planny.js` | The ground and Planny: surfaces, shelves, landing, and how he runs, jumps and falls. |
|
||||
| `public/activities/ghoul-rush/core/ghoul-monsters.js` | The monsters: spawning, how each kind moves, and what they throw. |
|
||||
| `public/activities/ghoul-rush/core/ghoul-fight.js` | Bosses and damage: a boss's fight and fall, hurting and killing a monster, losing a life. |
|
||||
| `public/activities/ghoul-rush/core/ghoul-play.js` | The play loop: `KIT` and `RUN_KIT`, the blaster and bolts, hits, stomps, timers, one slice of play, and `advance()`. |
|
||||
| `public/activities/ghoul-rush/core/ghoul-window.js` | The game's contract with the Activities page: `create`, keys and pointer, what events set off, `ROOM_MUSIC`, the view handed to the drawing. |
|
||||
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow.js` | The finale's rules (`MARROW`, a pack in `PACKS`): Marrow, the house itself, the boss of `FINALE` (`core/ghoul-rooms.js`: after `RUN_STAGES` stages a run goes there with no offer, and clearing its last room wins). Kill I, The Lawn (room `lawn`): the house stands at the arena's right and YOU are kept `WALL_GAP` off it; its real hit box sits at the room's far end and is always `guard`ed, so only its twelve `WINDOWS` hurt it, through the pack's `target` (`windowShot`: the first lit window at a bolt's height; each holds `ceil(bossHp / 12)`, `b.hp` their sum; a bolt past the far wall is spent). Windows are `dark`, `lit` (a few at a time, `LIT_N`, `LIT_MS`, `RELIGHT_MS`) or `out` for good, kept in `round.marrow` across a life lost; rows open by windows out (`rowsOpen`). Moves by weighted `pickMove` (shingles, carpet, pickets; bricks and doormen from phase 1; stomp in phase 2; and only while YOU are up in the oak, `isHigh`, `HIGH_WEIGHTS`: lightning, a `marrowBolt` hazard that glows on YOUR branch then strikes down to it, and crows out of the door's mouth, the Graveyard's carrion crows marked `houseCrow`, at most `CROWS_CAP`). After the kill `b.t` runs the retreat (`retreatStep`: sag, a false "YOU ESCAPED!", a laugh, the sink, `b.gone`, which lifts the wall to its standing front door) |
|
||||
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-draw.js` | The finale's drawing: `LOOKS` (`lawn`, `pack: "marrow"`), `VOICES` (the House's acts, tones in `ghoul-sfx-marrow.js`), `LOSE_WORDS`, `LOSE_SOUNDS` and `marrowArt(d)`: the storm on the hill, the dead oak whose branches are the shelves, the mailbox, the house as a face (its windows lit, shuttered or shot out, the door its mouth), its hazards and waves, its retreat (drawn through its fall: `LINGERS` in `ghoul-draw.js`), lights and every event's look and sound |
|
||||
| `public/activities/ghoul-rush/stages/marrow/ghoul-sfx-marrow.js` | The finale's own sounds as data (no imports): `MARROW_SFX` with `tones` (a `ghoulMarrow<Act>` tone per act of the House, first drafts until the sound vote); merged by `ghoul-sfx.js` via `STAGE_SFX`; the lawn borrows the Drowning Pool's track until its own is picked |
|
||||
| `public/activities/ghoul-rush/rides/mat/ghoul-mat-room.js` | Down the Hatch's room as data, written by `prototypes/ghoul-rush-tools/gen-mat.mjs --write` (`ready: true`; `ride.hearts` 3) |
|
||||
| `public/activities/ghoul-rush/rides/mat/ghoul-mat.js` | Rules for the finale's first ride, Down the Hatch (pack `MAT`, state in `round.runner` with id `mat`): surfing the WELCOME mat down the House's throat, floor lines and gristle ledges over holes, ribs (jump), uvulas (duck), peristalsis squeezes that throb before they close (duck), swallowed furniture (shoot or jump, an act), bile stretches that speed YOU up, three hearts through `ride.hearts`, `mat`-prefixed events and causes, no random numbers |
|
||||
| `public/activities/ghoul-rush/rides/mat/ghoul-mat-draw.js` | Down the Hatch's drawing: `LOOKS.mat` (pack `mat`), `VOICES` (`mat`, `matsqueeze`, `matfurn`), `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS` and `matArt(d)` (the throat in `moving`; uvulas, squeezes, the mat and the telegraph glyphs in `front`; `lights`, `react`) |
|
||||
| `public/activities/ghoul-rush/rides/mat/ghoul-sfx-mat.js` | Down the Hatch's `ghoulMat*` tones, the user's picks (`MAT_SFX`, wired by `prototypes/ghoul-rush-tools/wire-mat-sounds.cjs`), and its track `ghoulMarrowMat` |
|
||||
| `public/activities/ghoul-rush/stages/marrow/ghoul-dollhouse-room.js` | Kill II's room as data: the dollhouse (132 long, a 36-unit landing, floors at 6, 20 and 34 across the arena, stair landings at 13 and 27 at each end, door at 119.5, boss `marroweye`), `ready: true` |
|
||||
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-eye.js` | Kill II's rules as pack `EYE`: the Eye opens in one of nine rooms after a lamp flare, can be hit only through the pack's `target` (`eyeShot`) and clanks while flaring or shutting; in its last phase a false flare. Shades of the keepers beaten this run (`SHADE_MOVES`, one move each, `eyeShade` monsters out of `eyeDoorway` hazards). The lurch pushes YOU in the pack's `tick` and slides an `eyeDresser`. The retreat runs on `b.t` and keeps YOU off the door until `b.gone` |
|
||||
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-eye-draw.js` | Kill II's drawing: the dollhouse cutaway and nursery backdrop, floors and landings, lamps, the Eye, shades drawn small and pale through `d.bossArt`, every hazard, the retreat and the bone stair, the card picture, `lights`, `react`; `LOOKS`, `VOICES`, `LOSE_WORDS`, `LOSE_SOUNDS` |
|
||||
| `public/activities/ghoul-rush/stages/marrow/ghoul-sfx-marrow-eye.js` | Kill II's `ghoulEye*` and `ghoulEyeShade*` tones, the user's picks (`EYE_SFX`, wired by `wire-eye-sounds.cjs`), and its track `ghoulMarrowRooms` |
|
||||
| `public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair-room.js` | The Bone Stair's room as data (`ready: true`), written by `prototypes/ghoul-rush-tools/gen-bonestair.mjs` |
|
||||
| `public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair.js` | The Bone Stair's rules, pack `BONESTAIR` (`ride`, `place`, `target`), state in `round.runner` with id `bonestair`: spiral flights with seams, the rubble's gap meter behind YOU, treads that give way, ribcages, skeletons, bone hands and masonry; causes and events prefixed `stair`; no random numbers; 3 hearts |
|
||||
| `public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair-draw.js` | The Bone Stair's drawing: `LOOKS.bonestair`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, the telegraph glyphs, and `bonestairArt(d)`: the shaft, the bone treads, the columns, every obstacle, the rubble wall and its meter, and the Pit's dark |
|
||||
| `public/activities/ghoul-rush/rides/bonestair/ghoul-sfx-bonestair.js` | The Bone Stair's `ghoulStair*` tones, the user's picks (`BONESTAIR_SFX`, wired by `wire-bonestair-sounds.cjs`), and its track `ghoulMarrowStair` |
|
||||
| `public/activities/ghoul-rush/stages/marrow/ghoul-pit-room.js` | Kill III's room as data: the Pit (160 long, always dark, the heart's plinth with a pit each side, three ledges, door at 154, boss `marrowheart`), `ready: true` |
|
||||
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-heart.js` | Kill III's rules as pack `HEART`: the beat on `b.t` (`BEAT_MS` 1500 falling to 750), a `heartBeat` wave each way, the ribs open between beats (`guard` is `!b.open`), roots, ledge grabs, clots, falling chunks, a stopped beat and a double wave; bolts clamp at 1 hp, then HOLD FIRE (`round.flood`, the meter filled by `round.input.fire`, state on `round.heart`), the white-out, the last thump, the fall, and daylight with a door of light (`b.gone`) |
|
||||
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-heart-draw.js` | Kill III's drawing: `LOOKS.pit` (dark, `noLightning`), the cavern, the heart in ribs, roots and chains, every hazard and wave, the red flood, the HOLD FIRE meter and growing beam, the white-out and the daylight shaft; `VOICES.marrowheart` (`hold` is `ghoulStoryClick`), `LOSE_WORDS`, `LOSE_SOUNDS`, `react` |
|
||||
| `public/activities/ghoul-rush/stages/marrow/ghoul-sfx-marrow-heart.js` | Kill III's `ghoulHeart*` tones, the user's picks (`HEART_SFX`, wired by `wire-heart-sounds.cjs`), and its track `ghoulMarrowPit` |
|
||||
| `public/activities/ghoul-rush/story/ghoul-ending.js` | The ending's four pages (lights out, the road, morning, final notice) and their rules in phase `ending`: a lockout, typing finished first, a minimum time per page, a one-second fire hold to skip, `skipEnding`; it wins the run once at its end (`won` with `n: round.winN`) |
|
||||
| `public/activities/ghoul-rush/story/ghoul-ending-draw.js` | `endingArt(d)` returns `{ card, react }`: four animated scenes in the story's layout; `react` answers only `endingPage` |
|
||||
| `public/activities/ghoul-rush/story/ghoul-sfx-ending.js` | `ENDING_SFX`: the ending's `ghoulEnding*` tones, the user's picks (wired by `wire-ending-sounds.cjs`), and its track `ghoulMarrowEnding` (`ENDING_TRACK`) |
|
||||
| `public/activities/ghoul-rush/draw/ghoul-draw.js` | Ghoul Rush's drawing: `drawScene(ctx, view)` from one view object `ghoul.js` refills each frame, in room units turned the right way up and scrolled by the camera: the strip above the field in the page's colors with the pills (laid out by `hudLayout`: the room, lives, the bonus, the chain with its window emptying, the key once held, the power-ups; a second row rather than run off the board, the rows centered in the strip), still layers `CHUNK` units of a room wide drawn off screen once per room and scale and copied each frame (a few kept; each room's look in fixed colors, `LOOKS`: wallpaper, moonlit windows, decor by room (portraits, bookcases, curtains, pots, ferns, rafters with cobwebs, headstones), wainscot, floorboards, pits, shelves, wall doors and loose boards), the crumbling boards, a wall door standing open, the chandeliers, the exit door (padlocked, then open and glowing), candy, power-ups and the key, the monsters (a zombie in a ragged shirt with mismatched eyes, lurching; a crawler's hand through the boards, then crawling; a bat with flapping wings; a sheet ghost fading in and out; a skeleton raising a bone; gourdlings), bones and shockwaves, the bosses (the Great Gourd with a carved glowing face and a red shadow where it will land; Old Rattlebones, drawn by `ghoul-bones-draw.js`) and the boss bar, Planny (his star eye in your highlight in every state, stick arms, one holding the flashlight blaster that flares as it fires, stepping, arms up in the air or cheering, spinning with an "o" when hit, slumped at the end, garlic circling him while he has some; arms and feet in `limbInk(look)`), the bolts, sparks, rings, floating words kept on the field by `labelSpot`, the chain's big number, banners (`BANNER_SHADE`) the stage pick (`drawPicker`: a card per stage offered with its picture, `drawStagePicture`, its first room's wall and moonlit window over its boss room's floor with its boss standing there drawn by the same `BOSS_ART` as in play, name, line and boss, the one picked out raised and edged in gold, `stageColor` its boss room's), and the start and end strip with the big final score and a dot per stage, lit in each cleared stage's color (gold for the record before a run); `react(e, kit)` turns each event into those effects and its blips, a monster's own sound through `VOICES` (each kind's tone in `ghoul-sfx.js` by act: `appear` (a runner's `warn`, a bat's `wake`, a wraith's `notice`), `climb`, `hop`, `growl`, `lunge`, `shriek`, `dive`, `spit`, `throw`, `hurt` (one every 140 ms), `die`, and a boss's `wake`, `hop`, `slam`, `windup`; a "throw" event names its thrower in `by` and a "spit" its spitter in `kind`); the stage packs' drawing (`ART`: an `outdoor` look draws its pack's backdrop instead of walls, graves for doors, and each pack's monsters, bosses, missiles, hazards and lights by kind; a pack may also draw `sky` (every frame, under the still layers, so its backdrop leaves the sky clear) and `moving` (what moves in its scenery, over the still layers)); `readColors(canvas)`, `contrast`, `lookOf`; decides nothing |
|
||||
| `public/activities/ghoul-rush/core/ghoul-rooms.js` | Ghoul Rush's rooms and stages as data (no imports): the long hall every run starts in (`ROOMS[0]`), then `STAGES` (each an id, title, line and four room ids, the last a boss's, checked at load; `stageById`, `roomById`), `FIELD_W`, `FIELD_H`, `FLOOR_Y`, `CEILING_Y`, `CHANDELIER_Y`, and per room its look, name and line, length, ground pieces (pits between, steps and walls), shelves (`crumble` kind), start, key, door, candy rows, power-ups, spawns (zombies, wall doors, crawlers' boards, bats, ghosts, skeletons), chandeliers and boss (`gourd`, `bones` or a pack's, the last room of its stage); a door's fifth entry names what comes out of it (rotters out of the Graveyard's graves) |
|
||||
| `public/activities/ghoul-rush/stages/wing/ghoul-bones.js` | Old Rattlebones' fight, the East Wing's boss, as a boss pack in the shape of the stage packs (no imports; `ghoul.js` hands each rule its kit `k`; it plugs in through `PACKS` with `bosses`, `boss` and `hazards`, and `ghoul.js` re-exports `BONES_KEEP`, `BONES_MS`, `BONES_RAGE_MS`, `BONES_WINDUP_MS` and `VOLLEY`): 90 hp; every `BONES_MS` he winds up for a volley, a slam or the skull, picked at random by `pickAct` (never one three times running, the first a volley); the skull is a `skull` hazard that flies level at your chest `SKULL_REACH` past you and curves back to his neck while `b.headless` (no weak spot; a bolt to the skull does `SKULL_HIT`, eaten, with `SKULL_STAGGER_MS` between hits); at half his hp (`BONES_RAGE`) he shakes (`BONES_SHAKE_MS`), attacks every `BONES_RAGE_MS`, slams in a double (`DOUBLE_GAP_MS`), hurls bone rain (`rain` hazards: a shadow for `RAIN_WARN_MS`, then a bone) and raises skeletons (`raise` hazards, at most `MAX_BONY` alive or cracking). |
|
||||
| `public/activities/ghoul-rush/stages/wing/ghoul-bones-draw.js` | Old Rattlebones' drawing, `boneArt(d)` plugged into `ghoul-draw.js`'s `PACK_ART`: the boss (headless while the skull is out, arms to the skull or up for rain, shaking with flaring eyes in his rage), the skull in flight, the bone rain's shadows and falling bones, the cracking floor, `lights`, `react` cases for his new events (`skullWind`, `skullThrow`, `skullTurn`, `skullBack`, `rainWind`, `rainThrow`, `rainLand`, `bonesRage`, `raiseWind`, `raised`), and `LOSE_WORDS` / `LOSE_SOUNDS` for `skull` and `rain`. |
|
||||
| `scripts/test-web-console-activities-ghoul-bones.mjs` | Old Rattlebones' suite: the random attack order, the volley and slam, the skull's flight and the headless window, the skull shot, the rage, the double slam, bone rain, the skeleton cap and the reactions. |
|
||||
| `public/activities/ghoul-rush/stages/graveyard/ghoul-graveyard.js` | Ghoul Rush's Graveyard stage pack, its rules (no imports: `ghoul.js` hands each rule a kit `k` of its own helpers). A stage pack is plain data and functions that `ghoul.js` merges into its own tables (`PACKS`): `monsters` (with `perch`: its spawn names its height, `flies`: a horde one comes in high), `walkers`/`zombies`/`stackers`/`climbers` (joining the sets of those names), `act` (start), `solid`, `move`, `kill`, `horde` (fields a horde one comes with), `bosses`, `boss` (one slice of its fight), `guard` (true while shots and stomps glance off, a `bossBlock` event) and `hazards` (by kind, one slice of a box on the floor that hurts while `live`; kept in `round.hazards`). Three more fields a stage may add (the Grounds does): `cut` (kinds the Hedge shears kill outright), `weak` (by boss kind, `(boss, shot) => damage multiplier` for a weak spot; `bossHit` then carries `how: "weak"` and `weak: true`) and `cause` (what a boss's touch is called when it costs a life). The Chapel adds more: `tick(round, ms, k)` (a stage-wide twist run first in every slice; it may set `round.stunMs`, which freezes you and every monster, boss, hazard and missile while bolts in flight still fly, and keeps its state in `round.twist`), `stone` (by kind, true while shots glance off and a stomp does nothing; `glance` event), `shot(round, m, s, k, random)` (the damage multiplier of a bolt that hit `m`, free to splash), `target(round, s, k)` (true when a bolt struck something of the pack's that is no monster, such as an organ pipe) and, on a monster, `hasteMs` and `haste` (its time runs faster while `hasteMs` is over 0). On the drawing side a look may be `custom: true` with a `pack` id (the pack's art then draws the whole wall, floor and shelves) and the art may return `decor` (by the look's `decor` name). On the drawing side a stage's art may also return `react(e, k)` (its own events; `ghoul-draw.js`'s `react` falls through to `ART.react`, which returns true when it handled `e`), `ground` and `shelf` (the floor pieces and shelves of an outdoor look), `waves` and `powers`; a boss event must carry `kind` or its voice never plays. The Graveyard's: grasping hands (`HANDS_*`: lurk unseen, rise, grab, sink, creep under level ground after you), the mourner (wails every `WAIL_MS`, slowing you to `SLOW_SHARE` speed for `SLOW_MS` within `WAIL_REACH`; `round.you.slowMs`), the grave robber (digs in within `ROBBER_DIG`, comes up `ROBBER_BEHIND` behind you), the rotter (a zombie whose body-shot death leaves its `legs` walking), the carrion crow (perches, dives at your chest, climbs, dives again), and Mother Mourning (`angel`: weeps `ANGEL_WEEP_MS` as stone flinging headstones, turns `ANGEL_TURN_MS`, watches `ANGEL_WATCH_MS` when only she can be hurt and any move drops a `fist` hazard after `FIST_WARN_MS`; at `ANGEL_RAGE` her wings spread, the weep shorter, the watch longer, a shockwave each way as each weep begins) |
|
||||
| `public/activities/ghoul-rush/stages/graveyard/ghoul-graveyard-draw.js` | The Graveyard's drawing: `LOOKS` for its four rooms (`outdoor: true`, so `ghoul-draw.js` draws `backdrop` instead of walls: the night sky, stars, the moon, hills with dead trees, iron fences, mausoleums, fog and headstones) and `graveyardArt(d)`, handed `ghoul-draw.js`'s helpers, returning the open `grave` and `openGrave` a rotter climbs out of, `monsters`, `bosses` (Mother Mourning: hands over her face while she weeps, lowered with burning eyes while she watches, wings spread in a rage, cracks as she is worn down), `missiles` (a flung headstone), `hazards` (a stone fist: its shadow, then the fist) and `lights` |
|
||||
| `public/activities/ghoul-rush/stages/grounds/ghoul-grounds.js` | Ghoul Rush's Grounds stage pack, its rules (no imports; same shape as the Graveyard's, plus the pack fields `cut`, `weak` and `cause`): the topiary beast (`still` while you face it, `creep` when your back is turned; events `rustle` and `freeze`), the rootling (`trail`, `warn`, `up`, `sink`; events `rootWarn` and `rootUp`), the lantern moth (flocks of three, quicker in the dark), the mulch crawler (`pile`, `burst`, `crawl`; event `leaves`), the Hedge shears' `snip` event, and the Groundskeeper (`keeper`: a scythe sweep along the floor (or, now and then, a high `sweep` hazard you stay on the ground under), a lobbed lantern fire hazard, his lantern a `weak` spot only while open (`b.lit`), and at half hp a mower with `rev`, `charge` and `stall`) |
|
||||
| `public/activities/ghoul-rush/stages/grounds/ghoul-grounds-draw.js` | The Grounds' drawing: `LOOKS` for its four rooms (`outdoor: true`), `groundsArt(d)` returning `monsters`, `bosses`, `hazards` (the fire), `waves` (the scythe), `powers` (the shears), `lights`, `backdrop`, `ground`, `shelf` and `react(e, k)` for the Grounds' own events; its `VOICES` (each kind's tone per act, `keeper.weak` for a weak-spot hit instead of `keeper.hurt`, `shears.snip` for a cut instead of the dying cry), `LOSE_WORDS` and `LOSE_SOUNDS`, which `ghoul-draw.js` spreads into its own tables |
|
||||
| `public/activities/ghoul-rush/stages/chapel/ghoul-chapel.js` | Ghoul Rush's Chapel stage pack, its rules (no imports; same shape as the Grounds', plus the pack hooks `tick`, `stone`, `shot` and `target`, and a room field `toll`): the gargoyle (`perch` as stone, `wake`, `dive`, `return`; events `glance`, `gargoyleWake`, `gargoyleDive`, `gargoylePerch`), the choir ghost (sings, giving nearby monsters `hasteMs`), the censer monk (`smoke` hazard), the bell bat (`roost` until the toll), the bell toll (`tick`: `bellSwing`, `toll`, `tollEnd`, `round.stunMs`), Holy Water's splash (`shot`, event `holySplash`) and the Choirmaster (`choirmaster`: four pipes in `b.pipes` that bolts hit through `target`, a `guard` while any sounds, columns of `note` hazards with one gap, a rage that brings pipes back one by one) |
|
||||
| `public/activities/ghoul-rush/stages/chapel/ghoul-chapel-draw.js` | The Chapel's drawing: `LOOKS` for its four rooms (indoor but `custom: true` with `pack: "chapel"`, so `ghoul-draw.js` hands the walls, floor and shelves to `chapelArt(d)`'s `backdrop`, `ground` and `shelf`), `chapelArt(d)` returning those plus `decor` (the room's pews, belfry, organ or stalls), `monsters`, `bosses`, `hazards` (smoke, the bell, notes), `powers`, `lights` and `react(e, k)`; its `VOICES` (the bell has only `swing` and `toll`: the thaw after a toll is quiet on purpose), `LOSE_WORDS` and `LOSE_SOUNDS` |
|
||||
| `public/activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium.js` | Ghoul Rush's Blackmoor Sanatorium stage pack, its rules (no imports; same shape as the Chapel's, plus the pack fields `unseen`, `harmless`, `platform` and `land`, a room field `flicker`, `round.blackout`/`round.twist` for the lamps and the kit's `fling`): the orderly (`reach`, `hold`, a throw that costs no life, `you.heldMs`; events `orderlyReach`, `orderlyGrab`, `orderlyThrow`, `saltsBreak`), the gurney (`parked` as a floor you can stand on, `rattle`, `roll`, `rest`; `gurneyRattle`, `gurneyRoll`, `gurneyRest`), the flicker (`m.unseen`: bolts and touch go through it until a blackout, the Lantern's light or the Salts' glow; `flickerShow`), the specimen bloater (a `jar` missile with its own `cause` that `land`s as a `formaldehyde` hazard; `jarWind`, `jarBreak`), the lamps (`tick`: `flickerWarn`, `lightsOut`, `lightsOn`), the Salts and the Saw (`shot`) and the Night Matron (`matron`: `b.beam` cone, `b.heat`, `b.cabinets`, syringes, arms, rage; `syringeWind`, `syringes`, `armWarn`, `armReach`, `matronRage`) |
|
||||
| `public/activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium-draw.js` | The Sanatorium's art: `LOOKS` (indoor but `custom: true` with `pack: "sanatorium"` and `noMoon`, so `sanatoriumArt(d)`'s `backdrop`, `ground` and `shelf` draw the tiled walls, windows, decor, floors, the ward's cabinets, the baths' tubs and each room's boards), `monsters` (orderly with its grab pose, gurney, flicker with its fade and afterimage, specimen bloater), the `matron` with her cone cut by the floor and the cabinets, `missiles` (jar, syringe), `hazards` (formaldehyde, arm with its crack of light), `powers` (Salts, Saw), `lights`, `react(e, k)` and two generic hooks `ghoul-draw.js` calls: `front(ctx, v)` (over Planny and before the dark: the ceiling lamps, the tubs' water, the orderly's fingers, the Matron's heat on him) and `dim(v)` (the dark layer's alpha, raised in a blackout and in a stutter); its `VOICES` (borrowed tones; `lights`, `salts` and `saw` are no monsters), `LOSE_WORDS` and `LOSE_SOUNDS` |
|
||||
| `public/activities/ghoul-rush/stages/village/ghoul-village.js` | Ghoul Rush's Hollow End Village stage pack, its rules (no imports; no new pack field: it uses `tick`, `shot`, `land`, `weak` (now handed `(boss, shot, round, k)`) and `solid`, and draws no random number): the moonrise (`tick`; `round.twist` = `{ moon, full, ms }`, events `fullMoon`, `villagerTurn`, `villagerWolf`, `houndGrow`), the torch mob villager (a group of three, `torchWind`, the `torch` missile that `land`s as a `torchfire` hazard, `torchLand`; turned into a leaping wolf-man at full moon), the hanged man (`hangedWarn`, `hangedDrop`, `hangedSnap`, `hangedHaul`), the shutter ghoul (`solid` only while out; `shutterRattle`, `shutterLunge`, `shutterPull`), the moonhound (the hellhound's leap, grown at full moon), Wolfsbane's double damage and shying (`baneShy`) and the Beast of Hollow End (`beastLeap`, `beastCling`, `beastPounce` with a `shadow` hazard, `beastLand`, `swipeWind`, `beastSwipe` with a `claw` hazard, `beastHowl`, `houndCall`, `beastMoon`) |
|
||||
| `public/activities/ghoul-rush/stages/village/ghoul-village-draw.js` | The Village's art: `LOOKS` (street, square and green outdoors, the inn a `custom` indoor look, all `pack: "village"`), `villageArt(d)` returning the world's hooks plus the monsters (the torch mob villager and the wolf-man it turns into over 800 ms, the hanged man on his rope, the shutter ghoul reaching out of a window, the moonhound with a glowing mane when grown), the `beast` (a werewolf in every move: cling with a glowing weak spot, bound, pounce, land, swipe, howl at the moon, rage), `missiles` (torch), `hazards` (torchfire, the landing shadow, the claw swipe), `powers` (Wolfsbane's badge), `lights` and `react(e, k)`; its `VOICES` (borrowed tones, plus `moon.full` and `bane.active`), `EVENT_VOICE` (event to `[kind, act]`, each played once; the hounds' call is quiet), `LOSE_WORDS` and `LOSE_SOUNDS`. Its header lists what the art reads off the rules |
|
||||
| `public/activities/ghoul-rush/stages/village/ghoul-village-world.js` | The Village's world: the night sky and the moon that climbs and reddens with `round.twist.moon` (`sky`, drawn every frame under the still layers), the crooked timber-framed houses with a window for every shutter ghoul, the church and spire, the gallows, the green's far cottages, well and arena walls, the Crooked Inn (hearths, barrels, bar, lanterns, the moon in its windows), cobbles, planks and turf (`ground`), awnings, rooftops, balconies, tables, carts and thatch (`shelf`), and `moving` (curtains that twitch as you pass, fire, moonlight falling in), `front` (the full-moon wash, Wolfsbane's petals, the Beast's rage) and `lights` |
|
||||
| `public/activities/ghoul-rush/stages/mine/ghoul-mine-world.js` | The Deep Seam Mine's world (no imports; `mineWorld(d)` takes ghoul-draw.js's helpers): the rock wall with its strata and facets, the timber that holds it up (props and cap beams, scaffolds and galleries as `shelf`), rails and sleepers on the floor (`ground`), oil lamps on hooks with their flames and warm halos (`moving`) and their holes in the dark (`lights`, none in a blackout), the shaft's lining, walers, guide rails and headframe with the cage lift drawn on its cable over a winch wheel with a counterweight (`cage`, and its front bars in `front`), the tunnels' low roof, pipes, stalled pump, drips and knee-deep water with a lit surface and Planny's wake (`front`), the collapse's broken props, cracks, rubble heaps and buried cart, the seam's glittering ore vein, stalactites and galleries, and the `rock` hazard in its three states; layouts are worked out once per room from the room alone and kept. Scene tool: `prototypes/ghoul-rush-tools/scene-mine-world.mjs` |
|
||||
| `public/activities/ghoul-rush/stages/village/ghoul-village-wolf.js` | The Village's werewolf, one skeleton for the Beast and a turned villager: poses (`POSES`: stand, rear, swipe, howl, crouch, leap, land, rest, cling, shy, down, sleep), `mixPose` to blend them, and `wolfKit(d).figure` to draw one |
|
||||
| `public/activities/ghoul-rush/stages/mine/ghoul-mine.js` | Ghoul Rush's Deep Seam Mine stage pack, its rules (no imports; draws no random number): uses `tick`, `harmless`, `platform`, `solid`, `kill`, `weak` and a boss's blackout (`round.blackout`). The rockfall (`tick`; a room field `rocks` in ms; the `rock` hazard in states `warn`, `fall`, `rubble`, events `rockWarn`, `rockFall`, `rockLand`; the Hard Hat's `rockBounce`), the noise you make (`round.twist` = `{ next, quiet, noise, reach, wade }`, `wade` splashes), the knocker imp (touch steals light, not a life: `you.dimMs` and `you.dimBy`, `impSteal`, `impDrop`; the Hard Hat stops it), the canary ghost (`canaryScream`: three rocks), the dead miner (buried in the wall, `minerDig`, `pickWind`, `pickSwing` with a `pick` hazard, cause `pickaxe`), the blind crawler (`blindLost`, `blindHear`), the cage lift (a spawn row `["cage", x, lowest y, highest y]`, a `platform` kind that is not solid and never hurts), Dynamite placed in each room (its rules, the `stick` and `blast` hazards, `dynThrow` and `dynBlast`, moved to `ghoul-arms.js`) and the Tommyknocker (`tommyKnock`, `sweepWind`, `tommySweep` with a `hammer` hazard, `tommyDark`, `tommySink`, `tommyKnockDark`, `tommyBurst`, `tommyRage`; dazed double damage through `weak`) |
|
||||
| `public/activities/ghoul-rush/stages/mine/ghoul-mine-draw.js` | The Mine's art (the rooms in `ghoul-mine-world.js`, the Tommyknocker in `ghoul-mine-tommy.js`): `LOOKS` (`custom: true`, `pack: "mine"`, always dark), `mineArt(d)` returning `backdrop` (rock, strata, timber props, oil lamps), `ground` (rails), `shelf` (timber landings), `front` (the water along the floor), `dim` (the blackout), `monsters` (imp, canary, miner, blind crawler, cage), the `tommy` boss, `hazards` (rock, stick, blast, pick, hammer), `powers` (Hard Hat, Dynamite), `lights` and `react`; its `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS` and `LOSE_SOUNDS`. Its header lists every field the art reads off the rules; `ghoul-draw.js` shrinks Planny's glow and drops his cone while `you.dimMs` is over 0 |
|
||||
| `public/activities/ghoul-rush/stages/mine/ghoul-mine-tommy.js` | The Tommyknocker's figure for `ghoul-mine-draw.js`: `tommyKit(d)` (no imports, `ghoul-draw.js`'s helpers handed in) returns `figure(ctx, v, b)`, a miner-giant half grown into the seam (stone shoulder with crystals, lantern on his helmet, a door-sized hammer) drawn by act: leaning on the hammer, the overhead knocks, the drawn-back sweep, rest, sinking, bursting out dazed with stars, raged cracks, hurt flash. |
|
||||
| `public/activities/ghoul-rush/rides/cart/ghoul-cart.js` | Ghoul Rush's Runaway Cart, the Mine's ride room, its rules (no imports; draws no random number): the first room where a pack takes Planny's movement over. It adds the pack fields `ride` (a list of `(round, ms, k) => true` hooks run each slice before the walking rules; one that returns true has moved him) and `place` (a list of `(round, k)` hooks run whenever he is put down in a room: a room set up, a respawn), uses `target` (the crates), and `round.camLead` (units the camera leads further). The cart (`round.cart`, null elsewhere) rides the room's `ride.track` polylines (slope speed, lean and brake, jump, air steering, ramp launch, landing on the line under it, derail into the chasm), ducks under `ride.beams`, wrecks on `rubble` and unbroken `crates` (two bolts break one), is chased by the boulder, passes `checks` (a life lost puts it back at the last) and halts at `stop` where the door opens; a ledge imp (`ledgeimp`) leaps into it and steals light, a canary's scream drops a slide of rubble on the track ahead. Exports `flight`, `trackY`, `linesAt` and `linesOf` for the unit suite. Events `cartJump`, `cartLand`, `cartLaunch`, `cartBrake`, `cartDuck`, `crateHit`, `crateBreak`, `cartCrash`, `boulderNear`, `checkpoint`, `cartStop`, `ledgeLeap`, `slideWarn`, `slideFall`; causes `derail`, `beam`, `crash`, `boulder` |
|
||||
| `public/activities/ghoul-rush/rides/cart/ghoul-cart-draw.js` | The Runaway Cart's art: `LOOKS` (`custom: true`, `pack: "cart"`, always dark), `cartArt(d)` returning `backdrop`, `ground`, `moving` (every frame: the cave in cached parallax tiles over a chasm, the trestled track, ledge pillars, signal posts, rubble and the buffer stop in cached chunks, hanging lamps, signal lamps, crates, a slide's dust and pour; the cart too once it has stopped, so Planny walks out past it), `front` (the cart over Planny, the beams, the boulder, flying splinters, speed streaks, the foreground rock), `lights` (headlamp, hanging and far lamps, signals, beams), `monsters` (the ledge imp) and `react`; its `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS` and `LOSE_SOUNDS`. It keeps its own offscreen layer cache (keyed by scale), draws no random numbers (a hash) and leaves short-lived bits in the view's `fx` (`cartBits`, `cartPours`, `cartLand`, `cartStop`). Its header lists every field the art reads off the rules |
|
||||
| `public/activities/ghoul-rush/stages/mine/ghoul-sfx-mine.js` | The Mine's own sounds as data (no imports): `MINE_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` via `STAGE_SFX` (its rooms play existing tracks, set in `ROOM_MUSIC`) |
|
||||
| `public/activities/ghoul-rush/stages/bog/ghoul-bog.js` | Ghoul Rush's Gallows Bog stage pack, its rules (no imports; a pack `ghoul.js` plugs in through `PACKS`, handed the kit `k`): the lurker, leech swarm, will-o'-wisp and bog body (`MONSTERS`, with `walkers`/`zombies` sets), `act`, `solid`, `swoops`, `unseen`, `move`, `kill`, `horde`, `tick` (the wisp's lure), `bosses`/`boss`, `weak`, `cause` and `hazards`, and Old Mother Bog (`BOSSES`, hp 360, her fight in `moveMother` with `startMove` setting each move's wind-up act, wait and telegraph event: the wave opens, then a weighted `pickAttack` by phase (`phaseOf`, `WEIGHTS`; never one move three times running, `COOLDOWN` picks for the slow moves, a summon only under its cap, counted by `hagAdds` on adds marked `m.hag`). Full health: wave, spit, bog hands (`boghand` hazards: a ripple, then a hand), surge (a waist-deep charge past you), mud shell (`shellShot` in `target` chips it; broken she reels in `stagger` with the cauldron open, ignored she heals `SHELL_HEAL`) and dive (relocate); under three quarters the double wave, volley and leech brood join. Under half (after her first dive): stomp (a shadow, a leap, a slam and a wave each way), tide (a `tide` hazard over every plank after `TIDE_WARN_MS`; shelves are dry), drowning pull (drags `you.x` toward her on the planks, never off a plank's end) and call the drowned (bog bodies). Under a quarter: the wisp lantern (her wisps, gone for good once shot out) and combos (`toIdle`, `motherCombo`). `guard` is under water or shelled; `weak` is the open cauldron (late in a rest, or reeling). `planked` keeps her whole body on one plank height except in `UNSTOOD` acts; `b.floor` is the plank height; `b.plan` forces a move for tests). The stage's second twist lives in the engine, not here: a room field `mud` (frozen `[x0, x1]` spans), `mudAt` in `ghoul.js`, `you.mud` and `you.mudMs` (the run sags from `WATER_SPEED` toward `MUD_SPEED_MIN` and a jump toward `MUD_JUMP_MIN` over `MUD_MS`; a shelf, the air and Stilt Boots (`round.effects.boots`) let go of it) |
|
||||
| `public/activities/ghoul-rush/stages/bog/ghoul-bog-draw.js` | The Gallows Bog's drawing: `LOOKS` for its rooms (`outdoor: true`, `pack: "bog"`) and `bogArt(d)`, handed `ghoul-draw.js`'s helpers, returning the night swamp rooms (boardwalk planks over black water, moss veils, fireflies, the hag's lit stilt house and her open-water arena), `monsters` (a lurker's eyes, a leech swarm, a will-o'-wisp, a bog body), `bosses` (Old Mother Bog and her cauldron, a pose for every move, plus `motherMarks`: the boiling mud of a call, the stomp's shadow, the undertow's streaks), `hazards` (the mud wave, the muck patches, the bog hands' ripples and arms, the tide's warning and its water over the planks), the Stilt Boots' and Harpoon's badges and the events' looks and sounds; its `VOICES` are borrowed house tones until the sound page's vote, `LOSE_WORDS` and `LOSE_SOUNDS` already named |
|
||||
| `public/activities/ghoul-rush/rides/lantern/ghoul-lantern.js` | The Drowned Lantern (Gallows Bog's bonus round, not a ride) as a pack (`LANTERN`): a top-down game on one fixed screen where YOU carry a lantern over an island of mossy hummocks and plank walks round Old Mother Bog's pool, light five wisp shrines (stand on a stone `SHRINE_MS`, the time kept if you step off), then run back to the boat at the landing. Pack fields `ride` (moves Planny) and `place`; state in `round.runner` (`id` "lantern"), positions in field units with y counted down; the room's `ride` holds the island (`hummocks`, `planks` as hummock pairs, `shrines`, `start`, `boat`, `pool`, `bodies`) and the hunters' tables (`lurker` route, `leeches` routes, `wisps`: a guardian per shrine with its `phase`, roamers with `wake`). Keys: arrows walk (a walk into the water slides along the shore or plank, `slide`), SPACE flares (a ring `FLARE_R` that bursts wisps and scatters leeches, costing `FLARE_OIL`; a sputter without the oil); `fire()` and the arm double-tap are off for this room. The oil burns down over `OIL_MS` and the light (`lightR`) with it; a lit shrine fills it. One rule per hunter: the Lurker hears steps on wood, flares and shrines, swims to the spot, lines up a lane through it (`AIM_MS`) and dashes (it strikes where it heard you), rests deaf, and cowers once Mother rises; guardian wisps circle their shrine and rush a lantern within `GUARD_SENSE` on a `LEASH`, roamers leave the pool at the third to fifth shrine; leeches stay at the light's edge and bite only once the flame gutters; bog bodies rise only for someone standing still beside them; Mother's hand (from the third shrine or `MOTHER_LATE_S`) tracks, locks and slams, one after another once the fifth raises her. Catches cost the bonus round's hearts and never move Planny; `lanternMeet` names each hunter's rule once; `runner.marks` lists what a banner must keep clear of (read by ghoul.js's `underBanner`); `lanternHums` gives ghoul.js the held sounds; the grade is `total` 5, `hits` (kinds that caught you), `acts` (flare pops and close calls), `steady` (the flame never guttered). No random numbers; a Planny put at the door finishes too, as a ride's finish line does |
|
||||
| `public/activities/ghoul-rush/rides/lantern/ghoul-lantern-draw.js` | The Drowned Lantern's art, the whole field drawn by `lanternArt(d).field` (like Holy Roller's): `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `TAGS` (each hunter's rule, shown once over it, one at a time); the water and Mother's pool, the island and the boat, then one dark layer with a hole per light (`paintDark` from ghoul-draw.js), and over it what the dark must never hide: the island's moonlit edges, the shrines' beacons and progress, the bodies' bubbles and red reach, the leeches' eyes, Mother's eyes, head and hand shadow, the Lurker's eyes, its lane and dash, the wisps, Planny with the ring of his light (the leeches' line, red when the oil is low) and the boat's beacon; the HUD band (shrine flames, the hint line, the oil bar with its flare ticks); no random numbers, everything from a hash and the clock |
|
||||
| `public/activities/ghoul-rush/stages/bog/ghoul-sfx-bog.js` | Gallows Bog's own sounds as data (no imports): `BOG_SFX` with `tones` (a `ghoul<Kind><Act>` tone for each act of the lurker, leech, wisp, bog body and Old Mother Bog, her 22 newer acts first drafts too: a telegraph tone per move and one for each effect) and an empty `music` until the music vote is wired in (the rooms play borrowed tracks through `ROOM_MUSIC`); the tones are first drafts (option 1 of each act) until the sound vote; merged by `ghoul-sfx.js` via `STAGE_SFX` |
|
||||
| `public/activities/ghoul-rush/rides/lantern/ghoul-sfx-lantern.js` | The Drowned Lantern's own sounds as data (no imports): `LANTERN_SFX` with `tones` (`ghoulLantern<Act>`: a creak per step on wood, the flare, the shrine, a cue per hunter heard before it reaches you, Mother's wake, rise, hand and slam), `hums` (`ghoulLanternLurk`, `ghoulLanternMother`, asked for through `lanternHums`) and `music` (`ghoulLanternTheme`, the picked Tiptoe plucks track, named in `ROOM_MUSIC`); first drafts until the vote; merged by `ghoul-sfx.js` via `STAGE_SFX` |
|
||||
| `public/activities/ghoul-rush/stages/carnival/ghoul-carnival.js` | Ghoul Rush's Midnight Carnival stage pack, its rules (no imports; draws no random number): uses `tick` (the ring of samples Mirror You reads and its bolts in `round.twist`), `shot` (Cotton Candy's slow, a marionette's string at the top of its body), `target` (a bolt crossing a marionette's string or one of the puppet's three), `guard` (the Ringmaster is open only with the puppet down), `swoops` (a balloon, a circus hound's leap), `solid`, `kill` and `fourLegged`. Grinner and its acid balloons, marionette (drops when you pass under), Mirror You (copies you 500 ms late, mirrored, its bolts cancel yours), strongman (barbells), circus hound, and the Ringmaster (a gantry over the ring that follows its puppet at a lag, the puppet stalking you and working to a fixed script of leap, stomp, whip and charge, three strings from the gantry to its head and hands that move with it, open 4 s when they are cut, rage with hounds from the cages); `CARNIVAL_ROOMS` lists the stage's rooms, with a place before the Big Top for the dark ride. The room field `belts` and Planny's `you.belt` (the funhouse's conveyor floors) are run by `ghoul.js`. |
|
||||
| `public/activities/ghoul-rush/stages/carnival/ghoul-carnival-draw.js` | The Carnival's art: `LOOKS` (`custom: true`, `pack: "carnival"`), `carnivalArt(d)` returning the world's hooks (from `ghoul-carnival-world.js`) plus `monsters`, the `ringmaster` boss (gantry, puppet in each pose, strings, whip), `missiles` (barbell), `hazards` (foot, whip, charge), `waves` (the puppet's), `powers` (Cotton Candy), `front` (Mirror You's bolts, Cotton Candy's glow), `lights` and `react`, and `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`. Its header lists what the art reads off the rules. |
|
||||
| `public/activities/ghoul-rush/stages/carnival/ghoul-carnival-world.js` | The Carnival's world (no imports; `carnivalWorld(d)` takes ghoul-draw.js's helpers): the night sky with a Ferris wheel (`sky`), tents, booths and swagged bulbs on the Midway, the Hall of Mirrors' gilded panels and glints, the Funhouse's crooked walls, spiral discs and clown-mouth door, the Big Top's striped canvas, ring curb, crowd, trapeze boards, gantry rail and cages (open once the Ringmaster rages), and the belts' chevrons (`moving`). |
|
||||
| `public/activities/ghoul-rush/stages/carnival/ghoul-sfx-carnival.js` | The Carnival's own sounds as data (no imports): `CARNIVAL_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` via `STAGE_SFX` (its rooms play existing tracks, set in `ROOM_MUSIC`) |
|
||||
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride.js` | The Carnival's dark ride (a bonus round) as a pack (`RIDE`), the rules ported from `prototypes/ghoul-rush-ride/gallery.html`. Pack fields `ride` (returns true, so Planny never walks; steps the ride in 16 ms steps), `place` (makes `round.gallery`, the ride's state) and a new `pointer` (the mouse, handed on by `ghoul.js`'s `pointer(type, x, y)`); the entities (`K`: pop, lant, axe, chand, door, hand, head, eyes, boss, inno, mir, web, mini), hit tests with aim assist, the duck zone, hearts through `kit.lose`, the grade (5 to 9 dice, `perf.dice`). Events `ride<Name>` (`SOUNDS`), causes `CAUSES`. Its own seeded random stream; draws no `Math.random` |
|
||||
| `public/activities/ghoul-rush/rides/dark-ride/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-rush/rides/dark-ride/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-rush/rides/dark-ride/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-rush/rides/dark-ride/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-rush/rides/dark-ride/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-rush/rides/dark-ride/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-rush/rides/dark-ride/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-rush/rides/dark-ride/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-rush/rides/dark-ride/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-rush/stages/frozen/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 |
|
||||
| `public/activities/ghoul-rush/stages/frozen/ghoul-frozen-draw.js` | The Frozen Lake's art: `LOOKS` (`custom: true`), `frozenArt(d)` returning the world's hooks (from `ghoul-frozen-world.js`) plus `monsters`, the Frost Widow boss, `hazards` (shards, spikes, webs, barrels, the flare and its fire), `powers` (Hot Cocoa), `front`, `lights` and `react`, and `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`. Its header lists what the art reads off the rules |
|
||||
| `public/activities/ghoul-rush/stages/frozen/ghoul-frozen-world.js` | The Frozen Lake's world (no imports; `frozenWorld(d)` takes ghoul-draw.js's helpers): the night sky with moon, aurora and far mountains (`sky`), the huts, the Lodge's fallen roof, the Black Ice and the Widow's web (`backdrop`, `ground` with the ice's gloss, `shelf`), and `moving` (open water in the holes, thin ice drawn from `round.thin`, never from `spec.ground`, the faces under the Black Ice, falling snow) and `lights`. Draws no random number |
|
||||
| `public/activities/ghoul-rush/arms/ghoul-flare.js` | The Road Flare's rules (`useFlare`, `stepFlareFly`, `stepRoadFire`; no imports, handed the helpers by `ghoul-arms.js`): a lob that lands as a patch of fire, burns monsters on a tick, melts a Frozen Ghoul at once, shows a shade and melts the Widow's veil; never hurts Planny |
|
||||
| `public/activities/ghoul-rush/rides/sled/ghoul-sled.js` | The Coffin Sled (the Frozen Lake's bonus round) as a pack (`SLED`), modeled on the Runaway Cart (`ghoul-cart.js`): pack fields `ride`, `place` and `target`; the track of ice lines with cracks, headstones, drifts, low branches, hands, icicles and popping ghouls, checkpoints, hearts through the Cart's bonus machinery and the grade (3 to 9 dice). Adds no monster, boss or hazard kind and draws no random number; every number is an exported constant documented in its header |
|
||||
| `public/activities/ghoul-rush/rides/hearse/ghoul-hearse.js` | The Midnight Hearse (the Graveyard's bonus round) as a pack (`HEARSE`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; state in `round.runner` (`id: "hearse"`); a flat road of two lanes (road and verge) switched with LEFT/RIGHT inside the lane gates, open graves, headstones and crosses to jump, low branches and the lychgate arch to duck, hands and crows to shoot, closed stretches to go round, lanterns that keep the lamp lit (an unbroken lamp is the grade's `steady` die), and coffins thrown out by each hit with a ghoul to shoot in each. Adds no monster, boss or hazard kind and draws no random number; every number is an exported constant documented in its header |
|
||||
| `public/activities/ghoul-rush/rides/hearse/ghoul-hearse-draw.js` | The Midnight Hearse's art: `LOOKS` (`pack: "hearse"`), `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` (JUMP, DUCK, SHOOT and SWITCH glyphs for the hearse's lane) and `hearseArt(d)` (sky, hills, cemetery, road, verge, things and the hearse by `moving`; the cab door, lows, fog, glyphs and lamp gauge by `front`; `dim` when the lamp is out); no random numbers. Its header lists what the art reads off the rules |
|
||||
| `public/activities/ghoul-rush/rides/sled/ghoul-sled-draw.js` | The Coffin Sled's art: `LOOKS`, `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS` and `sledArt(d)` (the sky, hills, ice and things by `moving`, the lid, the lows and foreground flakes by `front`); no random numbers. Its header lists what the art reads off the rules |
|
||||
| `public/activities/ghoul-rush/rides/gurney/ghoul-gurney.js` | Code Blue (Blackmoor Sanatorium's bonus round) as a pack (`GURNEY`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; the gurney along `ride.track` (shafts are the gaps), wheelchairs that roll, IV stands, lamps and doors overhead, orderlies in doorways, the lights-out waves (`lightsAt`), the surge lamps and the heartbeat monitor's beat; its state is `round.runner` (`pack: "codeblue"`, put back if another pack's `place` clears the shared slot); draws no random number; imports the cart's track helpers |
|
||||
| `public/activities/ghoul-rush/rides/gurney/ghoul-gurney-draw.js` | Code Blue's art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` and `gurneyArt(d)` (the corridors, shafts and floors by `moving`; the gurney, lows, glyphs, countdown and monitor by `front`; `dim` and `lights` for the blackouts); no imports but the Sled's glyph colors |
|
||||
| `public/activities/ghoul-rush/rides/mower/ghoul-mower.js` | The Gardener's Revenge (the Grounds' bonus round) as a pack (`MOWER`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; state in the shared `round.runner` slot (id `mower`); a flat lawn run on a ride-on mower with gaps (ponds, ha-ha ditches), junk, hedge arches, clothes lines of gloves and snapping topiary beasts, and the twist: holding fire lowers the blades, which cut tall grass, weeds and thorn hedges in the zone ahead (the blades heat and jam, so they are pulsed); the lawn-cut share is the grade's steady die; hearts through the Cart's bonus machinery; no random numbers |
|
||||
| `public/activities/ghoul-rush/rides/mower/ghoul-mower-draw.js` | The Gardener's Revenge's art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` (JUMP, DUCK and CUT glyphs) and `mowerArt(d)` (sky, manor, topiary and railings by `moving`, the lawn with its ponds and ditches, the mower with its blades and heat gauge, the lows and the lawn gauge by `front`); no random numbers |
|
||||
| `public/activities/ghoul-rush/stages/frozen/ghoul-sfx-frozen.js` | The Frozen Lake's own sounds as data (no imports): `FROZEN_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` via `STAGE_SFX` (its rooms play existing tracks, set in `ROOM_MUSIC`) |
|
||||
| `public/activities/ghoul-rush/rides/mower/ghoul-sfx-mower.js` | The Gardener's Revenge's own sounds as data (no imports): `MOWER_SFX` with first-draft `tones` (`ghoulMower<Act>`, each under 1.2 s) and the `ghoulMowerRide` track (sound and music picks still pending); merged by `ghoul-sfx.js` via `STAGE_SFX`, the track set in `ROOM_MUSIC` |
|
||||
| `public/activities/ghoul-rush/rides/pew/ghoul-pew.js` | Holy Roller (the Chapel's bonus round) as a pack (`PEW`): a Subway-Surfers style endless-runner seen from behind, pack fields `ride`, `place` and `target`; state in the shared `round.runner` slot (id `pew`). `you.x` is only the distance run; the pew's own `lane` (a float to `laneTo`), `h`, `slide`, `combo` and `magnet` live in `round.runner`. Left/right presses change lane (a wall bump at the edge), up jumps, down slides (fast-fall in the air), fire shoots down the lane; a speed ramp by distance (`speedAt`); `KINDS` (switch: pillar, confessional, pewx; jump: kneeler, stand, cracks, hatch; slide: censer, banner, beam; shoot: garg with 2 hp, bell rope), wax souls and halos, the combo and the steady die (souls share); a hit shoves the pew to a calm lane. Pure rules, no random numbers |
|
||||
| `public/activities/ghoul-rush/rides/pew/ghoul-pew-course.js` | Holy Roller's seeded course (no imports): written in seconds and laid by the speed ramp (`xAt`, `speedAt`, `V0`, `ACC`), `COURSE` { items [x, lane, kind, len], souls, checks, finish } |
|
||||
| `public/activities/ghoul-rush/rides/pew/ghoul-pew-draw.js` | Holy Roller's art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS` and `pewArt(d)`, whose `field(ctx, view)` draws the WHOLE field (ghoul-draw.js has a `round.runner.id === "pew"` branch like the dark ride's `round.gallery` one, then adds the hearts, flash, banner, cards and HUD pills) plus the progress track, souls and combo strip, and the events' effects |
|
||||
| `public/activities/ghoul-rush/rides/pew/ghoul-pew-world.js` | Holy Roller's pseudo-3D nave: `worldArt(d)` with `paint(ctx, view)`; the projection `(lane, depth, height)` to the screen with scale = near / (near + depth) toward a vanishing point, far-to-near cells with fog as alpha, stained glass, pillars and ribs, pews, candlelight and god rays pulsing on the organ's beat (`pulse`, `BPM`), every thing's art and telegraph glyph, the souls, bolts, the pew and hero from behind, speed streaks and vignette. A reusable pattern for "run into the screen" rides. No random numbers (hashes) |
|
||||
| `public/activities/ghoul-rush/rides/pew/ghoul-sfx-pew.js` | Holy Roller's own sounds as data (no imports): `PEW_SFX` with 17 tones (lane, bump, jump, land, slide, dive, soul, halo, crash, check, finish, speed swell, gargoyle and bell) and the driving `ghoulPewDirge` track at 132 BPM (first drafts, merged by `ghoul-sfx.js`) |
|
||||
| `public/activities/ghoul-rush/rides/hearse/ghoul-sfx-hearse.js` | The Midnight Hearse's own sounds as data (no imports): `HEARSE_SFX` with 19 first-draft `ghoulHearse<Act>` tones (none over 1.2 s) and the `ghoulHearseRide` track (a funeral march at a gallop, built from three four-bar parts); merged by `ghoul-sfx.js`, named in `ROOM_MUSIC`. Sounds and music still to be picked by ear |
|
||||
| `public/activities/ghoul-rush/rides/sled/ghoul-sfx-sled.js` | The Coffin Sled's own sounds as data (no imports): `SLED_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` (the room plays the Graveyard's `ghoulGraves`) |
|
||||
| `public/activities/ghoul-rush/rides/banister/ghoul-banister.js` | The Grand Banister (the Manor's bonus round) as a pack (`BANISTER`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; state in the shared `round.runner` slot (id `banister`); YOU slide down a grand staircase's banister along `ride.track` (the first `rails` lines are the handrail, the breaks between them gaps to jump; the rest are brass under-rails beside it, the split track: a jump with DOWN held dives onto one, a jump off its end lands back on the handrail), vases and candlesticks to jump, hanging portrait frames to duck, chandeliers on a pendulum (`swingAt`: a wall from the bob to the roof, lethal to a ducking rider while the bob is mid-swing, so you brake or lean (LEFT/RIGHT) to time them or take the under-rail), ghostly butlers that lunge (jump or two bolts) and cobwebs to shoot. Adds no monster, boss or hazard kind; no random numbers. Its header documents the room fields |
|
||||
| `public/activities/ghoul-rush/rides/banister/ghoul-banister-draw.js` | The Grand Banister's art: `LOOKS` (`pack: "banister"`), `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` (JUMP, DUCK and DIVE glyphs) and `banisterArt(d)` (damask wall, moonlit windows, a zig-zag of staircase flights, portraits whose eyes follow YOU, the rails, props, butlers and webs by `moving`; the hanging frames, the chandeliers with the arc they swing through, sparks and glyphs by `front`); no random numbers. Its header lists what the art reads off the rules |
|
||||
| `public/activities/ghoul-rush/rides/banister/ghoul-sfx-banister.js` | The Grand Banister's own sounds as data (no imports): `BANISTER_SFX` with 14 first-draft `ghoulBan<Act>` tones (each under 1.2 s) and the `ghoulBanister` track (a harpsichord waltz at a gallop, built from three four-bar parts); merged by `ghoul-sfx.js` via `STAGE_SFX`, named in `ROOM_MUSIC` (sound and music picks still pending) |
|
||||
| `public/activities/ghoul-rush/rides/wagon/ghoul-wagon.js` | The Torch Mob (Hollow End Village's bonus round) as a pack (`WAGON`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; a hay wagon along `ride.track` (ditches and the collapsed bridge are the gaps, a rising line end a ramp), barrels and crates, washing lines and inn signs, villagers who hurl pitchforks (duck) and torches (jump), spooked horses, and the pursuit meter (`gap`: the mob runs at `MOB_V`, DOWN is a duck and the brake, a hit, a burning hay load and the surge close it, a shot torch or fork opens it, inside `PANIC_ON` the horses bolt, at `CATCH_GAP` it is a heart); its state is `round.runner` (`id: "wagon"`); draws no random number; imports the cart's track helpers |
|
||||
| `public/activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js` | The Torch Mob's art: `LOOKS` (`pack: "wagon"`), `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` and `wagonArt(d)` (the sky, rooftops, street, cobbled road, ditches, the bridge and river, the things, the mob and the wagon by `moving`; the lows, throws in the air, the hay fire, glyphs and the mob's meter by `front`); no random numbers; imports the Sled's glyph colors and the rules' constants |
|
||||
| `public/activities/ghoul-rush/rides/wagon/ghoul-sfx-wagon.js` | The Torch Mob's own sounds as data (no imports): `WAGON_SFX` with 18 first-sketch `ghoulWagon<Act>` tones and the `ghoulWagonRide` track (a D minor gallop built from three 4-bar patterns); merged by `ghoul-sfx.js`, the room's track named in `ROOM_MUSIC` (`wagon`) |
|
||||
| `public/activities/ghoul-rush/story/ghoul-story.js` | Ghoul Rush's intro story: the pages' text as data and the rules (lockout, reveal, skip) as plain functions over a round; drawn by `ghoul-story-draw.js`, sounded by `ghoul-sfx-story.js`, the lore bible in `prototypes/Ghoul-Rush-TODO.md` |
|
||||
| `public/activities/ghoul-rush/story/ghoul-story-draw.js` | The intro story's drawing (`storyArt(d)`): eight animated scenes in canvas shapes (the road, the house on the hill, the hunger, the long arms, the farthest rooms, why YOU, no way back, the door to The Long Hall) with the heading, the lines typing out, the page dots, the always-visible skip hint with its hold bar and the pulsing continue hint; drawn over the field while `round.phase === "story"`; reuses the intro card's helpers (`poly`, `dot`, `stroke`, `faint`, `flame`, `titleLayout`, `dropAt`); no gradients |
|
||||
| `public/activities/ghoul-rush/story/ghoul-sfx-story.js` | The intro story's own sounds as data (no imports): `STORY_SFX` tones for the pages' `cues` (wind, a bell, a heartbeat, a door creak, knocks, a whisper, the flashlight click, the page turn) and the `hums` drone under the whole story; merged by `ghoul-sfx.js` |
|
||||
| `public/activities/ghoul-rush/rides/gurney/ghoul-sfx-gurney.js` | Code Blue's own sounds as data (no imports): `GURNEY_SFX`, 18 first-pick `ghoulBlue<Act>` tones and the track `ghoulBlueRide`; merged by `ghoul-sfx.js` (the room plays it via `ROOM_MUSIC.codeblue`) |
|
||||
| `public/activities/ghoul-rush/rides/tray/ghoul-tray.js` | The Servants' Back Stairs (the East Wing's bonus round) as a pack (`TRAY`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; the track of shelves and stair flights with gaps, rolling pots and cutlery, hams and pans, cooks who fling dishes, the courses (silver domes and flying plates, seven is the grade's acts die), the cherries, grease stretches, checkpoints and the grade (3 to 9 dice). State is `round.runner` (id `tray`), the shared slot for a rolling bonus ride. Adds no monster, boss or hazard kind and draws no random number; every number is an exported constant documented in its header |
|
||||
| `public/activities/ghoul-rush/rides/tray/ghoul-tray-draw.js` | The Servants' Back Stairs' art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, the telegraph glyphs (`telegraphMarks`, `telegraphs`: JUMP, DUCK, SHOOT) and `trayArt(d)` (the kitchen, shelves and stairs, things and cooks by `moving`; the tray, hams and pans, flour and glyphs by `front`); no random numbers |
|
||||
| `public/activities/ghoul-rush/rides/tray/ghoul-sfx-tray.js` | The Servants' Back Stairs' sounds and music as data (no imports): `TRAY_SFX` with 13 first-draft tones and the `ghoulTrayRide` track; merged by `ghoul-sfx.js` |
|
||||
| `public/activities/ghoul-rush/stages/chapel/ghoul-sfx-chapel.js` | The Chapel's own sounds as data (no imports): `CHAPEL_SFX`, its `tones` (the 35 picked `ghoul<Kind><Act>` sounds of the gargoyles, choir ghosts, monks, bell bats, the Choirmaster, the bell and Holy Water's splash) and `music` (`ghoulNave`, `ghoulTower`, `ghoulLoft`, `ghoulChoir`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` via `STAGE_SFX` |
|
||||
| `public/activities/ghoul-rush/stages/sanatorium/ghoul-sfx-sanatorium.js` | Blackmoor Sanatorium's own sounds as data (no imports): `SANATORIUM_SFX`, its `tones` (the 38 picked `ghoul<Kind><Act>` sounds of the orderlies, gurneys, flickers, specimen bloaters, the Night Matron, the lamps, Smelling Salts and the Bone Saw) and `music` (`ghoulAdmissions`, `ghoulBaths`, `ghoulTheater`, `ghoulWard`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` via `STAGE_SFX` |
|
||||
| `public/activities/ghoul-rush/stages/village/ghoul-sfx-village.js` | Hollow End Village's own sounds as data (no imports): `VILLAGE_SFX`, its `tones` (the 42 picked `ghoul<Kind><Act>` sounds of the torch mob, hanged men, shutter ghouls, moonhounds, the Beast, the full moon and Wolfsbane) and `music` (`ghoulStreet`, `ghoulInn`, `ghoulSquare`, `ghoulGreen`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` via `STAGE_SFX` |
|
||||
| `scripts/test-web-console-activities-ghoul-chapel.mjs` | The Chapel's suite: each monster, the bell toll and its freeze, Holy Water's splash, the Choirmaster's pipes, notes and rage, a voice for every act, each event playing exactly one picked sound, and every picked tone present in the merged tones and in `ghoul-sfx-chapel.js` |
|
||||
| `scripts/test-web-console-activities-ghoul-sanatorium.mjs` | The Sanatorium's suite: the orderly's reach, hold and throw (and the Salts), the gurney's park, rattle, roll and rest and its floor, the flicker's unseen state, the lamps' timing, the specimen's jar and puddle, both power-ups (stage-only), the Matron's cone, heat, cabinets, syringes, arms and rage, endless lives for every new cause, and a voice for every act |
|
||||
| `scripts/test-web-console-activities-ghoul-village.mjs` | The Village's suite: the rooms, the moonrise timing, the turn and the grow at full moon (and the per-room reset), the villager's group, torch and fire, the hanged man's drop, the shutter ghoul hit only while out, the moonhound, Wolfsbane (stage-only, double damage, shying), the Beast's wall leap, cling weak spot, pounce shadow, swipe, howl and its cap, the rage, endless lives for every new cause, no random draws, and a voice for every act and event |
|
||||
| `scripts/test-web-console-activities-ghoul-mine.mjs` | The Mine's suite: the rooms and the cage rows, rockfall timing, aim and crush, the Hard Hat (stage-only, bounce), the imp's light steal (no life, ended by a shot or a stomp, blocked by the hat), the canary's scream and its three rocks, the miner's dig and swing, the blind crawler losing and hearing you (and the water's louder steps), water slowing you, the cage carrying Planny, Dynamite (a double tap, the bag, the blast), every Tommyknocker move including the dark, the decoy, the burst, the dazed double damage and the rage cap on imps, no random draws, endless lives for every new cause, and a voice for every act and event |
|
||||
| `scripts/test-web-console-activities-ghoul-carnival.mjs` | The Carnival's suite: the rooms and the belts, grinners and their balloon cap, balloons and their acid, the marionette's drop and its string, Mirror You (the delay, the mirrored moves, jumps, its bolts and their canceling, stunned by a pie), the strongman, the circus hound (a swoop, duckable), Cotton Candy, the Custard Pie, every Ringmaster move (stalk, leap, charge, stomp, whip, the strings following, open, rage, hounds, the script), no random draws, endless lives for every new cause, and a voice for every act |
|
||||
| `scripts/test-web-console-activities-ghoul-grounds.mjs` | The Grounds' suite: each monster's behavior, the shears, the Groundskeeper's moves and phases, a voice for every act, each event playing exactly one picked sound, and every picked tone present in the merged tones |
|
||||
| `scripts/test-web-console-activities-ghoul-bog.mjs` | Gallows Bog's suite: the stage row and its rooms, the mud (slow, sink, jump, shelf, boots), each monster's behavior (the lurker's eyes and snap, the leech's latch, the wisp's light, the bog body's rise), the wisp lure and its fairness cap, the harpoon under the water, Old Mother Bog's wave, weak cauldron, muck, sink and resurface, every move (wind-up, telegraph event, effect, a clean dodge costs nothing, a hit a heart), the phase unlocks, cooldowns and caps, planks while standing, her fall clearing every hazard and add, a skilled bot that must kill her in 60 to 120 s on four seeds and an idle bot she kills, a voice for every act with exactly one picked sound per event, words and a sound for every cause, both cards, the round flow, drawing dark and lit, and a seeded bot on a draw that throws if the pack asks for a random number |
|
||||
| `scripts/test-web-console-activities-ghoul-marrow.mjs` | The finale's suite: the win condition (`RUN_STAGES` picks that never repeat, then the House with no offer, its stage card and the boss's, the win), the select listing it last at depth 0, the memo (one past every stage only on a win, never from practice) and the words that count `RUN_STAGES`; Kill I, The Lawn: the wall and the out-of-reach guarded box, every window hit from the surface serving its row and passed while shuttered, a window out for good across a life lost, rows opening by windows out, `pickMove`'s rules, each move's telegraph, hit (its cause) and dodge, the doormen's cap, endless lives, the retreat's beats in order and the door it leaves, a steady bot's fight length at full depth and an idle one's death, the voices, words and sounds, and drawing every state lit and dark |
|
||||
| `scripts/test-web-console-activities-ghoul-mat.mjs` | Down the Hatch's suite: the track, every obstacle's telegraph, hit and dodge, the squeezes, bile, the grade, a good bot finishing and one that never dodges losing its three hearts without a game over |
|
||||
| `scripts/test-web-console-activities-ghoul-eye.mjs` | Kill II's suite: the Eye's flare, opening and guard, a shade move for every boss in `STAGES`, the lurch and the dresser, the retreat, a bot's fight length, voices and drawing |
|
||||
| `scripts/test-web-console-activities-ghoul-bonestair.mjs` | The Bone Stair's suite: the flights and seams, the rubble's meter, every obstacle's telegraph, hit and dodge, the grade, and the bot sims |
|
||||
| `scripts/test-web-console-activities-ghoul-heart.mjs` | Kill III's suite: the beat and its waves, the ribs' window, every attack's warning, the clamp at 1 hp and HOLD FIRE, the white-out and the door of light, a bot's fight length, voices and drawing |
|
||||
| `scripts/test-web-console-activities-ghoul-ending.mjs` | The ending's suite: the pages' rules, a press turning pages, holding fire to skip, the win once at the end, every scene drawn |
|
||||
| `scripts/test-web-console-activities-ghoul-lantern.mjs` | The Drowned Lantern's suite: the room and its tables, the walk and the slide, steps on wood, the flare and the oil, the shrines, Mother's wake and rise and the boat, each hunter's rule (the Lurker's hearing, lane and dash, the guardian and roaming wisps, the leeches at the light's edge and their bite, the bodies that take only the still, Mother's hand and its gaps), hearts, endless lives and the grade, the clock, determinism (no random drawn), the balance (a bot that ignores the hunters loses every shrine order, one that plays them wins each with hearts left), the rule tags and banner marks, the hums, voices and drawing |
|
||||
| `public/activities/ghoul-rush/draw/ghoul-picker-draw.js` | The choice of stage, its drawing: `pickerArt(d)`, handed `ghoul-draw.js`'s helpers (`lookOf`, `label`, `roundRect`, `circle`, `BOSS_ART`, `drawGourdFire`, `GOLD`), returning `drawPicker` (a card per stage offered: its picture of its rooms with its boss standing there, its name, line and boss, the pick raised and edged in gold, and how to choose), `drawSelect` (the stage select for testing: every stage in a list, two columns past 8, the one picked out with its picture and a chip per room) and `stageColor` (a stage's boss room's color, also the tally dots'). Split from `ghoul-draw.js` to keep it under the 3,000-line cap |
|
||||
| `public/activities/ghoul-rush/core/ghoul-powers.js` | Ghoul Rush's power-ups and pickups (no imports: `ghoul.js` hands its rules a kit, `POWER_KIT`, of `landing` 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-rush/arms/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-rush/arms/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-rush/arms/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-rush/arms/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-rush/arms/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-rush/arms/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-rush/core/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 |
|
||||
| `public/activities/ghoul-rush/core/ghoul-dice.js` | Ghoul Rush's Lucky die rules (no imports: `ghoul.js` hands them `DICE_KIT`): `MAX_DICE` (9, the most one bonus or ride pays; dice in hand have no limit), `ROLL_MS`, `TUMBLE_MS`, `SAVED_TIME_MS`, `markRest` (the last solid ground Planny stood on), `reviveSpot`, `beginRoll` (called by `lose` when `round.dice > 0` and not `round.infinite`: the round holds in the phase `ask` and asks "Use a Lucky Die?", the event `diceAsk`), `askStep`, `steerAsk`, `answerAsk` (Yes spends one die and holds in the phase `roll`; No keeps every die, the event `diceKeep`, and lets the loss go ahead; a press inside `ASK_GUARD_MS` is ignored so the key held at the death cannot answer), , `rollDice` (one die at a time from advance's `random`, events `diceStart`, `diceRoll`, `diceFace`, `diceSaved`, `diceFail`; a six revives with the Garlic shield and `SAFE_MS`, and blows apart every monster in view in a room without a boss (`diceBlast`, kills with `how: "luck"`, points but no drops); no six hands the loss back to `takeLife`) |
|
||||
| `public/activities/ghoul-rush/core/ghoul-bonus.js` | Ghoul Rush's bonus rounds, the rules (imports only `MAX_DICE`; no random numbers): a room with `bonus: true` (the Runaway Cart; the Carnival's dark ride is meant to follow) gets `round.bonusRound = { hearts, max, dice, over, won, perf }` on entering it (null elsewhere; `round.bonus` is already the time bonus score). A life lost in it is a heart lost through the same `lose`/`takeLife` (so Garlic, the safe moment and `round.infinite` work as ever; no Lucky die is rolled for a heart); the last heart gone calls `endBonus(round, false)` from `respawn` (no dice, no game over, the run's lives untouched), and a finish alive calls `endBonus(round, true)` from `clearRoom` (`diceFor`: `BONUS_FLOOR` 3 plus up to 6 by hearts, clean obstacles, acts and a steady hand, added to `round.dice`, which has no limit). A room's pack notes its performance in `bonusRound.perf` (`total`, `hits`, `acts`, `goal`, `steady`); both ends hold the phase "clear" for the card (`CARD_MS`, `CARD_LOST_MS`) and set `bonusRound.result`. Events `bonusStart`, `bonusEnd`; `heartsText(b)` is the HUD pill |
|
||||
| `public/activities/ghoul-rush/core/ghoul-bonus-draw.js` | The bonus rounds' art (`bonusArt(d, die)`): `card` ("BONUS CLEARED! +N LUCKY DICE" with the dice tumbling in, or the short "BONUS LOST"), `react` (the intro banner, the end, the hearts-left float) and `tick` (a click for each die landed) |
|
||||
| `public/activities/ghoul-rush/core/ghoul-dice-draw.js` | The Lucky die's art (`diceArt(d)`: the small drop, the rolling die on a panel placed away from Planny, the `ask` panel ("Use a Lucky Die?" with YES and NO, the lit one gold), the sweeping "LUCKY-SAVE" word, and `react` for the dice events, which plays `ghoulLuckySave` once on the revive) |
|
||||
| `public/activities/ghoul-rush/story/ghoul-gameover-draw.js` | The lost end screen's "G A M E - O V E R" (`gameOverBanner(d)`, `dropAt`): nine letters dropping in with a stagger and one bounce, then bobbing on a sine wave under a slow pulse, red and bone with a dark shadow, drawn above the score panel and never on a win. `ghoul.js` keeps ticking the clock on the lost end screen (`view.overMs`) and plays the mechanical laugh track there: `ghoulLaughTrack`, `ghoulLaughTrack2` and `ghoulLaughTrack3` in `ghoul-sfx.js`, one second apiece (a tone may not pass 1.2 s). |
|
||||
| `public/activities/ghoul-rush/story/ghoul-intros.js` | The stage intro cards' words and colors: `INTROS` per stage id (`title`, `palette` {a, b, glow}, `kicker`, 3 or 4 `lines` of flavor text at most `MAX_LINE` characters, `boss`), `introFor(id)`. Always addressed to YOU. A test fails for a stage in `STAGES` with no card. |
|
||||
| `public/activities/ghoul-rush/story/ghoul-intro-draw.js` | The intro card's drawing (`introArt(d)`, `titleLayout`, `dropAt`): the title's letters dropping in and glowing, one themed flourish per stage (frost crystals, bunting, pickaxe sparks, leaves, candle flames, ...), the lines fading in, the boss and the pulsing "Press any move key or fire to enter". Drawn over the field while `round.phase === "intro"`. The phase itself lives in `ghoul-run.js` (`startIntro`, `stepIntro`, `takeIntro`, `INTRO_MIN_MS` 1.2 s: any fresh move key, fire or a click moves on after it, repeats never, and the card never moves on by itself); the tone is `ghoulStageIntro`. |
|
||||
| `public/activities/ghoul-rush/story/ghoul-boss-intros.js` | The boss intro cards' words: `BOSS_INTROS` per boss id (`name`, which must equal the boss's `name` in its pack's `bosses` table, an `epithet` of at most `MAX_EPITHET` characters and an optional `accent` color), `bossIntroFor(id)`. A test fails for a boss room whose boss has no entry. |
|
||||
| `public/activities/ghoul-rush/story/ghoul-bossintro-draw.js` | The boss intro card's drawing (`bossIntroArt(d)`): a "BOSS FIGHT" title whose letters slam in with a screen shake and a heartbeat pulse, the boss drawn from its own art (`BOSS_ART`, the way the stage pick does) at a big scale in a spotlight on the stage's palette, its name, the epithet and the pulsing "Press any move key or fire to start the fight"; a boss whose art throws falls back to a silhouette. Drawn over the field while `round.phase === "bossintro"`. The phase lives in `ghoul-run.js` (`startBossIntro`, run by `enter` on every boss room, and `onCard`; it shares `introMs`, `stepIntro`, `takeIntro` and `INTRO_MIN_MS` with the stage card, and a respawn never shows it); the tone is `ghoulBossIntro`. |
|
||||
| `public/activities/ghoul-rush/draw/ghoul-monsters-draw.js` | The generic monsters' art (`monsterArt(d)`, no imports; `ghoul-draw.js` hands it its helpers `ellipse`, `circle`, `line`, `rotate`, `turned`, `eye` and the colors): `drawZombie`, `drawZombieKin`, `drawHuntsman`, `drawCrawler`, `drawBat`, `drawGhost`, `drawSkeleton`, `drawGourdling`, `drawHound`, `drawSpider`, `drawWraith`, `drawSpitter` and the missiles `drawBoneShape` and `drawGlob`. Split from `ghoul-draw.js` to keep it under the 3,000-line cap |
|
||||
| `public/activities/pills.js` | The pills every game but Mini golf draws along its top (no imports): `drawPill(ctx, x, y, w, h, text, color, fill, textY)` on one opaque dark backing, `PILL`, the same in light and dark and over any scene, a timer's share still left tinted at `PILL_TINT`, and the text in `pillInk(color, tinted)`: the pill's own color when it reads at `PILL_CONTRAST` (4.5:1) on the backing (and on the tint while a timer runs), else the least step toward white that does, so warnings stay red; lives are the one solid pill: a pill in the `LIVES` color is drawn on `LIVES_BACK` in white (`LIVES_INK`), its text from `livesText(n)` (a heart per life up to five, `♥ xN` past that, `♡` at none); `pillTint` and `pillContrast` for the unit suite |
|
||||
| `public/activities/golf.js` | Mini golf: six eighteen-hole courses, one round at a time; its rules and physics as plain exported functions (`newRound(courseId)`, `holesOf`, `coursePar`, `strike`, `advance` on a fixed 4 ms sub-step, `nextHole`, `total`, `toPar`, `predictPath` for the spyglass, `moverAt`, `gateShut`, plus ice that barely slows the ball and wells that pull it in or push it away), the `POWERUPS` held for the next putt (`round.held`, then `round.active` for that putt), the arcade swing (`startSwing`, `setPower`, `meterAt`, `meterZone`, `swingShot`: a ping-pong power meter, slow at the bottom and fast at the top, with a MAX band that boosts and an overswing band that shanks; a shot clock in `advance()` that starts the meter after `SHOT_CLOCK_MS` and dribbles the ball after `METER_TRIPS` trips; all on the round's own clock), the pop-up gags, and the game contract with `pointer()` (the aim follows the pointer, a press swings, a press held on a roll fast-forwards), `release()` (held arrows turn the aim, held space fast-forwards) and `lowerIsBetter`, `courses` (the dashboard's cards), `preview(canvas, id, w, h)` (a course's card art) and `setCourse(id)`; deterministic (no `Math.random()`), a read-only `round` getter for the unit suite only |
|
||||
| `public/activities/golf-draw.js` | Mini golf's drawing: `drawCourse(ctx, view)` from a plain view `golf.js` builds, each hole in its theme's fixed palette (`pirate`, `cave` with its darkness and glows, or a newer course's look from `golf-looks.js`, asked first for its grounds, water, tunnels, gates and wells), ice, the scorecard and banners in the course's voice, a bare view for the dashboard's card art, `knownGround`/`knownLiquid` for the unit suite, and `readColors(canvas)`, which reads the `--golf-*` properties `styles/activities.css` mixes from the tokens for the ball, pills and scorecard; decides nothing |
|
||||
| `public/activities/golf-decor.js` | Mini golf's scenery and props for Pirate Cove and the Caves of Doom: each `decor` kind (sharks, ships, parrots, bats, torches, eyes, a dragon) on its layer, the looks of bumpers, movers and spinners, and the power-up icons, each asking the hole's course look first (`decorKinds(theme)` lists a theme's scenery); drawing only, moving with the round's clock |
|
||||
| `public/activities/golf-holes.js` | Mini golf's courses: `COURSES`, the six eighteen-hole courses in dashboard order (Pirate Cove, Caves of Doom, Dino Valley, Candy Carnival, Cosmic Glow, Frosty Peaks), `courseById`, `HOLE_COUNT`, `FRONT_NINE`, `COURSE_W`, `COURSE_H` |
|
||||
| `public/activities/golf-kit.js` | Mini golf's course kit, data only: `COURSE_W`, `COURSE_H`, the helpers course files build holes with (`pt`, `rect`, `wall`, `bump`, `pad`, `deco`), `hole(def, defaults)` (what a hole holds: theme, quip, ground, liquid, tee, cup, outline, walls, bumpers, sand, ice, water, slopes, wells, bridges, spinners, tunnels, movers, gates, powerups, decor) and `course()`, which freezes a course with its name, card line, cover hole and voice |
|
||||
| `public/activities/golf-course-pirate.js` | Mini golf's Pirate Cove course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
|
||||
| `public/activities/golf-course-cave.js` | Mini golf's the Caves of Doom course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
|
||||
| `public/activities/golf-course-dino.js` | Mini golf's Dino Valley course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
|
||||
| `public/activities/golf-course-candy.js` | Mini golf's Candy Carnival course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
|
||||
| `public/activities/golf-course-space.js` | Mini golf's Cosmic Glow course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
|
||||
| `public/activities/golf-course-frost.js` | Mini golf's Frosty Peaks course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
|
||||
| `public/activities/golf-looks.js` | Mini golf's course looks by theme id, and the look contract (palette, liquids, grounds, rough, tunnel, lights, and the looks of bumpers, movers, spinners, gates, wells and scenery) |
|
||||
| `public/activities/golf-look-dino.js` | How Dino Valley is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
|
||||
| `public/activities/golf-look-candy.js` | How Candy Carnival is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
|
||||
| `public/activities/golf-look-space.js` | How Cosmic Glow is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
|
||||
| `public/activities/golf-look-frost.js` | How Frosty Peaks is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
|
||||
| `public/activities/golf-paint.js` | Mini golf's shared canvas helpers (`polygon`, `circle`, `ellipse`, `radial`, `fill`, `stroke`, `line`, `label`, `turned`, `t`, `scatter`, `bounds`), no imports, so the drawing files and the looks share them without import loops |
|
||||
| `public/app.js` | the page's entry and the only page file that starts anything: the start-up block. `index.html` loads it; it imports `screens/core.js` and the screens beside it |
|
||||
| `public/doc-files.js` | a document as the page shows it, and as a file: blocks, Markdown and HTML download |
|
||||
| `public/hops.js` | no imports: the hop rule, `startsClean(from, to)`, which says whether a hop from one workflow to another starts the new skill on a clean page (to or from the dashboard, into Git, or from one skill into another off a finished screen, but never out of Git or into Review); shared by `cmd-open.mjs`, `server.mjs` (its Ask reset) and `screens/core.js` |
|
||||
| `public/looks.js` | how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches |
|
||||
| `public/mention-box.js` | the @name suggestions popover under a text box |
|
||||
| `public/net.js` | the page talking to its own server |
|
||||
| `public/palette.js` | the highlight colors, the sound events and the card widths, as data (importable by Node so a test can check every shade in both themes) |
|
||||
| `public/render.js` | Markdown to DOM, safely: no HTML string is ever produced, only nodes built with `createElement` and `textContent`; also the shared page helpers (`el`, `md`, `copyButton`, `lightDismiss`) |
|
||||
| `public/selectors.js` | what the page reads off its state: the questions, the finish, the scan, who has the ball |
|
||||
| `public/send-state.js` | whether Send is available, and what its button says |
|
||||
| `public/skills.js` | the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (`SKILL_CATALOG`, `START_POSES`, `CONSOLE_WORKFLOWS` and the rest, in `answers.js`) are lookups on it. Each entry also carries `weight` (what its launch and `run` score on the meter, or null), `started` and `ran` (the meter's labels for them, or null), `resume` (`"overview"`, `"folder"` or null: what the resume command takes after the skill's command) and an optional `card.help` (Help's line for the card when it differs from `blurb`). `WORKFLOWS` (every entry's workflow, in order) and `isWorkflow()` are what the CLI checks a `--workflow` against. The meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS`, `resumeCommand()`, Help's card list and `cmd-help`'s workflow list are all derived from it, so a new skill is one entry here, not an edit to each of those |
|
||||
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click |
|
||||
| `public/spec-states.js` | the spec states (`diagnosed`, `fixed`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
|
||||
| `public/state.js` | the page's shared state (`page.S` the server's truth, `page.local` what is staged) and the `redraw()` / save hooks every screen calls; defines only |
|
||||
| `public/tones.js` | the activities' sound engine, all synthesized in the browser. Three parts: a shared kit of rich one-shot sounds (`RICH`: `layers` of parts played together, each a wave or a noise (`noise`, `pink`, `brown`) with its own `delay`, `gain`, `attack`, a sweeping `filter` and `vibrato`: `explode`, `smash`, `skid`, `whoosh`, `splashBig`, `fanfare`, `gameOver` and some fifty more, up to 1.2 s, at most `MAX_VOICES` parts sounding at once), held **hums** (`hum(id, name, level, pitch)`, called every frame a game wants it: oscillators and noise through one filter that follows the pitch, pulsed for an engine's strokes; a hum not asked for within `HUM_HOLD_MS` fades by itself, so a paused or closed game goes quiet without saying so, `hushTones()` quiets every one and the Activities window calls it whenever it stops ticking; at most `MAX_HUMS`; shared ones `car`, `toycar`, `electric`, `outboard`, `river`, `wind`, `cycle`, `fuse`, `haunt`, `squeal`, `meter`, `swarm`, `train`, `crowd`), and each game's own extras in `public/activities/<id>-sfx.js` (`{ tones, hums }`, plain objects, names prefixed with the game id, merged and frozen here; a name may be defined once across all of them, which `scripts/test-web-console-tones.mjs` checks along with every spec's shape and every name a game's source asks for). Everything plays through one compressor. The older single blips (`BLIPS`): `tone(name, level, pitch)` with an optional loudness from 0 to 1 and an optional pitch that scales every frequency, kept between 0.25 and 4, and an optional fourth `louder` (a game lifting its sounds as a whole, up to `LOUDER_MAX`, also the fifth argument of `hum()`), `unlockTones()`; Snake's blips plus golf's `putt`, `wall`, `bump`, `cup`, `ace` (a three-note rise), `splash`, `power` (a power-up, three notes), `tunnel`, `boom` (a cannon putt), `sizzle` (lava) and `fall` (the pit), the countdown's `count` and `go`, Stack Deploy's `thunk`, `slice` and `perfect`, which it pitches up a scale step for each perfect in a row, and Bumper Ring's `ram`, pitched and leveled by how hard the hit, and `rev`, a rival winding up a dash, and Hot Potato's `tick`, the fuse, which it ticks quicker and pitches higher as the fuse burns down, and `pop`, a pass, and Crossing Rush's `hop`, which it pitches up a step for each quick hop forward in a row, `boing`, a send-back, `bell`, a train coming, and `horn`, and Bounce Road's `engine`, a soft low triangle hum it plays every few frames while you pick up speed (quiet once you cruise or coast), pitched up with your speed, `spring`, a jump, pitched with your speed, and `squash`, a rival flattened, pitched up a step for each in a chain, and `beat`, a low thump while your wheels run on the verge (it borrows the other games' blips for its hazards and rivals), and Rapids Run's `pew` (a shot, a short soft triangle played quietly about seven times a second while fire is held), `charge` (a buoy taken), `lowcell` (the low battery's two-note beep, quicker the lower it runs), `dambreak` (a dam bursting) and `skim` (a bank skimmed at speed, pitched up the more you have skimmed), and Ghoul Rush's `ghoulBlast` (the blaster's bolt, a short soft triangle repeated while fire is held), `zombiePop` (a kill, pitched up a step for each in the chain), `ghoulStomp`, `ghoulBoo`, `ghoulRoar` and `zombieGroan` (now kept for the other games and the tests: Ghoul Rush's monsters speak with their own voices from `ghoul-sfx.js`), `ghoulCandy` (pitched up for candy in quick succession), `batSwoop` (a bat's kill), `doorUnlock` (the key), `doorThrough` (the door to the next room) and `creakBoard` (a crawler coming up, a chandelier or a crumbling board about to go), all soft triangles and sines), silent while Play sounds is off; separate from `sound.js`'s cue queue |
|
||||
| `public/music.js` | the games' chiptune music: a small sequencer over `tones.js`'s context and compressor (`audioOut()`). A game calls `music(name, intensity)` from its `tick`; the track fades out within `MUSIC_HOLD_MS` once it stops being asked for, picks up again on the bar it left, asking for a different track crossfades the two over `CROSSFADE_S` (the old one keeps playing as it fades, so a new level is not a cut), and `hushMusic()` stops it at once. Tracks are note data under `music` in each game's `activities/<id>-sfx.js` (`{ bpm, rush, bar, voices, patterns, order }`, `bar` the steps in a bar when it is not 16, so the track resumes on a bar start and each pattern is whole bars: pulse, triangle and noise-drum voices, each joining once the intensity reaches its `from`; a step a token, `A4`, `-` to hold, `.` a rest, `A3^037` an arpeggio, drums `k s h o`), read by `compileTrack()` and booked `LOOKAHEAD_S` ahead on the audio clock. It also plays recorded **songs**: mp3s a game names under `songs` in its sfx file (a name to a served path, merged by `tones.js` as `SONG_TABLES`, listed by `songNames()`), asked for the same way, one `<audio>` element each made on first use, at `SONG_PEAK` times the volume, faded over `SONG_FADE_MS`; a song plays once, never looped, `music()` returning `"playing"` or `"ended"` (which the window's wrapper passes back to the game), `{ restart: true }` taking it back to the top with `load()` (no seeking, since the server sends no byte ranges), and a song no longer asked for fades and pauses where it was. The window plays it only while Play sounds, Play game sounds and Play game music (`looks.gameMusic`, off by default) are all on |
|
||||
| `public/activities/snake-sfx.js` · `public/activities/flock-sfx.js` · `public/activities/golf-sfx.js` · `public/activities/trails-sfx.js` · `public/activities/bugs-sfx.js` · `public/activities/drive-sfx.js` · `public/activities/stack-sfx.js` · `public/activities/bumper-sfx.js` · `public/activities/rapids-sfx.js` · `public/activities/fuse-sfx.js` · `public/activities/hop-sfx.js` · `public/activities/bounce-sfx.js` · `public/activities/ghoul-rush/sfx/ghoul-sfx.js` | each game's own sound effects as data, `{ tones, hums }` in the shapes `tones.js` documents, every name prefixed with the game id (`driveEngine`, `ghoulMoan`), merged and frozen by `tones.js`; no imports, but for `ghoul-sfx.js`, which merges each Ghoul Rush stage's own `ghoul-sfx-<stage>.js` into its `tones`, `hums` and `music`, and `snake-sfx.js`, which merges `snake-music.js` as its `music`; `trails-sfx.js` and `flock-sfx.js` have `songs` instead of `music` |
|
||||
| `public/activities/snake-music.js` | Snake's ten music tracks as data (no imports): `SNAKE_MUSIC`, `{ bpm, rush, voices, patterns, order }` each, named `snake<Place>` and listed in `MUSIC_TRACKS` in `snake.js`. A round deals them in a fresh order, one to each level, so a run hears a different track at every level and none twice. They were picked on the pages in `prototypes/music/snake` (rhythm-first folk and world tunes led by something plucked or reedy, mostly dark or modal), and their bars are not all sixteen steps: 6/8 is 12, 7/8 is 14, ten beats is 20, twelve beats is 24, each pattern a whole number of its bars; merged by `snake-sfx.js` |
|
||||
| `public/activities/light-trails/1.mp3` to `5.mp3` | Light Trails' five background songs, named `trailsSong1` to `trailsSong5` under `songs` in `trails-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 7.6 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm |
|
||||
| `public/activities/flock-dash/1.mp3` to `5.mp3` | Flock Dash's five background songs, named `flockSong1` to `flockSong5` under `songs` in `flock-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg the way Light Trails' were (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 6.4 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm; `flock.js` deals all five in a fresh order each round with `dealMusic()`, plays each in full one after another and deals again after the last, never opening on the song that just ended |
|
||||
| `public/activities/ghoul-rush/stages/graveyard/ghoul-sfx-graveyard.js` | The Graveyard's own sounds as data (no imports): `GRAVEYARD_SFX`, its `tones` (the picked `ghoul<Kind><Act>` sounds of the grasping hands, mourners, grave robbers, rotters and their legs, carrion crows and Mother Mourning) and `music` (`ghoulLychgate`, `ghoulGraves`, `ghoulMausoleums`, `ghoulAngel`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` after the house's own. Every new stage gets its own `ghoul-sfx-<stage>.js`, listed in `STAGE_SFX` there |
|
||||
| `public/activities/ghoul-rush/stages/grounds/ghoul-sfx-grounds.js` | The Grounds' own sounds as data (no imports): `GROUNDS_SFX`, its `tones` (the 32 picked `ghoul<Kind><Act>` sounds of the topiary beasts, rootlings, lantern moths, mulch crawlers, the Groundskeeper and the Hedge shears' snip) and `music` (`ghoulMaze`, `ghoulTopiary`, `ghoulGazebo`, `ghoulYard`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` after the house's own via `STAGE_SFX` |
|
||||
| `public/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry, and the page's shared full-screen picture preview (`openPicview`, the `#picview` dialog every thumbnail opens) |
|
||||
| `public/screens/ask.js` | the Ask chat, the Subagents tab, and attaching files to notes |
|
||||
| `public/screens/cards.js` | question cards: every kind, the pager, settled and in-flight records |
|
||||
| `public/screens/cleanup.js` | User Preferences' Cleanup section, on the System tab |
|
||||
| `public/screens/core.js` | the core every screen sits inside: connection, the render loop, the page chrome and Send; the only file that imports the screens, and only `app.js` imports it |
|
||||
| `public/screens/dashboard.js` | the dashboard: cards, the spec picker, handoff chips, delete, and the first-open wake-up |
|
||||
| `public/screens/loop-setup.js` | the Implementation Loop's setup screen on the dashboard (app only): the fields, their defaults and read-only facts, the Start checks, and the request to the app. The page locks while `state.loop.driving` is set (`loopDriving()` in `selectors.js`) until the app posts `loopEnd`; Activities, Notebook, Help and Preferences stay usable. `loopEnd.can` accepts `ask` (`LOOP_CAN` in `patches.mjs`); the app adds it first to every stop that offers `resume`, and the stopped screen's **Ask a question** wakes an ordinary agent on the same session |
|
||||
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button |
|
||||
| `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home |
|
||||
| `public/screens/git-host.js` | hosts the git board: tabs, panels and what each click sends |
|
||||
| `public/screens/help-dialog.js` | the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js). Help reads right in both modes: a phrase that differs under the desktop app carries its app wording in `data-app` (swapped in by `renderAppWording()`), and a paragraph that differs is a `.for-browser` / `.for-app` sibling pair, switched by `:root.in-app` (set in `core.js` from `page.inApp`, rule in `help.css`). The older `render*Help()` functions patch a few ids the same way. `scripts/test-web-console-page-help.mjs` sweeps every topic's visible text in each mode for the other mode's wording |
|
||||
| `public/screens/looks.js` | User Preferences: the look and sound controls, which save as they change |
|
||||
| `public/screens/agents-view.js` | the agents view's mount, state and server calls, serving both User Preferences' Agents & models tab and the setup page as a master-detail split: the pickable list on the left, the picked agent's form or state in the right pane. Picking a row is the navigation; a dirty form asks the dialog's unsaved prompt first. Each form edits a draft; Save sends the saved list with only that draft swapped in (`POST /models` or `POST /agents`), Discard drops it. `hasUnsaved`, `saveOpen` and `discardOpen` feed the dialog's unsaved prompt. `mountAgentsView(container, {mode, forCli, onStart})` hands its renderers one `ctx` (state plus callbacks); `mode: "prefs"` draws the agent rows with Found / Not found on PATH badges and a v3 orchestrator placeholder, `mode: "setup"` draws the pick list (found / outside-PATH / missing states, install lines, Use it from here, templates, Start) inside a caller-supplied container |
|
||||
| `public/screens/agents/agents-data.js` | PURE, no imports, `node --test` importable: the agents view's data helpers. `MODEL_CLIS`/`BUILT_IN` (the built-in rows, pinned to `src/launcher/agents.json` by a test), `emptyLists`, `newAgent`, `normalizeAgent`, `cliOf`/`agentId` draft keys, `savedEntry`, `canonical`/`isDirty`, `nameOf`, `modelNames`, `summaryRows`, `serverStateFor`, `cleanAgent` and `templateDraft` |
|
||||
| `public/screens/agents/agents-list-editor.js` | the one row-list editor behind the three argument lists and the models list: `listEditor({list, kind, field, placeholder, addLabel, optionalName, aria, onChange})` draws `div.agent-rows` (a Remove per row, an Add that appends and focuses the new row, edits written into the live list) |
|
||||
| `public/screens/agents/agents-summary.js` | the agents view's collection side: `renderSummary(ctx)` draws the left column for both modes (prefs rows with found badges, the shipped templates under "Or start from a template" and the orchestrator placeholder; setup pick rows, badges and templates), `drawSummaryPane(ctx)` draws the right pane while nothing is open (empty text, a picked template's note and Use this template, or the picked setup entry's state area: Start, Use it from here, install lines), plus `BADGES`/`drawBadge` |
|
||||
| `public/screens/agents/agents-form.js` | the agents view's per-agent form: `drawForm(ctx)` draws the detail pane (the built-in's Models fold, or an added agent's identity fields plus folded Models and Command-line arguments sections), `renderDirty(ctx)` toggles the Unsaved badge and Save/Discard; the foot (Save, Discard, Save anyway on 409, Delete with inline confirm), `input.invalid[data-field]` marking and the `FORM_FOCUSABLE` focus save/restore |
|
||||
| `public/screens/agents/agents-strengths.js` | the "Strengths in the loop" fold under Models in an agent's form: `strengthsFold(ctx, agentId, draft, { models, hasEffort })` maps Thrifty, Balanced and Best to one of the agent's own models (and an effort for Claude and Codex), shows untouched rows as shipped with a "default" tag and changed rows with Reset, and keeps only changed rows in `ctx.strengthDrafts` for the form's Save |
|
||||
| `public/strengths.js` | the loop's strength rule, shared by the page and the server: `resolveStrengths` and `nextStrength`, held to `scripts/fixtures/strength-cases.json` (the Rust twin is in `models.rs`) |
|
||||
| `strengths.mjs` | the server-side name for `public/strengths.js` (a re-export) |
|
||||
| `strengths` key (`src/launcher/models.json`, `~/.plan2code/models.json`) | per agent, `thrifty`/`balanced`/`best` rows of `{model, effort?}`; a user row beats the shipped one, and a row whose model is not in the agent's Models list is ignored. `models.rs` `strengths_for` and the JS resolver are held to `scripts/fixtures/strength-cases.json` (change the fixture first, then both) |
|
||||
| loop setup `phaseStrength` / `strengths` | `loop-setup.mjs` keeps the per-project toggle and, per spec folder, a list of `{n, name, strength}` picks, pruned as specs finish and phases move (twin: `LoopSetup` in `loop_driver.rs`). `loop_driver.rs` starts a phase with `AgentManager::start_phase_on(prompt, model, effort, env)` and sets `PLAN2CODE_LOOP_STRENGTH` (thrifty, balanced or best) in its environment, which `cmd-open.mjs` reads to give the phase's helpers the same Helper strength line; a retry goes one step up with `models::next_strength` (Rust twin of `nextStrength`; a Match my session phase stays) |
|
||||
| `public/screens/setup.js` | the agent-less setup screen (`workflow === "setup"`, opened by `plan2code` or the app when no agent can run): the "No agent yet" headline, Planny's setup pose, the agent list from `mountAgentsView` in setup mode, Check again, and the "Starting <Label>..." pane after a Start send (`{i:"__start"}` via `/submit`). `setupMoved(url)` disarms the 2-minute no-page notice once the `move` event lands |
|
||||
| `public/screens/prefs-dialog.js` | User Preferences as a dialog: its four tabs (wired by `tabs.js` from `PREFS_TABS`), `openPrefs(tab)` (the one way in, loading Agents & models each time), the fading Saved mark beside a fieldset (`markSaved`), Back to default for the tab on screen, and `confirmUnsaved()`, the in-dialog Save / Discard / Keep editing prompt before Close, Esc, a backdrop click, a tab switch or picking another agent leaves an unsaved agent edit. Other screens reach it through `hooks` |
|
||||
| `public/screens/starting.js` | the launching, starting and waiting screens, with Planny's poses |
|
||||
| `public/screens/workspace.js` | the read-only Workspace of extra folders, and @mentions |
|
||||
| `public/styles/ask.css` | The Ask pane and its Quick question chat |
|
||||
| `public/styles/dashboard.css` | The dashboard: the menu, the spec picker, its confirm and the launching pane |
|
||||
| `public/styles/docs.css` | Documents and the doc tools |
|
||||
| `public/styles/ending.css` | The end of a session: the hand-off and the stopping screen |
|
||||
| `public/styles/git.css` | The git board |
|
||||
| `public/styles/help.css` | The help dialog, its diagrams and its tabs |
|
||||
| `public/styles/looks.css` | The looks button and the highlight swatches |
|
||||
| `public/styles/prefs.css` | User Preferences' side list of tabs, the strip below 720 px, the Saved mark, the setup screen's own chrome, and the in-dialog unsaved prompt (new classes only: the Subagents dialog shares `.looks`) |
|
||||
| `public/styles/agents.css` | the Agents & models view: the master-detail `.split` (list column, pickable `.split-row`s with `aria-current`, the `.split-pane`), badges, the form's fields, folds and foot, the models lists, the setup pane's state area, and the under-720 px single-column treatment |
|
||||
| `public/styles/pieces.css` | Shared pieces: cards, options, settled answers, pager, forms, checklist, markdown and the modal |
|
||||
| `public/styles/planny.css` | Planny the mascot: the flight, his moods and variants, and the wake-up |
|
||||
| `public/styles/poses.css` | The start-screen poses, one per skill. After the dashboard on purpose: its narrow-window rules override the dashboard's |
|
||||
| `public/styles/responsive.css` | Print, then the narrow-window rules: last, so its overrides come after everything they override |
|
||||
| `public/styles/shell.css` | The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival |
|
||||
| `public/styles/tokens.css` | Colors, type, sizes and the light and dark themes: the variables every other file reads |
|
||||
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (20 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; Implementation Loop sits right after Watching a build, The git board right after it, and Activities right after Ask a quick question), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping; a re-export of `tabs.js`'s `tabKeyTarget`). No module-scope DOM, so `node --test` covers it |
|
||||
| `public/tabs.js` | the WAI-ARIA tabs shared by Help and User Preferences: `wireTabs()` (buttons and panel links, roving tabindex, automatic activation, `aria-orientation` switching at 720 px, an optional `beforeSelect` guard) and the pure `tabKeyTarget()` |
|
||||
| `public/prefs.js` | User Preferences' PURE rules: `PREFS_TABS` (Appearance, Agents & models, System, Sounds & activities, with hints and the sections each holds), `prefsOpenTab()` and `prefsResetScope()` (the looks keys Back to default resets per tab, or null) |
|
||||
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `cmd-open.mjs`, `cmd-post-wait.mjs` and `sessions.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
|
||||
| `public/git-board.js` | PURE, one import (`pr-url.js`): the git board's rules from a `state.git` snapshot: branch order and the Remote only fold at `REMOTE_FOLD` 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (`boardAwaiting()`: from a click until the agent's next post, not just until `wait` collects it), the plain sentence each click sends as `reply`, the "Last refreshed" line, which files start ticked in the commit dialog, and the pull-request link; the next step (ten rules, `nextStep()`), the tab that owns it, per-tab badges (`tabBadges()`), the busy mode and per-control gate (`busyMode()`, `controlAllowed()`), the tab to show (`pickTab()`), and the create-panel sources and clean-up groups. `app.js` only renders what it says |
|
||||
| `public/git-board-view.js` | No DOM access of its own: `drawGitBoard(ctx)` draws the tabbed board (header, tab strip with Done with git, the card slot, step strip, Changes / Branches / Sync) from the helpers it is handed (`el`, `md`, `copyButton`), every control through one gate; `screens/git-host.js` hosts it, and `scripts/test-web-console-git-board.mjs` drives it with a recording fake `el` |
|
||||
| `public/pr-url.js` | PURE, no imports: `prUrl()`, the "open a pull request" link for the GitHub, GitLab, Azure DevOps and Bitbucket shapes (`null` for an unknown kind, no web address, or a non-https result). `git-repo.mjs` re-exports it, and the board's base picker rebuilds the link in the browser with the same code |
|
||||
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `cmd-chat.mjs`, `cmd-post-wait.mjs`, `workspace.mjs` and the page |
|
||||
| `public/meter.js` | PURE, imports only `skills.js`: the session meter. `WEIGHTS` (the events that are not a skill's own launch, merged with each skill's `weight` from `skills.js`; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
|
||||
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
|
||||
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, `console.mjs`, `lib.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (`done`, `happy`); a finished screen gets no special case, so one still offering a press points and lights `ready` (the desktop app's taskbar dot follows), a stranded press is `attention`, and only all done or paused is `plain`; `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
|
||||
| `public/continue-button.js` | The one control that wakes a quiet agent. `continueButton(label, cls)` is a button asking the app for `agent-continue` (held off 4 s after a press); `reconnectOffer(cls)` is that button labeled **Reconnect to agent** under the app and, in a browser, a line telling the person to type `continue` in their terminal. Used by the status line (`screens/core.js`: the dashboard's quiet, launch-saved and way-home-saved lines), the Ask tab (`screens/ask.js`, left of Send while the red no-agent line shows) and the saved-and-waiting launch screen (`screens/starting.js`, app only; a browser reads the hint). |
|
||||
| `public/app-bridge.js` | The messages the page posts to the desktop app that frames it. `framed()` is true inside a frame; `tellApp(kind, extra)` posts `{ plan2code: kind }`, a named request with no free text: `looks` (the highlight's dark shades, from `applyLooks()`, for the app bar's buttons), `agent-continue` (the in-app **continue** button on the Not running line: the app types the keystrokes `continueKeys()` in `plan2code-app/ui/meter.js` names into the agent's terminal, `continue` and Enter, then under Claude Code its send-now chord ctrl+x ctrl+s, so a word queued behind a stuck turn is delivered), `terminal-open` (the in-app **terminal** button, shown in place of the word in every What to check line while the app's terminal panel is collapsed: the app presses the panel's own Collapse/View button, and only when collapsed; the app tells the page the panel's state with `terminal-state` `{ collapsed }` on the page's `console-ready` and on every change, heard through `onAppMessage` into `page.terminalCollapsed`), `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all) and `activities-full` (`{ on }`, an Activities game going in or out of full screen: the app lays the console's frame over its bar and terminal and puts the window in full screen, and out of it only if it put it there; `taskbarSwitch()` checks the boolean, and the window permissions are in `capabilities/default.json`). Nothing outside a frame |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table, one entry per non-null `subagents` field in `skills.js`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max, strength }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20, `strength` not one of `STRENGTHS`; `strength` is `balanced`, `thrifty`, `best` or `session`, missing reads as `balanced`, saved per project and skill in each `subagents.json` entry and sent as a `Helper strength:` line in the "on" block), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
|
||||
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created, sent? } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
|
||||
| `public/notepad.js` | PURE, no imports: the Notebook's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `TAB_NAME_MAX` / `NOTEPAD_MAX_TABS` / `IMAGE_ID_RE` / `TAB_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `tabSwitch()` (whether leaving a tab must save it first), `NOT_LOADED`, `EDITOR_NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), the tab rules `cleanTabName()`, `nameTaken()`, `tabNameProblem()`, `moveTab()`, `dropTab()` and the two-confirm delete `nextDelete()` / `DELETE_STAGES`, and `step()` (wrapping through the pictures) |
|
||||
| `public/screens/notepad.js` | the Notebook: `#btn-notepad` in the top bar on every screen (disabled while the server is gone, `renderNotepadButton()` in the render pass), `#notepad-modal`, the one CodeMirror editor (made on first open by a dynamic import of `notepad-editor.js`), the page's view of the notepad as `{ tabs, activeId }`, the name form (New tab and Rename, never `window.prompt`), the in-modal two-step delete, and autosave through `nextSave()` to `POST /notepad/text?tab=<id>`, flushed on close, when the page is hidden and before a switch. The editor stays read-only until the first read lands, so nothing typed into an empty editor is saved over a note. **Every save and every picture is bound to the tab it was made in**: `saveTab` is fixed when the change is made, a picture entry carries its `tab`, and a switch waits for the save (`settled()`), stays put with "Not saved yet, so staying on this tab." when it cannot, and drops a deleted tab's unsaved text without sending it |
|
||||
| `public/screens/activities.js` | Activities: `#btn-activities` (the die right of the megaphone), `#activities-modal`, the one frame timer (`requestAnimationFrame`, swappable with `setTickSource()` for the page tests), the keys (arrows, W/A/S/D, space, P, Esc; stopped at the dialog so none reach the page behind; `CHEAT_CODE`, typed on a game's board, turns on endless lives through the game's `cheat(on)` until the round starts over, and `dropCheats()` turns it off on leaving for the picker or closing; `STAGE_CODE`, the same arrows then S, calls the game's `stageSelect()` where it has one, Ghoul Rush's practice stage select) and `pauseAll()`, which a new question, a finish, a hidden page, a window blur and a close all go through and which never resumes a game (it also sends a pointer game a cancel, dropping a drag). Canvas pointer events (down, move, up, cancel, with pointer capture) go to a game with `pointer()`, and key releases to a game with `release()`; a press on a paused board resumes without starting a drag. While paused, any game key or a board click resumes, except while a round is `held`: a question or finish that pauses a round on an open window holds it, the banner adds `#activities-unpause` (**Unpause game**) beside **Go to it**, and only that button plays on (`play()` refuses a held round), since a key or click already on its way used to dismiss the banner unread. Go to it, or closing the window any other way, lets the hold go, and a banner with nothing left to say drops it. Every start and play-on first counts down 3, 2, 1 (`COUNT_FROM`, 700 ms a number, `setCountdownMs()` for the page tests, which set 0 unless they test it): the game is already `running`, the frame timer just does not tick it, and game keys, overlay clicks and board presses wait, while P and Esc still pause. With two or more games listed the window opens on the picker (`view`: `"picker"` or `"game"`, `applyView()`): a card button per game (`drawPicker()`, covers in `COVERS` drawn as SVG with `cv-*` token classes, since the page's policy refuses a style attribute) with its blurb, best and a **Last played** or **Round paused** tag, arrows walking the cards (`moveFocus()`), and `#activities-back` (**All games**) back to it. One game at a time: `pick()` drops the last game from `games` when another is picked, and `openActivities()` goes straight back into a paused round. The last pick is kept as `lastActivity` and gets the focus; `lowerIsBetter` games keep the lowest round as the best; the header shows the current game's best (`paintTitle()`). `renderActivities()` in the render pass compares `myTurn()` and `finish()` with the last render and shows the banner with **Go to it**. Loads a game with `import()` when it is picked and keeps it until another is picked; `setActivityList()` lets a test list a stub second game, which brings up the picker |
|
||||
| `public/notepad-tabs.js` | the tab bar: `createTabs({ onSwitch, onChange })` with `draw(tabs, activeId)` (`role="tab"` buttons, roving `tabindex`, arrow keys, Alt+arrows to reorder, F2 and double-click to rename, native drag and drop with an `.is-drop-before` mark that only a tab drag lights, focus kept across redraws, `#notepad-empty` and `#notepad-body` toggled) and `focusTab()`. No fetches: it calls back, and `screens/notepad.js` owns every request |
|
||||
| `public/notepad-editor.js` | the Notebook's live-preview editor on CodeMirror 6 (`makeCodeMirrorEditor(parent, { onChange, label })` returning `{ getValue, setValue, setReadOnly, focus, destroy }`). A `ViewPlugin` decorates only the lines in view from the Markdown syntax tree: heading line classes `cm-h1` to `cm-h6`, bullets drawn as a widget, the marks around bold, links, quotes and a heading hidden on every line the selection is not on. The editor sits in a shadow root (`.notepad-cm-host`), because CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, and adopts them as a constructed stylesheet inside a shadow root. `setValue()` is `setState()`: not reported through `onChange`, and the undo history is cleared (so each tab starts with a clean one) |
|
||||
| `public/notepad-editor.css` | the one stylesheet of that shadow root, linked from `notepad-editor.js` (a `<link>` inside the root, in `SERVABLE`, not in `CSS_ORDER`): heading sizes, bullets, quote, code and link looks on the console's tokens (custom properties inherit across the boundary, so both themes work). Rules that meet CodeMirror's own base theme use `div.cm-editor` for the specificity |
|
||||
| `public/vendor/codemirror.esm.js` | CodeMirror 6 (state, view, language, commands, lang-markdown, MIT), bundled into one minified ES module by `scripts/vendor-codemirror.mjs` (sha256 `4ff96d58fc1a5497eb933426bd2d160d2fb0cf490de8bb9302c304096c71c1d4`, the six top-level versions in the script and the file's header comment, everything they pull in pinned by `scripts/vendor-codemirror-lock.json` and installed with `npm ci`, so the same lock gives the same bytes). Never edited by hand: change a version in the script and run `node scripts/vendor-codemirror.mjs --update-lock` (needs npm and network; the packages install in a temp folder, never in the repo), or without the flag to rebuild from the lock |
|
||||
| `public/styles/notepad.css` | the notebook's own rules: the top bar button, the dialog, the tab bar and its tools, the name form, the delete question, the empty state and the pictures. The editor's look is `notepad-editor.css`, inside its shadow root |
|
||||
| `public/styles/activities.css` | the Activities rules: the die in the top bar, the Notebook-sized dialog, the board and its state overlay, the your-turn banner in the highlight color, the picker and the notes |
|
||||
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
|
||||
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network |
|
||||
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) |
|
||||
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
|
||||
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by `app.js` and the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
||||
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Split out of `app.js` because `app.js` cannot be imported outside a browser, so anything left in it is untestable. `scripts/test-web-console.mjs` imports this directly. |
|
||||
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by the page's looks and screens and by the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
||||
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Kept out of the page's entry because `app.js` cannot be imported outside a browser, so anything left in it is untestable. The `scripts/test-web-console-*.mjs` tests import it directly. |
|
||||
| `public/labels.js` | `taskLabel()` / `activityLabel()`: rewrites a build's `Task 4.2 of 6` activity line to `Task 2 of 6` (only for `implement` / `implement-review`; a plan's `Task 2.1` is a real section number). A separate module for the same reason as `answers.js`: pure, so `node --test` can import it |
|
||||
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `app.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of `app.js`'s render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
|
||||
| `console.md` | the agent-facing contract, which is what every console prompt points at. Its **Workflow notes** section holds the per-workflow detail (Dashboard, Init and Init Update, Document, Review, Handoff, Pathfinder, Planning, Revision, Finalize), which keeps the prompts themselves to a one-line pointer |
|
||||
| `building.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`), the sign-off (with the review offer as a verdict), the finish, and running the review on the page mid-session |
|
||||
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `screens/dashboard.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of the screens' render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
|
||||
| `console.md` | the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (`post --wait`, the exit codes, handling a send, `settle`), posting, the payload and its kinds, documents (including `file` blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters |
|
||||
| `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, and recovery |
|
||||
| `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `loop` for a build the desktop app's Implementation Loop runs with `--loop` (where it reports a `loopOutcome` instead of asking for sign-off), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`, `pr-prep`, `test`). Each skill's Interface line reads `<D>/console.md` and its own notes file right after `open`; a test checks every skill names one that exists |
|
||||
| `building.md` · `building-review.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`, `file` blocks re-read with `refresh`), the chat check between tasks, questions mid-build and stop requests; `building-review.md` is the review run on the page (the sign-off's `review` verdict, **Review it now**, Implement + Review's Stage 2, Finalize's Step 2.5), read only when asked for |
|
||||
|
||||
Key design points:
|
||||
|
||||
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `app.js`.
|
||||
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences: Role, Theme, Card width, Highlight color, Sounds and Models. `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `DEFAULT_ACCENT` in `palette.js` is `ocean`.
|
||||
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (`server.mjs` `/version` route). `renderHelpVersion()` in `app.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
|
||||
- **Models in User Preferences.** `GET` / `POST /models` in `server.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `lib.mjs`). `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
|
||||
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (cancelled). The agent loops. Nothing blocks for the whole time a person takes.
|
||||
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `console.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch }` when it found anything to clean.
|
||||
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `screens/help-dialog.js`.
|
||||
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences (see User Preferences below). `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `DEFAULT_ACCENT` in `palette.js` is `ocean`.
|
||||
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (the `/version` route in `routes.mjs`). `renderHelpVersion()` in `screens/help-dialog.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
|
||||
- **User Preferences is four tabs in a side list.** Appearance (Theme, Card width, Highlight color, Role), Agents & models, System (Cleanup, and Desktop app inside the app only) and Sounds & activities (Sounds, Activities), a sideways strip below 720 px. The tabs are the static `<section class="prefs-panel">` panels in `#looks-modal`, each fieldset in exactly one (its `data-section`, listed in `PREFS_TABS`), wired by the shared `public/tabs.js` (`wireTabs()`, the same helper Help uses: `helpKeyTarget()` re-exports its `tabKeyTarget()`). `public/prefs.js` is the pure part: `PREFS_TABS`, `prefsOpenTab()` (the gear and the dashboard's Set up preferences both open Appearance; nothing is remembered between opens) and `prefsResetScope()` (Back to default resets only the shown tab's looks keys, and is hidden on Agents & models and System). `screens/prefs-dialog.js` owns `openPrefs(tab)`, the one way in, the Saved mark and the unsaved prompt; `screens/looks.js` keeps the look and sound controls, which save to `looks.json` as they change; `screens/agents-view.js` mounts the Agents & models tab, a master-detail split over today's `models.json` and `agents.json` (formats unchanged) whose per-agent form has its own Save and Discard: Save sends the last saved list with only that form's draft swapped in, so another form's half-typed edit is never written. The split's components live under `screens/agents/` (data, list editor, summary, form); the mount owns all state and every fetch and hands them one `ctx`.
|
||||
- **Models in User Preferences.** `GET` / `POST /models` in `routes.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `files.mjs`), edited from each built-in agent's form on the Agents & models tab. `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
|
||||
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (canceled). The agent loops. Nothing blocks for the whole time a person takes.
|
||||
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `patches.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`, `__pickup`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`), a pick-up also with `handoffFile`. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
|
||||
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean.
|
||||
- **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `<gitdir>/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it.
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `server.mjs`, which paints `data-width` on first load; `app.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or with `?file=map` / `?file=draft` the spec's `pathfinder/map.md` / live `PLAN-DRAFT-*.md` (the dashboard's Map and Plan draft tabs, shown only while the spec has no overview; `readSpecFile()` picks the file and names it in `x-spec-file`), or an empty `204` when there is no such file (normal for most specs, and no failed request in the browser console). A dashboard session honors `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readSpecFile()` (which `readOverview()` wraps) resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all get the same 204, as do an unscanned `?spec=` and an unknown `?file=`.
|
||||
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
|
||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `models.json`). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **User Preferences → System → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`, `app`, `app.json`, `agents.json`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
|
||||
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). When it is `false` the Git commit card stays clickable and shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `lib.mjs`: one `git status --porcelain -z` (3 second timeout, `null` when git cannot say) counting modified, staged, deleted and untracked paths. At `0` the card greys out with `GIT_CLEAN_REASON`; above it the detail line is `pendingNote(n)` ("3 files to commit"); `null` leaves it clickable. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git-commit` in the same session. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
|
||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `app.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `app.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never grayed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the twelve opted-in skills (`defaultSetting()`); a saved Off stays off.
|
||||
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
|
||||
- **No git process.** `repoRoots()` in `lib.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
|
||||
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `lib.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
|
||||
- **The first paint needs no fetch.** `server.mjs` renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to `app.css`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
|
||||
- **No git process.** `repoRoots()` in `sessions.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
|
||||
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `sessions.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
|
||||
- **The first paint needs no fetch.** `routes.mjs` (`renderIndex()`) renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to the joined stylesheet by `static.mjs`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
|
||||
- **Reads are stat-gated.** `fileStamp()` (mtime:size:ino) decides whether `state.json`, `result.json` and `looks.json` changed before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (`readState()` returns it; `/submit` clones before editing). `wait` stats `result.json` every 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
|
||||
- **The Workspace and the session meter live beside `state.json`, one writer each, and outlive every hop.** Three session files, none of which `switchWorkflow()` ever touches, so both survive dashboard → skill → dashboard (a new console session starts with a count of 0, and with the folders remembered for its folder and spec, below):
|
||||
|
||||
| File | Writer | Holds |
|
||||
|---|---|---|
|
||||
| `workspace.json` | `server.mjs` | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()`, now in `lib.mjs`, computed by the server at boot) |
|
||||
| `workspace.json` | the server (`workspace.mjs`) | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()` in `sessions.mjs`, computed by the server at boot) |
|
||||
| `ledger.ndjson` | `console.mjs` | append-only, one JSON line per entry. Meter events: `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch, with `tasks` when a built phase reports one) and `answer` (one per item the person answered in a collected send, written by `ledgerAnswers()`, id `<launch>:answer:<send stamp>:<item>`). Also `folder-issue` reports |
|
||||
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
|
||||
|
||||
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `lib.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console.md` (Workspace; Posting an update → Session meter) and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
||||
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `workspace.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console-workspace.md` and `console-meter.md`, and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
||||
- **The Subagents switch is a standing instruction, injected only on change.** The page's icon button (`#btn-subagents`, after Write a brief) and `#subagents-modal` show only when the frame's `subagents` block says `offered && supported`. `offered` comes from `public/subagents.js`; `supported` means the latest `{ "type": "open" }` line in `events.ndjson` carries `caps: ["subagents"]` (`latestOpenCaps()`), so an older skill copy's `open` hides the button. Four places hold it, one writer each:
|
||||
|
||||
| File | Writer | Holds |
|
||||
|---|---|---|
|
||||
| `~/.plan2code/console/subagents.json` | `server.mjs` | per project folder → workflow: `{ on, instruction, max }`, `instruction: null` being the shipped default; on `PROTECTED_CONSOLE_FILES` |
|
||||
| `<session>/subagents-setting.json` | `server.mjs` | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`syncSubagentSetting()`), `revision` bumped only by a real change |
|
||||
| `<session>/subagents-setting.json` | the server (`settings.mjs`) | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`serverSubagents().sync` in `settings.mjs`), `revision` bumped only by a real change |
|
||||
| `<session>/subagents-cursor.json` | `console.mjs` | `{ revision, state }`, the last block handed over; `open` resets it, and it moves only after the print |
|
||||
| `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.md` → Standing instructions.
|
||||
- **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.
|
||||
- **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 `server.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 `lib.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.
|
||||
`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 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, suggest? }` (paths and names only; `suggest` only when the action's is exactly `true`, the **Ask for suggestions** chip, which always writes a thread entry, note or not, and is left out of the `submitted` event's `ids` so the card's staged pick stays), 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.
|
||||
- **A finished quick task's review button is a request through the wait loop**, like the brief: `{ "i": "__review" }` or `{ "i": "__done" }`. The agent keeps waiting after posting a finish that carries `review`, and takes the review up by posting `"finish": null`, which puts the session back to work. Implementation's review needs no such machinery: it is a verdict on the sign-off card, asked before approval, so the session never left work to take it up.
|
||||
- **Back to the dashboard is the same kind of post-finish request.** A finish with `finish.dashboard: true` shows the button; a press arrives as `{ "i": "__dashboard", "type": "dashboard" }`, and the agent runs `open --resume <sid> --no-open --workflow dashboard` then posts `"finish": null` with a fresh `menu`. The agent waits ~10 minutes after the finish for it (alongside `__review` / `__done` on a quick task); after that the page swaps the button for the `/plan2code` command. `finish.command` is optional — without one the page shows the "All done" line — and `validate()` rejects a `<placeholder>` command and a non-boolean `dashboard`. The session-level actions are therefore `__brief`, `__stop`, `__launch`, `__review`, `__done` and `__dashboard`; a new post-finish button should copy this precedent.
|
||||
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console.md → Stop requests → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
|
||||
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `lib.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
||||
- **`validate()` in `lib.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
||||
- **Continue here, Update CHANGELOG first and Ask prompt blocks.** Three small additions on the same pattern. **Continue here** is page-only: `continueOffer(fin)` (`public/answers.js`) reads `finish.command`, and when it starts with a Plan2Code skill (and the finish is not a pause) `screens/ending.js` draws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own `{ "i": "__launch", ... }` through `sendAfterBuild("launch", offer)`, so the agent writes nothing new (`startsClean()` cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts `"finish": null`). **Update CHANGELOG first** is `finish.changelog: true`, accepted by `validate()` only on `quick-task` and `finalize` (a paused finish is exempt from that check and the page ignores the flag), and it belongs with `commit: true`; the press is `__changelog`, a `HOP_ACTIONS` entry in `cmd-post-wait.mjs` that resumes as `changelog`, whose "Commit this now?" yes carries on to Git. **Ask prompt blocks** are contract only (`console-chat.md` → Prompts to carry away): the page already draws a Copy button on every fenced block.
|
||||
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
|
||||
- **Handoffs live outside every repo, in `~/.plan2code/handoffs/`, and the console owns them** (`handoffs.mjs`; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through `console.mjs`). `handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]` claims one for this checkout and prints `{ ok, id, path, meta }` (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers **Stop with a handoff** (`#stop-handoff`, suggested) above **Just stop and save** (`#stop-go`); the first sends `__stop` with `handoff: true` and `STOP_HANDOFF_REPLY`, and `wait` adds `handoffSkill` (the built Handoff skill's `SKILL.md`, `handoffFor()`); console-stop.md gives the order (answers, save, `handoff new --from-stop`, write, paused finish naming the file, `stop`). On a dashboard, `cmdOpen()` adds `scan.handoffs` (`listHandoffs(worktree)`) and `scan.handoffsDir` after `scanProject()`, which stays handoff-free because `specs.mjs list` shares it. The picker draws them as dashed `.spec-chip.is-handoff` chips after the specs (`specSel = "handoff:<id>"`); a picked one replaces the skill cards with `renderHandoffPreview()`: **Pick it up here**, **Read it all** (`GET /handoff?id=`, served only for an id in the dashboard's own `state.scan.handoffs`), **Copy for a new conversation** (`handoffCopyText()`) and **Delete** (`openHandoffDelete()`, one step). Pick it up sends `{ "i": "__pickup", "type": "pickup", "handoff": <id> }`; `HOP_ACTIONS.pickup` (`pickupHop()`) reads the stored `.json` only, never the page, and falls back to Quick Task with `fallback: true` when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); `markPickedUp()` stamps `usedAt` as the hop is printed, so the next scan drops the chip. Delete sends `__delete` with `handoff` in place of `spec`, and the agent runs `delete-handoff --handoff <id>` (`removeHandoff()`, exit 3 on a refusal, nothing touched). `open` sweeps handoffs untouched for 30 days (`staleHandoffs()`, the `.json`'s mtime, else the `.md`'s), picked up or not, and reports them in `swept.handoffs`; Cleanup never lists the folder (`KEPT_PLAN2CODE_ENTRIES`).
|
||||
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and the agent's only when the person sends a tab.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created, sent? } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** twelve, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) `/notepad/tab/last` (`{ id }`) and `/notepad/tab/sent` (`{ id, workflow, spec? }`, `markTabSent()`: sets `sent: { workflow, spec?, at }` on the tab, replacing an earlier one; `workflow` one of `pathfinder`, `plan`, `quick-task`, `revise-plan`, `spec` matching `^specs/[A-Za-z0-9._-]+$`, else 400 `bad-sent`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The eleven POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` and the `cmd-*.mjs` files never import `notepads.mjs` (a source test pins it; `sessions.mjs` loads it lazily for Cleanup only, listing and removing whole notepads), so nothing in a notepad reaches `state.json` or anything `wait` prints except a tab the person sends (see **Send to a skill**). **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notLine truncated
|
||||
- **A Bug fixed spec deletes in one step.** Its chip shows a visible **Delete** (`.spec-chip-del-label`) instead of the hover ✕, `openDeleteConfirm()` gives it a fixed-bug warning and a **Delete it** button, and `deleteStep()` sends `__delete` on the first press, with no name to type. `chipDetail()` drops the scan's repeated "bug fixed" detail under the label.
|
||||
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `inbox.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard keeps the conversation: `switchWorkflow()` carries `chat.replies` across and the page keeps its Ask state, so only New conversation appends a `reset` after the opening one. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
||||
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
||||
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 17 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `app.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||
- **Stuck sessions are explained twice, in Help and on the status line.** `stuck` ("When something looks stuck") is the second tab in `HELP_TABS`; its panel opens with a `help-callout` ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (`openHelpOn("stuck")`) inside the existing `role="status"` element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from `renderCloseGuide()` in `renderHandoff()` (Safe to close, Start fresh, Carry on). Tests in `scripts/test-web-console.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 21 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||
- **Stuck sessions are explained twice, in Help and on the status line.** `stuck` ("When something looks stuck") is the second tab in `HELP_TABS`; its panel opens with a `help-callout` ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (`openHelpOn("stuck")`) inside the existing `role="status"` element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from `renderCloseGuide()` in `renderHandoff()` (Safe to close, Start fresh, Carry on). Tests in `scripts/test-web-console-source.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
|
||||
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
|
||||
|
||||
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then `node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-getting-started.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs scripts/test-script-git-commit.mjs scripts/test-script-changelog.mjs`. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
||||
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
||||
|
||||
**Adding a file under `public/` needs three edits, not one:** the file itself, the `SERVABLE` allow-list in `server.mjs`, and (for a module the page imports) a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a new module missing from it 404s and the page dies at import with no useful error (a test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint.
|
||||
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files table above, which the docs-table test (same file) checks.
|
||||
|
||||
**Building an Activities game:** the rules every game follows, so a new one plays like the rest.
|
||||
|
||||
- **Lives are prominent.** A game with lives draws them as the lives pill: `livesText(round.lives)` in the `LIVES` color from `pills.js`, placed right after the level/stage pill, which `drawPill()` draws solid pink with a heart per life. Never a plain `♥ N` on the dark backing: that was hard to read at a glance. The unit suite checks every game with lives for it.
|
||||
- **Every game with lives takes the endless-lives code.** Typing up, down, up, down, left, right, left, right, B, A, space on the board gives endless lives until the round starts over or the person leaves the game (`CHEAT_CODE` in `screens/activities.js`, which calls the game's `cheat(true)` and `cheat(false)` on leaving for the picker or closing). A game with lives answers `cheat(on)` by setting `round.infinite`, never takes a life while it is set (`if (!round.infinite) round.lives -= 1`), lets `start()` make a new round without it, and shows `livesText(Infinity)` ("♥ x∞") in its lives pill. `scripts/test-web-console-activities.mjs` checks every listed game whose round has `lives`.
|
||||
- **Banners never get in the way.** A banner over the board (`"Hit!"`, a new level, a power-up) is placed on the frame it first shows, on the part of the board away from the player, and fades to `BANNER_SEE_THROUGH` (0.12) over `BANNER_FADE_MS` while the player, or anything the player must react to (a diving bug, a bomb, a rival, a hazard, the road over a hill), is in its strip; Snake's `bannerRow()` and `underBanner()` are the model. Give the banner object a `see` field, multiply the draw's alpha by it, and export the strip check (`underBanner`) for the unit suite.
|
||||
- **The window owns pausing.** A game never resumes itself; `screens/activities.js` decides when a key or click plays on, including the hold on a question or finish (see the row above), so a game needs nothing of its own for it. Full screen is the window's too (`setFull()`: the button, `F`, and a turn or finish putting it back; `fitFull()` sizes the game to the whole screen (black bars where its shape leaves room) and docks the overlaid panel in a bar that holds it, `data-dock="side"` or `"below"`, or floats it, `"float"`, shrunk to the score while a round plays and the pointer is still; and tells the desktop app `activities-full`); a game only sees a bigger `resize()`, so a new game needs nothing for it, as long as its `resize()` sets the canvas's CSS size.
|
||||
- **Every moment has a sound, and moving things hum.** A game plays a one-shot through the `tone` it is handed for each event worth hearing (a hit, a pickup, a level, a new best, game over) and keeps continuous things (an engine, a motor, wind, water, a fuse, a monster close by) going with `hum(id, name, level, pitch)` from its `tick`, pitch following speed. Never a one-shot every frame: a repeating cue is throttled by a timer in the round. Its own sounds live in `activities/<id>-sfx.js`, named with the game id; the shared kit is in `tones.js`. `create()` defaults `tone` and `hum` to no-ops, since the suites make games with neither, and a sound never changes the game's state.
|
||||
- **Its logic tests pin the dice.** A game rolls `Math.random` for roads, spawns and layouts, and an unlucky roll once failed a test on CI at random (Ghoul Rush's Eye, Bounce Road twice). Import `./seed-random.mjs` FIRST in every `scripts/test-web-console-activities*.mjs` file: it seeds `Math.random` (set `PLAN2CODE_TEST_SEED` to try another roll), so a test sees the same world on every run.
|
||||
|
||||
## Status Line
|
||||
|
||||
@@ -278,23 +633,26 @@ src/statusline-claude/
|
||||
|
||||
## Global `plan2code` Command
|
||||
|
||||
Typing `plan2code` in any directory opens the dashboard skill against the current project, **in that directory**, in one of three CLIs (the `CLIS` table in the launcher):
|
||||
Typing `plan2code` in any directory opens the dashboard skill against the current project, **in that directory**, in one of the built-in CLIs (the shipped `src/launcher/agents.json`, plus any custom entries in `~/.plan2code/agents.json`):
|
||||
|
||||
| CLI | Runs |
|
||||
| --- | --- |
|
||||
| Claude Code | `claude /plan2code --permission-mode bypassPermissions [args]` |
|
||||
| Devin | `devin --permission-mode bypass [args] -- /plan2code` |
|
||||
| Codex | `codex --dangerously-bypass-approvals-and-sandbox [args] $plan2code` (Codex starts a skill with `$name`; the launch line follows Codex's documentation) |
|
||||
| Claude Code | `claude /plan2code [--permission-mode bypassPermissions] [args]` |
|
||||
| Devin | `devin [--permission-mode bypass] [args] -- /plan2code` |
|
||||
| Codex | `codex [--dangerously-bypass-approvals-and-sandbox] [args] $plan2code` (Codex starts a skill with `$name`; the launch line follows Codex's documentation) |
|
||||
|
||||
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 the same steps after its error. `--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=`, it asks `Which model should <CLI> use?` from the curated `src/launcher/models.json` (copied to `~/.plan2code/bin/models.json`, overwritten by every install) merged with the user's additions in `~/.plan2code/models.json` (edited in the console's User Preferences → Models). Enter keeps the model the CLI last used; a pick appends `--model <id>`. 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. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin` commands and a temp home.
|
||||
The bracketed flags (each entry's `bypassArgs`; a custom agent's own `bypassArgs`) go in only when permission prompts are off. Right after the agent is chosen, and only when it has such a flag, `chooseBypass()` asks `Turn <CLI>'s permission prompts off?` with Yes as the default; `--keep-permissions` (never forwarded) answers no, and with no TTY on stdin the prompts are off, as before. When the desktop app will take over, the question is skipped (its launch card has its own tick) and asked only if the app fails to start. The installer prints no warning about it.
|
||||
|
||||
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 runs the setup flow when a person can see a page (`hasDisplay()` and a TTY or the shortcut; the desktop app first when it is installed, else the console's agent-less `setup` page in the browser) and otherwise prints the install steps (`printNoAgentGuidance()`: each built-in's install command and page, how to add another agent in `~/.plan2code/agents.json`, and to run `plan2code` again) and exits 127. An uninstalled `--cli` pick goes to the same setup flow on that agent when a page can open, else prints that CLI's own steps after its error. `--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. (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), `agents.json` and `agent-lookup.mjs` (the shared agent list and lookup rule; `plan2code update` restores a missing copy) and a `version.json` (the installed version). (The metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||
- **The setup flow and hand-over.** With no runnable agent, `runSetupFlow()` finds `console.mjs` (the order the app's `find_console_dir` uses) and runs `open --workflow setup [--for-cli <id>]` as a child process, then `wait` in 240-second slices (the agent-less console keeps its app variables out, NFR-2). An `__start` action ends the wait with the pick; the launcher spawns that agent with `PLAN2CODE_SETUP_ANNOUNCE` (the setup server's base URL) and `PLAN2CODE_SETUP_TOKEN`, and the new agent's `open` POSTs its sign-in URL to `POST /handover` on the setup server, which broadcasts a `move` event the waiting tab follows. The post failing or the wait ending unmoved falls back to opening a browser / the printed steps.
|
||||
- **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`.
|
||||
- **Resolving the CLI** — `findAgent()` in the shared `agent-lookup.mjs` does the lookup: `PATH` (+ `PATHEXT` on Windows), the saved Windows PATH from the registry (`addSavedWindowsPath()`), npm's global bin and each entry's `installDirs`, giving `found` / `outside` / `missing` (the desktop app's `find_on_path` in `agents.rs` is its twin, held to `scripts/fixtures/agent-lookup-cases.json`). 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`.
|
||||
- **No bin-name overlap** — the installer's own bin in `package.json` is `plan2code-install` (→ `install.js`), so `plan2code` belongs to the launcher alone. npx runs a package's only bin whatever it's named, so the README's `npx … plan2code.git` command is unaffected; keep it the only bin, or npx will need `-c plan2code-install`.
|
||||
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person cancelled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
|
||||
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person canceled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
|
||||
|
||||
**Desktop shortcut** — after the shims are written, `installLauncher()` (now async) calls `offerDesktopShortcut()`. It asks `Also add a Plan2Code shortcut to your desktop? (y/N)`, skips the question when stdin isn't a TTY, and refreshes an existing marked shortcut without asking. `installDesktopShortcut()` writes it to the real desktop (`[Environment]::GetFolderPath('Desktop')` on Windows, which covers OneDrive redirection; `xdg-user-dir DESKTOP` on Linux; `~/Desktop` otherwise):
|
||||
|
||||
@@ -306,4 +664,4 @@ On a terminal it first prints a Planny banner (`renderBanner()`). With more than
|
||||
|
||||
The macOS and Linux shortcuts carry the `plan2code-launcher` marker as a comment line. A `.lnk` has nowhere to hide one (its Description is the hover tooltip), so it's recognized by what it runs: the UTF-16 strings `plan2code.ps1` and `--pick-folder` stored in the file (`plan2code.cmd` also matches, so shortcuts from before the PowerShell switch get refreshed). `uninstallLauncher()` removes only a recognized shortcut, plus the icons (`plan2code.ico`, `plan2code.png`), `bin/models.json` and `launcher.json` (never the user's `~/.plan2code/models.json`). A shortcut failure prints a warning and never fails the command install.
|
||||
|
||||
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
|
||||
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. Every global install writes `~/.plan2code/install.json`, the install record listing the pieces installed (skills, launcher, statusline, loop, metrics, bot); `install.js --update` (what `plan2code update` runs) reinstalls those (metrics and bot only when run from a git checkout), with no menu and never uninstalling, or with no record the skills and the `plan2code` command. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
|
||||
@@ -4,35 +4,35 @@
|
||||
## 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. Rename one only together with every reader. `aria-labelledby` is HTML and stays; vendored files (`public/vendor/`) stay as shipped.
|
||||
|
||||
## Gotchas / Pitfalls
|
||||
|
||||
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` and `docs/index.html` (footer `Version X.Y.Z`) also carry the version. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number.
|
||||
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` (the `Version X.Y.Z` line near the top) also carries the version, and `version.json`'s `releaseDate` moves with it. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number. The desktop app carries it too (`plan2code-app/src-tauri/tauri.conf.json`, `plan2code-app/package.json`, `plan2code-app/src-tauri/Cargo.toml`, and `Cargo.lock`'s `plan2code-app` entry follows the build): `node scripts/check-versions.mjs [--tag vX.Y.Z]` compares all six, and the release workflow runs it before building. It reports a mismatch today because the app is at 3.0.0 while the rest is still 2.x; it is deliberately not part of `npm test`, so bump the app's files with the release that ships v3.0.0.
|
||||
- **CHANGELOG ordering:** Entries in `CHANGELOG.md` must be in reverse-chronological order — newest version at the top, oldest at the bottom. New entries are always inserted immediately after the file header.
|
||||
- **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.
|
||||
- **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 `npm test`, so run it before committing. Sub-package tests are separate; see [Development Commands](./AGENTS-development-commands.md).
|
||||
- **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 the LF fix, then the char-count check:** `.husky/pre-commit` is `node scripts/fix-line-endings.mjs` followed by `node scripts/validate-char-count.js`. `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).
|
||||
- **`skills/` is generated build output (gitignored):** edit `src/` only. The installer rebuilds `skills/` on every run, so it is always up to date at install time. `npm test` runs `install.js --build-skills` so a broken `SOURCE_PROMPTS` entry or unreadable source fails CI. Never hand-edit `skills/`; `install.js --verify-skills` can diff a stale tree against `src/` when diagnosing.
|
||||
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 20,000 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
|
||||
- **User Feedback table format:** The `## User Feedback` markdown table in `overview.md` has a strict format the collector regex depends on. Field names must be exactly `Rating`, `Reason`, `Went Well`, `Went Poorly`. Pipe characters in values must be escaped as `\|`.
|
||||
- **User Feedback table format:** The `## User Feedback` markdown table in `overview.md` has a strict format the collector regex depends on. Field names are matched case-insensitively; the house form is `Rating`, `Reason`, `Went Well`, `Went Poorly`, and `Rating` must parse to an integer from 1 to 10. Pipe characters in values must be escaped as `\|`.
|
||||
- **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class.
|
||||
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console.mjs` guards it. Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `lib.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
|
||||
- **Web console oversized bodies:** `readBody()` in `server.mjs` calls `req.destroy()` past `MAX_BODY`, so an oversized JSON body gets no response at all: the client sees a connection reset, never a status code. A route that must answer 413 has to stop buffering and drain the rest of the body instead, as `readRaw()` (the `POST /upload` reader) does; memory still stays capped.
|
||||
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `lib.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
|
||||
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalises its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
|
||||
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `patches.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
|
||||
- **Web console oversized bodies:** `readBody()` and `readRaw()` (the `POST /upload` reader) in `routes.mjs` drain the rest of the body past `MAX_BODY` instead of calling `req.destroy()`, so an oversized body gets a 413 rather than a connection reset, and memory still stays capped. A new body reader must drain the same way.
|
||||
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `sessions.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console` (`-<uid>` on Linux and macOS, a 0700 folder with 0600 handles), or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
|
||||
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalizes its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
|
||||
- **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`.
|
||||
- **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/app.css`. No test ties them together.
|
||||
- **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.
|
||||
@@ -5,7 +5,8 @@
|
||||
|
||||
```bash
|
||||
# Install dev dependencies (sets up husky pre-commit hooks only; each sub-package
|
||||
# below needs its own npm install, Node 18+)
|
||||
# below needs its own npm install. Running `npm test` needs Node 20+; users of
|
||||
# the installed skills still need only Node 18+)
|
||||
npm install
|
||||
|
||||
# Run the interactive installer
|
||||
@@ -14,48 +15,84 @@ node install.js
|
||||
# Regenerate skills/ from src/ (non-interactive)
|
||||
npm run build:skills
|
||||
|
||||
# Try the Activities games from src/: opens the console in the browser, served
|
||||
# fresh from disk, so a saved game file shows on the next page reload
|
||||
npm run play
|
||||
|
||||
# Full check (about 70s): char limits, skills/ build, browser-module parse check,
|
||||
# dashboard skill-table check, web console + launcher + getting-started node:test suites
|
||||
npm test
|
||||
|
||||
# One web console or launcher test
|
||||
node --test --test-name-pattern "<regex>" scripts/test-web-console.mjs
|
||||
# Put every text file git sees back to LF (also runs by itself as pretest and in
|
||||
# the pre-commit hook); --check only lists
|
||||
npm run fix:eol
|
||||
|
||||
# Web console start-up benchmark (puppeteer-core optional)
|
||||
# One web console or launcher test
|
||||
node --test --test-name-pattern "<regex>" scripts/test-web-console-<area>.mjs
|
||||
|
||||
# Web console start-up benchmark (the paint columns use a local Chrome or Edge through
|
||||
# playwright-core, which `npm install` already provides)
|
||||
node scripts/bench-web-console.mjs [--runs 7] [--workflow dashboard]
|
||||
|
||||
# Refresh the web console screenshots in docs/screenshots/ (needs a local Chrome or Edge).
|
||||
# Rerun after any change a person would see on the console page, and open every image
|
||||
# before committing: right screen, both themes, no username or home path in frame.
|
||||
npm i --no-save puppeteer-core # once; never added to package.json
|
||||
# PLAN2CODE_TEST_BROWSER=chrome|msedge forces which browser the page tests and these scripts use
|
||||
node scripts/capture-screenshots.mjs # every screen
|
||||
node scripts/capture-screenshots.mjs --only dashboard # one screen (dashboard-utilities scrolls to the utility cards)
|
||||
|
||||
# Plan2Code Loop
|
||||
cd plan2code-loop && npm install # First time setup
|
||||
cd plan2code-loop && npm run build # Build the CLI
|
||||
# Compare every element's computed style on every screen before and after a stylesheet change
|
||||
# (dev-only, not in npm test): take a baseline first, then compare after each move
|
||||
node scripts/css-snapshot.mjs --out before.json
|
||||
node scripts/css-snapshot.mjs --compare before.json
|
||||
|
||||
# Plan2Code Metrics
|
||||
cd plan2code-metrics && npm install # First time setup
|
||||
cd plan2code-metrics && npm run build # Build the CLI
|
||||
cd plan2code-metrics && npm test # vitest (aggregator, community, improver)
|
||||
|
||||
# Desktop app (plan2code-app/, Rust + Tauri). CI's `app` workflow runs all three on
|
||||
# Windows, macOS and Linux and fails on any rustfmt difference or clippy warning, so run
|
||||
# them before pushing, not only cargo test (see plan2code-app/README.md "Tests").
|
||||
# First time: rustup component add rustfmt clippy (for the toolchain in rust-toolchain.toml)
|
||||
cd plan2code-app && node scripts/vendor.mjs && cargo fmt --check
|
||||
cd plan2code-app && cargo clippy --workspace --all-targets -- -D warnings
|
||||
cd plan2code-app && cargo test --workspace
|
||||
|
||||
# Plan2Code Bot (end-to-end workflow runner, Claude Agent SDK)
|
||||
cd plan2code-bot && npm install && npm run build
|
||||
cd plan2code-bot && npm test # vitest
|
||||
```
|
||||
|
||||
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/test-web-console.mjs:191`), so they never open a browser or touch your real console home. Almost all of the ~70s is the web console suite.
|
||||
## Targeted tests first
|
||||
|
||||
The full `npm test` takes minutes and drives a browser per page suite. When a change stays inside one part of the project, run that part's suites instead (with the `PLAN2CODE_*` app variables unset, as for `npm test`), and leave the full run for when a change reaches shared code.
|
||||
|
||||
| What changed | Run |
|
||||
|---|---|
|
||||
| An Activities game (`public/activities/*`), `public/tones.js` or `public/music.js` | `node --test scripts/test-web-console-tones.mjs scripts/test-web-console-activities.mjs`, plus the game's own `scripts/test-web-console-activities-<game>*.mjs` when it has one; add `test-web-console-page-activities.mjs` when the Activities window or its switches changed |
|
||||
| A music prototype (`prototypes/music/<game>/`) | `node prototypes/music/check.cjs <game>` (nothing in `npm test` reads `prototypes/`) |
|
||||
| One web console area (server routes, chat, git board, workspace, notepad, Implementation Loop...) | that area's `scripts/test-web-console-<area>.mjs` (the loop's is `test-web-console-loop.mjs`), and its `test-web-console-page-<area>.mjs` when the page changed; `node scripts/parse-check.mjs` after editing any browser module under `public/` |
|
||||
| The launcher (`src/launcher/`) | `node --test scripts/test-launcher.mjs` |
|
||||
| A skill's script | `npm run build:skills`, then `node --test scripts/test-script-<skill>.mjs` (and `test-skill-scripts.mjs` for the shared plumbing) |
|
||||
| A workflow prompt (`src/plan2code-*.md`) | `node scripts/validate-char-count.js` and `node scripts/check-skill-table.mjs` |
|
||||
| A new skill or console workflow | First update the hand-written tables that list every workflow: the `SUBAGENT_WORKFLOWS` count and the meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS` in `test-web-console-logic.mjs`, `notesFor` in `test-web-console-speed.mjs`, the event list in `src/web-console/console-meter.md` (checked by `test-web-console-chat-stress.mjs`) and a `BUDGETS.notes` entry in `test-console-wire-budgets.mjs`. Then run those four suites plus `test-web-console-skills.mjs` and `test-web-console-spec-states.mjs`; the PR Prep and Test build missed all five tables and only the full suite caught them |
|
||||
| Docs or comments only | `node --test scripts/test-us-english.mjs scripts/test-line-endings.mjs` |
|
||||
|
||||
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 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
|
||||
|
||||
| Variable | Effect |
|
||||
|----------|--------|
|
||||
| `PLAN2CODE_CONSOLE_HOME` | Replaces `~/.plan2code/console`: sessions, `looks.json` and the runtime handle dir all move under it (`src/web-console/lib.mjs`). Always set it for scratch runs so `stop --all` cannot reach real sessions. |
|
||||
| `PLAN2CODE_CONSOLE_HOME` | Replaces `~/.plan2code/console`: sessions, `looks.json` and the runtime handle dir all move under it (`src/web-console/files.mjs`). Always set it for scratch runs so `stop --all` cannot reach real sessions. |
|
||||
| `PLAN2CODE_NO_BROWSER` | `open` does not launch a browser (`NO_BROWSER` also works). |
|
||||
| `PLAN2CODE_BROWSER` | Browser command line to run with the link appended, instead of the system default. |
|
||||
| `PLAN2CODE_MODELS_DIR` | Moves the launcher model menus (`bin/models.json`, `models.json`) away from `~/.plan2code`, for tests. |
|
||||
| `PLAN2CODE_PICKER_ECHO` | Tests only: `/workspace/browse` returns this as the picked folder instead of opening a picker (`-` means cancelled). |
|
||||
| `PLAN2CODE_PICKER_ECHO` | Tests only: `/workspace/browse` returns this as the picked folder instead of opening a picker (`-` means canceled). |
|
||||
| `PLAN2CODE_CONSOLE_DEV` | Set to `1` (by `npm run play`) and the server reads every page file from disk on each request instead of once, so a reload shows edits (`src/web-console/static.mjs`). |
|
||||
| `PLAN2CODE_CONSOLE_TRACE` | Set to `1` on `open` to print a start-up step timeline to stderr. |
|
||||
|
||||
## Installer Menu Options
|
||||
@@ -65,7 +102,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 |
|
||||
|
||||
@@ -74,22 +111,22 @@ 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
|
||||
|
||||
`install.js` takes no arguments for normal use, but exposes two build hooks. Any argument other than these two (when neither is present) exits 1 with usage; extra arguments beside either flag are ignored.
|
||||
`install.js` takes no arguments for normal use, but exposes two build hooks and the non-interactive update. Any argument other than these three (when none is present) exits 1 with usage; extra arguments beside `--build-skills` or `--verify-skills` are ignored, while `--update` must be the only argument.
|
||||
|
||||
| Flag | Action |
|
||||
|------|--------|
|
||||
| `--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, app, statusline; metrics and bot only when run from a git checkout, since they run from the install folder, which npx's cache is not), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx |
|
||||
|
||||
## How the Installer Works
|
||||
|
||||
@@ -134,6 +171,15 @@ See the `skills/` build-artifact gotcha in [Code Style & Gotchas](./AGENTS-code-
|
||||
## Adding a New Workflow Prompt / Skill
|
||||
|
||||
1. Create `src/plan2code-<name>.md` with body content only and keep it under 20,000 characters.
|
||||
2. Register it in `SOURCE_PROMPTS` in `install.js` (with the web-console `additionalReferences` entry every skill carries); add a `generateStepLabel()` case when needed. List any shared scripts it runs in `scripts: [...]`, and put its own scripts in `src/plan2code-<name>-scripts/`. Add it to the skill/workflow table and the "What each skill reads and writes" table in `src/plan2code.md` (the latter is checked by `scripts/check-skill-table.mjs`), and to the workflow lists in `src/web-console/public/answers.js`, `public/meter.js` and the `console.mjs` usage text.
|
||||
3. Update command inventories in `README.md`, `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md`, and `CHANGELOG.md`. Update `docs/index.html` only for core pipeline steps.
|
||||
4. Run `npm run build:skills` and `npm test`.
|
||||
2. Register it in `SOURCE_PROMPTS` in `install.js` (with the web-console `additionalReferences` entry every skill carries); add a `generateStepLabel()` case when needed. List any shared scripts it runs in `scripts: [...]`, and put its own scripts in `src/plan2code-<name>-scripts/` (with a `scripts/test-script-<name>.mjs` added to `package.json`'s `test` list).
|
||||
3. Register it with the web console. The meter's points and labels, the resume command, Help's card list and `console.mjs help`'s workflow list are all derived from `skills.js`, so the edits are `skills.js`, `install.js` (step 2), the skill's prompt (step 1), its pose and its notes; `npm test` names anything else left out:
|
||||
- `src/web-console/public/skills.js`: one entry (workflow, label, start pose, flags, subagents line, the meter's `weight`, `started` and `ran`, and `resume`) with its card (plus `help` when Help's line should differ from the blurb), and the card's `states` and `grayed`. Utilities go in group `"extra"` before Changelog.
|
||||
- `src/web-console/public/index.html`: its start pose, an `<svg class="pose pose-<workflow>" data-pose="<workflow>">` in `<template id="start-poses">` (pose CSS in `public/styles/poses.css`), unless its `pose` borrows an existing one (as Implement + Review borrows Implement's).
|
||||
- Its help topic: a `src/web-console/notes/<workflow>.md` (named in the skill's Interface line) or a `HELP_TOPICS` alias in `src/web-console/cmd-help.mjs`.
|
||||
- `src/plan2code.md`: the skill/workflow table and "What each skill reads and writes" (`scripts/check-skill-table.mjs`: every backticked token must appear in the skill's prompt).
|
||||
- `console.md` (the `open --workflow` list and the `notes/<workflow>.md` row).
|
||||
- Optional: `STARTER_SET_FOR` in `public/starters.js` (unlisted gets "general").
|
||||
|
||||
**Adding a spec state** is shorter: one entry in `src/web-console/public/spec-states.js`, the detection in `classifySpec()` in `src/web-console/scan.mjs`, the `states` of each card in `skills.js` that takes it, and a line in the dashboard skill (`src/plan2code.md`); then `npm test`.
|
||||
4. Update command inventories in `README.md` (dashboard-card and command tables), `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md` (prompt table, own-script rows, notes list), and `CHANGELOG.md`. Update `docs/index.html` for core pipeline steps, and for a utility only when it is a headline change (its `.utils` block).
|
||||
5. Run `npm run build:skills` and `npm test`.
|
||||
@@ -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) |
|
||||
@@ -0,0 +1,79 @@
|
||||
# Web Console Contract: the Why
|
||||
> Part of [AGENTS.md](../AGENTS.md): project guidance for AI coding agents.
|
||||
|
||||
Maintainer notes for the agent-facing console docs in `src/web-console/`. Installed skills never ship or load this file (nothing under `.agents-docs/` is in `install.js` `additionalReferences`), and the shipped files carry only what an agent must do. Put an explanation here, not there. If a shipped file starts to explain, move the sentence into this file and keep the instruction.
|
||||
|
||||
The shape: a short card (`console.md`) read once per session, topic files the console names in its own `read` output at the moment each is due, and refusals for the silent slips the console can see. Size budgets in `npm test` stop the docs growing back (Phase 7 of `specs--completed/console-wire-format`).
|
||||
|
||||
## Why pointers and refusals instead of repeated rules
|
||||
|
||||
A rule stated in six files is read six times and still skipped. The console sees most slips (a `stop` with no `finish`, a `finish` with `stopWarning` set, a reply left unanswered), so it refuses them and says the fix, and it names a topic file once per session per topic when that topic's moment arrives. The card states each silent rule once. A rule that was broken twice in repeated prose becomes a check in the console, not another sentence.
|
||||
|
||||
## console.md (the card)
|
||||
|
||||
- **Print then stamp.** `wait` prints a result and only then marks it collected (`advanceCursor`). A kill between the two repeats a delivery and never loses one. That is why "handle it once" is in `console-trouble.md`, and why `thread` (which appends) needs care on a repeat.
|
||||
- **Bounded slices.** A wait runs for a limited number of seconds sized under the agent's shell timeout, so the command returns by itself. A killed wait loses nothing. People step away for hours, so there is no cap on the number of slices.
|
||||
- **Every turn ends on a `wait`.** The page tells the person "the next question will appear here on its own". A turn that ends on text leaves that promise unkept and strands their next click. The console cannot see this slip, which is why the card states it.
|
||||
- **Three open questions at most.** More than three open cards turns the page into a form to fill in, not a conversation, and people answer the first three and skip the rest. The server enforces the cap.
|
||||
- **`settle`.** The server records a send on an item but only the agent decides it is final (a pick that still owes its recap is not). `settle` marks cards answered in the same post that moves on; a card left open stays on the page as a question still owed.
|
||||
- **Defaults are filled by the console** (`status`, `required`, `allowOther`, empty `options` and `thread`, option keys by position, doc `version` and `stale`): an obvious default costs tokens every patch and carries no decision. A default the console fills is the only thing the card may leave out.
|
||||
- **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.
|
||||
- **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.
|
||||
- **Skill invocation tools.** Every skill below the dashboard ships `disable-model-invocation: true`, so a hop reads `skillFile` with a file tool and follows it.
|
||||
|
||||
## console-docs.md
|
||||
|
||||
Documents are read from `file` blocks rather than pasted so the page and the disk cannot disagree, and a progress post only has to ask for `refresh`. `assumed` and `draft` exist so a half-finished doc is not read as decisions. A doc `version` never goes back because the page keys its "new version" marker on it.
|
||||
|
||||
## console-finish.md and console-stop.md
|
||||
|
||||
- **Finish before stop.** The page tells the person to leave the tab open until the next question appears. Stopping first leaves them looking at a promise about a session that is over, and the one thing they need, a command to run in a terminal they are not looking at, never reaches them. The console refuses a `stop` with no `finish` (`--force` for a dead page).
|
||||
- **Every ending posts a finish**, not only the last: an off-ramp, a checkpoint that saves and stops, a stop request.
|
||||
- **Nothing of yours still running.** Subagents and background jobs run inside the agent's terminal. When the page says the session ended the person is free to close it, which kills them mid-write. A `finish` is refused while any reported helper is `running`.
|
||||
- **Keep waiting after a finish.** The dashboard, Commit it now and review buttons live exactly as long as the agent listens, so a press an hour later works like one a minute later. A pause is the exception: it keeps a place to come back to and stops at once.
|
||||
- **The paused word.** A headline starting "Paused" is what the page and `open --resume` both key off.
|
||||
- **`stopWarning`.** Some points have nothing on disk yet and stopping loses answers. The page cannot know where the agent is, so the agent says so. A paused `finish` clears it in the same patch, and the console refuses one posted while it is set.
|
||||
- **Stop is offered on the person's turn only,** so a stop never arrives while the agent is halfway through writing their last answers.
|
||||
- **Write the bare command.** The page appends `--web` to a Plan2Code command it shows and copies, so someone who worked here lands back here. Placeholders (`<` or `>`) are refused because a rendered command is copied and run verbatim.
|
||||
- **Continue here and Commit it now** are buttons the page derives from `command` and `commit`, so the agent writes nothing extra for them.
|
||||
|
||||
## console-chat.md
|
||||
|
||||
- **Every message gets a reply.** The Ask tab shows "working on the answer" until one lands. The console warns on `post` and `wait` about unanswered Quick questions for that reason.
|
||||
- **Chat never steers the workflow.** A chat answer that approved a gate would make the record under `specs/` depend on a side channel.
|
||||
- **Edits need approval first** and happen only at check-ins, so a change cannot land mid-task.
|
||||
- **Prompts to carry away** start with prose because the page treats a fenced block whose first line looks like a shell command as a command, not a prompt.
|
||||
- **Replies merge by `id`,** so a repeated delivery is answered by re-posting the same reply, not by answering twice.
|
||||
|
||||
## console-workspace.md
|
||||
|
||||
Added folders are read-only reference because the person added them as context, not as a place to work. The first read of a folder's `AGENTS.md` is once per folder per skill run so layout rules are known without re-reading. A `folderIssue` goes to the ledger, not the page state, so a failed read is reported once.
|
||||
|
||||
## console-subagents.md
|
||||
|
||||
The setting arrives as a standing instruction only when it changes, so a long session is not repeated at. Pathfinder research always uses helpers whatever the switch says; the switch governs recon and lookups. Questions for the person stay with the agent, because a helper has no way to ask and an answer only reaches the agent holding the session. Helpers add no session meter points.
|
||||
|
||||
## building.md and building-review.md
|
||||
|
||||
A build is mostly the agent working, so each task's checkbox write is posted at once (the Disk Write Rule): a session that dies mid-phase must leave disk true. `quietMinutes` exists because the page calls a working agent stuck after two silent minutes and a task can honestly take twenty. A question stops the build because the page reads `working` as "not your turn". The review runs inside the build's session and scores itself once on the meter, so it never resumes under `--workflow review` as well. The way back from a review lands on the sign-off without the review verdict, because re-offering a review that just ran reads as though nothing happened.
|
||||
|
||||
## console-launches.md and console-trouble.md
|
||||
|
||||
A session handed over by the dashboard is resumed, never re-opened, because a fresh `open` strands the page the person is watching. The console never writes into a project, so deletes go through `delete-spec` and `delete-handoff`, which refuse links and anything outside `specs/<name>`.
|
||||
|
||||
## console-meter.md
|
||||
|
||||
The meter is advice, not a gate: it tells the person when a fresh session would be sharper. Per-unit work is reported by the agent with `run`; the same `id` is ignored in the same run so a repeat never double counts.
|
||||
|
||||
## console-attachments.md
|
||||
|
||||
Attachments live in the session folder and are swept with it, so a spec file that cites one keeps it first through `keep`: the file is copied under `specs/<idea>/` and the link the console returns is the durable one. Uncited attachments stay with the session on purpose: a picture sent to answer a question was context for it, not a deliverable. A refused `keep` links nothing, because a spec must never point at a path the sweep removes.
|
||||
|
||||
## Wire format (outputs)
|
||||
|
||||
Outputs carry what the agent acts on and nothing else. Anything kept in the session files (`type`, `at`, `rev`, answer actions, full chat entries, structured workspace and subagents objects) is dropped from stdout. The desktop app reads `sid`, `url`, `pid`, `port` and `embed` from `open` in every context, so those stay. See `specs--completed/console-wire-format/overview.md` (API Design) for the table.
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write|Edit|MultiEdit|NotebookEdit",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "node \"$CLAUDE_PROJECT_DIR/scripts/fix-line-endings.mjs\" --hook",
|
||||
"timeout": 30
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -115,7 +115,7 @@ Conventions to follow, drawn from existing entries:
|
||||
|
||||
- Bold lead-in naming the prompt, file, or area, then an em dash (`—`), then the description.
|
||||
- Reference prompts by their command (`/plan2code-1-plan`) or path (`src/plan2code-init.md`), not by informal name.
|
||||
- One paragraph per bullet is fine — this CHANGELOG favours substantive entries over terse one-liners, and a bullet may carry extra indented paragraphs for detail.
|
||||
- One paragraph per bullet is fine — this CHANGELOG favors substantive entries over terse one-liners, and a bullet may carry extra indented paragraphs for detail.
|
||||
- A release with a big theme may open with a one-line summary paragraph directly under the `## vX.Y.Z` heading, before the first `###`.
|
||||
|
||||
Insert the new section directly below the `All notable changes...` line and above the previous version's heading.
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
---
|
||||
name: plan2code-launcher-update
|
||||
description: "Refresh the plan2code launcher's shipped data: the curated model menu in src/launcher/models.json from `devin models list` and Claude Code's documented model aliases, and the agent list's install data in src/launcher/agents.json re-checked against each vendor's docs, with the maintainer approving every change before anything is written. Use this skill when the user says 'update the models', 'refresh models.json', 'new Claude model', 'devin models changed', 'update the agents', 'refresh agents.json', 'agent install commands changed', 're-check the agent list', or otherwise asks to bring the launcher's model menu or agent install data up to date."
|
||||
---
|
||||
|
||||
# Plan2Code Launcher Update
|
||||
|
||||
Bring the launcher's shipped data up to date: the curated model menu (`src/launcher/models.json`) with the models each CLI offers today, and the agent list (`src/launcher/agents.json`) with what each vendor's docs say today. Discover the current facts, show the maintainer a diff against the shipped files, apply only the changes they approve, validate both files, and run `npm test`. This skill never commits.
|
||||
|
||||
**Repo-local by design.** This skill lives in the repo's `.claude/skills/` and is intentionally NOT wired into `install.js` — it is a maintainer dev tool, not part of the shipped product, so it is never installed to `~/.claude/skills/`. Do **not** copy it there: the uninstaller (`uninstallSkills()` in `install.js`) and every re-install (`install()`) both run `cleanLegacyPaths()`, which deletes every entry matching `/^plan2code-/` under `~/.claude/skills/` (the `LEGACY_PATHS` row for Claude Code skills), so a copy placed there would be silently removed.
|
||||
|
||||
**Terminal only.** This skill runs in the terminal, with no web console session. Ask every question here.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1 — Preflight
|
||||
|
||||
Run from the repo root (the folder holding `install.js` and `src/launcher/`). Run `git status --porcelain -- src/launcher/models.json src/launcher/agents.json`. If it prints anything, warn — do not stop:
|
||||
|
||||
> The shipped launcher files already have uncommitted changes. The diff below compares against the files as they stand on disk, including those changes.
|
||||
|
||||
### Step 2 — Read the current files
|
||||
|
||||
Read `src/launcher/models.json`. It has five keys: `_note` (a string), `claude`, `devin` and `codex` (each an array of `{ "id", "label" }`) and `strengths` (an object, see Step 4c). Keep the `_note` text exactly as read — Step 9 writes it back verbatim and the Validation rules check it.
|
||||
|
||||
Read `src/launcher/agents.json`. It has `schema` (currently `1`) and `agents`, a list of entries. Each entry carries `id`, `name`, `kind` (`builtin` or `template`), `command`, `prompt`, `args`, `bypassArgs`, `modelArgs`, and optional `note`. A `builtin` entry also carries `installUrl`, `install` (lists under `win`, `mac` and `linux`, each `{ label, run, note? }`) and `installDirs` (the same OS keys). Keep the file's shape and order exactly as read.
|
||||
|
||||
### Step 3 — Discover Devin's models
|
||||
|
||||
If `devin` is on PATH (`command -v devin` in bash, `Get-Command devin` in PowerShell), run:
|
||||
|
||||
```bash
|
||||
devin models list
|
||||
```
|
||||
|
||||
Show its raw output to the maintainer before any interpretation — the format is not a stable contract. The output is long (hundreds of ids across about twenty families), so save it to a scratch file outside the repo, say where, and show the family headings in full. From it, take the explicit ids at Low, Medium and High effort only, plus `adaptive`. Skip every id the Validation rules forbid (`xhigh`, `max`, `fast`, `priority` endings), and also skip `none`-effort ids, ids with no effort suffix (such as `swe-1-7`, which is a Max model), and `fusion-*` combinations.
|
||||
|
||||
The 30-entry cap means the file can never hold every family at three efforts. Propose additions by family — newest and most-used first — and say how many entries that leaves.
|
||||
|
||||
If `devin` is not on PATH or the command fails, say so with the error, and switch to **guided manual edits** for Devin: ask the maintainer which ids to add, remove or relabel, one at a time, and carry those into Step 7 as the proposed list.
|
||||
|
||||
### Step 4 — Discover Claude Code's models
|
||||
|
||||
Look up Claude Code's current model documentation — the model configuration page in the Claude Code docs. Locate it on each run (search the Claude Code docs for model configuration) rather than using a remembered URL; docs move. List the documented model aliases (for example `default`, `sonnet`, `opus`, `haiku`, `opusplan`) and what each one means, and name the page you used. Keep `default` as the file's first entry even though the docs call it a special value rather than an alias. Bracketed aliases such as `opus[1m]` are valid ids; propose them only when the maintainer wants them in the menu.
|
||||
|
||||
If the lookup fails or the page does not list aliases, say so, and switch to **guided manual edits** for Claude, exactly as in Step 3.
|
||||
|
||||
### Step 4b: Check Codex's models
|
||||
|
||||
Look up Codex's current model documentation (locate it on each run). Propose `codex` entries only for model ids the docs name explicitly. If they name none, say so and leave `codex` empty. If entries are added, the `_note` sentence about Codex goes stale; keep `_note` verbatim as everywhere else, but tell the maintainer so they can reword it by hand. If the lookup fails, use guided manual edits as in Step 3.
|
||||
|
||||
### Step 4c: Check the strengths mapping
|
||||
|
||||
`models.json` also has a top-level `strengths` object: for an agent id, the loop's `thrifty`, `balanced` and `best` words, each `{ "model", "effort"? }`. After Steps 3 to 4b settled the refreshed lists, check that every `strengths` row still names a `model` that is in that agent's refreshed list (an `effort` is kept only for an agent that takes one, and is `low`, `medium` or `high`). For a row whose model is **gone**, propose a replacement from the same family, one step lighter or stronger as the word implies (Thrifty lighter, Best stronger), and show it in Step 7's table as a `strengths.<agent>.<word>` change. Never add a mapping for an agent that has none: only agents already under `strengths` are checked.
|
||||
|
||||
### Step 5: Re-check the agent list against vendor docs
|
||||
|
||||
For each entry in `agents.json`, locate the vendor's current install documentation on each run (search for it; do not use a remembered URL, since docs move and `installUrl` itself may be stale). Compare the file against what the docs say today:
|
||||
|
||||
- **Built-ins** (`claude`, `devin`, `codex`): `installUrl`, every `install` line per OS (`label`, `run`, `note`), and `installDirs` per OS. Keep the lead-installer order: the vendor's native installer first, then npm where it exists, with requirement notes (like Claude Code's Node 22+ npm note) carried on their lines. Also re-check `command`, `prompt`, `args`, `bypassArgs` and `modelArgs` against the vendor's CLI reference.
|
||||
- **Templates** (`copilot`, `opencode`, `gemini`, `pi`): `command`, the first-prompt form (`prompt` plus where `{prompt}` sits in `args`), `bypassArgs`, `modelArgs`, and any `note`. Confirm the template rule still holds: the docs must confirm both that the agent loads the installed Plan2Code skills (the skills folders the vendor documents) and that it starts an interactive session with a first prompt. A template that no longer passes the rule is proposed for removal, and the maintainer is told why.
|
||||
|
||||
Name the docs page used for each entry. If an entry's docs cannot be found or read, say so, and carry nothing for that entry into Step 7. Never propose a change from memory.
|
||||
|
||||
### Step 6: Re-check Cursor CLI and Aider
|
||||
|
||||
Cursor CLI and Aider were left out of the templates for want of one confirmation each: Cursor CLI's skills loading in the CLI (its editor docs list skills folders, the CLI's did not), and Aider's skills support and an interactive first prompt. Re-check both against the same template rule as Step 5: the docs must confirm both that the agent loads the installed Plan2Code skills and that it starts an interactive session with a first prompt.
|
||||
|
||||
Propose a new `template` entry only when both are confirmed, in the shape of the existing entries (`id`, `name`, `command`, `prompt` worded for that agent's skill invocation, `args` with the prompt in the vendor's documented first-prompt form, `bypassArgs`, `modelArgs`). When one side is still unconfirmed, say which and propose nothing.
|
||||
|
||||
### Step 7 — Show the diff
|
||||
|
||||
For `models.json`, compare the discovered list with the current one by `id` and show one table:
|
||||
|
||||
| Change | id | Current label | Proposed label | Source |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| added | `new-id` | — | New label | `devin models list` |
|
||||
| gone | `old-id` | Old label | — | not in `devin models list` |
|
||||
| relabeled | `same-id` | Old label | New label | Claude Code docs: <page> |
|
||||
|
||||
- **added:** offered by the CLI, not in the file.
|
||||
- **gone:** in the file, no longer offered.
|
||||
- **relabeled:** same `id`, a better or changed label. Propose a label in the file's existing style.
|
||||
|
||||
For `agents.json`, show one table with one row per changed field:
|
||||
|
||||
| Change | Entry | Field | Current | Proposed | Source |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| changed | `claude` | `install.win[0].run` | old command | new command | <vendor docs page> |
|
||||
| added | `cursor` | new template | | template entry | <vendor docs page> |
|
||||
| gone | `gemini` | whole entry | template | | skills no longer confirmed |
|
||||
|
||||
Summarize unchanged entries as a count under each table ("19 Devin entries unchanged", "3 built-ins unchanged") instead of listing them. If approving every **added** Devin row would take the list past 30 entries, say so above the table and by how many. Call out any likely rename before approval (see the rename warning under Validation rules). If all tables are empty, say the files are current and stop.
|
||||
|
||||
### Step 8 — Approve each change
|
||||
|
||||
Ask about each row, one at a time: **yes**, **no**, or **edit** (they type the value to use). Write nothing until every row has an answer. A "no" leaves that entry exactly as it is today.
|
||||
|
||||
### Step 9 — Edit the files
|
||||
|
||||
Apply only the approved rows:
|
||||
|
||||
- Keep `_note` in `models.json` and `schema` in `agents.json` verbatim.
|
||||
- Keep the existing order. Remove a **gone** entry where it stands, change a **changed** or **relabeled** value in place, and append each **added** entry at the end of its list.
|
||||
- Write two-space-indented JSON with a trailing newline, matching each file's current formatting.
|
||||
|
||||
### Step 10 — Validate
|
||||
|
||||
Check the edited files against every rule under Validation rules. On a failure, show the rule and the entry that broke it, and go back to Step 8 for the affected rows. Do not run tests on a file that fails validation.
|
||||
|
||||
### Step 11 — Test
|
||||
|
||||
Run `npm test` from the repo root and report the result honestly: pass, or the failing suite and its output. Never describe a failing run as passing.
|
||||
|
||||
### Step 12 — Remind about the release
|
||||
|
||||
A launcher data change reaches people only with the next release. Remind the maintainer to add a `CHANGELOG.md` line and keep `CHANGELOG.md`, `version.json` and `package.json` on the same version — `/plan2code-changelog` does both.
|
||||
|
||||
### Step 13 — Suggest a commit
|
||||
|
||||
Suggest a one-line commit message that says what changed, and do not run it:
|
||||
|
||||
```bash
|
||||
git add src/launcher/models.json src/launcher/agents.json
|
||||
git commit -m "Refresh the launcher's model menu and agent install data"
|
||||
```
|
||||
|
||||
Give `add` and `commit` as two separate commands (Windows PowerShell 5.1 has no `&&`).
|
||||
|
||||
## Validation rules
|
||||
|
||||
Check every rule before `npm test` (Step 10). They mirror the shipped-file tests in `scripts/test-launcher.mjs` ("the shipped models.json is curated Devin at low/medium/high only") and `scripts/test-agent-lookup.mjs` (the shipped `agents.json` loads clean) plus the menus' own needs:
|
||||
|
||||
**`models.json`:**
|
||||
|
||||
- The file is valid JSON.
|
||||
- `_note` is present and unchanged from what Step 2 read.
|
||||
- `claude` and `devin` are both non-empty arrays; `codex` is an array (empty is allowed).
|
||||
- `devin` has at most 30 entries.
|
||||
- Every entry in `claude`, `devin` and `codex` has a non-empty string `id` and a non-empty string `label`.
|
||||
- Ids are unique within each list, and labels are unique within each list.
|
||||
- No Devin id ends in `xhigh`, `max`, `fast` or `priority`.
|
||||
- Every `strengths` row names a `model` that is in that agent's list in the same file, uses only the words `thrifty`, `balanced` and `best`, and no agent other than the ones already under `strengths` gains a mapping.
|
||||
|
||||
**`agents.json`:**
|
||||
|
||||
- The file is valid JSON, `schema` is `1`, and `agents` is a non-empty array.
|
||||
- Ids are unique, and `kind` is `builtin` or `template` on every entry.
|
||||
- The `builtin` entries are exactly `claude`, `devin` and `codex`, and each carries a non-empty `installUrl`, an `install` list under each of `win`, `mac` and `linux` (every line a non-empty `label` and `run`), and `installDirs` under the same keys.
|
||||
- Every entry has a non-empty `id`, `name` and `command`; `name` is at most 60 characters.
|
||||
- Every `template` entry would pass `normalizeAgents()` in `src/web-console/agents.mjs` with no warnings (the check `scripts/test-agent-lookup.mjs` runs): a kebab-case `id` that is not a built-in id, `args`, `bypassArgs` and `modelArgs` lists of strings when present.
|
||||
- Every `template` entry's docs still confirm both skill loading and an interactive first prompt (Steps 5 and 6); the maintainer approved any removal this breaks.
|
||||
|
||||
**Warn on renames.** When an entry is **gone** and a near-identical id is **added** in the same list (a changed version number or suffix, say `glm-5-3-high` → `glm-5-4-high`), call the pair out before approval as a likely rename. People's own lists in `~/.plan2code/models.json` merge with the shipped one by id (`mergeModels()` in `src/launcher/plan2code.js`), so a renamed id can bring back a user's old copy of the entry beside the new one. Approve the pair knowingly, or keep the old id.
|
||||
|
||||
## Rules
|
||||
|
||||
- **Never commit and never push** — Step 13 suggests the commit; the maintainer runs it.
|
||||
- **Touch only `src/launcher/models.json` and `src/launcher/agents.json`**, plus `CHANGELOG.md` only if the maintainer asks for the release line.
|
||||
- **Nothing is written before every row is answered** (Step 8).
|
||||
- **Never install this skill** — never add it to `install.js`, and never copy it to `~/.claude/skills/` (the uninstaller deletes `plan2code-*` entries there).
|
||||
@@ -1,116 +0,0 @@
|
||||
---
|
||||
name: plan2code-model-update
|
||||
description: "Refresh the plan2code launcher's curated model menu in src/launcher/models.json from `devin models list` and Claude Code's documented model aliases, with the maintainer approving every change before anything is written. Use this skill when the user says 'update the models', 'refresh models.json', 'new Claude model', 'devin models changed', or otherwise asks to bring the launcher's model list up to date."
|
||||
---
|
||||
|
||||
# Plan2Code Model Update
|
||||
|
||||
Bring the launcher's curated model menu (`src/launcher/models.json`) up to date with the models each CLI offers today. Discover what Devin and Claude Code currently offer, show the maintainer a diff against the shipped file, apply only the changes they approve, validate the file, and run `npm test`. This skill never commits.
|
||||
|
||||
**Repo-local by design.** This skill lives in the repo's `.claude/skills/` and is intentionally NOT wired into `install.js` — it is a maintainer dev tool, not part of the shipped product, so it is never installed to `~/.claude/skills/`. Do **not** copy it there: the uninstaller (`uninstallSkills()` in `install.js`) and every re-install (`install()`) both run `cleanLegacyPaths()`, which deletes every entry matching `/^plan2code-/` under `~/.claude/skills/` (the `LEGACY_PATHS` row for Claude Code skills), so a copy placed there would be silently removed.
|
||||
|
||||
**Terminal only.** This skill runs in the terminal, with no web console session. Ask every question here.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1 — Preflight
|
||||
|
||||
Run from the repo root (the folder holding `install.js` and `src/launcher/`). Run `git status --porcelain -- src/launcher/models.json`. If it prints anything, warn — do not stop:
|
||||
|
||||
> `src/launcher/models.json` already has uncommitted changes. The diff below compares against the file as it stands on disk, including those changes.
|
||||
|
||||
### Step 2 — Read the current file
|
||||
|
||||
Read `src/launcher/models.json`. It has three keys: `_note` (a string), `claude` and `devin` (each an array of `{ "id", "label" }`). Keep the `_note` text exactly as read — Step 7 writes it back verbatim and the Validation rules check it.
|
||||
|
||||
### Step 3 — Discover Devin's models
|
||||
|
||||
If `devin` is on PATH (`command -v devin` in bash, `Get-Command devin` in PowerShell), run:
|
||||
|
||||
```bash
|
||||
devin models list
|
||||
```
|
||||
|
||||
Show its raw output to the maintainer before any interpretation — the format is not a stable contract. The output is long (hundreds of ids across about twenty families), so save it to a scratch file outside the repo, say where, and show the family headings in full. From it, take the explicit ids at Low, Medium and High effort only, plus `adaptive`. Skip every id the Validation rules forbid (`xhigh`, `max`, `fast`, `priority` endings), and also skip `none`-effort ids, ids with no effort suffix (such as `swe-1-7`, which is a Max model), and `fusion-*` combinations.
|
||||
|
||||
The 30-entry cap means the file can never hold every family at three efforts. Propose additions by family — newest and most-used first — and say how many entries that leaves.
|
||||
|
||||
If `devin` is not on PATH or the command fails, say so with the error, and switch to **guided manual edits** for Devin: ask the maintainer which ids to add, remove or relabel, one at a time, and carry those into Step 5 as the proposed list.
|
||||
|
||||
### Step 4 — Discover Claude Code's models
|
||||
|
||||
Look up Claude Code's current model documentation — the model configuration page in the Claude Code docs. Locate it on each run (search the Claude Code docs for model configuration) rather than using a remembered URL; docs move. List the documented model aliases (for example `default`, `sonnet`, `opus`, `haiku`, `opusplan`) and what each one means, and name the page you used. Keep `default` as the file's first entry even though the docs call it a special value rather than an alias. Bracketed aliases such as `opus[1m]` are valid ids; propose them only when the maintainer wants them in the menu.
|
||||
|
||||
If the lookup fails or the page does not list aliases, say so, and switch to **guided manual edits** for Claude, exactly as in Step 3.
|
||||
|
||||
### Step 5 — Show the diff
|
||||
|
||||
For each CLI, compare the discovered list with the current one by `id` and show one table:
|
||||
|
||||
| Change | id | Current label | Proposed label | Source |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| added | `new-id` | — | New label | `devin models list` |
|
||||
| gone | `old-id` | Old label | — | not in `devin models list` |
|
||||
| relabelled | `same-id` | Old label | New label | Claude Code docs: <page> |
|
||||
|
||||
- **added:** offered by the CLI, not in the file.
|
||||
- **gone:** in the file, no longer offered.
|
||||
- **relabelled:** same `id`, a better or changed label. Propose a label in the file's existing style.
|
||||
|
||||
Summarise unchanged entries as a count under the table ("19 Devin entries unchanged") instead of listing them. If approving every **added** Devin row would take the list past 30 entries, say so above the table and by how many. Call out any likely rename before approval (see the rename warning under Validation rules). If both tables are empty, say the file is current and stop.
|
||||
|
||||
### Step 6 — Approve each change
|
||||
|
||||
Ask about each row, one at a time: **yes**, **no**, or **edit the label** (they type the label to use). Write nothing until every row has an answer. A "no" leaves that entry exactly as it is today.
|
||||
|
||||
### Step 7 — Edit `models.json`
|
||||
|
||||
Apply only the approved rows:
|
||||
|
||||
- Keep `_note` verbatim.
|
||||
- Keep the existing order. Remove a **gone** entry where it stands, change a **relabelled** label in place, and append each **added** entry at the end of its list.
|
||||
- Write two-space-indented JSON with a trailing newline, matching the file's current formatting.
|
||||
|
||||
### Step 8 — Validate
|
||||
|
||||
Check the edited file against every rule under Validation rules. On a failure, show the rule and the entry that broke it, and go back to Step 6 for the affected rows. Do not run tests on a file that fails validation.
|
||||
|
||||
### Step 9 — Test
|
||||
|
||||
Run `npm test` from the repo root and report the result honestly: pass, or the failing suite and its output. Never describe a failing run as passing.
|
||||
|
||||
### Step 10 — Remind about the release
|
||||
|
||||
A launcher model change reaches people only with the next release. Remind the maintainer to add a `CHANGELOG.md` line and keep `CHANGELOG.md`, `version.json` and `package.json` on the same version — `/plan2code-changelog` does both.
|
||||
|
||||
### Step 11 — Suggest a commit
|
||||
|
||||
Suggest a one-line commit message that says what changed, and do not run it:
|
||||
|
||||
```bash
|
||||
git add src/launcher/models.json
|
||||
git commit -m "Refresh the launcher's model menu"
|
||||
```
|
||||
|
||||
Give `add` and `commit` as two separate commands (Windows PowerShell 5.1 has no `&&`).
|
||||
|
||||
## Validation rules
|
||||
|
||||
Check every rule before `npm test` (Step 8). They mirror the shipped-file test in `scripts/test-launcher.mjs` ("the shipped models.json is curated Devin at low/medium/high only") plus the menu's own needs:
|
||||
|
||||
- The file is valid JSON.
|
||||
- `_note` is present and unchanged from what Step 2 read.
|
||||
- `claude` and `devin` are both non-empty arrays.
|
||||
- `devin` has at most 30 entries.
|
||||
- Every entry has a non-empty string `id` and a non-empty string `label`.
|
||||
- Ids are unique within each list, and labels are unique within each list.
|
||||
- No Devin id ends in `xhigh`, `max`, `fast` or `priority`.
|
||||
|
||||
**Warn on renames.** When an entry is **gone** and a near-identical id is **added** in the same list (a changed version number or suffix, say `glm-5-3-high` → `glm-5-4-high`), call the pair out before approval as a likely rename. People's own lists in `~/.plan2code/models.json` merge with the shipped one by id (`mergeModels()` in `src/launcher/plan2code.js`), so a renamed id can bring back a user's old copy of the entry beside the new one. Approve the pair knowingly, or keep the old id.
|
||||
|
||||
## Rules
|
||||
|
||||
- **Never commit and never push** — Step 11 suggests the commit; the maintainer runs it.
|
||||
- **Touch only `src/launcher/models.json`**, plus `CHANGELOG.md` only if the maintainer asks for the release line.
|
||||
- **Nothing is written before every row is answered** (Step 6).
|
||||
- **Never install this skill** — never add it to `install.js`, and never copy it to `~/.claude/skills/` (the uninstaller deletes `plan2code-*` entries there).
|
||||
@@ -1 +1 @@
|
||||
U0VOQwHlDc6GXsacM1cljlQP8y5A2pfARxFGNkmxiK3VxP1nQ9BIp3Z9PZAvB/qlVfrIGc7bCpdtmhsc42H0uveWo+th315m1M0PZWI9GzUWFTL5kShCH6ffFbL3oZpZwdz8l/+oncjsGShQMy0tUp+46YIPBJZGbF6SLG8/O5MC9IcsJfIob7WQUDca0IuSbxPkqC5WqN9PiZNM5P0tXayc3ARK+tUmpO3ywLT+0AJi0m1HWxNMNr3jCqCbwfMzpv5AMZR8jwkJHnCfUZ2DlfmTptnRFx7BjbPIDE8O3nlzOzQj2IFF5CNkPFM+uHvWcd/vUYgqCeBzG51Hi+urt6gW9Q/geoDR8AfioqNeVjakuH3pSjE4kBFsvyO7RSO8wXlwgc/nZHW5BIzHKWVUB12THRtIA0kOmnf/Tk5Da20dRENuCP35KZvBXu1KKn/BQ4hJ/dCB1K4FqKOnqHKE8+CoYCTvlursoAC0rphfufcwXvuAysmtPZGgrOTM7x3z825I8HY6K2Y1dh6h0kxwZ9UDbMzrSH/3WP/jMywD76Ep2qMFMdXKRsypxvIkwJCsptq0NilJN9hALdGwq5G5nRvBCP+nxy6brdCknbKxb8XHkcS8fDAUSifBD4/K9EbDDkXrykKFnA1Vh82LC9tU8o6Uwi99EzpZeWkoZCLHMqJlXPu+FEKvBQYiVa4pDQ/XHSu6lUvUFbdQlRL0vHjNfOq5hjF1kqHj4B+cCiD/FNMqAu9N57+UQNgjI2KzvdlOUAySqp22Bg9sTWa4Nj1ObWRqEx2WH+d4BLkd8N3RgA8OAlOPfF1BCUrDQAnhFoWZmyiPkfm8nCx1eHGFBB/Q4uLloBvhwv2EAoPy2U2pCqO723/C/NJNc4BFK0iuvBaoCNYm1P8mDpzX/fYRQq7kMLlQ+/5urLNfDclPJaJ0bCEHYfcssnrcpt+xshHfNhrLnQ6Ns/ULS8queCAJeNaxe7fOZ+WE1AiSWdXeXFdjnQbFgl0A91zntdfsB0wVW1X4q5sGzQo1NUOYHWi53M+ROBszKXpp4GHSML1OpJQixydcRpQIfNPg2j96RfFOXrJZWc05QSEnjckj3b6sIJLNATEKLY9314CunAG70y/GryqOoLtQmLwXTBRgTx/et7/ItKsvUaK3Z3cEFLflEU5Ny9iHA7Yuxs0rmdn6NjV+IXA9eEf+Uc+2eSHmVCaUgJuhDtnyaO6RpqCJkbs5wf7c/udW2G5QfWZCTLHG80p/7BsA3q2VvEvbQnC+LLPgnyJJpDKL+q/x8KdZ1x/iY4P1J3B5nehEztoMHi8dgUsL3NkItdnJMKf5VQsyW1vnv4kZo7qZ+6+Z/IuqZZNy0aT3N1hJZWDPboFRmcGpTE8ShwblGnrTdnIZlhyk0m951creqltUp13bPWSFOj1zt/yDmW1yBUkkOmpnbJzmzxd9G4kpzHsV6NvGE4JsFVAQnGHgMI6zxMwKM7He+As/+FlwJgdmAPeIZ+PtciZMv+ySi9/xSXMwpJHSXFo2NkkWj8QJke5l9BsDGj66ZTjkW5R1RmYNhVAPTrP32a02kPj2JYgDOAIAGcz0q1Somb4LqVNAp6/Y6DFY3iniC3bV6vZagVLcgQFngHRgZ3HzILWcytJZwhVoMpE18DXpTBuubqytM/bnVFRZ6GxLJtcRCt24RnMRYipuR19kq+ncxEN7Xl7LkPdpsfFPelS9srxAWbivtD32SjCxsIKte+vns2lU6J12UoXP86LVDtTZCRkh/bmCDs4ecks02NVu2htm47UjPMVx1KDqTGPlPGZA+Vuj/eaWdoqvpEJzeOCgcrhUehDqQCpm0ZfCPJ924eGdfZGQZaaO4CZ6H4asHTTabWpu1cuLqVQkO030VAHJaDNE8fqxiPN3rsXmRjxTTSuc/N2i5OyGdqJdXbItMdmaWOU7p5XkmkUDVhhKiHBBcGsUekx0TSMmNkkbLJBy0DK2wkMP9utLDAxAzT5v0uTKKbPPpMYqGbhveN9+HClsD3cHGZ1xT3ag8Xg3s04zwoOhmXNvoDOOtcDaqbJacrMBhj8Hj6PUKGd2JlaU8M6GuBRXHzbmfPlDL7eQLhvRuwDAlVTfePRFs/L7i45xQ40t2z+Mxu1h+eQRuw3ePVscNX7xe7h+l+6MddyT7XuR2hiP4CapOJQ8uYgjdIUDDTAblNhIh99KvM4mevwzcZ+K6J/Kc3MFCeJzOIGYL0xCSKKnrvdihkYiw02U9okgkfz2eVwtmGHWl4iu/ymPc89d/4kmwflIIL3aYNCIyO7UaZHyRHLg8MrCZOZk4p/cY9CecHQStTZ2pnii7CeXzrckFa0JFwU6DKI192FbthJ3/F/9DZFWb10CIYVxzjWM7EwQtCzP9BAZQ2v89CxMh82arb6BgOnTWr55vH7UJFeKDQYSc/MT/VNnzhWCJZaLiJcB7RXwL2HFI6K/d7a5frcEEBGWhVACJjjqnFGBBlrOT1QMLeJX1Ru1sXqVsEYte8hg5/WzKs2LFmJcp/FqapQmpXa5vSKzgqD14GLij/LHA/2tTnS3Idb42A3rMDvm6ekrv/3gv/KFg+udrZv5cWLgX9QNktHBEUJNEQWVR1R7xAvdIo5SPrQxj7mu+wRsu8JXm8wXvTZFw9wJADOPUPrim6fU5JbGKhOVlIgePXisGYuh6doIl7ZKfdvwaFzOT2Fp+8KHmlmK6FPEGNEG9QaltbjIwg/XXmzjjTUfrSmgOeWay7e+MABTPnc2OUk+moSYKO1fhEgynVtd9xeeX7w+Rpcy6QL9Ut6Mz77/vLkZD0QviJReItBKajsIoKtrOGgHJ/R/z/XcdMsdbEwFweb3bp43B83jFKb0GeuWxhzzjtqIBeXnJvL8kGv3dXmDNM6BWi/JBs9r0Cyx1KCHSPDc3UIhk1FAOkKiu4a043D064M+IC+JqMcQT62eUw+uZ/dPh8x6rJIWSCRldOondtJDvKfsVYU/7gC73i31RD2SRZCj67JB8wFpXkOS+EjDFtkNvN8c2BJ0W8bMXE1UwKrPktOV6O/XpY6tsj+BqzaeU6DMPP7WVlrQ5NjLCUerxwTKXCcUqH00b8pkkvRZoBTz/nuhdBTsQWE9YZ2L/UTX38Y+eTNPOdBeBHkyTc/GHbvDOM5xsw8/Y4Mx4+NSDdrdWd0EL3uc9W16QmQKTzozRYJbSmat2xQNbGlOJRCUoX1FZoQXFJQfFNLjg3VzlhzFusAkxEICXS/6nOESDTH3xIw44vkegypd3xiizZ9RrhdEYiaU+0zfJp6p91v5czqUqRfnyKbLS9bv8/nHUq5HGz/AfumZKS2yXjHxSxYD/zbKc1Z88BsMvFXhOFD4GnN2Y5W0RP02XBwWDxP5BdWTfXB6dkgVw4HFDFnbmgeZWfc0AgRzZTuua5gCjGc0kmDYayJrojW7mGMTJYQJzwLCrKp2pDr5A6n8bNPCbCdp2RK6I8sgTyJjrX+2TbkMlulE/Vne1yKOdtdzkMeQ7jcO3rEK77pRymnmRtBxcp4DUEhkSHyfedXwr/9UewQPZ8eXWJOQPzJng3IrvY+L1diu0NBYu4qYCtNscNfkju52+wnluL2I8kOUWVPuDfRtF3tloaohl0nEnnXjyMuC+53+2F4MKNJRsE2eiPTVV1lfRuBgFfIcEI8q+E+GN3vXZ2lr3ouVt5bI5y1xZW8Sjt7zmPmSiyKkU3NZsL65b1PA718YO8i9+YBemw8VYfGfDn3JEc3f1P5WFYl0POYWWnCwlPe13J4ErZ8k3PBIuPGAqaE6W1d5yIkrLUnthDIOREghCve5L0HfguZZt+TUuHoq7iYLeJpYDYhGawnINJfUiZJH1MzYPixy+GZKyVBqZdr/dxPpdt/BVOsZ6WDNifkRrHaN18QrOJ4zFUAvFJDYq/1jYkLVflaoyxDlviOwAX/geIMRRTeDyZM9ucc0FG5h8qyeqoJQErMqaQT9BfvrvBI3JuRQiH5XuXRbz+uQMJljvhqs/lRhkeTWtMu9BdkEqlnyJskehE9qBzfLIw6lHYrtGs0NAPwN1m2Es+c502RAUp5nlIinJUR5/f7q2p7jgqVWuj1ifD7N2XoWFdMqM2+kb7suSYlY+gUPYK/Uz7T2as77U9OVzqS+udjWgdy3v/gfZOhuXhs0zrP/hBxswvSrpyhTq61bAAH7xOQGO3+IMxW4G4OgrfArNDMCflsFAgpktwmjkyTfM1YrZSEC9/65b1WE5lUi7r1Vx2PF0gogexigbz//Dp5MlfTsQkjRlLVv0rb6tnLXriCW9rdt2c491XRTMPR+348A9ckMYBbgRebXsfxVNrHK1ehgFT3C/vDbp4fXKGTNMITfvneJEN+RvfJFJW2JCNeAGwdqmpZJ5by+xlMP5a1K6eZNxnyqEhad/hfkvWMmBZo7dbuiDksFZm9iyaXJARGUsu+laEJClYyjEfhP9YvVdAs/5sL0NPCAw9OfqgUB+ZpFOFvtRun8E4Vmu4k4EZHgdW3bIrOmtUxFkkpOVQN+5EqmeiiB39dpOb8pn7KhhDLgnG8CTwA0Q9+WI3QtLA7BouOO49Y45K/7RrmKy1dgknDkv2Pe+7axcyI87UnY6XlpEaWrebS8YPlCpiAF8ZASKV93VDIx83RmhMe8SP6iiF2jYvXR6N7na6B9LW9/waV8U/1O8thqf45UgJ2LprQjjGYyXJ51VeFn0iRPEkyIygzdW02hq3COIWW2CAPIqxmtT3SuG7tqFb6Oa/QN2XS1d4ilSuEU7jIxkrvTVjQGtptVXFPxVylBLYVc6rsM+5gPHvQRpeg4t7OwbAJBPWvwa9dPIB01GdK0ppG6rTtNWvdtdzME1PSExjw035fI0OIC2AnMKqIufE0AkYYFO48ugN0Lg5SKSllypChiI2m80+wFDhe+X3AfX8t4pldQhdW84sV0mfWllfwqYhGU4LWOuIMYiK2Clx+9F2s8VwjSwRs7102mxu8f0vQoIq5A+7/Line truncated
|
||||
U0VOQwFCLraZiofXGk3ma3rfAp+AwimbD2xmPARjOXLQKQDASKq6WUdAn5Xu24Z6rJgFAocX+aoaxr7aEcSFrlFujCdvGz8V8xc24n8bf5xsAEXkLEYouPry356TXt0FXr6hMN0uJvih1b0zJQI2g0NP0Nqjb6W3QsusKfvxJdVSWCC6fXd8YVGjqXIBBB0TnReajLcbE6innfSbpK9bPioIuychW0VEPtytUTo/+z8xxIwZphis8Wx4zVUUm2b6CZVgbh/Uhxq54dkicULYd58KfsBgRaUscASNvjwgw6ggjvo7R1Wj47xm0L0nSFDPoERuOomxW0lI4ib5wfJ+3j2hBoueX5dHVMpVaGOZpL7RLvJf0AbBE8kwCL4hLxjBuatt95R+sfCpxHXu8hga1AzFKa2gL/IE6nzq5GMC5UKJ9JIhjmM6GxekM3c5yh+AbBgUxfv4Fa2OnRzNBvICB+xJfDSP3G0lE+OwkenYURIzMrW+gS24NXJ12rzhlyhEp0iAvr6wGAskcTpe9nXShyL9M69FXmCJuNZdenQv8pPr9zuw0M5b6BdKG9Tcp8j1Qm4BBA8J22Vd0uF7D6ByjpKkknbPdQMh3A/s09qix7t20eP/OGTh1JBZkOXxbSt5N/mjYUeLXAzqCYN0c3GsX6Za45OU618l4PO+kC223EdAjD4dWbN1CW65uJY0m2XckZr+2p3f9ow00BHnfzIZVG+aMSicaIJdGGudWdABVCsb7zvFr/Pv2pRWZjSOtSh2OrIkFeobEuqOFra1ifRCn6Y2/LChsPJBUqDwV4qDNjFouWL1JR59XntCn/Vcn94S9HmeP1gFS0ceOWGDDnaocbqCF3RL6SW9PN7GZCORjiyYhVZn6i7gIBIvmlg8mqmYYAaTGm9abwB278V2UJEn/YD/Hbr2krnVZEoEG73pk+oFGDRiY+G+cA2bpWhVt0bXKluanQJV1UTby0/RhbGGjhFMr+dPqHLRoeuLbnYkvcvLbdjz3vRXRbJdO3GARy81hWjPEZnvEaT0SR0683uMsCzCz3pWqL8BMIN2GuMIIsn7D0lZwb5eKrDjEZIkyVZhYiwX1kSsjK+JfIweRvxRoa2fCZ20tP5alIozh6m+Q2eWyzdxyRqXCHZkd8kUUT+XbLj5cw9tl3oINfwRUFYxAPwq/bhJS3bpl5ElPdo/ZKOKQuHpjt2nLdyXDYjXtpY9nUMKDO5in/bkqzSnSM52Va++1vaaYBtZnYx0v1HFoPtepx34pwkX0yjKIqIsHOzQVNNAYL5cQlzATMNISYsmne8c8ioRRuK07nyHGZhLroVaxJ2fgL6VQVjlxWmyeI9b+tBf3fRGtYwP3SwS1B4SYySFZ70bNZyROaQdE8Rin8mH7Pw8WquuCEE+LR63KLdC0QnV3iAr8d4aJSsYlDjqMXMASgtqof/jKCE2KZtCR+T2DrnXMhvgsRVwZ18Iufd9clv8hxrEUYx8D0sP+Ao9LJYAWGJ0Kt7GSfdwDLaRjL4jkToeFIImwIZPDpckCsraOcWD+vuR+kuuOBCtSxN+rm9pZ1VulMAG0KkkpydTeNPlbRuLbgfmwk8o7QQnmjcWL96sLQszm0JnYlQDHLRfAmaBj7L4JbsiGhCe5+2SfIrfqDCZhUYF+OwILtwXbhBGl5DcbCeRUSz9NUrz3ywF8TZa8TgBM89PiJb/pvMNrE7m+SmDJugiQ6UWcoYD9eC/katecM+b7KLGBYpO5qFx2+QpJff/YRhmHpz5O8UjJVKJK+xLAbvyiVs44OL+yJ5MIq8TUB7ojZDaTkpuwLKeezycktpzUENMbona5GbjvSaJWmD97TgBgAY9iP38h6lOHzKh0Mda5aVSWVn1Rq1pJ3IsZBPSC9QQe/p4DItw5aXeiMQwdozY5j95qICXfxvfnZP/MSIAyj9SZWKhNIuCDvOUxDHj2h4EZ6X+sCBAvhQG4YFAIzPqS8nnUIdgBtbStZBkQoY+n+m8qPsaYf7QdWeGPRI2vcfcCXyR9DvePV6ER3sTI2GKUUr61peCejc+cBwIWvqacr7Xl5QqTgTXGYvgu/Sh3FMws9iEPNScfd9K/hRbqTpJv4CeDu4fyFwTzuP/BHRQuv5pqJvzHdmTppwAfqAmo5pAWig9WpglQc+rWmlJYAtUvF7SIop/uXcH3r0xmlMilpc4PDMzaw3gu6kLIec63jrS0+cX5CD0DjfuT9nSgsdR8plkFi7UwtIRGhFO3B0gCIG+frznPAFUpm5KtnjjG1jIKsAXcfB1ZViS7/yHVcC4FeO4XOOJyVZSAImWKJ7ljGtpjLCK8BtiqrCuf26wlj3iw9jMm8wS5f+G+INg7bFgnlNRfqId2EeYJ21q9rODCCLMf2DUjJmVEuqk/grPparL3OgIV579+RUhXMUechv3zwkSdk/w5zyKyCc4j6tbAERg2KJP3CEQnCrdUeqMSdy06/prdkHnByPAX+7tx3JzVjOPxv3L7FNmahhTW6lWSJX2IR2VRwsP1UL6kf4pPeT9T5Ou47mmRy3CP+JLFDYt+3cQs9qYry+Xz2MfTJnyNJb7vGfPaQv/rPfJZyOmlFhQSzXfGtAPVF8srKnUNgdX6EJsw08rDZQhr0pCcu92VkNvNigzDtxIb+u+WYNprGb+sJFT+rtPQbP5v9+akyBw1Op7+Kek+S1XgK4PF+29QiEHKfPq4pgYnO5BLaUvNJVEImZV4nXM1ve2+YRDjtxRB0f2zBau0CfI+QpSfAHPk/COZojZU5Pdd/IiVPttEaSo7dvlhINIbmvTmHIA/XcHuOERmTpIZycVumSeKhDXxnahJzEeWZwDoxIkxIhFM94hLH6rc13fcAUvo3T+jKt7d9k13rF6dw+rd63+Bq83bBDHFero8tZmWdQ0Tpnv231EbSwv4L16N7J7ALtvPbnyNWR5wWzN9bc2/xglGys4txTcBt32P/dBR8QsBQ26CISfoElUR+vWQyo+OTOMP9sXyWPN0q2jC+EA/j+xg0TT2dW7RtkpjLR9uEMZpvJSMYnep+HtWw+6fns+W8kTV8zjv9cwod0TOA+qLbd3VCaQr/TDImqHigciRLV4NCLOTWGYuZiWbHCfikIyG4HBJlRgFumVTlgGKsVPRtdx5gqZBvZqaE2CSAtESC/O7q6ocoGx7cyLEs5Oq9sp2JZQPfxyLTtfG77OdAsr4KFFwGvgjH1Laz6rqw+DL15Ysj/WTl7yJ6toQ0KaRVTUf+3pNhpyCsqfWOLy4A8bMWAoPTdvh4sN+lOgNmHfe5Wym/UfR/UTz6cDGSrQgbSN3PXFzzSBM/Lm77MRljbBbFp0qXJAsteajVeXJX2JVFhGhQ8TzAUL3jhblbY0psVHuBoW9oyQ+UREc5/fH9hbRSDVcCr/5BWnY3Og3YOESOhHFx+lNFT+v96QU5lkat8b80llUwM/aJ8t+tzK+nyKhQwGgXpek6hVwnDhAFuwGXbxaCJNR5XJWrvChcn+m/5TDEm/U7mRblkiwEBm+i3mBDEioH9vHcRTu7wB+FoR6Q0FJbr1tm2lG3tvBg05pEglHkXrz//3iH61NjH251++zW93BFzngQLoRRBcreFfdiEP6VoHsVC5cFjzcnymLEdUtBp/ihbDZ3Tzn72c0oOzV8td4lgDDzxlJLZglwqj2Yx0yJLAPUAG7hJCWk+NbvyDsYSLWxn+ywOMH2onyh3pnPV7S3nKuJ3k6o52gdLmBOM6kHZvDmyTl4yua5zABGr6UWSHlgtCS1BRs8bH+RV79irRp1F8LUl8C+aENK1OlvD37kRRrlbZlqUV0cFib1ItRy2I69E2H1MfjgPE8gwksVmvX/JSGR6GC1SOFEqRRaGQtVAgSNrZ9W+qVpevtsK7Eytg2HVo8ZmPifWRZe5YOawhE7fFaih0/4gEoegRa6hDGK+X0uWao+95Vgtf1DosETrxlICRbDZT6oyqqWjGrIHi4X3ZSAgXF7VsZ+EeYRLRbJ84H8l552PnjXXPufQkOP3o6fFJYCMEnqowtqRhTIl5stzBbHLWVmQ6UCKPlhUHePsjI5snYy8/zuw6HRxYY+p6odEi0sn31PXO3RCeRBMtNQ5xWhddJK2KX33Ygc+qXBLSe3LG1PcbTCCf1H+E8x06JM5tVGG1WsmZnEIBxCpQUZN3/fUe65B37QYyxBwZDFwxetjthnT2E4WR1INRVUgJySBYrgHJr9PJF84dAdyrbXJsh2TckR4rCRYpOC4Yf4p/GqQim69YA09EIHA+9PgywDyiZ3lSKYHwrLgGZliiJx0envl2YlL9udzPcLzpjGOLzwTj2vpOAe3cDgscYGLPSUK76yqS1cPCXfz+xpmrvVFgUxRSx5i/hj4TFQotyI9sTfHTSXBJBvywpxC2GMoZrTSR+4ksLv2kLatRtVGnUHSAA/Lx6fbFKQleOqN3sFn9exSQAo3EWEA1wT/Uep6uSBWAg12Laf8l9hgoIniThbqv3D1AgfRth3aXfY5sK0S7HQfwCfbMWr2HSU0JydhxufKFV3z6aV1fCpXAgkXoZ151Brrpgi4urtwgFWfD4Cvlrq1SXM8aW2F84EpvOkADhrEvpzf2ZJ8w7mOzZxZCxoQ3CbBhjHjyfnoPMUMldvYctLobZxOBUqfwxC2SlcCyQCvlRLDs+M6z/qONNOhg29pZK368WHEbzUNmevtq7cleE4MGk2NU88Br99YPFc0qaxY+xDSaZKFDhERe+2QRNY3jTC07aK8tfoChkK4uahAghWDImK50i3DCLnUI5TlOaxkOaujA40QtEmnt5CNQuLeSCKtduT4rmDn2zDdep+BCCJlS1lJfonIhtDl/fCUT1Zj4Q/JWOlwUJDs+3yalPC78fqWTgHrNOREN/o5VRkOegZDz36eE6sFr4cpKfjSdeeojMb8MMKAFRAJce3MR6HflkKqEpTyVPMkeB/u48Z2wANGcYDwhqzi9c54DDjbSh1Vw4BbkuxgFUgdREipn1NJLine truncated
|
||||
@@ -42,7 +42,7 @@ body:
|
||||
- Finalize
|
||||
- Handoff
|
||||
- Web console (page itself)
|
||||
- Loop (plan2code-loop)
|
||||
- Implementation Loop (desktop app)
|
||||
- Metrics
|
||||
- Status line
|
||||
- Installer
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
name: app
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
# Run the full three-system matrix by hand on any branch.
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A newer push to a pull request replaces its still-running checks. A push to main always
|
||||
# finishes, so a merged change is never left half checked.
|
||||
concurrency:
|
||||
group: app-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
# Speed: a pull request runs on Ubuntu only (the cheapest runner) unless it carries the
|
||||
# `full-matrix` label; pushes to main and manual runs use all three systems. A change that
|
||||
# touches only the website, the README, the changelog or similar skips the heavy jobs and runs
|
||||
# the fast `prose` job instead, which keeps the checks that read those files.
|
||||
jobs:
|
||||
changes:
|
||||
name: changes
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
code: ${{ steps.diff.outputs.code }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4.2.2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- id: diff
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
case "${{ github.event_name }}" in
|
||||
pull_request) base="${{ github.event.pull_request.base.sha }}" ;;
|
||||
push) base="${{ github.event.before }}" ;;
|
||||
*) base="" ;;
|
||||
esac
|
||||
# A manual run, a new branch or a base git cannot find: run everything.
|
||||
if [ -z "$base" ] || [ "$base" = "0000000000000000000000000000000000000000" ] || ! git cat-file -e "$base^{commit}" 2>/dev/null; then
|
||||
echo "code=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
files="$(git diff --name-only "$base" HEAD)"
|
||||
echo "Changed files:"; echo "$files"
|
||||
# .readme/, AGENTS.md and .agents-docs/ are read by tests, so they count as code.
|
||||
if [ -n "$files" ] && ! echo "$files" | grep -qvE '^(docs/|prototypes/|README\.md$|CHANGELOG\.md$|QUICK-REFERENCE\.md$|LICENSE$)'; then
|
||||
echo "code=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "code=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
prose:
|
||||
name: prose checks
|
||||
needs: changes
|
||||
if: needs.changes.outputs.code == 'false'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4.2.2
|
||||
- uses: actions/setup-node@v4.4.0
|
||||
with:
|
||||
node-version: 20
|
||||
- name: Versions agree
|
||||
run: node scripts/check-versions.mjs
|
||||
- name: Spelling, install command in the docs, line endings
|
||||
run: node --test scripts/test-us-english.mjs scripts/test-getting-started.mjs scripts/test-line-endings.mjs scripts/test-check-versions.mjs
|
||||
|
||||
app:
|
||||
name: app (${{ matrix.os }})
|
||||
needs: changes
|
||||
if: needs.changes.outputs.code == 'true'
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: ${{ fromJSON(github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'full-matrix') && '["ubuntu-latest"]' || '["windows-latest","macos-latest","ubuntu-latest"]') }}
|
||||
defaults:
|
||||
run:
|
||||
working-directory: plan2code-app
|
||||
steps:
|
||||
- uses: actions/checkout@v4.2.2
|
||||
- uses: actions/setup-node@v4.4.0
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: plan2code-app/package-lock.json
|
||||
- name: Check the versions agree
|
||||
working-directory: .
|
||||
run: node scripts/check-versions.mjs
|
||||
- name: Install the pinned Rust toolchain
|
||||
shell: bash
|
||||
# clippy and rustfmt are not part of rust-toolchain.toml's minimal profile.
|
||||
run: rustup toolchain install "$(grep channel rust-toolchain.toml | cut -d '"' -f2)" --profile minimal --component clippy --component rustfmt
|
||||
- name: Cache the Cargo registry and build output
|
||||
uses: actions/cache@v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
plan2code-app/target
|
||||
key: cargo-${{ runner.os }}-${{ hashFiles('plan2code-app/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
cargo-${{ runner.os }}-
|
||||
- name: Name this week for the apt cache
|
||||
if: runner.os == 'Linux'
|
||||
id: week
|
||||
run: echo "week=$(date +%G-%V)" >> "$GITHUB_OUTPUT"
|
||||
- name: Cache the Linux system packages
|
||||
# The WebKit packages are hundreds of MB, and the runner's Ubuntu mirror is sometimes
|
||||
# slow (one download took 7 minutes), so keep the downloaded .deb files. The key rolls
|
||||
# over weekly so versions do not go stale; an older week still restores what it can.
|
||||
if: runner.os == 'Linux'
|
||||
uses: actions/cache@v6.1.0
|
||||
with:
|
||||
path: ~/apt-archives
|
||||
key: apt-tauri-${{ runner.os }}-${{ steps.week.outputs.week }}
|
||||
restore-keys: |
|
||||
apt-tauri-${{ runner.os }}-
|
||||
- name: Install Linux system packages
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
mkdir -p "$HOME/apt-archives/partial"
|
||||
sudo apt-get update
|
||||
sudo apt-get -o Dir::Cache::archives="$HOME/apt-archives" install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev xvfb
|
||||
# apt ran as root: hand the folder back so the cache step can read and save it.
|
||||
sudo chown -R "$(id -u):$(id -g)" "$HOME/apt-archives"
|
||||
- name: Install the app's packages
|
||||
run: npm ci
|
||||
- name: Vendor the xterm files cargo needs
|
||||
# `tauri build` runs this itself (beforeBuildCommand in tauri.conf.json); the cargo
|
||||
# steps below call straight into cargo and skip that, so they need it run by hand.
|
||||
run: node scripts/vendor.mjs
|
||||
- name: Format check
|
||||
run: cargo fmt --check
|
||||
- name: Lint
|
||||
run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
- name: Test
|
||||
run: cargo test --workspace
|
||||
- name: Build
|
||||
run: cargo build --workspace
|
||||
- name: Build the app (tauri build --no-bundle)
|
||||
run: npm run tauri -- build --no-bundle
|
||||
- name: Smoke-test the built app against the fake agent
|
||||
shell: bash
|
||||
# Points the real app at tests/agent_manager.rs's fake-agent fixture (already built
|
||||
# by the "Build" step above, in target/debug) and checks the real binary comes up and
|
||||
# stays up for a few seconds instead of crashing. Linux has no display by default.
|
||||
run: |
|
||||
exe=plan2code-app
|
||||
agent=fake-agent
|
||||
if [ "${{ runner.os }}" = "Windows" ]; then exe="$exe.exe"; agent="$agent.exe"; fi
|
||||
export PLAN2CODE_APP_AGENT_BIN="$(pwd)/target/debug/$agent"
|
||||
launch=("target/release/$exe")
|
||||
if [ "${{ runner.os }}" = "Linux" ]; then launch=(xvfb-run -a "target/release/$exe"); fi
|
||||
"${launch[@]}" &
|
||||
pid=$!
|
||||
sleep 5
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
echo "plan2code-app is still running after 5s; smoke test passed"
|
||||
kill "$pid"
|
||||
else
|
||||
wait "$pid"
|
||||
echo "plan2code-app exited within 5s (exit code $?); smoke test failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
node-tests:
|
||||
name: npm test (${{ matrix.os }})
|
||||
needs: changes
|
||||
if: needs.changes.outputs.code == 'true'
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: ${{ fromJSON(github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'full-matrix') && '["ubuntu-latest"]' || '["windows-latest","macos-latest","ubuntu-latest"]') }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4.2.2
|
||||
- uses: actions/setup-node@v4.4.0
|
||||
with:
|
||||
node-version: 20
|
||||
- name: Cache the npm downloads
|
||||
# setup-node's own cache needs a tracked lockfile and the root has none, so cache npm's
|
||||
# download folder directly (both places it lives: Linux and macOS, then Windows).
|
||||
uses: actions/cache@v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.npm
|
||||
~/AppData/Local/npm-cache
|
||||
key: npm-${{ runner.os }}-${{ hashFiles('package.json', 'plan2code-metrics/package.json') }}
|
||||
restore-keys: |
|
||||
npm-${{ runner.os }}-
|
||||
- run: npm install
|
||||
- run: npm test
|
||||
- name: Metrics tests
|
||||
working-directory: plan2code-metrics
|
||||
run: |
|
||||
npm install
|
||||
npm test
|
||||
@@ -0,0 +1,131 @@
|
||||
name: release-app
|
||||
|
||||
# Builds the desktop app on four systems when a GitHub release is published, or a v* tag is
|
||||
# pushed ahead of one, and attaches one file per system, named
|
||||
# plan2code-app-<version>-<os>-<arch>[.exe], plus one checksum file
|
||||
# (plan2code-app-<version>-SHA256SUMS.txt). install.js fetches the matching file and checks it
|
||||
# against that list. Linux ships the plain binary, not an AppImage: docs/desktop-app.md documents
|
||||
# its WebKitGTK 4.1 dependency instead. The first release is unsigned: docs/desktop-app.md says
|
||||
# how to allow it.
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
# Read-only by default: the build jobs run dependency install scripts and build scripts, so
|
||||
# only the publish job holds a write token.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A release published after its tag push starts a second run for the same tag: queue it behind
|
||||
# the first so two builds never upload over each other.
|
||||
concurrency:
|
||||
group: release-app-${{ github.event.release.tag_name || github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: build (${{ matrix.label }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { runner: windows-latest, label: windows-x64, built: plan2code-app.exe, suffix: .exe }
|
||||
- { runner: macos-latest, label: macos-arm64, built: plan2code-app, suffix: '' }
|
||||
- { runner: macos-15-intel, label: macos-x64, built: plan2code-app, suffix: '' }
|
||||
- { runner: ubuntu-latest, label: linux-x64, built: plan2code-app, suffix: '' }
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v4.4.0
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: plan2code-app/package-lock.json
|
||||
- name: Check the versions agree with the release tag
|
||||
env:
|
||||
TAG: ${{ github.event.release.tag_name || github.ref_name }}
|
||||
run: node scripts/check-versions.mjs --tag "$TAG"
|
||||
- name: Install the pinned Rust toolchain
|
||||
working-directory: plan2code-app
|
||||
run: rustup toolchain install "$(grep channel rust-toolchain.toml | cut -d '"' -f2)" --profile minimal
|
||||
- name: Cache the Cargo registry and build output
|
||||
uses: actions/cache@v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
plan2code-app/target
|
||||
key: cargo-release-${{ matrix.label }}-${{ hashFiles('plan2code-app/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
cargo-release-${{ matrix.label }}-
|
||||
- name: Install Linux system packages
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev
|
||||
- name: Install the app's packages
|
||||
working-directory: plan2code-app
|
||||
run: npm ci
|
||||
# One plain executable per system: the web page is built into it, so it needs no installer.
|
||||
- name: Build
|
||||
working-directory: plan2code-app
|
||||
run: npm run tauri -- build --no-bundle
|
||||
- name: Name the file
|
||||
run: |
|
||||
VERSION="$(node -p "require('./plan2code-app/src-tauri/tauri.conf.json').version")"
|
||||
mkdir -p dist
|
||||
cp "plan2code-app/target/release/${{ matrix.built }}" "dist/plan2code-app-${VERSION}-${{ matrix.label }}${{ matrix.suffix }}"
|
||||
- uses: actions/upload-artifact@v4.6.2
|
||||
with:
|
||||
name: app-${{ matrix.label }}
|
||||
path: dist/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish:
|
||||
name: attach to the release
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ github.event.release.tag_name || github.ref_name }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4.2.2
|
||||
- uses: actions/download-artifact@v4.3.0
|
||||
with:
|
||||
path: dist
|
||||
pattern: app-*
|
||||
merge-multiple: true
|
||||
- name: Verify every system's file is here
|
||||
run: |
|
||||
VERSION="$(node -p "require('./plan2code-app/src-tauri/tauri.conf.json').version")"
|
||||
cd dist
|
||||
missing=0
|
||||
for name in "plan2code-app-${VERSION}-windows-x64.exe" "plan2code-app-${VERSION}-macos-arm64" "plan2code-app-${VERSION}-macos-x64" "plan2code-app-${VERSION}-linux-x64"; do
|
||||
if [ ! -f "$name" ]; then
|
||||
echo "::error::missing release asset $name"
|
||||
missing=1
|
||||
fi
|
||||
done
|
||||
[ "$missing" -eq 0 ]
|
||||
- name: Write the checksum file
|
||||
run: |
|
||||
VERSION="$(node -p "require('./plan2code-app/src-tauri/tauri.conf.json').version")"
|
||||
cd dist
|
||||
sha256sum plan2code-app-* > "plan2code-app-${VERSION}-SHA256SUMS.txt"
|
||||
cat "plan2code-app-${VERSION}-SHA256SUMS.txt"
|
||||
- name: Make sure the release exists
|
||||
# A tag push alone names no release; create one (same tag, generated notes) so the
|
||||
# upload below always has somewhere to go, whichever trigger ran it.
|
||||
run: gh release view "$TAG" || gh release create "$TAG" --title "$TAG" --generate-notes
|
||||
- name: Attach to the release
|
||||
run: gh release upload "$TAG" dist/* --clobber
|
||||
@@ -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
|
||||
@@ -13,7 +10,7 @@ nul
|
||||
.cognition/
|
||||
handoffs/
|
||||
node_modules/
|
||||
package-lock.json
|
||||
/package-lock.json
|
||||
SYNC.md
|
||||
|
||||
# Generated by install.js/`npm run build:skills` from src/, regenerated on
|
||||
@@ -24,3 +21,8 @@ SYNC.md
|
||||
# Throwaway design prototypes (ai-assist-prototype). The decision they
|
||||
# recorded lives in the code and the CHANGELOG; the files stay local.
|
||||
prototypes/
|
||||
|
||||
# The Tauri app (plan2code-app/)
|
||||
plan2code-app/target/
|
||||
plan2code-app/src-tauri/gen/
|
||||
plan2code-app/ui/vendor/
|
||||
@@ -1 +1,2 @@
|
||||
node scripts/fix-line-endings.mjs
|
||||
node scripts/validate-char-count.js
|
||||
@@ -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)
|
||||
@@ -38,7 +38,7 @@ plan2code-metrics # → "View metrics status" the dashboard
|
||||
|------|--------------|
|
||||
| **1** | Raw data and a basic dashboard. Start here. |
|
||||
| **3+** | AI analysis unlocks. Pattern detection starts working. |
|
||||
| **5–10+** | Averages stabilise; generation-over-generation comparisons become meaningful. |
|
||||
| **5–10+** | Averages stabilize; generation-over-generation comparisons become meaningful. |
|
||||
|
||||
You're looking for trends, not individual scores.
|
||||
|
||||
@@ -46,7 +46,7 @@ You're looking for trends, not individual scores.
|
||||
|
||||
## Sending feedback upstream
|
||||
|
||||
`/plan2code-4-finalize` can submit an anonymised metrics payload to the maintainers as a
|
||||
`/plan2code-4-finalize` can submit an anonymized metrics payload to the maintainers as a
|
||||
`community-feedback` issue on the repo. Community runs are cohorted by the Plan2Code version that
|
||||
produced them, so your data improves the prompts everyone installs — without displacing the
|
||||
maintainer's own measurements.
|
||||
|
||||
@@ -17,16 +17,16 @@ On Pro / Max / Teams accounts, where rate limits are available:
|
||||
```
|
||||
╭───╮ Opus 5 / high │ plan2code │ feature/pathfinder-github-iss │ +12 -3
|
||||
│ ★ │ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
|
||||
╰┬─┬╯ 3h 5m ($4.62) │ ▰▰▰▰▰▱▱▱▱▱▱▱ 42% (84K) │ 5h: 28% · 7d: 61%
|
||||
╰┬─┬╯ 84k ⋅ ▰▰▰▰▰▱▱▱▱▱▱▱ 42% │ 5h: 28% · 7d: 61% | 3h 5m ($4.62)
|
||||
```
|
||||
|
||||
On Enterprise / Bedrock / Vertex / pay-as-you-go, where they aren't, the last segment becomes session
|
||||
On Enterprise / Bedrock / Vertex / pay-as-you-go, where they aren't, the usage segment becomes session
|
||||
token counts instead:
|
||||
|
||||
```
|
||||
╭───╮ Sonnet 5 │ plan2code │ main │ +12 -3
|
||||
│ ★ │ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
|
||||
╰┬─┬╯ 2m ($0.18) │ ▰▰▱▱▱▱▱▱▱▱▱▱ 18% │ 88k in · 3k out
|
||||
╰┬─┬╯ ▰▰▱▱▱▱▱▱▱▱▱▱ 18% │ 88k in · 3k out | 2m ($0.18)
|
||||
```
|
||||
|
||||
The icons down the left are Planny, the project mascot.
|
||||
|
||||
@@ -12,10 +12,17 @@ Each session stays short, and the specs on disk carry everything from one sessio
|
||||
- **Node.js 18 or newer.** Check with `node --version`. No Node? Get it from [nodejs.org](https://nodejs.org/) (the LTS download), or run `winget install OpenJS.NodeJS.LTS` on Windows, `brew install node` on macOS, or use `nvm` on Linux. Then open a new terminal.
|
||||
- **Start from your project.** Open your terminal in the project you want to work on (`cd` into it) before you run anything. Plan2Code works on the folder you start it in.
|
||||
- **Ways in.** `plan2code` (Claude Code, Devin or Codex), or type `/plan2code` in your agent (`$plan2code` in Codex).
|
||||
- **No agent yet?** Install Claude Code, Codex or Devin first.
|
||||
- **No agent yet?** Install Claude Code, Codex or Devin first, or let the `plan2code` command's setup page walk you through it.
|
||||
|
||||
Not installed yet? The install steps are in the [README](../README.md#install-and-start).
|
||||
|
||||
> **Running `plan2code` with no agent installed** opens a setup page instead of a dashboard: it
|
||||
> lists each built-in as found, found outside PATH or not found, with its install commands for
|
||||
> your system and an Install page link. Install one, press **Check again**, then **Start with
|
||||
> this agent** and the run carries on in the same tab. On a machine with no browser (over SSH, a
|
||||
> server) it prints the install steps instead and exits with code 127. The rest of this
|
||||
> walkthrough assumes an agent is already in place.
|
||||
|
||||
---
|
||||
|
||||
## Session 1: Plan
|
||||
|
||||
@@ -32,7 +32,7 @@ Every console request carries two extra fields:
|
||||
|
||||
Clicking **Approve** in the browser is then byte-identical to typing `approved` in the terminal. No prompt logic ever forks. If the console is absent, refused, or times out, the agent prints `fallbackText` and the session continues in the terminal with nothing lost. Mid-session switching in either direction is free, because the markdown files under `specs/` remain the only source of truth.
|
||||
|
||||
This one decision is what keeps the integration from metastasising across twelve prompt files.
|
||||
This one decision is what keeps the integration from metastasizing across twelve prompt files.
|
||||
|
||||
---
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -90,12 +90,12 @@ Both are cheap to enforce mechanically in the server's write path.
|
||||
```
|
||||
src/web-console/
|
||||
console.mjs CLI: open | post | wait | status | stop
|
||||
server.mjs the HTTP server (spawned detached by `open`)
|
||||
lib.mjs paths, atomic writes, patch merge, validate()
|
||||
server.mjs the HTTP server (spawned detached by `open`); routes.mjs lists its URLs
|
||||
files.mjs, sessions.mjs, patches.mjs, scan.mjs, ... paths, atomic writes, patch merge, validate(), the repo scan
|
||||
console.md the agent-facing contract
|
||||
public/index.html markup shell only
|
||||
public/app.js the client (no inline script, see CSP below)
|
||||
public/app.css
|
||||
public/app.js the client's entry (no inline script, see CSP below); screens/ and state.js hold the rest
|
||||
public/styles/ the stylesheet, joined by the server into /app.css
|
||||
public/render.js markdown tokens to DOM nodes
|
||||
public/vendor/marked.esm.js pinned 15.0.7, MIT, lexer only
|
||||
```
|
||||
@@ -152,22 +152,22 @@ The waiter uses `fs.watch` on the session **directory** (watching a file breaks
|
||||
| --- | --- |
|
||||
| Port | `listen(0, '127.0.0.1')`, handle file in `os.tmpdir()/<tool>/<sha1(cwd).slice(0,8)>/`. This is Jupyter's `jpserver-<pid>.json` pattern and RFC 8252 §7.3. A fixed port is fatal here: you run git worktrees, so two agents in two checkouts of one repo is routine, and a fixed port makes that silently wrong. |
|
||||
| Bind | the literal `127.0.0.1`, never `0.0.0.0`, never the string `localhost` (which may resolve to `::1` and produce the classic "server is up but the browser gets ECONNREFUSED" bug on Windows). |
|
||||
| Auto-open | best-effort, never fatal. Skip when `DISPLAY` and `WAYLAND_DISPLAY` are both unset, or `SSH_CONNECTION` / `REMOTE_CONTAINERS` is set. Honour `BROWSER=` and `--no-open`. |
|
||||
| Auto-open | best-effort, never fatal. Skip when `DISPLAY` and `WAYLAND_DISPLAY` are both unset, or `SSH_CONNECTION` / `REMOTE_CONTAINERS` is set. Honor `BROWSER=` and `--no-open`. |
|
||||
| Orphan prevention | a **server-side idle deadline** (30 min, bumped by any authenticated request) is the mechanism, not a nicety. Windows has no real SIGTERM, and a detached server with no console never sees `SIGINT`, so signal handlers cannot be relied on. Plus a 4h absolute cap, a `pagehide` beacon, an explicit `stop`, and a reap sweep on every `start`. |
|
||||
| Liveness test | `process.kill(pid, 0)` **and** a `/health` check whose returned session id matches the handle. PID reuse is real; the sid match is what disambiguates. |
|
||||
|
||||
Security, six controls, about 60 lines:
|
||||
|
||||
1. Bind `127.0.0.1`.
|
||||
2. **`Host` header allowlist.** This is the DNS-rebinding defence and the highest-value line in the server. Vite shipped GHSA-vg6x-rcgg-rjx6 for exactly this omission.
|
||||
2. **`Host` header allowlist.** This is the DNS-rebinding defense and the highest-value line in the server. Vite shipped GHSA-vg6x-rcgg-rjx6 for exactly this omission.
|
||||
3. 128-bit token **in the URL path**, not the query string. Path placement also kills the Windows `cmd /c start` `&`-injection hazard, because the URL then contains no `&`.
|
||||
4. First `GET /s/<token>/` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free.
|
||||
5. `Origin` check on every mutating request.
|
||||
6. Strict CSP with no `unsafe-inline`, which is why JS and CSS are separate files rather than one inlined HTML.
|
||||
|
||||
**On whether XSS matters here.** The tempting argument is "it is the user's own machine and the model would not write `<script>`". That misses the real risk. The page is same-origin with a server that reads and writes the user's files and holds the session token, so script in that page can post arbitrary answers back to the agent, which then acts on them with the agent's full tool permissions. And the markdown is only nominally agent-authored: in practice the agent is summarising a dependency README, a scraped page, a PR description, a log. Treat it as attacker-controlled.
|
||||
**On whether XSS matters here.** The tempting argument is "it is the user's own machine and the model would not write `<script>`". That misses the real risk. The page is same-origin with a server that reads and writes the user's files and holds the session token, so script in that page can post arbitrary answers back to the agent, which then acts on them with the agent's full tool permissions. And the markdown is only nominally agent-authored: in practice the agent is summarizing a dependency README, a scraped page, a PR description, a log. Treat it as attacker-controlled.
|
||||
|
||||
The structural fix, rather than a filter: **vendor `marked` for `lexer()` only and render tokens to the DOM with `createElement` and `textContent`.** No HTML string is ever produced, so there is nothing for a sanitiser bypass to bypass, and the strict CSP holds. Roughly 120 lines of renderer. Hand-rolling the parser instead is a trap: hand-rolled markdown fails exactly where agent-authored technical documents live (a table inside a list item, a fenced block containing backticks) and its failure mode is usually an injection hole.
|
||||
The structural fix, rather than a filter: **vendor `marked` for `lexer()` only and render tokens to the DOM with `createElement` and `textContent`.** No HTML string is ever produced, so there is nothing for a sanitizer bypass to bypass, and the strict CSP holds. Roughly 120 lines of renderer. Hand-rolling the parser instead is a trap: hand-rolled markdown fails exactly where agent-authored technical documents live (a table inside a list item, a fenced block containing backticks) and its failure mode is usually an injection hole.
|
||||
|
||||
### 3.4 Browser transport
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -223,7 +223,7 @@ Recovery matrix:
|
||||
}
|
||||
```
|
||||
|
||||
Note `recommended` is **optional per option**. Handoff explicitly wants its inferred task offered as the recommendation; the `.gitignore` question in handoff explicitly does not ("present it, don't force it").
|
||||
Note `recommended` is **optional per option**. Handoff explicitly wants its inferred task offered as the recommendation.
|
||||
|
||||
### 4.2 Primitives
|
||||
|
||||
@@ -283,7 +283,7 @@ Three panes, plus view tabs, closer to pathfinder's own vocabulary than to a gri
|
||||
### What to take from grill-with-ui
|
||||
|
||||
- **Batch staging with one explicit Send.** Everything is local and reversible until one deliberate press. For a non-technical user this removes the terror of "did I just commit to that?"
|
||||
- **The three-tier commitment vocabulary**: staged (amber, removable) → sent and pending (dashed, spinner) → recorded (green check). Honoured consistently on every surface.
|
||||
- **The three-tier commitment vocabulary**: staged (amber, removable) → sent and pending (dashed, spinner) → recorded (green check). Honored consistently on every surface.
|
||||
- **The whole stuck-agent apparatus**: live elapsed counter, disabled Send while working, a five-minute grace that re-enables Send with an explanation, server-gone detection with self-reconnect. About 40 lines, and more honest about agent latency than most commercial agent UIs.
|
||||
- **Assumed regions.** The best idea in that repo: the generated artifact marks regions that depend on still-open questions with a dashed outline and "assumed, pending Q3". This transplants directly onto a plan taking shape.
|
||||
- **Versioned artifacts with a staleness flag** and a one-line change note.
|
||||
@@ -308,14 +308,14 @@ Three panes, plus view tabs, closer to pathfinder's own vocabulary than to a gri
|
||||
|
||||
Built for a mixed product and engineering room reading one screen together.
|
||||
|
||||
- **One width variable.** `--card-width` on `:root` in `app.css` sets the column the card, the pager and the document tabs share (`max-width: min(var(--card-width), 100%)`, so a narrow window still wins); no fixed `720px` column rule is left outside a media query. Three presets, picked under *Card width* in the looks panel and saved as `looks.width`: `narrow` 720px, `comfortable` 880px (the default, and the variable's own value), `wide` 1080px, applied as `:root[data-width="…"]`. `CARD_WIDTHS` in `palette.js` is the same list for the page's validation and the server's first-paint `data-width`; **`palette.js` and `app.css` must agree**, which is the one place the number is written twice. The dashboard keeps its own 860px layout. Inside the card the `62ch` / `68ch` measure caps come off (`.card .md, .card .prompt { max-width: none; }`) so a wider card is not a narrow column in a wide frame; documents keep `.md`'s 68ch.
|
||||
- **One width variable.** `--card-width` on `:root` in `styles/tokens.css` sets the column the card, the pager and the document tabs share (`max-width: min(var(--card-width), 100%)`, so a narrow window still wins); no fixed `720px` column rule is left outside a media query. Three presets, picked under *Card width* in the looks panel and saved as `looks.width`: `narrow` 720px, `comfortable` 880px (the default, and the variable's own value), `wide` 1080px, applied as `:root[data-width="…"]`. `CARD_WIDTHS` in `palette.js` is the same list for the page's validation and the server's first-paint `data-width`; **`palette.js` and `app.css` must agree**, which is the one place the number is written twice. The dashboard keeps its own 860px layout. Inside the card the `62ch` / `68ch` measure caps come off (`.card .md, .card .prompt { max-width: none; }`) so a wider card is not a narrow column in a wide frame; documents keep `.md`'s 68ch.
|
||||
- **One box grows.** On the primary card, the answer box that is being typed in — a `text` question's box, a choice's *Something else* box once picked, or the note under a verdict / confirm / recap once shown — is `textarea.grow`, and the card takes the column's full height above the pager (`.card.is-primary.has-grow { flex: 1 1 auto; }`). `fitGrowBox()` in `app.js` writes the card's free height as the box's `min-height`, **never under 160px**; a `ResizeObserver` watches the main column rather than the box, so the box growing can never retrigger it, and it writes only on a change over 1px. `resize: vertical` with that moving floor makes the handle taller-only; past the fill the card scrolls. Every other box keeps its ordinary size, and the notes panel is untouched.
|
||||
- **A switch per sound.** Every cue is an event in `SOUND_EVENTS` (`palette.js`), each naming its file and rank: `startSkill` (`start-skill.mp3`, played once the dashboard's **Start** is accepted) 5, `bootup` 4, `sessionStart` / `sessionEnd` (`start-stop.mp3`) 3, `question` / `skillReady` / `chatReply` (`next.mp3`) 2, `newTab` (`insert.mp3`) 1, `snore` (`sleeping.mp3`, looped by the wake-up outside the queue) 0. The queue, the held slot and the one-at-a-time rule in `app.js` work on events, one `Audio` per file shared by the events that use it. User Preferences shows a *Play sounds* master (`looks.sound`) over one box per event, saved flat as `sound<Event>` (`soundStartSkill`, …) because `looks.json` only holds flat values; `soundPrefs()` turns any missing or non-boolean switch on, so a file from before the switches keeps every sound. A cue plays only while the master and its own switch are both on; the master off greys the boxes but keeps their ticks, and ticking a box plays it.
|
||||
- **A switch per sound.** Every cue is an event in `SOUND_EVENTS` (`palette.js`), each naming its file and rank: `startSkill` (`start-skill.mp3`, played once the dashboard's **Start** is accepted) 5, `bootup` 4, `sessionStart` / `sessionEnd` (`start-stop.mp3`) 3, `question` / `skillReady` / `chatReply` (`next.mp3`) 2, `newTab` (`insert.mp3`) 1, `snore` (`sleeping.mp3`, looped by the wake-up outside the queue) 0. The queue, the held slot and the one-at-a-time rule in `app.js` work on events, one `Audio` per file shared by the events that use it. User Preferences shows a *Play sounds* master (`looks.sound`) over one box per event, saved flat as `sound<Event>` (`soundStartSkill`, …) because `looks.json` only holds flat values; `soundPrefs()` turns any missing or non-boolean switch on, so a file from before the switches keeps every sound. A cue plays only while the master and its own switch are both on; the master off grays the boxes but keeps their ticks, and ticking a box plays it.
|
||||
- **Send breathes.** `#btn-send:not(:disabled)` runs `send-pulse`, a soft accent ring that spreads and fades every 2.4s; a disabled Send is still, and reduced motion switches it off.
|
||||
- **Per-tab scroll memory.** An in-memory `Map` keyed by view id holds the scroller's position (the main column on a document or the Overview, the card on the questions view, with the item it belonged to), restored when the tab comes back. Page-local, never persisted, cleared when the session turns into or out of the dashboard.
|
||||
- **The Overview tab.** Appears only while `GET /overview` returns a file for the session's spec (on the dashboard: the picker's spec; gone for *start from scratch*), fetched with `no-store` on load, on a spec change and on every tab click, so it always shows the file as it is on disk. Rendered through the same DOM-only markdown path as every doc, captioned read-only. It never becomes a doc: the page is not the record.
|
||||
- **The footer slot.** The workspace label sits centred in the footer's middle track, 12px and muted: `footerLabel()` in `public/workspace.js` builds `folder · branch` (from the workspace's original folder and `state.branch`), or `folder + N folders · branch` once folders are added, and `renderWhere()` steps down through its narrower tiers (`FOOTER_TIERS`) until the text fits. A warning dot marks a missing or unreadable folder. A click opens the Workspace dialog (`#workspace-modal`), where each folder has its own **Copy path**. The notification pill is fixed over the same spot and covers it while it shows, on purpose: nothing there needs pressing while the pill is up. The dashboard keeps the footer for this label alone: `renderFooter()` puts `is-dash` on it, which hides the summary and Send (and on a narrow screen keeps the label, the one thing left in the bar); the footer only disappears there when there is no label to show.
|
||||
- **The wake-up.** A fresh dashboard (`state.wake`, plus a per-sid `sessionStorage` guard) plays Planny powering on centre stage, as proven in `pathfinder/sketch-01`. The wake layer hides the dashboard behind a solid `var(--bg)` backdrop (`.wake::before`, so it follows the theme) whose opacity fades out over the same 0.6s as the glide, revealing the menu as he lands; the notification pill (`.banner`, z-index 46) stays above the layer (45). Before the first click or key he sleeps there on loop under a "Click to wake Planny" hint (`.wake.dormant`): Z's rising, slow breathing, slack arms swaying out of step, his feet pulsing like a standby light. While he sleeps the page tries to loop `sleeping.mp3` (browsers usually refuse until the first click, so this is normally silent). That click fades the hint and nudges him (`.wake.stirring`): he rocks gently about his feet (`wake-nudge`) while exactly one snore plays from the top, via the `stir()` callback `playWake()` awaits — timed by the snore's `ended`, capped at 6s, or a 2.6s timer when sounds are off or refused. Then the boot starts to `bootup.mp3` (in place of the opening chime; outranked only by the Start-skill cue, which cannot coincide with it because the wake layer swallows every click and key until the run ends), which fades out over 0.5s the moment the run ends or is aborted. The boot pops the Z's outward: 0.4s power-on and his feet blink · 1.35s feet plant · 1.5s / 1.9s arms lift off his sides · 2.5s the star opens lit, with a scan · 2.85s he glances left, right, then ahead · 3.2s smile · 3.6s hop and a cheer, star back to ink · 4.3s a 0.6s glide into the rail, measured once by `boot.js` and handed to CSS as `--wake-glide` · the menu groups rise in 60ms apart as he lands, and the note types in. Done by 5s (a fallback timer covers a hidden tab whose transition never fires). The beats are CSS keyframes on delays under `.wake.booting`, all inside `@media (prefers-reduced-motion: no-preference)`; there is no skip: from the waking click on, clicks and plain keys (no Ctrl/Meta/Alt) are swallowed so the nudge, boot and sound always play out; only a launch mid-run aborts it (snore stopped, boot-up faded), and under reduced motion `playWake()` resolves at once and the awake dashboard is simply there.
|
||||
- **The Overview tab.** Appears only while `GET /overview` returns a file for the session's spec (on the dashboard: the picker's spec; gone for *start from scratch*), fetched with `no-store` on load, on a spec change and on every tab click, so it always shows the file as it is on disk. On the dashboard, a spec with no overview gets a **Map** tab (`?file=map`, `pathfinder/map.md`) and a **Plan draft** tab (`?file=draft`, the live `PLAN-DRAFT-*.md`) in its place, each while its file exists, fetched and drawn the same way; away from the dashboard only the overview is read, since a session's own map or draft is the work already in front of it. Rendered through the same DOM-only markdown path as every doc, captioned read-only. It never becomes a doc: the page is not the record.
|
||||
- **The footer slot.** The workspace label sits centered in the footer's middle track, 12px and muted: `footerLabel()` in `public/workspace.js` builds `folder · branch` (from the workspace's original folder and `state.branch`), or `folder + N folders · branch` once folders are added, and `renderWhere()` steps down through its narrower tiers (`FOOTER_TIERS`) until the text fits. A warning dot marks a missing or unreadable folder. A click opens the Workspace dialog (`#workspace-modal`), where each folder has its own **Copy path**. The notification pill is fixed over the same spot and covers it while it shows, on purpose: nothing there needs pressing while the pill is up. The dashboard keeps the footer for this label alone: `renderFooter()` puts `is-dash` on it, which hides the summary and Send (and on a narrow screen keeps the label, the one thing left in the bar); the footer only disappears there when there is no label to show.
|
||||
- **The wake-up.** A fresh dashboard (`state.wake`, plus a per-sid `sessionStorage` guard) plays Planny powering on center stage, as proven in `pathfinder/sketch-01`. The wake layer hides the dashboard behind a solid `var(--bg)` backdrop (`.wake::before`, so it follows the theme) whose opacity fades out over the same 0.6s as the glide, revealing the menu as he lands; the notification pill (`.banner`, z-index 46) stays above the layer (45). Before the first click or key he sleeps there on loop under a "Click to wake Planny" hint (`.wake.dormant`): Z's rising, slow breathing, slack arms swaying out of step, his feet pulsing like a standby light. While he sleeps the page tries to loop `sleeping.mp3` (browsers usually refuse until the first click, so this is normally silent). That click fades the hint and nudges him (`.wake.stirring`): he rocks gently about his feet (`wake-nudge`) while exactly one snore plays from the top, via the `stir()` callback `playWake()` awaits — timed by the snore's `ended`, capped at 6s, or a 2.6s timer when sounds are off or refused. Then the boot starts to `bootup.mp3` (in place of the opening chime; outranked only by the Start-skill cue, which cannot coincide with it because the wake layer swallows every click and key until the run ends), which fades out over 0.5s the moment the run ends or is aborted. The boot pops the Z's outward: 0.4s power-on and his feet blink · 1.35s feet plant · 1.5s / 1.9s arms lift off his sides · 2.5s the star opens lit, with a scan · 2.85s he glances left, right, then ahead · 3.2s smile · 3.6s hop and a cheer, star back to ink · 4.3s a 0.6s glide into the rail, measured once by `boot.js` and handed to CSS as `--wake-glide` · the menu groups rise in 60ms apart as he lands, and the note types in. Done by 5s (a fallback timer covers a hidden tab whose transition never fires). The beats are CSS keyframes on delays under `.wake.booting`, all inside `@media (prefers-reduced-motion: no-preference)`; there is no skip: from the waking click on, clicks and plain keys (no Ctrl/Meta/Alt) are swallowed so the nudge, boot and sound always play out; only a launch mid-run aborts it (snore stopped, boot-up faded), and under reduced motion `playWake()` resolves at once and the awake dashboard is simply there.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -42,9 +36,12 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line
|
||||
|
||||
## Web Console
|
||||
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a built-in 17-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) a **Subagents** button in the top bar turns helpers on or off per project and skill (off by default, saved in `~/.plan2code/console/subagents.json`); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console.md` → Standing instructions). The agent-facing contract is `console.md` / `building.md`; the server never writes into a project.
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker page of game cards once two are listed that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest<Id>` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 21-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, Finalize, Changelog, Git and Handoff) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the twelve helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; taskLine truncated
|
||||
|
||||
One agent list and one lookup rule serve the launcher, the console and the app: `src/launcher/agents.json` (the built-ins and starter templates with per-OS install data) and `src/web-console/agent-lookup.mjs` (`loadAgentList()` and `findAgent()`, both copied by `install.js` into `~/.plan2code/bin/`); the app carries a Rust twin held to the same cases by `scripts/fixtures/agent-lookup-cases.json`.
|
||||
Building or changing an Activities game: follow the game rules in [Architecture](./.agents-docs/AGENTS-architecture.md) ("Building an Activities game": lives in the solid lives pill, the endless-lives code (`cheat(on)`) in every game with lives, banners placed away from the player and see-through over what matters, pausing left to the window).
|
||||
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
||||
Why the agent-facing console docs are shaped as they are (the card, pointers, refusals): [Web Console Contract](./.agents-docs/AGENTS-web-console-contract.md); it never ships.
|
||||
|
||||
## Skill Scripts
|
||||
|
||||
@@ -56,19 +53,21 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Skill Script
|
||||
|
||||
Build commands, installer menu options, non-interactive skill-build verification, skills CLI delegation, skill format, and how to edit workflow prompts.
|
||||
|
||||
Run the targeted suites for the part you changed, not the full `npm test`, when a change stays inside one area (a game, one console page, the launcher, one skill script); the full run is for changes to shared code, sync merges, version bumps and before a PR. The area-to-suite table is in "Targeted tests first".
|
||||
|
||||
Details: [Development Commands](./.agents-docs/AGENTS-development-commands.md)
|
||||
|
||||
## Code Style & Gotchas
|
||||
|
||||
Language/toolchain conventions for `install.js` vs TypeScript packages, and pitfalls to avoid (version sync, `.gitignore` pre-flight, character limits, User Feedback table format).
|
||||
Language/toolchain conventions for `install.js` vs TypeScript packages, US English spelling, and pitfalls to avoid (version sync, `.gitignore` pre-flight, character limits, User Feedback table format).
|
||||
|
||||
Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
|
||||
|
||||
## Mascot
|
||||
|
||||
The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` (and `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 colour 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 `app.js` switches mood with a single class, so the drawing stays in the markup and the styling in `app.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight color and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. Every skill start pose, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||
|
||||
```
|
||||
╭───╮
|
||||
@@ -83,10 +82,13 @@ The `Failure log` section below is a recording of mistakes made by previous AI A
|
||||
|
||||
When you make a mistake, get corrected, or discover something about this codebase that wasn't written down:
|
||||
|
||||
1. Add one line to the `Failure log` below, in the imperative, describing the correct behaviour.
|
||||
1. Add one line to the `Failure log` below, in the imperative, describing the correct behavior.
|
||||
2. Keep it specific to this repo. General advice belongs nowhere.
|
||||
3. If this fix is a workflow rather than a rule, put it in `.claude/skills/` and link it from here.
|
||||
4. Include the change in the same commit and mention it in your summary.
|
||||
5. A skill rule broken twice becomes a script check (a `scripts/` test or a skill-script check), not more prose.
|
||||
6. Before adding a line, look for one on the same topic: sharpen or extend that one rather than adding a near-duplicate.
|
||||
7. Keep the log to 17 entries at most. Over the cap, first merge entries that share a cause, then drop the lowest-value ones: one-offs unlikely to recur, rules a test or script now enforces, and entries about code that no longer exists.
|
||||
|
||||
## Failure log
|
||||
|
||||
@@ -94,6 +96,16 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
- Sync upstream only through `/sync-repo`, and verify its baseline against the real tree before porting: an earlier sync silently skipped a whole upstream release (the `3-implement-review` skill) while the recorded version froze. Update the baseline with `.claude/skills/sync-repo/set-synced.mjs`, never with a shell pipe over the decrypted body.
|
||||
- After a sync merge, run `npm test` before trusting a "clean" file: when upstream and plan2code fixed the same bug, `git merge-file` keeps both copies without a conflict (a sync once left `let pattern` declared twice in `app.js`, caught only by `parse-check`).
|
||||
- When extracting upstream files in Git Bash, run `git show <ref>:<path>` with `MSYS_NO_PATHCONV=1` and `C:/` style paths (never `/c/`): path conversion rewrites `origin/main:.readme/x.md` into `origin\main;.readme\x.md`, the show fails, and the merge silently runs against an empty "theirs". Check every extracted file is non-empty before merging.
|
||||
- After a sync, grep the result for the upstream owner slug and company name in any case (the `/sync-repo` body lists them): the rebrand map only rewrites URLs, so a bare owner slug once slipped through into `feedback-payload.mjs` (and its test) until it was fixed by hand to `jparkerweb/plan2code`. No upstream name may appear in plain text anywhere in this repo.
|
||||
- After a sync, grep the result for every upstream name the rebrand map can miss (the `/sync-repo` body lists them): the owner slug and company name in any case, the bare brand word inside identifiers and fixtures, and the ticket key followed by anything, not only digits. Each slipped through once: an owner slug in `feedback-payload.mjs` and its test (fixed by hand to `jparkerweb/plan2code`); in v2.7.0 a `KEPT_<BRAND>_ENTRIES` constant, a `<brand>Dir` option, a `"<brand>"` test folder and an owner slug in a git remote URL; in v2.8.0 git board fixtures built as `` `feature/<KEY>-${11000 + i}-…` `` template literals, which a digits-only rewrite to `ABC-<n>` misses. No upstream name may appear in plain text anywhere in this repo.
|
||||
- Keep plan2code's ticket-free `commit-msg.mjs` (`<subject>`, `AI Assisted`) in every `/sync-repo`: upstream's ticket-from-branch rule was ported by mistake once and removed in v2.6.0.
|
||||
- When a new first-run dialog is added to the web console, set its seen flag in `scripts/capture-screenshots.mjs`'s `looks.json` too: the Welcome dialog once covered the regenerated dashboard screenshots until `welcomeSeen: true` was added.
|
||||
- Import `scripts/skill-script-helpers.mjs` in any test that builds git fixtures for a skill script or `git-repo.mjs`: it scrubs the whole test process's git config, so fixtures, imported modules and spawned scripts agree. Mixed configs broke `git plan switch` once (a global `core.autocrlf=true` checked fixtures out with CRLF the scrubbed script read as changed). It also rebuilds `skills/` and prunes any skill folder `install.js` does not list, so register a new skill in `SOURCE_PROMPTS` before running its `scripts/test-script-<name>.mjs` or the script under test vanishes.
|
||||
- Before deleting a test file that upstream split or removed, diff plan2code's copy against the rebranded upstream base and port the plan2code-only tests: v2.7.0's split of the web console suite would otherwise have dropped seven hardening tests (now in `scripts/test-web-console-hardening.mjs`).
|
||||
- When a `CHANGELOG.md` heading gets a version number, set the same number in `version.json` (with its `releaseDate`), the root `package.json` and README's `Version X.Y.Z` line in the same change, then run `npm run build:skills`. The changelog skill only touches `package.json`: v2.9.0 nearly shipped with `version.json` at 2.8.1, and README's line sat at 2.6.0 for three releases.
|
||||
- When a page test (`scripts/test-web-console-page-*.mjs`) fails only on CI or only in a full run, look for a race with a redraw before suspecting the change, and fix the test, not the timeout: read styles and set scrolls through `styleOf()`, `stylesOf()` and `scrollCard()` in `page-test-helpers.mjs` (a card a redraw replaced reads "" for every style and scrolls nothing; `test-web-console-shape.mjs` now fails a raw `locator.evaluate` that does either), and wait for the page to hold what the next step needs before acting (the workspace frame before typing `@`, the notepad's drawn marks, a newly selected tab). Keep `npm test`'s file concurrency under `scripts/node-test.mjs`'s cap of one file per spare core: a flat `--test-concurrency=8` ran 8 browsers on 3 and 4 core runners and failed a different page test on every CI run. On a busy local machine, rerun the failing files alone first; the chat stress test and the session suite's "no submitted frame within 5s" cascade still fail that way under load.
|
||||
- Run `npm test` and `cargo test` from a terminal outside the desktop app, or with `PLAN2CODE_IN_APP`, `PLAN2CODE_APP_TOKEN`, `PLAN2CODE_APP_VERSION`, `PLAN2CODE_APP_ANNOUNCE`, `PLAN2CODE_EMBED_ORIGIN` and `PLAN2CODE_CONSOLE_SID` unset (`env -u ... npm test`): inherited from the app they fail about 34 tests that check behavior outside the app (the update banner, the terminal line, cookies, open's browser launch), and a test console announces itself to the live window. A `cargo test` run mid-build once took the window over that way, then left an agent-less dashboard in it, and the build's question was never seen. The app now ignores sessions outside its console store (`take_announced` in `main.rs`), and the Rust console tests scrub the variables, but the JS suites do not. Before pushing a change under `plan2code-app/`, also run `cargo fmt --check` and `cargo clippy --workspace --all-targets -- -D warnings` there, not only `cargo test`: CI's `app` workflow fails on either, and the Rust code once reached a PR never formatted (20 files) with three clippy errors, one only macOS and Linux could see (see plan2code-app/README.md "Tests"). `loop_driver` tests failing with `never saw ... agent generations` and no `ARGS` line in the output mean `target/debug/fake-agent` is older than its source (a file restored with an old time, so Cargo never rebuilds it): `touch plan2code-app/fake-agent/src/main.rs` and rerun. A stale binary once read as 2 real failures in PR Prep.
|
||||
- Never fix CRLF by hand, one file at a time: run `npm run fix:eol` (`scripts/fix-line-endings.mjs`). Windows Python in text mode, among other tools, writes CRLF into files git keeps as LF; a whole session's edits once came out CRLF and 14 other files were found the same way. It now also runs as `pretest`, in the pre-commit hook and after every agent Write or Edit (see the LF gotcha in Code Style).
|
||||
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
|
||||
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → System → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
|
||||
- When a test checks how `cmd.exe` finds a `.cmd`/`.bat` (current folder before PATH), clear `NoDefaultCurrentDirectoryInExePath` for the run under test (`env_remove` in Rust, `undefined` in a `test-launcher.mjs` `box.run` env): some shells (Claude Code's among them) already set it, and the decoy `.cmd` test for custom agents passed without its fix until it did.
|
||||
- On Windows, treat a console the agent opened as dying with the agent: the app ends the agent's whole Job Object, so a `detached` server goes too, with no `exit` event. A `console.mjs post` still succeeds because it writes the session's files, so it proves nothing about the server; only the window's reconnect brings the page back. Every loop phase ends this way, and a reconnect budget that never refilled once lost the loop's stop card after Phase 3.
|
||||
@@ -2,6 +2,212 @@
|
||||
|
||||
All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
## v3.0.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **desktop app**: a cross-platform app (Rust, Tauri) that is the single window for working with an AI agent. It opens the Plan2Code dashboard as its main surface and runs Claude Code, Devin, Codex or your own agent in a terminal panel it owns, with every console page (Ask, Workspace, Help, Preferences, Git, Notebook) inside the window. **New Session** replaces the agent with a fresh one on a brief the app builds from its own record of the session, so in-progress work carries over. **Update skills** brings the installed skills level with the app, and the taskbar shows when Plan2Code needs you. `plan2code` opens the app when a desktop is available; `plan2code --classic` keeps the terminal-only flow.
|
||||
- **implementation loop**: the app builds a spec phase by phase, each phase in a fresh agent, and writes a report. **Set strength per phase** runs each phase on the model and effort of a chosen strength (Thrifty, Balanced, Best or Match my session), the loop strip and report show what each phase ran on, and the end screen offers **Back to the dashboard** and a way to ask a stopped loop a question. It replaces the `plan2code-loop` CLI (see Breaking).
|
||||
- **helpers**: helpers (subagents) now run at a strength and effort matched to their job (`light`, `standard`, `strongest` or `inherit`), never tied to one model or vendor, and Plan and Revise Plan offer them too. In the web console, the **Subagents** dialog turns helpers on or off per project and skill and has a **Helper strength** choice (Balanced, Thrifty, Best or Match my session), and the Subagents tab shows what each helper ran with.
|
||||
- **custom agents**: add your own agent CLIs under **User Preferences → Agents & models** (saved in `~/.plan2code/agents.json`) and start them from `plan2code --cli <id>` or the app. When no agent can be used, a first-run **setup page** lists each built-in agent as found, found outside PATH or not found, with install commands for your OS, starter templates and **Check again**, then carries on once an agent is found.
|
||||
- **pr-prep**: a new utility, **Get a PR ready** (`/plan2code-pr-prep`), picks the checks that cover your branch's changes, runs them, says Ready, Ready with notes or Not ready, and writes a PR description to copy. It never commits, pushes or opens the PR.
|
||||
- **test**: a new utility, **Write missing tests** (`/plan2code-test`), finds source files no test covers and, once you approve its plan, writes tests in the project's own style. It never changes source code. Both utilities read an optional **test map** (a `## Test map` table in `AGENTS.md`), which Init can propose.
|
||||
- **activities**: a die in the console's top bar opens a window of thirteen small games to play while you wait: Snake, Mini golf (six 18-hole courses), Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash. A game pauses the moment Plan2Code needs you, has sounds and optional music, can go full screen, and keeps its best score privately. Off until you turn on **Show Activities** in **User Preferences → Sounds & activities**.
|
||||
- **web console**: start Pathfinder, Plan, Quick Task or Revise plan from a **Notebook** tab: the skill's first box arrives filled with the tab's text and pictures, and the agent reads it only once you send it.
|
||||
- **web console**: answer boxes render Markdown live, **Ask for suggestions** asks Plan2Code what it would pick and why on an open question, a **Clear** button takes a one-answer question back to unanswered, a plan's Build order card has **Combine phases**, and a spec that is not documented yet shows its Pathfinder map and plan draft as read-only tabs.
|
||||
- **workflows**: Finalize offers a final review and asks once before its rating questions, Diagnose lets you skip two of its opening questions, and Git names `/plan2code-pr-prep` as the likely next step after a push.
|
||||
- **contributors**: `npm run play` opens the web console straight from `src/`, so a change shows on the next page reload without rebuilding or reinstalling.
|
||||
|
||||
### 💥 Breaking
|
||||
|
||||
- **the `plan2code-loop` CLI is no longer an install target, and the package is removed.** The `plan2code-loop/` directory and the installer's `O. LOOP CLI` option are gone; the desktop app's **Implementation Loop** supersedes it. Stale installs are still cleaned up: update and uninstall remove the old global `plan2code-loop` command and npm package when they are present.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web console**: **User Preferences** is now four tabs (Appearance, Agents & models, System, Sounds & activities), **Agents & models** is a list beside a form for the picked agent, and **Highlight color** offers 38 colors.
|
||||
- **web console**: reads right inside the desktop app. Advice that assumed a terminal (the session meter, the update banner, the finished-step guide, Help) points at the app's **New Session**, **Update skills** and **Reconnect the console** instead.
|
||||
- **launcher**: `plan2code` asks whether to turn the agent's permission prompts off (Yes by default; `--keep-permissions` keeps them), and with no agent installed it prints each agent's install command and page before it exits.
|
||||
- **docs**: all prose, help text, skill prompts and comments use US English spelling, and `npm test` checks it.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **custom agents**: on Windows, an agent whose installer added its folder to the user PATH is offered right away, not only from a terminal opened after the install.
|
||||
- **web console**: a finished screen's press that nothing picks up now says Plan2Code is not running and how to continue, a failed Send says why, and links that leave the console open in the default browser from the desktop app.
|
||||
- **desktop app**: a test console started during a build can no longer take over the window, and a console too busy to answer a health check is no longer swapped for an empty dashboard mid-build.
|
||||
|
||||
## v2.11.1
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web console**: a card whose thread ends with the person's own words now blocks the patch that settles or reopens it, until the agent replies in the same thread. Exempt once the item is deleted, or the whole session is ending.
|
||||
|
||||
## v2.11.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web console**: the Notebook has named **tabs**. Each tab is its own Markdown note with its own pictures, kept in its own folder under the notebook's (`tabs/<id>/note.md` and `images/`, with a `tabs.json` index). **+ New tab** asks for a name (1 to 40 characters, no two alike in any case, up to 20 tabs). A tab can be renamed (button, double-click or F2), reordered (drag, Move left and Move right, or Alt with the arrow keys) and deleted, which asks twice and removes its text and pictures. The tab left open is the one that opens next, and with no tab left the dialog offers to make one. Saves and pictures are bound to the tab they were made in, so switching never moves either; a switch that cannot save first stays put and says why.
|
||||
- **web console**: five routes (`POST /notepad/tab`, `/tab/rename`, `/tab/delete`, `/tab/order`, `/tab/last`), `?tab=` on the text and picture routes, and picture addresses that carry the tab (`/notepad/images/<tab>/<uuid>.jpg`).
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web console**: the Notepad is now called the **Notebook** (the icon is unchanged), in the top bar, the dialog, the Help, the docs and the screenshots. Code names, routes and the `~/.plan2code/notepads/` folder keep their names, so nothing already saved moves. The dialog's line about it being never shared to the AI Agent is bold, in the highlight color.
|
||||
- **web console**: every document tab and the Overview has a **Back to Questions** button (Dashboard or Git on those screens) left of Print and Download, with a highlight border, and that header row stays at the top of the pane while the document scrolls.
|
||||
- **web console**: the Notebook editor is now CodeMirror 6 with live in-place Markdown: headings grow, bullets draw and the marks come back on the line the cursor is on. It replaces OverType after a spike showed typing in a 200 KB note about four times faster. The editor ships as one vendored file loaded only when the Notebook first opens, and runs in a shadow root so the page's content-security policy stays as strict as before.
|
||||
- **web console**: an existing notebook opens as one tab called **Notes**. Reading it writes nothing; the first edit moves the note and pictures into the tab, and a crash part way is finished by the next write.
|
||||
- **contributors**: `scripts/vendor-codemirror.mjs` and its lock file build the editor bundle reproducibly; the OverType vendor script, its CSS and its page helpers are gone.
|
||||
|
||||
## v2.10.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web console**: a private **Notepad** in the top bar, on every screen. It opens a modal with a Markdown editor that styles as you type (OverType 2.6.1, vendored, MIT) and saves as you go, with pictures: paste, drag and drop or **Add image**, each shrunk to JPEG in the browser, shown as a thumbnail strip with an X that asks before deleting, and a full-screen preview. There is one notepad per project folder, kept in `~/.plan2code/notepads/` (`notepads.mjs`) and never shown to the agent. User Preferences → Cleanup offers a notepad for removal only when its newest file is 30 days old or more, as one item that removes the whole folder; the automatic sweep at open never touches it.
|
||||
|
||||
- **web console**: a finished screen whose next step is a Plan2Code skill has a **Continue here** button beside the Next step block. One press starts that skill in the same session, as a dashboard card would, on a clean page. It is hidden when the session meter is red (a fresh conversation is the better choice), on a pause and for a git command. The page does it alone: the agent only handles the `__launch` the dashboard already sends, and posts `finish: null` first when the next step is the same skill (Implement to Implement).
|
||||
- **web console**: a finished Quick Task or Finalize can offer **Update CHANGELOG first** beside **Commit it now** (`finish.changelog: true`, refused on any other workflow). It hops into Changelog in the same session, and Changelog's yes to *Commit this now?* carries on to Git. The press arrives as `__changelog`.
|
||||
- **web console**: the Ask contract (`console-chat.md`, *Prompts to carry away*) tells the agent to answer a new-task question, or a request for a prompt, with the explanation and one self-contained prompt in a fenced block. The page already gave every fenced block a Copy button, so there is no page change.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web console**: the dashboard has one Implement card instead of Implement and Implement + Review. Its confirm pane has a Review checkbox, ticked by default, that launches Implement + Review when ticked and plain Implement when not; the command shown follows the box.
|
||||
- **web console**: `open` and `handoff new` refuse a `--workflow` the console does not know (exit 2, naming the valid ones), instead of opening a session no skill answers. `open` with no `--workflow` still opens Pathfinder.
|
||||
- **web console**: Help's list of dashboard cards is built from the cards themselves, so it can never name a card the dashboard lacks: it follows the dashboard's order (Handoff last under *Useful any time*), and X-ray's line is its card's.
|
||||
- **web console**: a hop into Git from any skill now starts the page clean on both sides. The server always cleared it; the page kept the last skill's tab and staged answers.
|
||||
- **contributors**: the per-skill tables that were still kept by hand now come from `public/skills.js`: the meter's weights and labels (`WEIGHTS`, `LAUNCH_LABELS`, `RUN_LABELS` in `meter.js`), `resumeCommand()`'s switch in `answers.js`, Help's card list in `index.html` (now filled by `buildHelp()` in `screens/help-dialog.js`) and `cmd-help.mjs`'s workflow list. Each entry gains `weight`, `started`, `ran`, `resume` and an optional `card.help`, and `skills.js` exports `WORKFLOWS` and `isWorkflow()`. A test fails, naming the file and the name, when `console.md`, `src/plan2code.md` or the CLI's help drift from the list.
|
||||
- **contributors**: two new shared modules. `src/web-console/spec-files.mjs` holds the task markers and the task-line, checkbox and Status-line patterns with `statusOf()` and `countTasks()`, read by `scan.mjs` and the `specs.mjs` skill script, which no longer keep copies of their own; `patches.mjs` now takes `TASK_LINE_RE` from it instead of from `scan.mjs`. `src/web-console/public/hops.js` holds `startsClean()`, the rule for which hops start the page clean, called by `cmd-open.mjs`, `server.mjs` and `screens/core.js`.
|
||||
- **contributors**: for the upstream port, these moved: the meter tables, `resumeCommand()`'s switch, Help's card markup and `cmd-help`'s workflow list into `skills.js` fields; the markers and patterns in `scan.mjs` and `specs.mjs` into `spec-files.mjs` (and `TASK_LINE_RE` tightened on the way: exactly one space before the box and a case-sensitive `Task`, matching `TASK_ID_RE`; keep that when porting); the hop test in `cmd-open.mjs`, `server.mjs` and `screens/core.js` into `hops.js`. Port upstream's changes to those tables into `skills.js` and the two modules, not back into the old files.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web console**: Workspace's Browse… folder picker (and the launcher's) no longer opens behind the browser on Windows. Windows refused the picker's `SetForegroundWindow`, because the picker is spawned by the detached console server and is not the process that last had input; the existing topmost flag is ignored by that dialog. It now waits until the dialog is visible, taps Alt (which lifts the foreground lock for the next call), and takes the foreground.
|
||||
- **dashboard**: an assumed task (`[?]`) counts as done and is named in the spec's line ("3 of 4 tasks done, 1 assumed"). It used to be left out of the count altogether, so that phase read "2 of 3 tasks done", and a spec whose tasks were all assumed read as not started. Numbered task lines (`1. [x] **Task ...`) count too, on the dashboard and in the `specs.mjs` skill script.
|
||||
|
||||
## v2.9.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **building habits**: Quick Task, Implement and Implement + Review now read one shared reference file, `references/building-habits.md`, at three moments. When a bug or an unexpected failing test turns up, they find the cause first: build a command that fails on the bug before changing code (or say why they cannot, rank their guesses with the evidence and let you decide), then keep the reproduction as a regression test in the project's existing test runner. When the plan asks for it, they build test first: write the test, see it fail for the right reason, then write the code. Before a restructure meant to change no behavior, they pin the behavior with tests that must pass unchanged afterwards. Adapted from Matt Pocock's [`diagnose`, `tdd` and `improve-codebase-architecture`](https://github.com/mattpocock/skills) skills and pstack's debugging playbook (both MIT).
|
||||
- **plan**: the testing question gains a fourth choice, **Approach**: code first (the default) or test first. Test first is recorded in the PLAN-DRAFT's Testing Strategy table, and Document then orders each task's test before its code with a `Test:` line under the task naming where the test drives the behavior.
|
||||
- **review**: reviews run in a fresh helper that never saw the build; reports say how they ran. Wherever the tool can start a helper and the web console's Subagents switch is not off, every review (`/plan2code-review`, Implement + Review's Stage 2, Implement's "review" at sign-off and Quick Task's "Review it now") hands its analysis to one helper briefed only with the spec and the change set (the new `references/reviewer-brief.md`). The main session checks every finding in the source before you see it and drops what it cannot confirm. Each report carries a **Reviewed by** line: a fresh helper (with how many findings were checked and dropped), or this session, said once as not independent. Adapted from pstack's independent reviewer and Matt Pocock's [`code-review`](https://github.com/mattpocock/skills) guidance (both MIT).
|
||||
- **xray**: a new skill, **Codebase X-ray** (`/plan2code-xray`), on the dashboard under *Useful any time*. Explain an area: how it works and why it is that way, citing files and the commits and pull requests behind it (git history always, `gh` when it is installed and signed in, and it says once which sources it could not use). Or find the rough spots: files that always change together, thin wrappers, tangled boundaries and busy code with no tests, ranked with a concrete "to change X today you must touch..." example each. You tick the ones worth fixing and only those go into `specs/<name>/ARCHITECTURE-BRIEF-<date>.md`, ready for Pathfinder or Plan. A new script, `xray.mjs`, does the counting from git history. Pathfinder and Plan point at it when the code is unfamiliar. Adapted from Matt Pocock's [`improve-codebase-architecture`](https://github.com/mattpocock/skills) skill (MIT) and pstack's codebase survey, `how` and `why`.
|
||||
- **diagnose**: a new skill, **Diagnose a bug** (`/plan2code-diagnose`), on the dashboard under *Useful any time*. It finds a bug's cause and writes it up without fixing it, under the find-the-cause-first habit: a command that fails on the bug first (or, when it cannot build one, its guesses ranked with the evidence), then the cause in `specs/<bug-name>/DIAGNOSIS-<date>.md`. It then offers `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big. The dashboard shows such a folder as a new spec state, **Bug diagnosed**, which lights Quick Task (suggested) and Plan and keeps Document, Implement, Implement + Review and Finalize grayed. Adapted from Matt Pocock's [`diagnose`](https://github.com/mattpocock/skills) skill and pstack's debugging playbook (both MIT).
|
||||
- **quick-task**: asks "Write the test first?" when the change alters behavior and the project already has a test runner, and names the test spot in the plan's Verify section. A bug fix starts with its reproduction.
|
||||
- **show me it working**: Implement, Implement + Review, Quick Task and Finalize offer to show the change running before you approve, never required: reply `show me` in the terminal, or press **Show me it working** on the web console. The agent starts the app the way `AGENTS.md` says (working it out from the project and offering the line for `AGENTS.md` when it is missing, or asking you), looks at the change, stops what it started and records one line saying what was run and what was seen. Screenshots appear on the page only, never under `specs/`. Init and Init Update now ask how to start the app and where to view it. Adapted from pstack's proof-on-the-running-app idea (MIT).
|
||||
- **web console**: a doc can show a picture. An image block (`"image": "shots/<name>.png"`) shows a PNG, JPEG or WebP the agent saved under the session's `shots/` folder; anything outside that folder, over 5 MB or not really an image is refused.
|
||||
- **launcher**: `plan2code update` updates everything that was installed (the skills, the `plan2code` command and any of the status line, `plan2code-loop`, `plan2code-metrics` and `plan2code-bot`), with no menu and never uninstalling. Every global install now writes `~/.plan2code/install.json` listing what it installed, which `install.js --update` reads; with no record it updates the skills and the `plan2code` command.
|
||||
- **launcher**: `plan2code` prints one line before it starts your agent when a newer release is out: `Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`. It reads the web console's saved release check, so it never waits on the network; when that check is missing or old it refreshes it in the background for the next start.
|
||||
- **web console**: **Stop session** gains a second way to stop, **Stop with a handoff**. It saves the skill's place as before and also writes a Handoff document, so a quick task, a review or a half-done changelog keeps its context; the paused screen names the file.
|
||||
- **dashboard**: this checkout's unused handoffs show as chips in the spec picker. **Pick it up here** carries on in the skill that stopped (a handoff from the Handoff skill carries on in Quick Task), in the same session, and the chip is gone afterwards; **Read it all**, **Copy for a new conversation** and **Delete** sit beside it.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **implement**, **quick-task**, **plan**, **document**: tightened as they took on the habits, so each stays well under 15,000 characters.
|
||||
- **pathfinder**: tightened to stay under 15,000 characters as it took on the X-ray pointer.
|
||||
- **quick-task**, **implement**: when the cause is unclear or the fix big, they stop and suggest `/plan2code-diagnose`.
|
||||
- **finalize**: its archive confirmation now reads "yes / no / show me", the last chance to look at the whole feature running before the spec moves.
|
||||
- **dashboard**: Handoff is now the last card in *Useful any time*, after Git.
|
||||
- **contributors**: the add-a-skill checklist in `.agents-docs/AGENTS-development-commands.md` now lists every place a new skill must be registered (it missed about a dozen).
|
||||
- **contributors**: `AGENTS.md` gains a rule that a skill rule broken twice becomes a script check, not more prose.
|
||||
- **web console**: the UPDATE AVAILABLE dialog now gives `plan2code update` as the command, keeping the install command beside it for a machine without the `plan2code` command. User Preferences → Cleanup never lists `~/.plan2code/install.json`.
|
||||
- **docs**: README, the quick reference and the web console guide say to update with `plan2code update` (or re-run the install command).
|
||||
- **handoff**: every handoff now lives in `~/.plan2code/handoffs/` (a Markdown file plus a small `.json` beside it), owned by the web console, and handoffs older than 30 days are swept when the console opens. The Handoff skill writes there with no folder or `.gitignore` question, and Cleanup never lists the folder. Handoffs written to the OS temp folder or a `handoffs/` folder before this change are not listed.
|
||||
- **dashboard**: a **Bug fixed** spec has a visible **Delete** that needs one confirm, and its chip no longer repeats the "bug fixed" line.
|
||||
- **web console**: the review sign-off card lists **Approve this phase** before **Show me it working**, with the approve button outlined in the accent color.
|
||||
- **web console**: a sign-off's **yes** button (Quick Task's **Build it**, Finalize's **Archive it**) is outlined in your highlight color too, like **Approve**. So is the yes of a yes/no question (such as Plan's **Write the plan**) and a recap's **Yes, that is right**, except on a question marked dangerous, whose yes stays red.
|
||||
- **web console**: **Skip this one** (and **Do not skip**) on an optional question is a small button in your highlight color, like a comment box's **No changes**, instead of an underlined link.
|
||||
- **init**, **init-update**: the *Keeping this file current* section they write into `AGENTS.md` gains three rules: a rule broken twice becomes an automated check, a new Failure log line first looks for one on the same topic to sharpen instead, and the log holds 17 entries at most (over the cap, merge entries that share a cause, then drop the lowest-value ones). Init update offers the missing rules to an existing section and tidies the log on every run, showing each merge and removal for a yes before it writes.
|
||||
- **contributors**: this repo's `AGENTS.md` follows the same Failure log rules, and its three post-sync grep entries are merged into one.
|
||||
- **contributors**: the web console's source is split by job: `lib.mjs`, `server.mjs`, `console.mjs`, `app.js` and `app.css` become `routes.mjs`, `static.mjs`, `cmd-*.mjs`, the by-job Node files, `public/screens/` and `public/styles/`. Nothing a person sees changes, and the page starts faster (ready in about 280 ms, was 450 ms).
|
||||
- **contributors**: the per-skill and per-spec-state tables live in two data files, `public/skills.js` and `public/spec-states.js`, so adding a skill or a state is a short list in `.agents-docs/AGENTS-development-commands.md` and `npm test` names anything missed. This replaces the long add-a-skill checklist noted above.
|
||||
- **contributors**: page tests drive the real console in Chrome or Edge through `playwright-core` inside `npm test` (running it needs Node 20 or newer; installed skills still need only Node 18). The screenshot and speed scripts use it too, with no hand install, and `scripts/css-snapshot.mjs` compares every computed style across a stylesheet change.
|
||||
- **contributors**: a test keeps the files table in `.agents-docs/AGENTS-architecture.md` complete: every console file needs a one-line row.
|
||||
- **contributors**: `post` now refuses a `finish` (exit 3) while any reported helper still shows `running`, so a finished page never keeps a spinning row. The agent contract in `console-finish.md` says to mark each helper `done` or `failed` first.
|
||||
|
||||
### 🗑️ Removed
|
||||
|
||||
- **handoff**: the Handoff skill's `handoff-path.mjs` script is retired in favor of `console.mjs handoff new`, which every skill can reach.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web console**: a short card on the git board (a confirm such as *Delete 2 branches?*) fills the board's width instead of sitting narrow in the middle.
|
||||
- **web console**: a redraw no longer throws you back to the top of the finished screen, a doc tab, the Overview or the dashboard menu (pressing **Review it now**, or an agent update landing while you read). The page kept your place only on question cards; it now keeps it for whatever is scrolling, as long as the same thing is still on screen.
|
||||
- **dashboard**: a bug folder whose diagnosis Quick Task had marked `Fixed` no longer sits on the dashboard forever as *Files on disk*, pre-selected as the most recent spec with no card to clear it. The scan reports it as a new spec state, **Bug fixed**: no pipeline card lights for it, the picker never opens on it (it opens on the most recent spec still in play, or *Start from scratch*), and it is hidden while *Hide unavailable workflows* is on, dimmed otherwise. Quick Task, right after marking a diagnosis-only folder `Fixed`, offers to archive it to `specs--completed/<bug>/` with the same `specs.mjs archive` Finalize uses (a confirm card on the web console).
|
||||
|
||||
## v2.8.1
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
- **docs**: the docs site now shows the git board, with a light and dark screenshot under the pipeline's "Any time" cards: the Changes, Branches and Sync tabs, opening on the likely next step, the tab badges, the single block for a stopped rebase or merge, and asking before every push, publish or delete.
|
||||
- **docs**: `scripts/capture-screenshots.mjs` gains a `git` shot. It builds a sample repository with a pushed feature branch and three changes to commit, so `node scripts/capture-screenshots.mjs --only git` regenerates the images.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **tests**: `npm test` no longer fails `git plan switch` on a machine with a global `core.autocrlf=true`. `scripts/skill-script-helpers.mjs` now strips back the git config for the whole test process, so test fixtures, imported modules and the scripts under test always use the same settings.
|
||||
|
||||
## v2.8.0
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **git**: the web console's git board is now three tabs, **Changes**, **Branches** and **Sync**, and opens on the tab holding the likely next step. Ten fixed rules pick that step from the repository's state (fix or continue a stopped rebase or merge, make the first commit, make a branch on a detached HEAD, commit or start a branch for your changes, pull, push, publish, open a pull request, clean up branches) and show it as one main button with at most one quieter one beside it. Each tab badges what is waiting on it, and the other tabs say "Next step is on ‹tab›" with a link to it. Your own click moves you to the next step's tab once it lands; a refresh or a commit from the terminal leaves you where you are, and a reload keeps your tab.
|
||||
- **git**: held-back files (secrets, files over 5 MB) no longer keep Commit as the next step forever. They get a quiet "held back" line and an **Add … to .gitignore** offer, which commits only `.gitignore`.
|
||||
- **git**: a busy board is read-only. While a git command runs or the agent has not picked up your last click, every button, tick and picker grays out (switching tabs, search and folds still work), and what is running shows where the next step usually sits. Plan2Code's questions now appear under the tab strip.
|
||||
- **git**: a rebase or merge stopped on conflicts shows one block on Sync with the files marked *markers left* or *resolved*, one main button and **Abort** once; Changes and Branches wait until it is finished or aborted.
|
||||
- **git**: **Done with git** is a normal button at the right of the tab strip. It grays while a git command runs (Stop session in the top bar still works), and while one of Plan2Code's questions waits it cancels that question and finishes.
|
||||
- **web-console**: Help → *The git board* is rewritten for the tabs, badges, the next step, the busy rules and Done with git. Handoff is described as packing the current session, not this conversation.
|
||||
- **docs**: the docs site's "Any time" skills now list **Changelog** and **Git** beside Quick task, Review and Handoff.
|
||||
- **tests**: `scripts/test-web-console-git-board.mjs` checks every sample repository state's next step, tab and badges, proves no control on a busy board is clickable, and that every board function is reachable on some tab.
|
||||
|
||||
## v2.7.1
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **implement**: Implement no longer says there is nothing left to do while the dashboard keeps Finalize grayed out. When every phase is approved but tasks under them are still open (usually manual steps an agent could not do, left blocked `[!]` with a "User action"), `specs.mjs status` now returns a `checkoff` verdict listing them, and Implement asks about each one in turn: "Is this done?" in the terminal, or a **Done, check it off** / **Not yet** card in the web console. A yes runs the new `specs.mjs tick <spec> --task <id>`, which marks the task `[x]` and adds a "Confirmed done by the user on <date>" line under it. Once nothing is left open, Implement points to `/plan2code-4-finalize` and the dashboard shows the spec as ready to finalize.
|
||||
|
||||
## v2.7.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **git**: a new `/plan2code-git` skill and dashboard card that puts branches, pull, push and commits on one board in the web console. The board shows the branch you are on with what is ahead or behind, when the remotes were last refreshed, and every local and remote branch: current and default first, **Merged** and **Remote copy deleted** marked, remote-only branches folded after 50, and a search box. Every click is one action the agent runs, and the bar locks until it is done.
|
||||
- **git**: branch actions on the board: switch (asking first when you have changes: **Switch and bring them**, **Commit first** or **Cancel**), create `<type>/<description>` branches from any branch, delete local branches (a red confirm when unmerged) and **Clean up** merged and remote-deleted ones in one go. A remote branch is never deleted.
|
||||
- **git**: pull with conflict help. A pull that stops on conflicts offers to resolve them, shows each stop's files with a reason and a diff, and waits for **Continue**, **Change it** or **Abort pull**. Files it cannot resolve with confidence are named and left alone.
|
||||
- **git**: push and publish, each asking first with the exact command, never a force-push. After a push or publish the board links to the host's new pull request page (GitHub, GitLab, Bitbucket, Azure DevOps); an unknown host is asked about once and remembered in `~/.plan2code/console/pr-hosts.json`. Bitbucket PR links are unverified.
|
||||
- **git**: plain instructions in the terminal, such as `/plan2code-git switch to main` or `/plan2code-git commit and push`, run at once with the same confirms the board shows. Commits keep the `<subject>` / `AI Assisted` format.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web-console**: agents get through each turn faster. The agent instructions are split: a short `console.md` (21 KB, was 86 KB) is read once per conversation, and every skill copy is the same, so a dashboard hop doesn't re-read it. Topic files (ending a session, Quick questions, Workspace, helpers, launches, the meter, troubleshooting, each workflow's notes, the in-page review) are read only when they're needed. `console.mjs help <topic>` prints any of them.
|
||||
- **web-console**: one command per turn. `post --wait <N>` posts and then waits. Collecting a send marks the agent working, and a new question (or a wait with one open) hands the turn back, so agents no longer post a status first. `"settle": true` records the cards just answered from what was sent.
|
||||
- **web-console**: builds no longer retype the phase file after every task. A doc block can name a file (`{ "file": "specs/x/phase-3.md" }`, `"select": "tasks"` for the task lines) that the console reads from the project. `"refresh": true` re-reads it, and a doc's version moves up by itself when its content changes. A hop (dashboard launch, Back to the dashboard, Commit it now) comes with the exact resume command and the skill file to read. A chat reply's id defaults to `r<seq>`, and `fallbackText` is no longer asked for (nothing read it).
|
||||
- **web-console**: a send is picked up without delay. The wait loop's server health check no longer holds the 50 ms polling for up to 4 s. A working agent's timer now restarts with each new turn instead of counting from when the session opened. The git board unlocks when a working agent stops checking in.
|
||||
- **web-console**: **Commit it now** on a finished Finalize, phase build or quick task now opens Git in the same session, which commits every changed file (risky ones left out and named) and leaves the board open with Push lit.
|
||||
- **changelog**: its closing "Commit this now?" hands the session to Git to commit the result.
|
||||
- **web-console**: Help has an 18th topic, **The git board**, right after **Watching a build**, and a Git session opens Help on it. The dashboard topic's Git line points to it.
|
||||
- **web-console**: a Quick Task build now ticks the steps on the **Plan** tab one by one as each finishes, alongside the "Task x of y" line beside Planny. The separate Build progress tab is gone. The plan is posted as Summary, Files to change, Steps and Verify blocks, and each step's post resends only the `steps` checklist. The waiting pane's "follow along" link opens the Plan tab.
|
||||
- **web-console**: User Preferences → Cleanup also lists this project's `specs--completed/<feature>/` folders that nobody has touched for 30 days. Deleting one is permanent, since that folder is usually gitignored, and the help text says so.
|
||||
- **web-console**: the **Subagents** tab shows the small spinner left of its label, like **Ask**, while any helper is Running.
|
||||
- **web-console**: User Preferences is wider (880px). Only its body scrolls, so **Back to default** and **Done** stay in view.
|
||||
- **installer**: the finish screen no longer ends with "Update later with: `npx skills update -g`" (the README sentence is gone too). Re-running the install command is the update path.
|
||||
- **tests**: `npm test` runs much faster with the same tests. The web console's tests are split by area into `scripts/test-web-console-*.mjs` so `node --test` runs them in parallel, git fixtures are built once per test file and copied for each test, and the skill-script tests no longer rebuild `skills/` when `npm test` has just built it. The hardening tests that were only in plan2code moved to `scripts/test-web-console-hardening.mjs`.
|
||||
- **docs**: wherever the install command is printed (README, quick reference, docs site, the console's Update modal), a line explains that no output at all means npm couldn't reach the repository and hid the reason, and that `git ls-remote https://github.com/jparkerweb/plan2code.git` shows why.
|
||||
|
||||
### 🗑️ Removed
|
||||
|
||||
- **git-commit**: `/plan2code-git-commit` was replaced by `/plan2code-git`; a terminal commit no longer offers a push, so say `commit and push` to do both.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **git**: a new repository now starts on `main` rather than git's legacy `master`, unless you set `init.defaultBranch` yourself. `init-check` returns the `branch` and the `commands` to run (`git init`, then `git symbolic-ref HEAD refs/heads/main`, which works on every supported git), and the init card names the branch.
|
||||
- **web-console**: answers are never lost or misfiled. `settle: true` records the send `wait` handed over, never a later one still waiting to be collected. A thread reply on a sent list, text or multi card puts what was sent back on the form. A card asked again keeps the note sent with its answer in its thread. A card the agent left open after collecting it no longer stays locked as "sent". Multi-line answers and notes are indented in `reply`, so typed text never passes for a console line. A list's `reply` names renames, additions and removals, and its first click after a rename works. A skipped card settles as skipped, and a note on a finished card reads "Your last note".
|
||||
- **web-console**: builds and the git board report the right state. A build's progress bar trusts `cleared: 0`, and a review between counts shows its stage. A later phase can ask for its own sign-off. After a commit hop the Ask tab no longer shows answered questions as pending. The board locks while an agent question is open above it, sends Publish without a remote when there are several, always offers Continue during a conflict, shows "main · rebasing" mid-rebase, updates the footer branch, keeps the last good refresh time after a failed one, and disables New branch mid-rebase or before the first commit. A `notice` no longer takes a question slot. `pr-url` refuses a pull request from the default branch into itself, deleting a branch with no unique commits is no longer a red confirm, and `classify-error` knows more network failures and a new `diverged` kind.
|
||||
- **web-console**: a send made before the last collection, or a skip, never stays locked as "with Plan2Code". A card left open by a partial settle keeps the person's edits, and a plain reopen frees the card and keeps the note in its thread. A list rename is kept while typing. Two dashboard tabs on different specs no longer trade the workspace back and forth. A branch whose remote copy was deleted offers Publish, not Pull. Refresh works with no remote, picking up edits made outside. The cleanup confirm is red only when commits would be lost. A stop past a warning no longer promises a saved place. `post` refuses a patch that is not one JSON object. A spec with no `overview.md` no longer logs a failed request.
|
||||
- **web-console**: the CLI is sturdier. `post --file` reads a BOM or UTF-16 patch (PowerShell's), `wait`, `chat` and `stop --session` find a session's server from any folder, `open --resume` gives a busy server a second look rather than starting another, `keep` refuses a `--from` outside the project and keeps one copy per upload, `agent.status` accepts only `working` or `waiting`, and the dashboard refuses question cards.
|
||||
- **web-console**: the page reads right. Doc images and links to kept attachments load, and other relative links show their path. HTML comments are hidden, blocked, in-progress and assumed tasks get markers, and long doc tab titles are cut. Cards with more below the fold fade at their bottom edge. Back on the dashboard the picker starts on the most recent spec, and the agent's note shows only for that spec. Pauses read as paused, the hand-off wording matches the `--web` flag and git commands, stop and leave dialogs with a warning no longer promise a saved place, and the "still being picked up" banner clears. Smaller fixes cover the Brief button and dates, the decision line, Workspace and Cleanup messages, the role banner, the Subagents dialog, the welcome dialog, the tab title, dialog links and the chips.
|
||||
- **web-console**: on the git board, a card with a note box (the proposed `.gitignore`, a split's review) no longer shrinks under the board with its buttons and note box drawn behind it; the card keeps its full height and the column scrolls. A note box there grows with what you type instead of scrolling inside itself, and before the first question lands, a folder with no repository says a question is coming rather than pointing at an empty space "above". A task line holding a code block or a long word no longer widens a doc tab past the page, the branch table scrolls on its own on a phone instead of pushing the board off screen, and the Ask tab's Send button wraps rather than being clipped on a narrow screen.
|
||||
- **web-console**: the dashboard's spec card counts only a phase file's `**Task N.M:**` lines, so an Acceptance Criteria checkbox no longer shows as a task or keeps a built spec from reading "built". `post` and `status` stop reporting `phase: "submitted"` once a send has been collected. Several "New conversation" lines arriving together reach the agent as one. A posted finish (a pause included) no longer leaves the agent shown as working, and resuming a paused session starts a fresh working turn.
|
||||
- **web-console**: **Commit it now** on a finished screen (and Changelog's "Commit this now?") no longer leaves the page stuck on the previous skill's ending. Resuming into Git now clears the previous skill's page, its ending included, as a dashboard launch does.
|
||||
- **web-console**: the top bar's three right-side buttons (Help, Colors & theme, feedback) keep to the right edge when the progress bar is hidden; on the dashboard and the git board they used to sit beside the title.
|
||||
- **web-console**: the git board's action bar (Refresh, Pull/Push, Commit, **Done**) stays pinned to the bottom of the pane while the branch table scrolls, and **Done** shows in the highlight color when it is live.
|
||||
- **web-console**: a finished screen's buttons (**Review it now**, **Commit it now**, **Back to the dashboard**) stay live for as long as the session is open; the copy-the-command fallback only appears once the session has closed.
|
||||
|
||||
## v2.6.0
|
||||
|
||||
### ✨ Added
|
||||
@@ -9,7 +215,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **web-console**: the breakdown question's "Anything else about this breakdown?" field has a **No changes** button. One click fills the box with "no changes", so you no longer type it. The old "(type 'no changes' if none)" hint is gone from the label.
|
||||
- **git-commit**: a new `/plan2code-git-commit` skill and dashboard card. It reads what changed, drafts the commit message for your approval, offers a new branch first on the default branch, suggests splitting work that is really two jobs, and asks before every commit and push (never a force-push). Outside a git repository it offers to start one.
|
||||
- **changelog**: a new `/plan2code-changelog` skill and dashboard card, just left of Git commit. It reads the default branch's latest version, classifies the branch's work and picks the version. When the branch already owns a version that is not released and not on another branch, it adds to that entry instead of starting a new one. It compares the branch with the newest entry, suggests the entries that are missing for you to edit, keeps `package.json` aligned, and offers to run Git commit next. The facts come from `changelog-state.mjs`, with tests in `scripts/test-script-changelog.mjs`.
|
||||
- **web-console**: the Git commit card counts the files waiting ("3 files to commit") and greys out on a clean tree, from a bounded `git status` the scan runs when the dashboard opens. If git cannot answer, the card stays clickable.
|
||||
- **web-console**: the Git commit card counts the files waiting ("3 files to commit") and grays out on a clean tree, from a bounded `git status` the scan runs when the dashboard opens. If git cannot answer, the card stays clickable.
|
||||
- **web-console**: the Commit this? question in Git commit has a collapsed **Show the N files** table of every path and its state, so "15 files" can be read before you say yes.
|
||||
- **web-console**: a finished quick task or phase build gets a **Commit it now** button beside the printed git command. It starts Git commit in the same session, as if you had clicked its dashboard card.
|
||||
- **web-console**: the dashboard scan reports `isGit`, found from the filesystem without spawning git (linked worktrees count). The Git commit card stays clickable outside a repository and says "Not a git repository yet: it offers to start one". The skill has its own Planny pose and a Help entry.
|
||||
@@ -31,7 +237,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web-console**: six new starter templates, each slotted into every role's order. **Refactor** (Plan, Quick Task) asks what behaviour must not change. **Performance problem** (Plan, Quick Task) asks for today's number and the target. **Dependency upgrade** (Quick Task) asks for the known breaking changes. **Spike** (Pathfinder) is a time-boxed question with an "answered when". **Integration** (Pathfinder, Plan) covers the other side's auth and limits and what happens when it fails. **Data migration** (Plan) asks for a rollback plan. Pathfinder now offers 8 templates, Plan 10 and Quick Task 10, 19 in all.
|
||||
- **web-console**: six new starter templates, each slotted into every role's order. **Refactor** (Plan, Quick Task) asks what behavior must not change. **Performance problem** (Plan, Quick Task) asks for today's number and the target. **Dependency upgrade** (Quick Task) asks for the known breaking changes. **Spike** (Pathfinder) is a time-boxed question with an "answered when". **Integration** (Pathfinder, Plan) covers the other side's auth and limits and what happens when it fails. **Data migration** (Plan) asks for a rollback plan. Pathfinder now offers 8 templates, Plan 10 and Quick Task 10, 19 in all.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
@@ -123,7 +329,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **review**: with no `main` or `master` and no `--base`, `review-scope.mjs` now stops with `no-base` instead of quietly counting only uncommitted changes.
|
||||
- **commit-msg.mjs**: the add step is `git add -- <paths>`, paths starting with `@` or `-` are quoted, and subjects with `\`, `!` or curly quotes are refused. The output also carries `add` and `commit` separately for Windows PowerShell 5.1, which has no `&&`.
|
||||
- **specs.mjs**: `mark` reads a Status line written as `Status:` or `**Status**:` too, and warns when a phase file has none; a path that is not a folder directly under `specs/` is refused (`not-a-spec`).
|
||||
- **pathfinder**: the map header carries `**Next NN:**`, so a deleted question's number is never handed out again. `claim`, `resolve` and `rule-out` honour `--dry-run`. Notes indented under a map row survive a marker change. Research questions are fired unclaimed; the one-claim rule is for the questions a person works through.
|
||||
- **pathfinder**: the map header carries `**Next NN:**`, so a deleted question's number is never handed out again. `claim`, `resolve` and `rule-out` honor `--dry-run`. Notes indented under a map row survive a marker change. Research questions are fired unclaimed; the one-claim rule is for the questions a person works through.
|
||||
- **finalize**: `feedback-payload.mjs` counts the same phase files `specs.mjs` does, `submit` refuses an oversize URL when `gh` is unavailable (`oversize`), and a bare spec name present in both `specs/` and `specs--completed/` is refused as ambiguous.
|
||||
- Every script was checked against real specs and Pathfinder maps in other repositories and by four independent reviews; each issue found has a regression test.
|
||||
|
||||
@@ -133,7 +339,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **web-console**: when the agent stops checking in, the status line and Help now say to type **continue** in an idle terminal so it picks your answers up.
|
||||
- **web-console**: `wait` exit 10 now carries a `next` instruction (relay one line, then wait again), and `console.md` opens with the one rule that keeps the page alive: every turn ends on a `wait` call, never on text.
|
||||
- **web-console**: a finished quick task offers **Back to the dashboard** as well as **Review it now**, so the finished screen is never a dead end.
|
||||
- **Windows**: the folder picker (the launcher's desktop shortcut and the Workspace **Browse…** button) now opens centred and in front of other windows instead of behind the terminal.
|
||||
- **Windows**: the folder picker (the launcher's desktop shortcut and the Workspace **Browse…** button) now opens centered and in front of other windows instead of behind the terminal.
|
||||
- **Launcher**: before asking which CLI to use, `plan2code` says what it is about to do and that running `/plan2code` inside your agent works too.
|
||||
- **web-console**: the session meter now weighs the work a session actually did instead of a flat amount per step. A built phase scores one point per 3 tasks it completed (rounded up), plus 1 for Implement + Review, so a twelve-task phase weighs four times a three-task one; the agent reports the count as `run.tasks`. Every 2 questions you answer on the page add a point to the skill you answered them in, so a long back-and-forth in Plan or Pathfinder counts for more than a short one. Each Pathfinder research question adds 1 through a new `pathfinder-research` event, since research fills the context with nobody answering anything. The levels move to match: yellow from 5 points, red from 10, and the ring is full at 15.
|
||||
|
||||
@@ -159,7 +365,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **`plan2code-3-implement-review`**: a quality-gated Step 3 that implements one phase, runs a focused review and the selected fixes before sign-off, and marks the phase complete only after the reviewed result is approved. Step 2's hand-off now offers it first, with `/plan2code-3-implement` as the review-free alternative.
|
||||
- **`--web` flag**: `/plan2code-1-plan --web plan a lunch voting app` opens the console without asking. Every next-step command the workflow prints (resume footers, NEXT STEP lines, the loop's completion banner) now carries `--web`.
|
||||
- **Console pages for builds and reviews**: a build shows the current task, a task-count progress bar and the phase's task list ticking as tasks land. After an approved phase or a finished quick task, **Review it now** runs `/plan2code-review` on the page, with *Which to fix* presets for critical-and-warnings or everything.
|
||||
- **Console conveniences**: nine question shapes with live validation and drag-to-reorder phases; drafts that survive a closed tab, reload, server restart or agent crash; an **Ask** tab for quick questions the agent answers at its next check-in (file edits need approval); image and document attachments; a read-only **Overview** tab; a **Workspace** of extra read-only folders addressed as `@name`; a green / yellow / red **session meter**; a **Role** preference that orders starter templates; nineteen highlight colours, light / dark themes and card widths; audio cues with per-event toggles; and a 16-topic Help dialog.
|
||||
- **Console conveniences**: nine question shapes with live validation and drag-to-reorder phases; drafts that survive a closed tab, reload, server restart or agent crash; an **Ask** tab for quick questions the agent answers at its next check-in (file edits need approval); image and document attachments; a read-only **Overview** tab; a **Workspace** of extra read-only folders addressed as `@name`; a green / yellow / red **session meter**; a **Role** preference that orders starter templates; nineteen highlight colors, light / dark themes and card widths; audio cues with per-event toggles; and a 16-topic Help dialog.
|
||||
- **Planny in the console**: drawn in SVG in his own dock above the question list, where he carries the page's state: his star lights and he waves when it is your turn, the star turns and he walks on the spot while the agent works, it goes green when all is caught up, he shows no arms when the agent is not answering, and he fades with his star shut when disconnected. He flies through a starfield while the agent thinks, wakes up on a fresh dashboard, and acts out each skill on its starting screen, arms holding that step's prop. The tab icon adds a busy, ready or attention bar, and the desktop shortcut uses him too.
|
||||
- **Tests**: `scripts/test-web-console.mjs` and `scripts/test-launcher.mjs` (run by `node --test`), `scripts/parse-check.mjs` (every shipped browser module parses as an ES module) and `scripts/check-skill-table.mjs` (the dashboard's "What each skill reads and writes" table matches the skills), all wired into `npm test`. `scripts/bench-web-console.mjs` measures time to first paint.
|
||||
- **install.js**: an animated progress indicator during the two long install phases, so the installer no longer looks hung.
|
||||
@@ -249,7 +455,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **`src/plan2code-0-pathfinder.md` recompressed** to absorb the new `## Backend` section within the 11,000-character workflow-file limit — duplication between the orchestrator and its reference files was removed (the local layout and marker legend now live only in `questions.md`; Form A/B footer detail only in `trail.md`), and step text tightened. No behaviour was dropped.
|
||||
- **`src/plan2code-0-pathfinder.md` recompressed** to absorb the new `## Backend` section within the 11,000-character workflow-file limit — duplication between the orchestrator and its reference files was removed (the local layout and marker legend now live only in `questions.md`; Form A/B footer detail only in `trail.md`), and step text tightened. No behavior was dropped.
|
||||
|
||||
## v2.0.0
|
||||
|
||||
@@ -259,7 +465,7 @@ Ports upstream v1.17.0 and v2.0.0 into Plan2Code.
|
||||
|
||||
- **Gemini CLI is no longer an install target.** The `.gemini/commands/*.toml` surface is removed, along with the build-time machinery it required: `generateTomlContent()`, `writeTomlToDestination()`, `inlineReferenceContent()`, and the `dest.type === 'toml'` branch in `syncPrompts()`. Every remaining target resolves `Read references/*.md` directives at runtime, so reference content no longer needs inlining at build time.
|
||||
|
||||
**Uninstall still cleans up Gemini files.** The `.gemini/commands` entry is deliberately retained in the uninstall target list (labelled `Gemini CLI (legacy — uninstall only)`) behind a new `uninstallOnly` flag, so `.toml` files written by v1.x installs can still be removed. Do not add it back to `LOCAL_DESTINATIONS` / `GLOBAL_DESTINATIONS`.
|
||||
**Uninstall still cleans up Gemini files.** The `.gemini/commands` entry is deliberately retained in the uninstall target list (labeled `Gemini CLI (legacy — uninstall only)`) behind a new `uninstallOnly` flag, so `.toml` files written by v1.x installs can still be removed. Do not add it back to `LOCAL_DESTINATIONS` / `GLOBAL_DESTINATIONS`.
|
||||
|
||||
All other platforms are unaffected — Claude Code (skills *and* commands), Cursor, Windsurf, Continue, Codeium, GitHub Copilot, VS Code Copilot, Pi, Crush, Amp, Devin, OpenCode, and Zed all install exactly as before.
|
||||
|
||||
@@ -289,7 +495,7 @@ Ports upstream v1.17.0 and v2.0.0 into Plan2Code.
|
||||
- **Docs site and README redesigned** around an "airmail" postcard theme — a fixed four-sided airmail-chevron page frame, sticky header, and the workflow presented as six posted letters, with Pathfinder and the optional Review step both surfaced. Adds a postage-stamp favicon set (`favicon.svg` / `.ico` / `.png` / `apple-touch-icon.png`) and a new README banner; removes three orphaned images (`desk.jpg`, `install-script.jpg`, `plan2code.jpg`).
|
||||
- **`/plan2code-4-finalize` archives `pathfinder/` with the spec** — STEP 6 now names `pathfinder/` in the move list and no longer describes the cleanup target as "research or scratch files," wording that pointed an agent straight at `pathfinder/questions/`. The map is the rationale record behind the plan, in the same class as `PLAN-CONVERSATION-*.md`.
|
||||
- **`/plan2code-1b-revise-plan` no longer deletes `pathfinder/`** — its Step 6 cleanup had the same "research or scratch files" wording.
|
||||
- **`/plan2code-quick-task` is no longer labelled "Step 0"** — pathfinder now owns step 0, and quick-task was never a pipeline step. It registers as a utility (like `init`, `review`, and `handoff`), so its generated description reads `Plan2Code Quick Task: Quick Task Mode`. Filename, skill name, and command path are unchanged.
|
||||
- **`/plan2code-quick-task` is no longer labeled "Step 0"** — pathfinder now owns step 0, and quick-task was never a pipeline step. It registers as a utility (like `init`, `review`, and `handoff`), so its generated description reads `Plan2Code Quick Task: Quick Task Mode`. Filename, skill name, and command path are unchanged.
|
||||
- **`/plan2code-handoff` asks where to save** — the OS temp directory is now the default, with `./handoffs/` or any other path available on request. Adds a spec-awareness section: when the session worked inside `specs/<feature>/`, the handoff cites the in-progress `phase-X.md` and its actual checkbox state rather than relying on conversation memory.
|
||||
- **`/plan2code-init-update` Step 7 offloaded to a reference file** — the AI Agent File Sync detail moves to `plan2code-init-update-references/ai-agent-file-sync.md` with an inline fallback. The `CLAUDE.md` MANDATORY-FIRST-STEP template is unchanged.
|
||||
- **`/plan2code-review` Session End offloaded to a reference file** — next-step routing moves to `plan2code-review-references/session-end.md` with an inline fallback.
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
- **Node.js 18 or newer.** Check with `node --version`. No Node? Get it from [nodejs.org](https://nodejs.org/) (the LTS download), or run `winget install OpenJS.NodeJS.LTS` on Windows, `brew install node` on macOS, or use `nvm` on Linux. Then open a new terminal.
|
||||
- **Start from your project.** Open your terminal in the project you want to work on (`cd` into it) before you run anything. Plan2Code works on the folder you start it in.
|
||||
- **Ways in.** `plan2code` (Claude Code, Devin or Codex), or type `/plan2code` in your agent (`$plan2code` in Codex).
|
||||
- **No agent yet?** Install Claude Code, Codex or Devin first.
|
||||
- **No agent yet?** Install Claude Code, Codex or Devin first, or let the `plan2code` command's setup page walk you through it.
|
||||
|
||||
## Launch
|
||||
|
||||
@@ -15,11 +15,16 @@ The web console is the main way in: a local page where questions, documents, bui
|
||||
| ------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------- |
|
||||
| From your project (shell) | `plan2code` | Opens Claude Code, Devin or Codex on the dashboard (`--cli claude` / `devin` / `codex` to choose) |
|
||||
| Inside any agent | `/plan2code` (`$plan2code` in Codex) | Opens the dashboard: a card for every skill, launched on the same page |
|
||||
| Install / update | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command; re-run it to update |
|
||||
| Install | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command (re-run it to update without the `plan2code` command) |
|
||||
| Update | `plan2code update` | Updates the skills, command, app and status line, with no menu (metrics and the bot only from a git checkout: `node install.js`); never uninstalls anything |
|
||||
| Straight into a skill | `/plan2code-1-plan --web` (any step) | Skips the "web console or terminal?" question and opens the page |
|
||||
|
||||
The install command always opens a menu. Back at your prompt with no output at all? npm could not reach the repository and hid the reason: run `git ls-remote https://github.com/jparkerweb/plan2code.git` to see it (usually the network, a proxy or the VPN).
|
||||
|
||||
Pick a skill on the dashboard and the same page becomes that session. Details: [.readme/web-console.md](.readme/web-console.md) · worked example: [.readme/walkthrough.md](.readme/walkthrough.md).
|
||||
|
||||
The **Notebook** icon in the top bar opens a private scratch pad for the folder you are in (Markdown and pictures, kept in `~/.plan2code/notepads/`). Private: the agent never reads your Notebook. A tab reaches it only when you start a workflow with it.
|
||||
|
||||
## Commands
|
||||
|
||||
Every command below is what a dashboard card runs. Typed on its own, each one asks "web console or terminal?" first.
|
||||
@@ -39,8 +44,12 @@ Every command below is what a dashboard card runs. Typed on its own, each one as
|
||||
| 3+review | /plan2code-3-implement-review | overview.md | Reviewed implementation ready for approval (alternative to `/plan2code-3-implement`) |
|
||||
| 4 | /plan2code-4-finalize | overview.md | Archived specs |
|
||||
| handoff | /plan2code-handoff | Conversation | Self-contained handoff doc (OS temp dir by default, or a folder you pick such as `handoffs/`) |
|
||||
| xray | /plan2code-xray | An area, or none | An explanation citing files and commits, or `ARCHITECTURE-BRIEF-<date>.md` with the rough spots you picked |
|
||||
| diagnose | /plan2code-diagnose | A bug, or none | `DIAGNOSIS-<date>.md` with the cause and its evidence, then Quick Task (or Plan for a big fix) to fix it |
|
||||
| pr-prep | /plan2code-pr-prep | Your branch | A readiness verdict (Ready, Ready with notes, Not ready) and a PR description to copy; no commits, no push |
|
||||
| test | /plan2code-test | An area, or none | New unit and integration tests in the project's style, run; a bug handed to Diagnose; no source changes |
|
||||
| changelog | /plan2code-changelog | Your branch | `CHANGELOG.md` entries and the `package.json` version, from the default branch's latest version |
|
||||
| git-commit | /plan2code-git-commit | Your changes | A commit (`<subject>` / `AI Assisted`): suggested splits, a branch offer on the default branch, optional push |
|
||||
| git | /plan2code-git | Your repo | Commits (`<subject>` / `AI Assisted`), branches, pull with conflict help, push, publish |
|
||||
|
||||
**Terminal instead:** run any command without `--web` and answer the interface question with **terminal**. Nothing is lost: same questions, same gates, same files under `specs/`. You can switch between the two mid-feature.
|
||||
|
||||
@@ -123,14 +132,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 2.6.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
Version 3.0.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
|
||||
---
|
||||
|
||||
@@ -35,9 +35,9 @@ The dashboard, in a project halfway through a build. It suggests the next step f
|
||||
- **Node.js 18 or newer.** Check with `node --version`. No Node? Get it from [nodejs.org](https://nodejs.org/) (the LTS download), or run `winget install OpenJS.NodeJS.LTS` on Windows, `brew install node` on macOS, or use `nvm` on Linux. Then open a new terminal.
|
||||
- **Start from your project.** Open your terminal in the project you want to work on (`cd` into it) before you run anything. Plan2Code works on the folder you start it in.
|
||||
- **Ways in.** `plan2code` (Claude Code, Devin or Codex), or type `/plan2code` in your agent (`$plan2code` in Codex).
|
||||
- **No agent yet?** Install Claude Code, Codex or Devin first.
|
||||
- **No agent yet?** Install Claude Code, Codex or Devin first, or let the `plan2code` command's setup page walk you through it.
|
||||
|
||||
Installation needs network access and runs through the [skills CLI](https://skills.sh). To update, re-run the install command.
|
||||
Installation needs network access and runs through the [skills CLI](https://skills.sh). To update, run `plan2code update` (or re-run the install command).
|
||||
|
||||
```bash
|
||||
npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git
|
||||
@@ -47,6 +47,11 @@ This fetches the installer to a temp directory, builds the workflow as Agent Ski
|
||||
installation to `skills add`, and cleans up after itself. The installed skills work independently
|
||||
from then on.
|
||||
|
||||
**Back at your prompt with no output at all?** The installer always opens the menu below, so nothing
|
||||
means npm could not reach the repository and hid the reason. Run
|
||||
`git ls-remote https://github.com/jparkerweb/plan2code.git` to see it: usually the network, a proxy
|
||||
or the VPN.
|
||||
|
||||
The installer opens this menu (cloning and running `node install.js`, below, opens the same one):
|
||||
|
||||
```
|
||||
@@ -77,18 +82,70 @@ Install (`I`) adds `plan2code` as a global command (Advanced `A` → `D` adds ju
|
||||
dashboard opens right there, in **Claude Code**, **Devin** or **Codex**. With more than one installed it asks which and
|
||||
remembers your pick; `plan2code --cli claude`, `--cli devin` or `--cli codex` skips the question, and `--model <name>`
|
||||
chooses the model. It works in cmd, PowerShell, Git Bash, macOS and Linux shells, and needs the
|
||||
Claude Code, Devin or Codex CLI on your `PATH`. It starts the agent with permission prompts off
|
||||
(`--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass` in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex); run
|
||||
`claude /plan2code` yourself if you want prompts. The installer then offers a desktop shortcut (answer `y`),
|
||||
Claude Code, Devin or Codex CLI on your `PATH`. After you pick the agent it asks whether to turn its
|
||||
permission prompts off (Yes by default; `--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass`
|
||||
in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex, a custom agent's bypass arguments, and no question for a
|
||||
custom agent that has none). `plan2code --keep-permissions` keeps the prompts without asking. The installer then offers a desktop shortcut (answer `y`),
|
||||
which opens a folder picker first. Uninstalling (`U`) removes both.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Using another agent CLI, or none yet</summary>
|
||||
|
||||
Plan2Code runs inside an AI coding agent CLI. With no agent it can run (none of Claude Code,
|
||||
Devin or Codex, and no working custom agent),
|
||||
`plan2code` opens a setup page in your browser (the web console runs it, so no agent is needed).
|
||||
The page lists each agent as **Found**, **Found outside PATH** or **Not found**, with its install
|
||||
commands for your system, a Copy button per command and an **Install page** link. Install one and
|
||||
press **Check again**: no restart needed. An agent found outside `PATH` gets **Use it from here**,
|
||||
which saves where it was found so you never touch `PATH` yourself. Below the list sit four starter
|
||||
templates (GitHub Copilot CLI, OpenCode, Gemini CLI and Pi) for agents Plan2Code does not ship.
|
||||
**Start with this agent** carries the run straight on in the same tab, onto the new agent's
|
||||
dashboard. Naming a built-in that is missing with `--cli <name>` opens the same page on that agent
|
||||
(a missing custom agent prints its own steps and exits 127). In the
|
||||
desktop app a **Set up an agent** button opens the same page in the window and returns to the
|
||||
launch card with the found agent picked. Where no page can open, such as over SSH or with no
|
||||
display, `plan2code` prints the install commands and install pages and exits with code 127.
|
||||
|
||||
Once an agent is running, to use a different agent CLI, open the web console's **User Preferences → Agents & models** and add it: a name, the
|
||||
command, and (optionally) its arguments, the start prompt, arguments for skipping permission prompts, and
|
||||
how it takes a model. Custom agents are saved in `~/.plan2code/agents.json` and used by both the
|
||||
`plan2code` command (listed after the built-ins; `--cli <id>` picks one) and the desktop app's picker. The
|
||||
`/plan2code` start prompt only does something in an agent that loads the installed Plan2Code skills; for
|
||||
any other, leave the start prompt blank and start a skill yourself. Details in
|
||||
[.readme/web-console.md](.readme/web-console.md#agents--models).
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>About the desktop app</summary>
|
||||
|
||||
The installer also offers the **Plan2Code desktop app**: one window with the dashboard and your agent's
|
||||
terminal side by side, docked right (or bottom) and collapsible. Every console page, not only the
|
||||
dashboard, opens inside it. A launch card asks which agent, model and effort to start on, with
|
||||
permission checks off as its own tick (on by default, matching the terminal flow; untick it to keep
|
||||
the agent's approval prompts). A **New Session** button in the top bar replaces the agent with a fresh
|
||||
one on a brief built from the session, and the console's own Session meter points at it when a
|
||||
session is getting long. Once it is installed, `plan2code` opens the app instead of running the agent
|
||||
in your terminal. `plan2code --classic` keeps the terminal flow, and so does a Linux machine with no
|
||||
display (over SSH, say) or any machine over an SSH session. `plan2code update` updates the skills, the
|
||||
command and the app together, and the bar offers the same **Update skills** when the app and the
|
||||
installed skills disagree.
|
||||
|
||||
The app can also build a whole spec unattended with the Implementation Loop; see [docs/desktop-app.md](docs/desktop-app.md#implementation-loop).
|
||||
|
||||
The first release is unsigned, so macOS (**Open Anyway** in System Settings, Privacy & Security) or
|
||||
Windows (**More info**, then **Run anyway**) may ask you to allow it once. The app starts the agent
|
||||
with its normal approval prompts unless you tick the launch card's permission-checks-off option (the
|
||||
plain `plan2code` command above, without the app, asks instead, with prompts off by default too). Details:
|
||||
[docs/desktop-app.md](docs/desktop-app.md).
|
||||
</details>
|
||||
|
||||
**Supported tools:** every agent supported by the skills CLI, including Claude Code · Cursor ·
|
||||
GitHub Copilot · Windsurf · Codex · Continue · Codeium · Zed · Amp · OpenCode · Devin · Crush · Pi ·
|
||||
Gemini CLI · Cline · Roo · Kilo · Goose · Trae · Qwen Code.
|
||||
|
||||
The installer keeps one canonical copy of each skill under `~/.agents/skills/` and links it into
|
||||
agents that maintain their own directory. To update, re-run the install command.
|
||||
agents that maintain their own directory. To update, run `plan2code update` (or re-run the install command).
|
||||
|
||||
Use the installer rather than calling `skills add` against the repository root: recursive discovery
|
||||
would also find maintainer-only skills under `.claude/skills/`. The installer targets `skills/`
|
||||
@@ -145,7 +202,10 @@ next check-in, and it never holds up your answers.
|
||||
|
||||
There is more on the page when you need it. Notes on any question can carry screenshots and
|
||||
documents. The folder label in the bottom bar opens your workspace, where you add other folders
|
||||
as read-only context and point at them by `@name`. The session meter in the top bar turns from green
|
||||
as read-only context and point at them by `@name`. The **Notebook** in the top bar is a private pad of your own for the
|
||||
folder, in Markdown with pictures, that the agent reads only when you start a workflow from one of its tabs on
|
||||
the dashboard and send the box it fills. The **die** beside it opens **Activities**,
|
||||
two small games (Snake and Mini golf) to play through a long wait, which pause the moment it is your turn. The session meter in the top bar turns from green
|
||||
to red as a session grows long and suggests a fresh one. **Stop session** saves your place and gives
|
||||
you the command to carry on later, and **Back to the dashboard** takes you home to pick the next
|
||||
step in the same session.
|
||||
@@ -179,17 +239,21 @@ The dashboard's cards, and when each one lights up for the spec you pick:
|
||||
| Set up this project | Reads your project and writes AGENTS.md, the guide every later step works from. | The project has no AGENTS.md yet |
|
||||
| Refresh AGENTS.md | Brings AGENTS.md and its notes up to date with what the project has learned lately. | The project has an AGENTS.md |
|
||||
| Pathfinder | A foggy idea becomes a clear list of decisions, settled one question at a time. | You start fresh, or the spec is still being explored |
|
||||
| Plan | Requirements, technical design and your approval: the shape of what gets built. | You start fresh, or the spec has a finished Pathfinder map or a drafted plan |
|
||||
| Revise the plan | Requirements changed mid-build? Adjust the plan without starting over. | The spec is written up into phases and not fully built |
|
||||
| Plan | Requirements, technical design and your approval: the shape of what gets built. | You start fresh, or the spec has a finished Pathfinder map, a drafted plan or a bug diagnosis |
|
||||
| Revise the plan | Requirements changed mid-build? Adjust the plan without starting over. | The spec is written up into phases, built or not |
|
||||
| Document | The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do. | The spec has a drafted plan |
|
||||
| Implement | Builds the next phase, task by task, with a report and your sign-off at the end. | The spec has phases with tasks still to build |
|
||||
| Implement + review | One phase built, then a careful review of the changes, then your sign-off. All in one run. | The spec has phases with tasks still to build |
|
||||
| Finalize | Checks the work, writes the summary, files the specs away and suggests the commit message. | Every task in the spec is done |
|
||||
| Quick task | Too small for the full process? A quick plan, then it just builds it. | Always |
|
||||
| Quick task | Too small for the full process? A quick plan, then it just builds it. | Always (suggested when the spec is a diagnosed bug) |
|
||||
| Review | A second opinion on the changes. Problems ranked, and you pick what gets fixed. | Always |
|
||||
| Handoff | Pack this conversation into a document a fresh session can pick up cold. | Always |
|
||||
| Handoff | Pack this conversation into a document a fresh session can pick up cold. Any skill's **Stop with a handoff** writes one too, and the dashboard lists them to pick up. | Always |
|
||||
| Codebase X-ray | Explain how and why an area works, or find the rough spots worth fixing. | Always |
|
||||
| Diagnose a bug | Find a bug's cause and write it up, without fixing it. | Always |
|
||||
| Get a PR ready | Runs the checks your branch needs, says if it is ready, and writes the PR description to copy. Never commits, pushes or opens the PR. | Always |
|
||||
| Write missing tests | Finds code with no tests and writes unit and integration tests in your project's own style. Never changes source code. | Always |
|
||||
| Changelog | Checks the CHANGELOG version against the main branch and suggests entries for what is new. | Always |
|
||||
| Git commit | Commits your changes with a clear message, suggests a split when it is really two jobs, and offers to push. | Always (offers to start a repository outside one) |
|
||||
| Git | Branches, pull, push and commits on one board, asking before anything leaves your machine. | Always (offers to start a repository outside one) |
|
||||
|
||||
---
|
||||
|
||||
@@ -217,7 +281,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
|
||||
@@ -355,15 +419,19 @@ console or the terminal; add `--web` to skip the question and go straight to the
|
||||
| `/plan2code-init-update` | Fold what you learned this session back into `AGENTS.md` |
|
||||
| `/plan2code-quick-task` | A small change that doesn't warrant the full sequence |
|
||||
| `/plan2code-1b-revise-plan` | Requirements moved mid-build. Revise the specs, not the code |
|
||||
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from |
|
||||
| `/plan2code-changelog` | Check the CHANGELOG version against the default branch, suggest entries for new work you can edit, keep `package.json` aligned, then offer Git commit |
|
||||
| `/plan2code-git-commit` | Commit with a clear message, suggested splits, a branch offer on the default branch, and an optional push |
|
||||
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from, saved in `~/.plan2code/handoffs/` and listed on the dashboard to pick up |
|
||||
| `/plan2code-xray` | Explain how and why an area of the code works (citing files, commits and PRs), or rank the rough spots worth fixing into a brief for Pathfinder or Plan; never edits code |
|
||||
| `/plan2code-diagnose` | Find a bug's cause and write it up as `specs/<bug-name>/DIAGNOSIS-<date>.md` without fixing it, then offer `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big |
|
||||
| `/plan2code-pr-prep` | Before you open a pull request. Picks the checks the branch's changes need from the project's `## Test map` (or its config files), runs the ones you keep, says Ready, Ready with notes or Not ready, and writes a PR description to copy with the create-a-PR link; never commits, pushes or opens the PR |
|
||||
| `/plan2code-test` | Parts of the code have no tests. Asks where to look, finds the untested files (plus real coverage when the project already has a coverage tool), shows a plan in the project's own style, then writes and runs unit and integration tests; never changes source code, hands a real bug to `/plan2code-diagnose` |
|
||||
| `/plan2code-changelog` | Check the CHANGELOG version against the default branch, suggest entries for new work you can edit, keep `package.json` aligned, then hand off to Git to commit |
|
||||
| `/plan2code-git` | Branches, pull, push and commits on one board (or plain instructions in the terminal); asks before every push, publish and delete |
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**The skills aren't recognised.** Re-run the installer and restart your AI tool. Confirm the global
|
||||
**The skills aren't recognized.** Re-run the installer and restart your AI tool. Confirm the global
|
||||
install with `npx skills list -g`. For a project install, check the generated directories aren't
|
||||
gitignored.
|
||||
|
||||
@@ -408,7 +476,7 @@ edits out through the skills CLI.
|
||||
|
||||
Core reference:
|
||||
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off, including the private Notebook and Activities in the top bar
|
||||
- **[QUICK-REFERENCE.md](QUICK-REFERENCE.md)** — the one-page card: commands, inputs, outputs, decision tree
|
||||
- **[.readme/walkthrough.md](.readme/walkthrough.md)** — one feature from a sentence to archived specs, session by session
|
||||
- **[AGENTS.md](AGENTS.md)** — architecture and contributor guide for this repo
|
||||
@@ -416,7 +484,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
|
||||
@@ -0,0 +1,272 @@
|
||||
# The Plan2Code desktop app
|
||||
|
||||
One window for working with an AI agent. The app opens the Plan2Code dashboard as its main surface,
|
||||
runs your agent (Claude Code, Devin or Codex) in a terminal panel it owns, and has a **New Session**
|
||||
button that replaces the agent with a fresh one on a brief the app builds from its own record of the
|
||||
session. The fresh agent gets a console session of its own, so the Session meter starts over with it.
|
||||
It is an addition: `/plan2code` typed inside an agent works exactly as before, with or
|
||||
without the app.
|
||||
|
||||
## Get it
|
||||
|
||||
The installer offers the app after the skills and the `plan2code` command:
|
||||
|
||||
```
|
||||
npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git
|
||||
```
|
||||
|
||||
Answer **Y** to "Also install the Plan2Code desktop app?" (it is the default). It downloads the file
|
||||
for your system from the GitHub release, checks it against the release's checksum list and puts it in
|
||||
`~/.plan2code/app/`. If a checksum does not match, the file is thrown away and nothing is installed.
|
||||
If the download fails, the skills and the `plan2code` command are still installed; the installer says
|
||||
so, and you can run the installer again later.
|
||||
|
||||
Releases carry one file per system:
|
||||
|
||||
| System | File |
|
||||
| --- | --- |
|
||||
| Windows (64-bit Intel or AMD) | `plan2code-app-<version>-windows-x64.exe` |
|
||||
| macOS (Apple silicon) | `plan2code-app-<version>-macos-arm64` |
|
||||
| macOS (Intel) | `plan2code-app-<version>-macos-x64` |
|
||||
| Linux (64-bit Intel or AMD) | `plan2code-app-<version>-linux-x64` |
|
||||
|
||||
On any other system the installer says there is no build for it and carries on without the app.
|
||||
|
||||
Each of those is a plain executable, not an OS-level installer package (no `.msi`, no NSIS `.exe`
|
||||
setup, no `.dmg` with a drag-to-Applications step): the installer above places it directly, already
|
||||
verified. `plan2code-app`'s own `npm run build` can produce `.msi`/NSIS/`.dmg`/`.deb` bundles locally
|
||||
(Tauri's bundler is on), but the release workflow does not build or publish them; nothing today
|
||||
downloads or runs one.
|
||||
|
||||
You also need Node.js 18 or newer (the app checks at start and says what to install) and:
|
||||
|
||||
- **Windows:** the WebView2 runtime, which comes with Windows 11 and current Windows 10.
|
||||
- **Linux:** WebKitGTK 4.1 (`libwebkit2gtk-4.1`) and a desktop session.
|
||||
|
||||
## Start it
|
||||
|
||||
Run `plan2code` in your project, as always. When the app is installed and a window can open,
|
||||
`plan2code` asks which agent and model (as before) and then opens the app on that folder instead of
|
||||
running the agent in your terminal. The desktop shortcut the installer can create runs the same
|
||||
command, so it opens the app too.
|
||||
|
||||
Three things keep today's terminal flow:
|
||||
|
||||
- **`plan2code --classic`** runs the agent in your terminal even when the app is installed.
|
||||
- **No display.** On Linux without a display (over SSH, in a container) `plan2code` falls back to the
|
||||
terminal flow by itself.
|
||||
- **An SSH or service session on macOS or Windows.** The same fallback applies there, since neither
|
||||
has a desktop to open a window on either.
|
||||
- **Not a project folder.** If the folder is not a git repository and has no `AGENTS.md` or `specs/`,
|
||||
`plan2code` asks you to confirm before opening the app on it.
|
||||
|
||||
## What's in the window
|
||||
|
||||
The first time the app opens on a folder, a checklist confirms Node, the agent CLI, the project
|
||||
folder and the skills version before anything else shows; a later launch skips straight past it.
|
||||
|
||||
A **launch card** then asks which agent, model and effort (Claude and Codex only) to start on. The
|
||||
picker lists Claude Code, Devin and Codex, then any custom agents you added in the web console's
|
||||
**User Preferences → Agents & models** (saved in `~/.plan2code/agents.json`, shared with the `plan2code`
|
||||
command), and starts on one that is actually installed, so a machine with only Devin or Codex is ready
|
||||
to go. Permission checks off is its own tick, on by default (see below; New Session keeps whatever
|
||||
you picked, and reuses the same agent); a CLI the app cannot find is named, with how to install it,
|
||||
instead of just being grayed out. The card is skipped when the launcher already passed an agent to
|
||||
start.
|
||||
|
||||
With no agent installed at all, the checklist and the launch card each show a **Set up an agent**
|
||||
button. It opens the same setup page the `plan2code` command uses, inside the app's window: every
|
||||
built-in listed as found, found outside PATH or not found, with its install commands for your
|
||||
system, an **Install page** link, **Check again**, **Use it from here** for one found outside
|
||||
PATH, and the starter templates for other agent CLIs. When the page reports an agent found, the
|
||||
app returns to where it was (the checklist or the launch card), re-checks, and picks that agent on
|
||||
the launch card ready for Start. A **Back** button leaves the page at any time. When the saved
|
||||
(last used) agent is gone but another works, a one-line notice on the launch card says so and the
|
||||
card carries on with the working one.
|
||||
|
||||
The window's own title (and so its taskbar entry) reads **Plan2Code - <folder name>** once a
|
||||
project is open, so two or more windows on different projects read apart without opening each one
|
||||
to check.
|
||||
|
||||
The taskbar entry also shows when Plan2Code needs you, the same states as the console's tab icon in
|
||||
a browser. On Windows a green dot means it is your move and a red dot means it needs attention, with
|
||||
one short burst of flashes when the window is not focused; on macOS the dock shows a red `!` badge on
|
||||
needs attention and bounces once; on Linux a count badge appears where the desktop supports it. There
|
||||
is no dot while the agent is busy or once a finished step has nothing left to press (a finished screen
|
||||
that still offers a button, such as back to the dashboard, keeps the green dot), and it clears when
|
||||
the agent ends or the page reloads. Turn it off with **Show on the taskbar when Plan2Code needs
|
||||
me** under **User Preferences → System → Desktop app** (shown only inside the app). The per-system details are in
|
||||
[plan2code-app/README.md](../plan2code-app/README.md#agents-and-the-taskbar).
|
||||
|
||||
A slim top bar reads, left to right: the project folder's name, a menu holding its full path and
|
||||
**Change project**; **New Session**, whenever an agent exists; the agent's own menu, with a dot for its
|
||||
state, an amber **checks off** badge while permission checks are off, and **Change agent** once it has
|
||||
ended; a short line (why the agent ended, a New Session's brief, or what went wrong); and, at the right
|
||||
end, the one next step for the console or the skills when there is one (**Reconnect the console**,
|
||||
**Update skills**), with "+N more" if anything else is waiting behind it. The console itself, opening inside the
|
||||
window (not only the dashboard — every console page, including Ask, Workspace, Notebook, Help,
|
||||
Preferences and Git), already shows which page is open and its own **Session** meter (how much plan2code
|
||||
work this session has done) in its own bar, so the app's bar does not repeat either. That Session meter
|
||||
is the one place for "is this session getting long" under the app, too: the app does not keep a second,
|
||||
separate context-window meter of its own, so there is only ever one gauge to read and only one place its
|
||||
threshold is tuned. The terminal panel has its own toolbar: dock it to the bottom or the right, collapse
|
||||
it to a thin strip, or maximize it; its size is remembered. An "agent may need you" badge appears on a
|
||||
collapsed or small panel once the agent has sat quiet for a while. **Change project** (in the project
|
||||
menu) asks first if an agent is running, then stops it and the console before opening the new folder.
|
||||
|
||||
If the console itself ever needs reconnecting (it stopped, or the skills were just updated), every path
|
||||
to that offers the same **Reconnect the console** button — never "Restart the console" in one place and
|
||||
"Start it again" in another for the same action — and only one shows at a time.
|
||||
|
||||
The console also knows when it is running inside the app (the agent it talks to carries that signal):
|
||||
its session meter, the "Before you close this" guide on a finished step, and the dashboard's red-session
|
||||
banner all point at the app's own **New Session** button instead of a command to paste into a new
|
||||
conversation, since New Session already does that in one click; and the console's own "update available"
|
||||
banner never shows, since the app's **Update skills** button (below) already covers it with no shell
|
||||
involved. A slash command still offered to continue a step (such as `/plan2code-4-finalize`) stays
|
||||
exactly as it would in a terminal: paste it into the app's own terminal panel, which runs the real
|
||||
agent CLI.
|
||||
|
||||
## Implementation Loop
|
||||
|
||||
The Implementation Loop builds every remaining phase of a documented spec for you, one after another,
|
||||
while you do something else. It is in the app only: the dashboard shows an **Implementation Loop**
|
||||
card there, and nowhere else. Pick a spec, answer a short setup, press **Start the loop**, and the app
|
||||
confirms it once in its own window before anything runs.
|
||||
|
||||
**How it runs.** Each phase gets a fresh agent session, so a long spec never grows one tired
|
||||
conversation. The app, not the agent, decides when a phase counts: it reads the spec's marks, runs the
|
||||
quick check, marks the phase done and commits it. With commits on, it commits to the branch you are on and never
|
||||
pushes. With commits on, Start needs a clean working tree (the setup offers the Git board when it is
|
||||
not), so your own edits never end up inside a phase's commit.
|
||||
|
||||
**The setup.** The fields and their defaults:
|
||||
|
||||
- **Review each phase** (on): a fresh agent reviews the phase before it counts.
|
||||
- **Fix findings**: **Smart pick** (the default) has a fresh agent read the findings and fix only the
|
||||
ones worth fixing, recording every skip. A skipped Critical stops the phase. **By level** fixes the
|
||||
Critical, Warning and Suggestion findings you tick (all three start ticked).
|
||||
- **Strength per phase** (off): turn on **Set strength per phase** to pick **Thrifty**, **Balanced**, **Best** or **Match my session** for each phase still to build (or **Set all to** one pick). A phase you leave untouched runs on the model the app was launched with, as before. A phase whose agent crashes or goes quiet gets its one retry (when the retry tick is on) one step up (Thrifty to Balanced, Balanced to Best; Best stays Best; **Match my session** runs on the launch model and its retry stays there), and the phase's helpers follow the same strength. Which model each word means for your agent is set in User Preferences, **Agents & models**, under **Strengths in the loop**; an agent with nothing mapped shows the toggle off with a link there. The picks are remembered per project and spec, and a pick for a phase that is done or gone is dropped.
|
||||
- **When a phase asks something**: **Take the agent's best guess** (the default), which records the
|
||||
assumption as a `[?]` task, **Pause and wait for me**, or **Stop the loop**.
|
||||
- **After the last phase**: **Stop and offer Finalize** (the default) or **Run Finalize automatically**.
|
||||
- **Quick check**: a command run after each phase, pre-filled from the project (for example
|
||||
`npm run build`). Clearing it still lets you start; the setup warns that nothing is checked.
|
||||
- **If a phase crashes or goes quiet**: **Retry it once** (on), and how many minutes with no file changes, in the project or the agent's
|
||||
session, count the agent as stuck (20). Waiting on your answer does not count.
|
||||
- **Send a notification** (no address, so off): a message from the loop when it waits on your answer or
|
||||
ends. Send it to a Discord, Slack, Microsoft Teams or Google Chat webhook, or to any `http` or `https`
|
||||
address with the message in its query string or a JSON body.
|
||||
- **Commit each phase** (on): one local commit per phase, with the subject and `AI Assisted`.
|
||||
|
||||
The last setup is remembered per project in `~/.plan2code/console/loop-setup.json`, so the next loop
|
||||
starts from it. The quick check is typed text the page never runs: the app reads it from that file
|
||||
itself and names it in its own window before the loop begins. The notification gets the same treatment,
|
||||
and Resume asks again if either one changed.
|
||||
|
||||
**The notification.** The loop says a question is waiting, that it is complete, or why it stopped. Nothing
|
||||
is sent when you stopped it yourself, and with **Take the agent's best guess** no question ever waits on
|
||||
you. What the app sends depends on the **Send to** choice:
|
||||
|
||||
| Send to | Request | Where the message goes |
|
||||
| --- | --- | --- |
|
||||
| A web address, query string | GET | A parameter you name (`message` by default), added to the address's own |
|
||||
| Discord webhook | POST JSON | `content`, with mentions turned off |
|
||||
| Slack webhook | POST JSON | `text` |
|
||||
| Microsoft Teams webhook | POST JSON | An Adaptive Card, for a Workflows "when a webhook request is received" trigger |
|
||||
| Google Chat webhook | POST JSON | `text` |
|
||||
| A web address, JSON body | POST JSON | A field you name (`message` by default) |
|
||||
|
||||
**Send a test** saves the setup and sends a test message right away, after the app names the address in its
|
||||
own window, so a wrong address shows up before a long run. A name can use letters, digits and `- _ . ~`. Pasting a Discord, Slack, Teams or Google Chat address picks
|
||||
its choice for you, since a plain GET to a Discord webhook answers 200 and posts nothing. The call has 10
|
||||
seconds and any 2xx answer counts. One that fails never changes what the loop does: the finish line or the
|
||||
stop screen's evidence says so, without repeating the address, which is stored in `loop-setup.json` and
|
||||
usually holds a token.
|
||||
|
||||
**It uses the app's agent.** The loop starts every phase on the agent and model you launched the app
|
||||
with, and it needs permission checks off. With them on, an agent would wait on a prompt that nobody
|
||||
sees, so **Start the loop** stays grayed out until you turn them off (see
|
||||
[Permission checks are off by default](#permission-checks-are-off-by-default-same-as-the-terminal)).
|
||||
|
||||
**What is locked while it drives.** Answers, sign-offs, launches, Workspace, Helpers, **Back** and
|
||||
**New Session** are read-only, and Ask is off, except for a question the loop is waiting on. Activities, Notebook, Help, Preferences, the documents
|
||||
and the code review stay usable, so you can watch, play, or read along.
|
||||
|
||||
**You can always see it's running.** From the moment you confirm Start until the loop ends, a banner runs
|
||||
across the top of the window, outside the console page, so it stays put as each phase's session comes and
|
||||
goes. It says what the loop is doing right now (starting, building, between phases, stopping), with the
|
||||
phase, its name and step, a pip per phase, the time so far and any retries. It turns amber when a question
|
||||
needs your answer. The window title says the same, for the taskbar. While the loop works, the page's Send
|
||||
button and "Nothing to send" line go away, and they come back when a question waits.
|
||||
|
||||
**Stopping it.** Two buttons on the banner: **Stop after this phase** lets the phase finish its
|
||||
review, mark and commit, then ends the loop; **Stop now** ends the agent at once, after you confirm, and never commits, retries or finishes the build (a commit already begun finishes first). Stop after can be canceled by pressing it again. After a window reload the banner and both buttons come back, and Change project and Change agent are blocked while the loop runs.
|
||||
Quitting the app ends the loop too, and the quit check says which phases are already committed.
|
||||
|
||||
**A question holds the loop.** When a phase needs an answer (with **Pause and wait for me**), the loop
|
||||
waits with no time limit and nothing is lost. The app calls you back with the taskbar dot, a flash
|
||||
of the window and the question sound, and carries on once you answer.
|
||||
|
||||
**When it stops by itself.** The loop ends on a stop screen, saying what failed and showing the
|
||||
evidence, when:
|
||||
|
||||
- the phase's named tests or the quick check fail;
|
||||
- Critical or Warning findings are left after the re-check, at a level the setup said to fix (a leftover Suggestion does not stop it);
|
||||
- a task is blocked or the spec conflicts with itself;
|
||||
- a commit is refused, for example by a pre-commit hook (the app puts the phase file back as it was, so the spec and git agree, and stops with the hook's first line; if the undo fails too, it says so and remembers it across a restart);
|
||||
- a staged file looks like a secret (`.env` and the like; `.example`, `.sample` and `.template` are fine) or is oversized (nothing stays staged, and the stop line names the file);
|
||||
- the project is on a detached HEAD (the loop will not start);
|
||||
- the agent's report is missing task data or says its tests failed (the phase is refused);
|
||||
- the watcher cannot read the session or hits an internal error (it ends on a stop screen, never a hang);
|
||||
- the Smart pick skipped a Critical finding.
|
||||
|
||||
A crashed or silent agent gets exactly one retry per phase when the retry tick is on, and none when it is off.
|
||||
It never retries a real failure. On a stop screen, **Ask a question** (first in the row, offered whenever Resume is) wakes an ordinary agent on the stopped phase on the same page, so the Ask tab answers; it starts no loop and changes nothing, and **Resume the loop** is still there afterwards. **Resume the loop** carries on from the stopped
|
||||
phase and **Fix it by hand** opens an ordinary Implement session on it.
|
||||
|
||||
**The report.** One report follows the whole build, across stops and Resume. For every phase it says what
|
||||
was built and committed, the tests, the findings fixed, the findings it chose not to fix and why, the
|
||||
findings left open, each assumption with its note, and any other decisions the agent reported, plus every
|
||||
retry and stop, in order. The agent writes most of this, so it holds what the agent noticed; the task marks,
|
||||
the quick check and the commits are the app's own. The finish screen counts each kind per phase, and **Read
|
||||
the full report** opens it, saved as `specs/<feature>/LOOP-SUMMARY-<date>.md` (`-2` and so on for another
|
||||
the same day). After a stop, **Read why, and the report so far** shows it on the stop screen. While a build
|
||||
is unfinished it lives in `~/.plan2code/console/loop-reports.json`, not the project, because Resume needs a
|
||||
clean tree. The in-app **Help** has a matching topic, **Implementation Loop**, which the loop card links to as "How the loop works".
|
||||
|
||||
## Keep it up to date
|
||||
|
||||
`plan2code update` brings the skills, the `plan2code` command and the app up together. If the app
|
||||
and the installed skills ever differ in version, the app's top bar says so and offers **Update
|
||||
skills**, which runs that same update when you press it. It never updates on its own.
|
||||
|
||||
## The first release is unsigned
|
||||
|
||||
The app is not code-signed yet, so your system may stop it the first time it starts. It is the same
|
||||
file the installer verified against the release's checksum list.
|
||||
|
||||
**macOS.** If macOS says the app "cannot be opened because Apple cannot check it for malicious
|
||||
software": open **System Settings**, then **Privacy & Security**, scroll to the message about
|
||||
`plan2code-app`, and press **Open Anyway**. Start `plan2code` again and confirm.
|
||||
|
||||
**Windows.** If SmartScreen shows "Windows protected your PC": press **More info**, then **Run
|
||||
anyway**.
|
||||
|
||||
**Linux.** Nothing to allow. If the file is not executable, run
|
||||
`chmod +x ~/.plan2code/app/plan2code-app`.
|
||||
|
||||
## Permission checks are off by default, same as the terminal
|
||||
|
||||
The launch card's permission-mode tick is **on by default** (checks off), matching `plan2code` run the
|
||||
plain way, where the same question defaults to prompts off: the agent starts with checks off (`--permission-mode bypassPermissions` in Claude Code,
|
||||
`--permission-mode bypass` in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex), reading,
|
||||
writing and running commands in your project folder without asking; the agent's amber **checks off** badge in
|
||||
the top bar says so while that agent runs. Untick it before pressing Start agent to keep the agent's normal approval prompts instead.
|
||||
New Session keeps the same choice. Work in a folder you are happy for the agent to change, and keep it under
|
||||
version control.
|
||||
|
||||
## Remove it
|
||||
|
||||
Choose **Uninstall** in the installer menu: it removes the app with everything else Plan2Code
|
||||
installed. To remove only the app, delete the `~/.plan2code/app/` folder.
|
||||
|
Before Width: | Height: | Size: 95 KiB After Width: | Height: | Size: 99 KiB |
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 107 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 81 KiB After Width: | Height: | Size: 90 KiB |
|
Before Width: | Height: | Size: 87 KiB After Width: | Height: | Size: 95 KiB |
|
Before Width: | Height: | Size: 92 KiB After Width: | Height: | Size: 113 KiB |
|
Before Width: | Height: | Size: 99 KiB After Width: | Height: | Size: 123 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 115 KiB After Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 94 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 100 KiB After Width: | Height: | Size: 101 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 67 KiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 113 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 86 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 95 KiB After Width: | Height: | Size: 105 KiB |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code",
|
||||
"version": "2.6.0",
|
||||
"version": "3.0.0",
|
||||
"private": true,
|
||||
"bin": {
|
||||
"plan2code-install": "./install.js"
|
||||
@@ -8,9 +8,14 @@
|
||||
"scripts": {
|
||||
"prepare": "husky",
|
||||
"build:skills": "node install.js --build-skills",
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-getting-started.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs scripts/test-script-git-commit.mjs scripts/test-script-changelog.mjs"
|
||||
"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-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-coverage.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-flock.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-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.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-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.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-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.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-send-state.mjs scripts/test-web-console-strengths.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-agent-lookup.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-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"husky": "^9.0.0"
|
||||
"gpt-tokenizer": "2.9.0",
|
||||
"husky": "^9.0.0",
|
||||
"playwright-core": "1.64.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["src-tauri", "fake-agent"]
|
||||
@@ -0,0 +1,55 @@
|
||||
# plan2code-app
|
||||
|
||||
The Plan2Code desktop app (v3.0): one window with the dashboard, a terminal panel for the agent, and a **New Session** button. Built with Tauri 2 (Rust and a web view).
|
||||
|
||||
The app is optional. The Node web console and the skills never depend on it, so running `/plan2code` inside an agent with no app works exactly as before.
|
||||
|
||||
## Agents and the taskbar
|
||||
|
||||
**Agent picker.** The launch card lists Claude Code, Devin and Codex, then any custom agents from `~/.plan2code/agents.json` (added in the console's User Preferences → Agents & models, the same list the `plan2code` command uses). The app starts on an agent that is installed (your last pick when it still is), never assumes Claude Code, and a custom agent has no effort row; New Session reuses whichever agent you started. The Model dropdown offers the same list the `plan2code` launcher's model question does (the shipped `models.json` plus anything you added in User Preferences), a custom agent its own `models`, and it hides for an agent with none; `/plan2code` only does something in an agent that loads the installed Plan2Code skills.
|
||||
|
||||
**No agent installed.** The first-run checklist and the launch card show what an agent CLI is, each built-in's install command and an **Install page** link, and a note that other agents are added under Agents. Install one, press **Check again** (the app looks at `PATH` and `agents.json` again), and Start works without restarting the app.
|
||||
|
||||
**Taskbar signal.** The console page tells the app when it is busy, your move, or needs attention (the same states as its tab icon), and the app shows it:
|
||||
|
||||
| System | Your move | Needs attention |
|
||||
|---|---|---|
|
||||
| Windows | green dot on the taskbar button, and one short burst of flashes when the window is not focused (the button then stays lit until focused) | red dot, and the same burst when not focused |
|
||||
| macOS | no badge (the system badge cannot be green), one bounce when not focused | red `!` dock badge, and one bounce when not focused |
|
||||
| Linux | the urgency hint when not focused | a count badge of 1 where the desktop supports it, and the urgency hint |
|
||||
|
||||
There is no dot while busy or once a finished step has nothing left to press; a finished screen that still offers a button (back to the dashboard, a review) keeps the green dot. The dot clears when the agent ends, the page reloads or the page stops answering, and a lit taskbar button goes back to normal when the window gets focus. **User Preferences → System → Desktop app** (shown only inside the app) has the switch **Show on the taskbar when Plan2Code needs me**, on by default; off clears the dot and stops flashes. It is saved as `taskbarSignal` in the app's own `~/.plan2code/app.json`.
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | What it is |
|
||||
|---|---|
|
||||
| `src-tauri/` | The Rust app |
|
||||
| `ui/` | The app page (plain HTML, CSS and JavaScript, no framework) |
|
||||
| `fake-agent/` | A stand-in agent program the tests run in a real pseudo-terminal |
|
||||
| `package.json` | The app's own npm packages (xterm, the Tauri CLI). Separate from the repo root so the root and the console stay dependency-free |
|
||||
|
||||
## Build and run
|
||||
|
||||
Needs the Rust toolchain pinned in `rust-toolchain.toml`, Node 18+, and the Tauri 2 system packages for your system (WebView2 on Windows, WebKitGTK on Linux).
|
||||
|
||||
```
|
||||
cd plan2code-app
|
||||
npm install
|
||||
npm run dev # run the app
|
||||
npm run build # build the installable bundle
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
```
|
||||
cd plan2code-app
|
||||
node scripts/vendor.mjs # once: the xterm files cargo builds against
|
||||
cargo fmt --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
```
|
||||
|
||||
The `app` workflow runs all three on Windows, macOS and Linux, and fails on any rustfmt difference or clippy warning, so run them before pushing, not only `cargo test`. Clippy on one system does not see code for another: an import used only inside a `#[cfg(windows)]` test is clean on Windows and an unused-import error on macOS and Linux, so put such imports inside the `cfg`'d item.
|
||||
|
||||
Real Claude, Devin and Codex are never started by a test. The real window and terminal panel are checked by hand before each release.
|
||||
@@ -0,0 +1,131 @@
|
||||
# Release checklist
|
||||
|
||||
Run this before every release of the desktop app, on each system the release builds for: Windows
|
||||
x64, macOS Apple silicon and Linux x64. Automated tests cover the logic and never start a real
|
||||
window, a real terminal panel, or a real Claude, Devin or Codex, so everything here is by hand.
|
||||
|
||||
Work from the pre-release build: publish a GitHub pre-release so `release-app.yml` attaches the files,
|
||||
then install from it. Tick each box per system and note anything that is a rough edge rather than a
|
||||
failure.
|
||||
|
||||
`npm run build` here runs `tauri build` with bundling on, so a local build also produces `.msi`/NSIS
|
||||
`.exe`/`.dmg`/`.deb` installer packages under `src-tauri/target/release/bundle/`. Ignore those: the
|
||||
release workflow builds with `--no-bundle` and attaches only the plain executable per system (see
|
||||
`.github/workflows/release-app.yml`); `install.js` is the only installer, and it places that plain
|
||||
file directly after checking it against the release's checksum list.
|
||||
|
||||
## Before you start
|
||||
|
||||
- [ ] `node scripts/check-versions.mjs --tag v<version>` passes (version.json, package.json,
|
||||
CHANGELOG.md and the app's tauri.conf.json, package.json and Cargo.toml all agree)
|
||||
- [ ] `npm test` passes at the repo root, with the app absent
|
||||
- [ ] `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings` and
|
||||
`cargo test --workspace` pass in `plan2code-app/`, and the `app` workflow is green on all
|
||||
three systems
|
||||
- [ ] The pre-release has one `plan2code-app-<version>-<os>-<arch>` file per system and a
|
||||
`plan2code-app-<version>-SHA256SUMS.txt`
|
||||
|
||||
## Install and launch (each system)
|
||||
|
||||
- [ ] Run the installer from the pre-release: it offers the app, downloads it, verifies the checksum
|
||||
and places it in `~/.plan2code/app/`
|
||||
- [ ] A deliberately corrupted download is rejected with the checksum message, and the skills and
|
||||
the `plan2code` command are still installed
|
||||
- [ ] `plan2code` in a project asks for the agent and model, then opens the app on that folder
|
||||
- [ ] The agent and model picked in the launcher are the ones the app starts at once, with no
|
||||
launch card or checklist shown first, and New Session keeps them
|
||||
- [ ] `plan2code --classic` runs the agent in the terminal with the app installed
|
||||
- [ ] Linux only: with `DISPLAY` and `WAYLAND_DISPLAY` unset, `plan2code` runs the terminal flow
|
||||
- [ ] The desktop shortcut opens the folder picker and then the app
|
||||
- [ ] macOS: the first start is stopped by Gatekeeper, **Open Anyway** in System Settings (Privacy &
|
||||
Security) lets it through, and `docs/desktop-app.md` describes what you saw
|
||||
- [ ] macOS and Linux: start the app from the Dock, Finder or a `.desktop` file (not a terminal) on
|
||||
a machine where Node is only on PATH through nvm, Homebrew or Volta: the first-run checklist
|
||||
still finds Node and the installed CLIs, and the console and an agent still start
|
||||
- [ ] Windows: SmartScreen's **More info**, then **Run anyway**, lets it through, and
|
||||
`docs/desktop-app.md` describes what you saw
|
||||
- [ ] `plan2code update` updates the skills, the command and the app, including while the app is
|
||||
running (Windows replaces the file by renaming the old one aside)
|
||||
|
||||
## The window (each system)
|
||||
|
||||
- [ ] The dashboard shows in the frame and the terminal panel is visible beneath it
|
||||
- [ ] Resizing the window keeps both usable; dragging the handle resizes the panel
|
||||
- [ ] The bar shows the project folder; the permission note appears only while an agent started
|
||||
with checks off is running, never otherwise
|
||||
- [ ] The OS window title (and so the taskbar entry) reads **Plan2Code - <folder name>**,
|
||||
not just **Plan2Code**; open a second window on a different folder and confirm they read
|
||||
apart in the taskbar without needing to restore either one
|
||||
- [ ] The first run (no `firstRunDone` saved yet) shows the checklist (Node, an agent CLI, the
|
||||
project folder, the skills version) before the launch card; a later launch goes straight to
|
||||
the launch card
|
||||
- [ ] The launch card offers agent, a model dropdown (the same models.json list the `plan2code`
|
||||
launcher asks with, hidden for an agent with no listed models), effort (Claude and Codex
|
||||
only) and permission mode (checks off is ticked by default, matching the plain `plan2code`
|
||||
launcher; untick it for an agent that keeps its normal approval prompts); a CLI it could
|
||||
not find is named, not just disabled
|
||||
- [ ] **Dock the terminal to the right**: the splitter becomes vertical, the toolbar stacks, and the
|
||||
dashboard keeps the rest of the width; dock it back to the bottom
|
||||
- [ ] **Collapse** the terminal to a thin strip (either dock) and **View Agent Terminal** brings it
|
||||
back; its size from before collapsing is remembered
|
||||
- [ ] Docked right, collapsed: the **View Agent Terminal** label reads top-to-bottom and fits inside the strip,
|
||||
not sideways text running off the edge
|
||||
- [ ] Collapse the terminal (or shrink it small), let the agent go quiet for a while mid-answer: the
|
||||
"agent may need you" badge appears on the strip; expanding it clears the badge
|
||||
- [ ] The top bar's project and agent menus open under their name, close on a click elsewhere (the
|
||||
console frame and the terminal included) or Escape, and are not cut off by the bar
|
||||
- [ ] **Change project** in the top bar's project menu, with an agent running: it asks first, then the folder
|
||||
picker opens; canceling the picker leaves the running agent and its project untouched
|
||||
- [ ] Change project, pick a different folder: the old agent and console stop, the new folder opens
|
||||
on the launch card (or the checklist, if its own first run has not passed yet)
|
||||
- [ ] Reload the window (or navigate away and back) while an agent is running: the terminal redraws
|
||||
from where it was, not blank, and the dashboard reconnects to the same session
|
||||
- [ ] When the app and the installed skills differ in version, the bar's right end offers **Update
|
||||
skills**, and nothing updates until it is pressed; with the console stopped as well, Reconnect
|
||||
the console shows first and "+1 more" names the update
|
||||
|
||||
## The terminal panel, with each real agent (each system)
|
||||
|
||||
Do each of Claude Code, Devin and Codex for a few minutes:
|
||||
|
||||
- [ ] Startup screen draws correctly
|
||||
- [ ] Typing a prompt and getting an answer
|
||||
- [ ] A long streamed answer scrolls and stays readable
|
||||
- [ ] Resizing the window reflows the agent's screen
|
||||
- [ ] Pasting several lines
|
||||
- [ ] A line with Unicode and emoji
|
||||
- [ ] Select text in the terminal: it copies on its own; Ctrl+Shift+C (Windows, Linux) or Cmd+C
|
||||
(macOS) copies the selection too; Ctrl+V / Cmd+V pastes
|
||||
- [ ] Exiting the agent: the agent menu reads "ended" with the reason beside it, and New Session stays
|
||||
just left of it
|
||||
|
||||
## Agent lifecycle
|
||||
|
||||
- [ ] Start, then **New Session**: it confirms once, with Planny on a coffee break and no claim about unsaved
|
||||
work, then a fresh agent starts on the same agent, model, effort and permission mode, and the
|
||||
dashboard shows the pick-up chip with a brief that matches the session
|
||||
- [ ] An agent that ends by itself leaves the app asking nothing until New Session or **Change agent**
|
||||
(in the agent menu) is pressed; Change agent reopens the launch card with a real choice to make again
|
||||
- [ ] Closing the window while an agent runs asks first, and "no" keeps the window open
|
||||
- [ ] Cmd+Q on macOS asks the same
|
||||
- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then New Session; check Task
|
||||
Manager and confirm no leftover `node.exe` (or the CLI's own process) is left running
|
||||
|
||||
## Agents and the taskbar (each system)
|
||||
|
||||
- [ ] A custom agent added in the console's User Preferences → Agents & models (the fake agent in `fake-agent/` works) shows in the launch card's picker after the built-ins, starts, and **New Session** starts the same agent again; the bypass box adds its bypass arguments
|
||||
- [ ] With no agent CLI on `PATH` and no custom agent, the first-run checklist and the launch card show the explainer with each install command and an **Install page** link, and Start is off
|
||||
- [ ] Each **Install page** link opens the right page in the default browser (Claude Code, Devin, Codex)
|
||||
- [ ] Install an agent (or add a custom one), press **Check again**: it appears and Start turns on without restarting the app
|
||||
- [ ] With only one agent installed and nothing remembered, the launch card starts on that agent, not Claude Code
|
||||
- [ ] Windows: the taskbar button shows a green dot when it is your move and a red dot when Plan2Code needs attention, a green dot on a finished screen that still offers a button (back to the dashboard, a review), and no dot while the agent is busy, once a finished step has nothing left to press, or after the agent ends
|
||||
- [ ] Windows: with the window unfocused, the button gives one short burst of flashes when it becomes your move or needs attention (not again on a repeat) and stays lit until the window gets focus
|
||||
- [ ] macOS: the dock shows a red `!` badge when Plan2Code needs attention (no badge on your move), and bounces once when it becomes your move or needs attention while the app is in the background
|
||||
- [ ] Linux: where the desktop shows badges, a count of 1 appears on needs attention, and the window is marked as wanting attention while unfocused
|
||||
- [ ] Reloading the window, or ending the agent, clears the dot
|
||||
- [ ] User Preferences → System → Desktop app (shown only inside the app, not in a browser tab) has **Show on the taskbar when Plan2Code needs me**, on by default; switching it off clears the dot at once and stops flashes, and the choice is still off after quitting and reopening the app
|
||||
|
||||
## Standalone path
|
||||
|
||||
- [ ] `/plan2code` typed inside an agent with the app closed opens the dashboard exactly as before
|
||||
- [ ] `npm test` still passes with the app installed on this machine
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "fake-agent"
|
||||
version = "3.0.0"
|
||||
description = "A stand-in agent program for the Plan2Code app's tests"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
terminal_size = "0.4"
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,246 @@
|
||||
//! A stand-in for Claude, Devin and Codex in the app's tests.
|
||||
//!
|
||||
//! It behaves the same on Windows, macOS and Linux. Commands, one per line on
|
||||
//! stdin (these words are the contract the app's integration tests rely on):
|
||||
//!
|
||||
//! STEP <n> print one progress line a second for n seconds, then `STEP DONE`
|
||||
//! EXIT <c> exit with code c
|
||||
//! SIZE print the terminal size once
|
||||
//! PID print the agent's process id as `PID <n>`
|
||||
//! REPORT <json> write <json> as `loopOutcome` into the session's state.json
|
||||
//! (PLAN2CODE_CONSOLE_HOME and PLAN2CODE_CONSOLE_SID name it), say
|
||||
//! `REPORT written` (`REPORT unavailable` when either is missing)
|
||||
//! ENV <name> print the variable as `ENV <name>=<value>`
|
||||
//! HANG say `HANGING`, then go silent for good (no more lines read)
|
||||
//! <other> echoed back as `echo: <line>`
|
||||
//!
|
||||
//! A change in terminal size is reported on its own as `SIZE <cols>x<rows>`.
|
||||
|
||||
use std::io::{self, BufRead, Write};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use terminal_size::{terminal_size, Height, Width};
|
||||
|
||||
fn size_text() -> Option<String> {
|
||||
terminal_size().map(|(Width(w), Height(h))| format!("SIZE {w}x{h}"))
|
||||
}
|
||||
|
||||
fn say(line: &str) {
|
||||
let mut out = io::stdout().lock();
|
||||
let _ = writeln!(out, "{line}\r");
|
||||
let _ = out.flush();
|
||||
}
|
||||
|
||||
/// What a command line asks the agent to do.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Command {
|
||||
Step(u64),
|
||||
Exit(i32),
|
||||
Size,
|
||||
Pid,
|
||||
/// `ENV NAME`: print the variable's value, for tests of what an agent is given.
|
||||
Env(String),
|
||||
/// `REPORT <json>`: the phase report the loop waits for, as the JSON text.
|
||||
Report(String),
|
||||
/// `HANG`: go silent, to model an agent that stops answering.
|
||||
Hang,
|
||||
Echo(String),
|
||||
}
|
||||
|
||||
/// Write `json` as the `loopOutcome` of the session named by the environment.
|
||||
/// Returns false when the session cannot be named.
|
||||
fn write_report(json: &str) -> bool {
|
||||
let (Ok(home), Ok(sid)) = (
|
||||
std::env::var("PLAN2CODE_CONSOLE_HOME"),
|
||||
std::env::var("PLAN2CODE_CONSOLE_SID"),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
write_report_to(std::path::Path::new(&home), &sid, json)
|
||||
}
|
||||
|
||||
/// `write_report` with the session named: `<home>/sessions/<sid>/state.json`.
|
||||
fn write_report_to(home: &std::path::Path, sid: &str, json: &str) -> bool {
|
||||
let Ok(outcome) = serde_json::from_str::<serde_json::Value>(json) else {
|
||||
return false;
|
||||
};
|
||||
let dir = home.join("sessions").join(sid);
|
||||
let file = dir.join("state.json");
|
||||
let mut state = std::fs::read_to_string(&file)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
|
||||
.filter(|value| value.is_object())
|
||||
// The console's own file always carries its schema number; a new one does too.
|
||||
.unwrap_or_else(|| serde_json::json!({ "schema": 1 }));
|
||||
state["loopOutcome"] = outcome;
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let temp = dir.join("state.json.tmp");
|
||||
let Ok(text) = serde_json::to_string(&state) else {
|
||||
return false;
|
||||
};
|
||||
std::fs::write(&temp, text).is_ok() && std::fs::rename(&temp, &file).is_ok()
|
||||
}
|
||||
|
||||
pub fn parse(line: &str) -> Command {
|
||||
let line = line.trim();
|
||||
if let Some(rest) = line.strip_prefix("STEP ") {
|
||||
if let Ok(n) = rest.trim().parse() {
|
||||
return Command::Step(n);
|
||||
}
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix("EXIT ") {
|
||||
if let Ok(code) = rest.trim().parse() {
|
||||
return Command::Exit(code);
|
||||
}
|
||||
}
|
||||
if line == "SIZE" {
|
||||
return Command::Size;
|
||||
}
|
||||
if line == "PID" {
|
||||
return Command::Pid;
|
||||
}
|
||||
if let Some(name) = line.strip_prefix("ENV ") {
|
||||
return Command::Env(name.trim().to_string());
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix("REPORT ") {
|
||||
let json = rest.trim();
|
||||
if serde_json::from_str::<serde_json::Value>(json).is_ok() {
|
||||
return Command::Report(json.to_string());
|
||||
}
|
||||
}
|
||||
if line == "HANG" {
|
||||
return Command::Hang;
|
||||
}
|
||||
Command::Echo(line.to_string())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
say("FAKE-AGENT ready");
|
||||
// What the app launched it with: the launch prompt is one of these, so a
|
||||
// test can read back which prompt a generation was started on.
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
say(&format!("ARGS {}", args.join(" ")));
|
||||
if let Some(size) = size_text() {
|
||||
say(&size);
|
||||
}
|
||||
|
||||
// Report a resize on its own, by watching the size, so the same code works
|
||||
// where there is no resize signal (Windows).
|
||||
thread::spawn(|| {
|
||||
let mut last = size_text();
|
||||
loop {
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
let now = size_text();
|
||||
if now != last {
|
||||
if let Some(text) = &now {
|
||||
say(text);
|
||||
}
|
||||
last = now;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let stdin = io::stdin();
|
||||
for line in stdin.lock().lines() {
|
||||
let Ok(line) = line else { break };
|
||||
match parse(&line) {
|
||||
Command::Step(n) => {
|
||||
for i in 1..=n {
|
||||
say(&format!("working {i}/{n}"));
|
||||
thread::sleep(Duration::from_secs(1));
|
||||
}
|
||||
say("STEP DONE");
|
||||
}
|
||||
Command::Exit(code) => {
|
||||
say(&format!("exiting {code}"));
|
||||
std::process::exit(code);
|
||||
}
|
||||
Command::Size => say(&size_text().unwrap_or_else(|| "SIZE unknown".into())),
|
||||
Command::Pid => say(&format!("PID {}", std::process::id())),
|
||||
Command::Env(name) => say(&format!(
|
||||
"ENV {name}={}",
|
||||
std::env::var(&name).unwrap_or_default()
|
||||
)),
|
||||
Command::Report(json) => {
|
||||
if write_report(&json) {
|
||||
say("REPORT written")
|
||||
} else {
|
||||
say("REPORT unavailable")
|
||||
}
|
||||
}
|
||||
Command::Hang => {
|
||||
say("HANGING");
|
||||
loop {
|
||||
thread::sleep(Duration::from_secs(3600));
|
||||
}
|
||||
}
|
||||
Command::Echo(text) => say(&format!("echo: {text}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_the_command_words() {
|
||||
assert_eq!(parse("STEP 3"), Command::Step(3));
|
||||
assert_eq!(parse("EXIT 7\r\n"), Command::Exit(7));
|
||||
assert_eq!(parse("SIZE"), Command::Size);
|
||||
assert_eq!(parse("PID"), Command::Pid);
|
||||
assert_eq!(
|
||||
parse("ENV PLAN2CODE_IN_APP"),
|
||||
Command::Env("PLAN2CODE_IN_APP".into())
|
||||
);
|
||||
assert_eq!(parse("hello there"), Command::Echo("hello there".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_report_and_hang() {
|
||||
assert_eq!(
|
||||
parse("REPORT {\"phase\":2}"),
|
||||
Command::Report("{\"phase\":2}".into())
|
||||
);
|
||||
assert_eq!(parse("HANG\r\n"), Command::Hang);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_lands_in_the_session_file_beside_what_was_there() {
|
||||
let home = std::env::temp_dir().join(format!("fake-agent-report-{}", std::process::id()));
|
||||
let dir = home.join("sessions").join("s9");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// No file yet: a new one with the schema number.
|
||||
assert!(write_report_to(&home, "s9", "{\"phase\":2}"));
|
||||
let read = || -> serde_json::Value {
|
||||
serde_json::from_str(&std::fs::read_to_string(dir.join("state.json")).unwrap()).unwrap()
|
||||
};
|
||||
assert_eq!(read()["loopOutcome"]["phase"], 2);
|
||||
assert_eq!(read()["schema"], 1);
|
||||
// An existing object keeps its keys.
|
||||
std::fs::write(dir.join("state.json"), "{\"schema\":1,\"title\":\"t\"}").unwrap();
|
||||
assert!(write_report_to(&home, "s9", "{\"phase\":3}"));
|
||||
assert_eq!(read()["title"], "t");
|
||||
assert_eq!(read()["loopOutcome"]["phase"], 3);
|
||||
// A garbage file is replaced, not trusted.
|
||||
std::fs::write(dir.join("state.json"), "not json").unwrap();
|
||||
assert!(write_report_to(&home, "s9", "{\"phase\":4}"));
|
||||
assert_eq!(read()["loopOutcome"]["phase"], 4);
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_with_bad_json_is_an_echo() {
|
||||
assert_eq!(
|
||||
parse("REPORT {not json"),
|
||||
Command::Echo("REPORT {not json".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_number_is_just_an_echo() {
|
||||
assert_eq!(parse("STEP x"), Command::Echo("STEP x".into()));
|
||||
assert_eq!(parse("EXIT"), Command::Echo("EXIT".into()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
{
|
||||
"name": "plan2code-app",
|
||||
"version": "3.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "plan2code-app",
|
||||
"version": "3.0.0",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "2.12.4",
|
||||
"@xterm/addon-fit": "0.11.0",
|
||||
"@xterm/xterm": "6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "2.12.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/api": {
|
||||
"version": "2.12.4",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.4.tgz",
|
||||
"integrity": "sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==",
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/tauri"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.3.tgz",
|
||||
"integrity": "sha512-f7/LsY74SVb1ChmOPw1ajOpxii0GSzDAgmWHRci8JUYuuai04rXsSbFobpmB0sP2DdlvMD/B5ZotEn8GOGMRUg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"bin": {
|
||||
"tauri": "tauri.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/tauri"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@tauri-apps/cli-darwin-arm64": "2.12.3",
|
||||
"@tauri-apps/cli-darwin-x64": "2.12.3",
|
||||
"@tauri-apps/cli-linux-arm-gnueabihf": "2.12.3",
|
||||
"@tauri-apps/cli-linux-arm64-gnu": "2.12.3",
|
||||
"@tauri-apps/cli-linux-arm64-musl": "2.12.3",
|
||||
"@tauri-apps/cli-linux-riscv64-gnu": "2.12.3",
|
||||
"@tauri-apps/cli-linux-x64-gnu": "2.12.3",
|
||||
"@tauri-apps/cli-linux-x64-musl": "2.12.3",
|
||||
"@tauri-apps/cli-win32-arm64-msvc": "2.12.3",
|
||||
"@tauri-apps/cli-win32-ia32-msvc": "2.12.3",
|
||||
"@tauri-apps/cli-win32-x64-msvc": "2.12.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-darwin-arm64": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.3.tgz",
|
||||
"integrity": "sha512-xmVNoJOOKzKLj7GLHXmXLimRby9M42aBIJa0sB80N7o24eKV5JiVmToKTRLVH9yhL05GZ/B6rSSOmbzNFJwBAA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-darwin-x64": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.3.tgz",
|
||||
"integrity": "sha512-URd+0usfmUQQyb5kNPiKt2OT8gp7oGU7QR+qOppB6e35mpVBFFVNhWc9oWb3p0u71fDJ09DpF4T6m9xYxoIB8g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-arm-gnueabihf": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.3.tgz",
|
||||
"integrity": "sha512-0kwUVx2LbmOoTRlwF1oDww7th4/NSluv4ZBQ6KRZsFKg4g0TlTcIiJ0VehqkQYUeC9xIT1Mk6XtF52mI155VSQ==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-arm64-gnu": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.3.tgz",
|
||||
"integrity": "sha512-gKSGDx6fx+HBLQmG6guChFdisbrCSdx9Yli+j5teOa64gm1CeM+C6NLru5Pj3ZkkEep05BmCFjxvX+cjqAycZQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-arm64-musl": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.3.tgz",
|
||||
"integrity": "sha512-Yr59qMy/gcvAfBuFdCGlAmGiLsYWMFDbsP4bAI6iNBzcJTGrYWZGeiQhGDo29MQwfF/NUBqyM2qljXu5tZ6wjQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-riscv64-gnu": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.3.tgz",
|
||||
"integrity": "sha512-jKr0/REBMnLKC0OwPQZkyge0mKDaNZ0b/AbfGwVyCgFfwS730EVLfVDo3nt7MUu6jJaytRq08+xSj5qfy+U1+Q==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-x64-gnu": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.3.tgz",
|
||||
"integrity": "sha512-gTkEqJAGCMROGanxHnzaJzQ+/rXl39HWVg0/hDODS1wDWBGqoceqGC6Qm1+mQbyT11xnsB8mKu/gyVID/YpFIw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-x64-musl": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.3.tgz",
|
||||
"integrity": "sha512-T2dTxL1svRym71fZtaW4pZYXbthbfFsEJr1NeOUg/p7laWXZbUt/8DMSZf8recu9f7+1F/Lv00HtzsEu6vDO9w==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-win32-arm64-msvc": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.3.tgz",
|
||||
"integrity": "sha512-eoiQwpEZWbpsVHcM9BAzqqe4TCHszvr3rsM7pUQ4ofLK0lF1i1d/jX0Qo5DYMqcrUtwQuDdDuOCbcT0Izf1VwQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-win32-ia32-msvc": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.3.tgz",
|
||||
"integrity": "sha512-kE+KUg6Dbbkgvcw0m99wJVIToFQzJqpMBAXah74WqxaLzssNwSTUccrHp6+QVzMhjQP330tvekFmnQF+0NbE6Q==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-win32-x64-msvc": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.3.tgz",
|
||||
"integrity": "sha512-L7wndWAgX2mLW7alswpL3d1R0P9FN2WYBgHaQkAYEBxHHGkY4vFX9CjcRQ1LAxDAMIJxrY7/aDziFJeChS84NQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@xterm/addon-fit": {
|
||||
"version": "0.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz",
|
||||
"integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@xterm/xterm": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz",
|
||||
"integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"addons/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "plan2code-app",
|
||||
"version": "3.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": {
|
||||
"tauri": "tauri",
|
||||
"dev": "tauri dev",
|
||||
"build": "tauri build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "2.12.4",
|
||||
"@xterm/addon-fit": "0.11.0",
|
||||
"@xterm/xterm": "6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "2.12.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
[toolchain]
|
||||
channel = "1.98.1"
|
||||
profile = "minimal"
|
||||
@@ -0,0 +1,17 @@
|
||||
// Copies the xterm files the page loads from node_modules into ui/vendor/, so the
|
||||
// page is plain files with no bundler. Run before `tauri dev` and `tauri build`.
|
||||
import { copyFileSync, mkdirSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const out = join(root, 'ui', 'vendor');
|
||||
mkdirSync(out, { recursive: true });
|
||||
|
||||
const files = [
|
||||
['node_modules/@xterm/xterm/lib/xterm.js', 'xterm.js'],
|
||||
['node_modules/@xterm/xterm/css/xterm.css', 'xterm.css'],
|
||||
['node_modules/@xterm/addon-fit/lib/addon-fit.js', 'addon-fit.js'],
|
||||
];
|
||||
for (const [from, to] of files) copyFileSync(join(root, from), join(out, to));
|
||||
console.log(`vendored ${files.length} xterm files into ui/vendor/`);
|
||||
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "plan2code-app"
|
||||
version = "3.0.0"
|
||||
description = "Plan2Code desktop app"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
name = "plan2code_app_lib"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.5", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2.12", features = [] }
|
||||
tauri-plugin-dialog = "2"
|
||||
portable-pty = "0.9.0"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
chrono = "0.4"
|
||||
# The loop's call to a web address. The operating system's TLS, so a company's
|
||||
# own root certificates work and no second TLS stack is built.
|
||||
reqwest = { version = "0.13", default-features = false, features = ["blocking", "native-tls"] }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# Already pulled in by portable-pty itself; named directly here only for the
|
||||
# Job Object APIs it does not expose (ending a `cmd /c` npm shim's whole
|
||||
# process tree, not just the shim), and for the quit check's own TaskDialog
|
||||
# (task_dialog.rs).
|
||||
winapi = { version = "0.3.9", features = ["commctrl", "handleapi", "jobapi2", "minwindef", "ntdef", "windef", "winerror", "winnt", "winuser"] }
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends, plus setting the window's own title to the open project's name and putting it in and out of full screen for an Activities game",
|
||||
"windows": ["main"],
|
||||
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "core:window:allow-set-title", "core:window:allow-is-fullscreen", "core:window:allow-set-fullscreen"]
|
||||
}
|
||||
|
After Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 43 KiB |
@@ -0,0 +1,671 @@
|
||||
//! At most one agent per project folder: start it, end it, restart it (always
|
||||
//! at once: the app confirms with the person first, so nothing here waits for
|
||||
//! a quiet moment), and notice when it ends by itself.
|
||||
//! Knows nothing about Tauri: state changes and output go to one callback.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::thread;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::agents::{agent_launch_spec, Agent, PermissionMode};
|
||||
use crate::pty_host::{PtyHost, StartOptions};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "state", rename_all = "lowercase")]
|
||||
pub enum AgentState {
|
||||
Idle,
|
||||
Running,
|
||||
/// The agent ended without a Restart press, or could not be started.
|
||||
Ended {
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Runs just before a Restart starts the fresh agent, and returns the line the
|
||||
/// bar shows about it (`None` for no line). It must not call back into the
|
||||
/// manager: it runs with the manager's state locked.
|
||||
pub type BeforeFresh = Arc<dyn Fn() -> Option<String> + Send + Sync>;
|
||||
|
||||
/// Runs when the Implementation Loop starts a phase's fresh agent: the app
|
||||
/// forgets the console session it was showing, so the new agent's `open`
|
||||
/// makes a session of its own. Like `BeforeFresh`, it must not call back into
|
||||
/// the manager.
|
||||
pub type ForgetSession = Arc<dyn Fn() + Send + Sync>;
|
||||
|
||||
/// What the page needs to draw the bar. `generation` counts the agents started
|
||||
/// so far: a new number means a fresh agent, so the terminal clears.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct AgentSnapshot {
|
||||
#[serde(flatten)]
|
||||
pub state: AgentState,
|
||||
pub kind: Option<String>,
|
||||
pub generation: u64,
|
||||
/// The running (or last started) agent's permission mode, so the bar's
|
||||
/// note can name it instead of assuming bypass.
|
||||
pub mode: Option<PermissionMode>,
|
||||
/// What the last Restart left for the dashboard, for the bar.
|
||||
#[serde(rename = "briefNote", skip_serializing_if = "Option::is_none")]
|
||||
pub brief_note: Option<String>,
|
||||
}
|
||||
|
||||
pub enum AgentEvent {
|
||||
Output(Vec<u8>),
|
||||
State(AgentSnapshot),
|
||||
}
|
||||
|
||||
/// Receives events from several threads. State events are sent while the
|
||||
/// manager holds its lock, so a sink must not call back into the manager.
|
||||
pub type Sink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
|
||||
|
||||
struct Running {
|
||||
host: Arc<PtyHost>,
|
||||
}
|
||||
|
||||
/// What a Restart starts again, besides the brief: the agent, its model and
|
||||
/// effort (when it has one), and its permission mode. Restart reuses this
|
||||
/// whole, unchanged choice (Task 9.6).
|
||||
#[derive(Clone)]
|
||||
struct StartChoice {
|
||||
kind: Agent,
|
||||
model: Option<String>,
|
||||
effort: Option<String>,
|
||||
mode: PermissionMode,
|
||||
}
|
||||
|
||||
/// Recent output from the current generation is kept bounded, so a page
|
||||
/// reload or a fresh output channel can redraw the screen instead of staying
|
||||
/// blank. About enough for a full screen redraw with some headroom, never
|
||||
/// the whole scrollback.
|
||||
const REPLAY_LIMIT: usize = 256 * 1024;
|
||||
|
||||
/// Appends `bytes` to `replay`, dropping from the front (the oldest) when
|
||||
/// that would put it over `limit`: the tail, what a redraw actually needs,
|
||||
/// is always what is kept.
|
||||
fn append_replay(replay: &mut Vec<u8>, bytes: &[u8], limit: usize) {
|
||||
replay.extend_from_slice(bytes);
|
||||
if replay.len() > limit {
|
||||
let excess = replay.len() - limit;
|
||||
replay.drain(..excess);
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
state: AgentState,
|
||||
running: Option<Running>,
|
||||
/// What a Restart starts again: the choice and its brief (the prompt a
|
||||
/// restart runs again, never a transient first prompt).
|
||||
last_start: Option<(StartChoice, Option<String>)>,
|
||||
size: (u16, u16),
|
||||
brief_note: Option<String>,
|
||||
/// Cleared when a fresh agent starts; see `REPLAY_LIMIT`.
|
||||
replay: Vec<u8>,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
folder: PathBuf,
|
||||
sink: Sink,
|
||||
before_fresh: Mutex<Option<BeforeFresh>>,
|
||||
forget_session: Mutex<Option<ForgetSession>>,
|
||||
/// Environment every agent this manager starts gets, on top of its own:
|
||||
/// the in-app signal that sends the agent's console pages to this window.
|
||||
extra_env: Mutex<Vec<(String, String)>>,
|
||||
/// Bumped for every agent started. Output and exits from an older agent
|
||||
/// compare against it and are dropped.
|
||||
generation: AtomicU64,
|
||||
inner: Mutex<Inner>,
|
||||
}
|
||||
|
||||
pub struct AgentManager {
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
fn lock(inner: &Mutex<Inner>) -> MutexGuard<'_, Inner> {
|
||||
// A panic in another thread must not take the whole app's agent control down.
|
||||
inner
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
pub fn new(folder: PathBuf, sink: Sink) -> AgentManager {
|
||||
AgentManager {
|
||||
shared: Arc::new(Shared {
|
||||
folder,
|
||||
sink,
|
||||
before_fresh: Mutex::new(None),
|
||||
forget_session: Mutex::new(None),
|
||||
extra_env: Mutex::new(Vec::new()),
|
||||
generation: AtomicU64::new(0),
|
||||
inner: Mutex::new(Inner {
|
||||
state: AgentState::Idle,
|
||||
running: None,
|
||||
last_start: None,
|
||||
size: (80, 24),
|
||||
brief_note: None,
|
||||
replay: Vec::new(),
|
||||
}),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn folder(&self) -> &PathBuf {
|
||||
&self.shared.folder
|
||||
}
|
||||
|
||||
/// Run `hook` before every Restart starts its fresh agent.
|
||||
pub fn set_before_fresh(&self, hook: BeforeFresh) {
|
||||
if let Ok(mut slot) = self.shared.before_fresh.lock() {
|
||||
*slot = Some(hook);
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `hook` whenever the loop starts a phase's fresh agent (`start_fresh`
|
||||
/// and `forget_session`).
|
||||
pub fn set_forget_session(&self, hook: ForgetSession) {
|
||||
if let Ok(mut slot) = self.shared.forget_session.lock() {
|
||||
*slot = Some(hook);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the app forget the console session it follows, so the next agent's
|
||||
/// `open` starts a new one.
|
||||
pub fn forget_session(&self) {
|
||||
self.shared.forget();
|
||||
}
|
||||
|
||||
/// Give every agent started from now on these variables (replacing any set before).
|
||||
pub fn set_env(&self, env: Vec<(String, String)>) {
|
||||
if let Ok(mut slot) = self.shared.extra_env.lock() {
|
||||
*slot = env;
|
||||
}
|
||||
}
|
||||
|
||||
/// Start `kind` (built-in or custom) on `model`, `effort` and `mode`, with `brief` (`None` is
|
||||
/// the placeholder brief: the plain `/plan2code` prompt, which opens the
|
||||
/// dashboard). A second start while an agent runs is refused. Restart
|
||||
/// reuses this exact choice, so a later call replaces it for good.
|
||||
pub fn start(
|
||||
&self,
|
||||
kind: Agent,
|
||||
model: Option<String>,
|
||||
effort: Option<String>,
|
||||
mode: PermissionMode,
|
||||
brief: Option<String>,
|
||||
) -> Result<(), String> {
|
||||
let prompt = brief
|
||||
.clone()
|
||||
.unwrap_or_else(|| kind.default_prompt().to_string());
|
||||
self.begin(
|
||||
StartChoice {
|
||||
kind,
|
||||
model,
|
||||
effort,
|
||||
mode,
|
||||
},
|
||||
brief,
|
||||
prompt,
|
||||
None,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Like `start`, but `prompt` is this launch's first prompt alone: a later
|
||||
/// Restart still opens the placeholder brief (the dashboard), it does not
|
||||
/// run `prompt` again. The loop's own agent starts take this path, so a
|
||||
/// phase prompt never becomes the brief a New Session repeats.
|
||||
pub fn start_transient(
|
||||
&self,
|
||||
kind: Agent,
|
||||
model: Option<String>,
|
||||
effort: Option<String>,
|
||||
mode: PermissionMode,
|
||||
prompt: String,
|
||||
) -> Result<(), String> {
|
||||
self.begin(
|
||||
StartChoice {
|
||||
kind,
|
||||
model,
|
||||
effort,
|
||||
mode,
|
||||
},
|
||||
None,
|
||||
prompt,
|
||||
None,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
/// `start_transient` for a loop phase that runs on its own strength after
|
||||
/// the agent was stopped: the stored launch choice is `kind`, `model`,
|
||||
/// `effort` and `mode` (so a later New Session or phase runs on it), while
|
||||
/// this one launch runs on `phase_model` and `phase_effort` with
|
||||
/// `extra_env` added.
|
||||
pub fn start_transient_on(
|
||||
&self,
|
||||
launch: (Agent, Option<String>, Option<String>, PermissionMode),
|
||||
prompt: String,
|
||||
phase_model: String,
|
||||
phase_effort: Option<String>,
|
||||
extra_env: Vec<(String, String)>,
|
||||
) -> Result<(), String> {
|
||||
let (kind, model, effort, mode) = launch;
|
||||
let on = StartChoice {
|
||||
kind: kind.clone(),
|
||||
model: Some(phase_model),
|
||||
effort: phase_effort,
|
||||
mode,
|
||||
};
|
||||
self.begin(
|
||||
StartChoice {
|
||||
kind,
|
||||
model,
|
||||
effort,
|
||||
mode,
|
||||
},
|
||||
None,
|
||||
prompt,
|
||||
Some(on),
|
||||
extra_env,
|
||||
)
|
||||
}
|
||||
|
||||
/// `start` and `start_transient` behind one door: remember `choice` with
|
||||
/// `restart_brief` (what a later Restart runs again), then spawn the agent
|
||||
/// on `first_prompt`, which is not always the same string.
|
||||
fn begin(
|
||||
&self,
|
||||
choice: StartChoice,
|
||||
restart_brief: Option<String>,
|
||||
first_prompt: String,
|
||||
launch_choice: Option<StartChoice>,
|
||||
launch_env: Vec<(String, String)>,
|
||||
) -> Result<(), String> {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
if inner.state == AgentState::Running {
|
||||
return Err("an agent is already running for this project".to_string());
|
||||
}
|
||||
inner.brief_note = None;
|
||||
let previous = inner.last_start.replace((choice, restart_brief));
|
||||
match self
|
||||
.shared
|
||||
.spawn(&mut inner, first_prompt, launch_choice, launch_env)
|
||||
{
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
// A start that never ran must not take away what Restart would
|
||||
// have started again.
|
||||
inner.last_start = previous;
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a fresh agent on the stored launch choice with `prompt` as its
|
||||
/// only first prompt: the Implementation Loop's way to begin a phase. A
|
||||
/// running agent is killed first (the same path as Restart), but without
|
||||
/// Restart's brief note; the app still forgets the console session, so
|
||||
/// the new agent's `open` makes a new one. An agent that ended, or never
|
||||
/// ran, starts directly. Needs a launch choice from an earlier start.
|
||||
/// `prompt` belongs to this launch alone: the stored brief stays what it
|
||||
/// was, so a later New Session still opens the dashboard, not this
|
||||
/// prompt again.
|
||||
pub fn start_fresh(&self, prompt: String) -> Result<(), String> {
|
||||
self.fresh(prompt, None, Vec::new())
|
||||
}
|
||||
|
||||
/// Like `start_fresh`, but the agent runs on `model` and `effort` for this
|
||||
/// launch alone, with `extra_env` added to its environment: the loop's way
|
||||
/// to start a phase on its strength. The agent kind and permission mode
|
||||
/// stay the stored launch choice's, and the stored choice itself is never
|
||||
/// written, so a later `start_fresh`, New Session or Restart runs on the
|
||||
/// original model and effort without `extra_env`.
|
||||
pub fn start_phase_on(
|
||||
&self,
|
||||
prompt: String,
|
||||
model: String,
|
||||
effort: Option<String>,
|
||||
extra_env: Vec<(String, String)>,
|
||||
) -> Result<(), String> {
|
||||
let stored = lock(&self.shared.inner)
|
||||
.last_start
|
||||
.as_ref()
|
||||
.map(|(choice, _)| choice.clone())
|
||||
.ok_or("no agent has been started")?;
|
||||
let choice = StartChoice {
|
||||
model: Some(model),
|
||||
effort,
|
||||
..stored
|
||||
};
|
||||
self.fresh(prompt, Some(choice), extra_env)
|
||||
}
|
||||
|
||||
/// The kill-then-spawn body `start_fresh` and `start_phase_on` share.
|
||||
fn fresh(
|
||||
&self,
|
||||
prompt: String,
|
||||
choice: Option<StartChoice>,
|
||||
extra_env: Vec<(String, String)>,
|
||||
) -> Result<(), String> {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
if inner.last_start.is_none() {
|
||||
return Err("no agent has been started".to_string());
|
||||
}
|
||||
inner.brief_note = None;
|
||||
self.shared.forget();
|
||||
if inner.state == AgentState::Running {
|
||||
self.shared.generation.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(old) = inner.running.take() {
|
||||
let _ = old.host.kill();
|
||||
}
|
||||
}
|
||||
match self.shared.spawn(&mut inner, prompt, choice, extra_env) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
inner.state = AgentState::Ended {
|
||||
reason: format!("could not start the agent: {e}"),
|
||||
};
|
||||
self.shared.emit(&inner);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored launch choice: agent, model, effort and permission mode.
|
||||
pub fn launch_choice(&self) -> Option<(Agent, Option<String>, Option<String>, PermissionMode)> {
|
||||
lock(&self.shared.inner)
|
||||
.last_start
|
||||
.as_ref()
|
||||
.map(|(choice, _)| {
|
||||
(
|
||||
choice.kind.clone(),
|
||||
choice.model.clone(),
|
||||
choice.effort.clone(),
|
||||
choice.mode,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> AgentSnapshot {
|
||||
self.shared.snapshot(&lock(&self.shared.inner))
|
||||
}
|
||||
|
||||
/// The current generation's recent output, for a page that just mounted
|
||||
/// (a reload or a fresh window) to redraw instead of staying blank.
|
||||
pub fn replay(&self) -> Vec<u8> {
|
||||
lock(&self.shared.inner).replay.clone()
|
||||
}
|
||||
|
||||
/// The model and effort the current (or last) start chose. The bar only
|
||||
/// ever needs `snapshot`'s `kind` and `mode`; this exists so a test can
|
||||
/// confirm Restart keeps the other two of the four just as unchanged.
|
||||
pub fn model_and_effort(&self) -> (Option<String>, Option<String>) {
|
||||
match &lock(&self.shared.inner).last_start {
|
||||
Some((choice, _)) => (choice.model.clone(), choice.effort.clone()),
|
||||
None => (None, None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_active(&self) -> bool {
|
||||
lock(&self.shared.inner).state == AgentState::Running
|
||||
}
|
||||
|
||||
pub fn input(&self, bytes: &[u8]) -> Result<(), String> {
|
||||
let host = lock(&self.shared.inner)
|
||||
.running
|
||||
.as_ref()
|
||||
.map(|r| Arc::clone(&r.host));
|
||||
match host {
|
||||
Some(host) => host.write(bytes),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The terminal changed size. Remembered, so a fresh agent starts at it.
|
||||
pub fn resize(&self, cols: u16, rows: u16) -> Result<(), String> {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
inner.size = (cols, rows);
|
||||
match &inner.running {
|
||||
Some(running) => running.host.resize(cols, rows),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Kill the agent (if any) and start a fresh one on the same brief, at
|
||||
/// once, whatever it is doing. The app asks the person to confirm before
|
||||
/// calling this: there is no in-between "waiting" state here, because the
|
||||
/// agent's own output (status lines, a spinner) never truly goes quiet, so
|
||||
/// a "wait for it to finish" rule would wait forever in practice. Restart
|
||||
/// also answers an ended agent, where nothing is lost by it.
|
||||
pub fn restart(&self) -> Result<(), String> {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
if inner.state == AgentState::Idle {
|
||||
return Err("no agent has been started".to_string());
|
||||
}
|
||||
self.shared.replace(&mut inner)
|
||||
}
|
||||
|
||||
/// End the agent for good (quitting). Nothing starts afterwards, and the
|
||||
/// agent's process is gone when this returns.
|
||||
pub fn stop(&self) {
|
||||
let host = {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
// Older agents' output and exits stop counting from here.
|
||||
self.shared.generation.fetch_add(1, Ordering::SeqCst);
|
||||
let host = inner.running.take().map(|r| r.host);
|
||||
inner.state = AgentState::Idle;
|
||||
inner.last_start = None;
|
||||
self.shared.emit(&inner);
|
||||
host
|
||||
};
|
||||
if let Some(host) = host {
|
||||
let _ = host.kill();
|
||||
let _ = host.wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AgentManager {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
fn snapshot(&self, inner: &Inner) -> AgentSnapshot {
|
||||
AgentSnapshot {
|
||||
state: inner.state.clone(),
|
||||
kind: inner
|
||||
.last_start
|
||||
.as_ref()
|
||||
.map(|(choice, _)| choice.kind.id().to_string()),
|
||||
mode: inner.last_start.as_ref().map(|(choice, _)| choice.mode),
|
||||
generation: self.generation.load(Ordering::SeqCst),
|
||||
brief_note: inner.brief_note.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn forget(&self) {
|
||||
let hook = self
|
||||
.forget_session
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|slot| slot.clone());
|
||||
if let Some(run) = hook {
|
||||
run();
|
||||
}
|
||||
}
|
||||
|
||||
fn emit(&self, inner: &Inner) {
|
||||
(self.sink)(AgentEvent::State(self.snapshot(inner)));
|
||||
}
|
||||
|
||||
/// Start the agent in `inner.last_start` on `prompt` and watch for it to
|
||||
/// end. `prompt` is this launch's first prompt: the stored brief for a
|
||||
/// start or a Restart, or a transient one (`start_fresh`,
|
||||
/// `start_transient`) that a Restart must not repeat.
|
||||
///
|
||||
/// `choice_override` runs this launch on another choice than the stored
|
||||
/// one (which it never replaces), and `launch_env` is added to the
|
||||
/// process env after the manager's own; both are empty for every caller
|
||||
/// but the loop's phase start.
|
||||
fn spawn(
|
||||
self: &Arc<Self>,
|
||||
inner: &mut Inner,
|
||||
prompt: String,
|
||||
choice_override: Option<StartChoice>,
|
||||
launch_env: Vec<(String, String)>,
|
||||
) -> Result<(), String> {
|
||||
let choice = match choice_override {
|
||||
Some(choice) => choice,
|
||||
None => {
|
||||
inner
|
||||
.last_start
|
||||
.clone()
|
||||
.ok_or("no agent has been started")?
|
||||
.0
|
||||
}
|
||||
};
|
||||
let mut spec = agent_launch_spec(
|
||||
&choice.kind,
|
||||
&self.folder,
|
||||
choice.model.as_deref(),
|
||||
choice.effort.as_deref(),
|
||||
choice.mode,
|
||||
&prompt,
|
||||
);
|
||||
if let Ok(extra) = self.extra_env.lock() {
|
||||
spec.env.extend(extra.iter().cloned());
|
||||
}
|
||||
spec.env.extend(launch_env);
|
||||
let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
|
||||
let on_output = {
|
||||
let shared = Arc::clone(self);
|
||||
move |bytes: Vec<u8>| {
|
||||
// Taking the lock here, briefly, keeps this behind the state
|
||||
// change that announces its agent (`spawn`'s caller holds the
|
||||
// lock until it has emitted), so the page clears its screen
|
||||
// before the banner. It is released before the send below,
|
||||
// which can be slow, so typing (`input`) is never stuck
|
||||
// behind a flood of output.
|
||||
let stale = {
|
||||
let mut in_order = lock(&shared.inner);
|
||||
if shared.generation.load(Ordering::SeqCst) != generation {
|
||||
true
|
||||
} else {
|
||||
append_replay(&mut in_order.replay, &bytes, REPLAY_LIMIT);
|
||||
false
|
||||
}
|
||||
};
|
||||
if stale {
|
||||
return;
|
||||
}
|
||||
(shared.sink)(AgentEvent::Output(bytes));
|
||||
}
|
||||
};
|
||||
let host = Arc::new(PtyHost::start(
|
||||
StartOptions {
|
||||
program: spec.program,
|
||||
args: spec.args,
|
||||
env: spec.env,
|
||||
cwd: Some(spec.cwd),
|
||||
cols: inner.size.0,
|
||||
rows: inner.size.1,
|
||||
},
|
||||
on_output,
|
||||
)?);
|
||||
|
||||
inner.running = Some(Running {
|
||||
host: Arc::clone(&host),
|
||||
});
|
||||
inner.state = AgentState::Running;
|
||||
// A fresh agent starts on a clean screen; its replay must too.
|
||||
inner.replay.clear();
|
||||
self.emit(inner);
|
||||
|
||||
let shared = Arc::clone(self);
|
||||
thread::spawn(move || {
|
||||
let reason = match host.wait_described() {
|
||||
Ok((_, Some(signal))) => format!("was ended by a signal ({signal})"),
|
||||
Ok((code, None)) => format!("exited with code {code}"),
|
||||
Err(e) => format!("stopped: {e}"),
|
||||
};
|
||||
shared.on_exit(generation, reason);
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Kill the running agent (if any) and start a fresh one on the same
|
||||
/// brief. A fresh agent that cannot start leaves the state `Ended`.
|
||||
fn replace(self: &Arc<Self>, inner: &mut Inner) -> Result<(), String> {
|
||||
// Bumping the generation first drops whatever the old agent still says.
|
||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(old) = inner.running.take() {
|
||||
let _ = old.host.kill();
|
||||
}
|
||||
let hook = self.before_fresh.lock().ok().and_then(|slot| slot.clone());
|
||||
inner.brief_note = hook.and_then(|run| run());
|
||||
let prompt = inner
|
||||
.last_start
|
||||
.as_ref()
|
||||
.map(|(choice, brief)| {
|
||||
brief
|
||||
.clone()
|
||||
.unwrap_or_else(|| choice.kind.default_prompt().to_string())
|
||||
})
|
||||
.ok_or("no agent has been started")?;
|
||||
match self.spawn(inner, prompt, None, Vec::new()) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
inner.state = AgentState::Ended {
|
||||
reason: format!("could not start the agent: {e}"),
|
||||
};
|
||||
self.emit(inner);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The agent's process ended. Stale if a newer agent has replaced it.
|
||||
fn on_exit(self: &Arc<Self>, generation: u64, reason: String) {
|
||||
let mut inner = lock(&self.inner);
|
||||
if self.generation.load(Ordering::SeqCst) != generation {
|
||||
return;
|
||||
}
|
||||
inner.running = None;
|
||||
// Ended on its own: say why and start nothing.
|
||||
inner.state = AgentState::Ended { reason };
|
||||
self.emit(&inner);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod replay_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn under_the_limit_keeps_everything() {
|
||||
let mut replay = b"hello ".to_vec();
|
||||
append_replay(&mut replay, b"world", 20);
|
||||
assert_eq!(replay, b"hello world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_the_limit_drops_the_oldest_bytes_and_keeps_the_tail() {
|
||||
let mut replay = b"0123456789".to_vec();
|
||||
append_replay(&mut replay, b"ABCDE", 10);
|
||||
// 15 bytes written, a 10-byte limit: the oldest 5 ("01234") are gone.
|
||||
assert_eq!(replay, b"56789ABCDE");
|
||||
assert_eq!(replay.len(), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_write_longer_than_the_limit_keeps_only_its_own_tail() {
|
||||
let mut replay = Vec::new();
|
||||
append_replay(&mut replay, b"0123456789", 4);
|
||||
assert_eq!(replay, b"6789");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
//! This window's announce endpoint: `console.mjs open`, run by the agent inside
|
||||
//! the app, POSTs the page it wants shown here instead of opening a browser.
|
||||
//! Loopback only, one random token per window, so two windows never hear each
|
||||
//! other's agents. Knows nothing about Tauri: the caller gets each accepted
|
||||
//! notice through a callback.
|
||||
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The most an announce request may weigh: a URL and two short names.
|
||||
const MAX_REQUEST: usize = 8 * 1024;
|
||||
const READ_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
/// A page the console wants shown: where it is, the session it belongs to and
|
||||
/// the skill it runs.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PageNotice {
|
||||
pub url: String,
|
||||
pub sid: String,
|
||||
pub workflow: String,
|
||||
}
|
||||
|
||||
/// Says whether the window took the page. Only a page it took becomes the
|
||||
/// window's current session, so a refused one never steers the next `open`.
|
||||
pub type OnPage = Arc<dyn Fn(PageNotice) -> bool + Send + Sync>;
|
||||
|
||||
pub struct AnnounceServer {
|
||||
port: u16,
|
||||
token: String,
|
||||
/// The page most recently announced: what `GET /session` answers, so an
|
||||
/// agent's `open` joins the window's current session whatever its own
|
||||
/// environment (fixed when it started) says.
|
||||
current: Arc<Mutex<Option<PageNotice>>>,
|
||||
}
|
||||
|
||||
/// What a checked request asks for.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Request {
|
||||
/// `POST /page`: show this page.
|
||||
Page(PageNotice),
|
||||
/// `GET /session`: name the session the window shows now.
|
||||
Session,
|
||||
}
|
||||
|
||||
/// Why a request was refused, as the status the caller answers with.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Refused(pub u16, pub &'static str);
|
||||
|
||||
/// A random token from the OS-seeded hasher: 128 bits as hex. The standard
|
||||
/// library's `RandomState` keys come from the operating system's random source.
|
||||
fn random_token() -> String {
|
||||
let mut out = String::new();
|
||||
for round in 0..2u8 {
|
||||
let mut hasher = RandomState::new().build_hasher();
|
||||
hasher.write_u8(round);
|
||||
hasher.write_u128(
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0),
|
||||
);
|
||||
out.push_str(&format!("{:016x}", hasher.finish()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn same_token(a: &str, b: &str) -> bool {
|
||||
// Compared in full whatever the first difference, so timing says nothing.
|
||||
let (a, b) = (a.as_bytes(), b.as_bytes());
|
||||
let mut diff = (a.len() != b.len()) as u8;
|
||||
for i in 0..a.len().min(b.len()) {
|
||||
diff |= a[i] ^ b[i];
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
/// A console page URL the app may show: plain http on loopback with a port and
|
||||
/// a `/s/<token>/` path, which is all the console ever hands out.
|
||||
pub fn acceptable_url(url: &str) -> bool {
|
||||
let Some(rest) = url.strip_prefix("http://127.0.0.1:") else {
|
||||
return false;
|
||||
};
|
||||
let Some((port, path)) = rest.split_once('/') else {
|
||||
return false;
|
||||
};
|
||||
port.parse::<u16>().is_ok_and(|p| p > 0)
|
||||
&& path.starts_with("s/")
|
||||
&& !url.contains(char::is_whitespace)
|
||||
}
|
||||
|
||||
/// Check one request (its head as text, its body as bytes) against `token`.
|
||||
pub fn check_request(head: &str, body: &[u8], token: &str) -> Result<Request, Refused> {
|
||||
let mut lines = head.split("\r\n");
|
||||
let request_line = lines.next().unwrap_or("");
|
||||
let route = request_line.split(' ').take(2).collect::<Vec<_>>();
|
||||
if route != ["POST", "/page"] && route != ["GET", "/session"] {
|
||||
return Err(Refused(404, "not found"));
|
||||
}
|
||||
let mut given = None;
|
||||
for line in lines {
|
||||
let Some((name, value)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
match name.trim().to_ascii_lowercase().as_str() {
|
||||
"x-plan2code-token" => given = Some(value.trim().to_string()),
|
||||
// A browser page sending this would be some site guessing at the port.
|
||||
"origin" => return Err(Refused(403, "not from a page")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !given.is_some_and(|given| same_token(&given, token)) {
|
||||
return Err(Refused(403, "bad token"));
|
||||
}
|
||||
if route[0] == "GET" {
|
||||
return Ok(Request::Session);
|
||||
}
|
||||
let notice: PageNotice = serde_json::from_slice(body).map_err(|_| Refused(400, "bad body"))?;
|
||||
if !acceptable_url(¬ice.url) || notice.sid.len() > 128 || notice.workflow.len() > 64 {
|
||||
return Err(Refused(400, "bad page"));
|
||||
}
|
||||
Ok(Request::Page(notice))
|
||||
}
|
||||
|
||||
fn reason(status: u16) -> &'static str {
|
||||
match status {
|
||||
200 => "OK",
|
||||
204 => "No Content",
|
||||
400 => "Bad Request",
|
||||
403 => "Forbidden",
|
||||
_ => "Not Found",
|
||||
}
|
||||
}
|
||||
|
||||
fn respond(stream: &mut TcpStream, status: u16, body: &str) {
|
||||
let _ = write!(
|
||||
stream,
|
||||
"HTTP/1.1 {status} {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
reason(status),
|
||||
body.len()
|
||||
);
|
||||
}
|
||||
|
||||
/// Read one request: the head up to the blank line, then the body the
|
||||
/// `Content-Length` header names. Anything over `MAX_REQUEST` is refused.
|
||||
fn read_request(stream: &mut TcpStream) -> Result<(String, Vec<u8>), Refused> {
|
||||
let _ = stream.set_read_timeout(Some(READ_TIMEOUT));
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 1024];
|
||||
let split = loop {
|
||||
if let Some(at) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
|
||||
break at;
|
||||
}
|
||||
if buf.len() > MAX_REQUEST {
|
||||
return Err(Refused(400, "too big"));
|
||||
}
|
||||
match stream.read(&mut chunk) {
|
||||
Ok(0) | Err(_) => return Err(Refused(400, "incomplete")),
|
||||
Ok(n) => buf.extend_from_slice(&chunk[..n]),
|
||||
}
|
||||
};
|
||||
let head = String::from_utf8_lossy(&buf[..split]).into_owned();
|
||||
let length = head
|
||||
.split("\r\n")
|
||||
.filter_map(|line| line.split_once(':'))
|
||||
.find(|(name, _)| name.trim().eq_ignore_ascii_case("content-length"))
|
||||
.and_then(|(_, value)| value.trim().parse::<usize>().ok())
|
||||
.unwrap_or(0);
|
||||
if length > MAX_REQUEST {
|
||||
return Err(Refused(400, "too big"));
|
||||
}
|
||||
let mut body = buf[split + 4..].to_vec();
|
||||
while body.len() < length {
|
||||
match stream.read(&mut chunk) {
|
||||
Ok(0) | Err(_) => return Err(Refused(400, "incomplete")),
|
||||
Ok(n) => body.extend_from_slice(&chunk[..n]),
|
||||
}
|
||||
}
|
||||
body.truncate(length);
|
||||
Ok((head, body))
|
||||
}
|
||||
|
||||
impl AnnounceServer {
|
||||
/// Listen on a random loopback port. `on_page` runs on the server's own
|
||||
/// thread for every accepted notice.
|
||||
pub fn start(on_page: OnPage) -> Result<AnnounceServer, String> {
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
|
||||
let token = random_token();
|
||||
let expected = token.clone();
|
||||
let current: Arc<Mutex<Option<PageNotice>>> = Arc::new(Mutex::new(None));
|
||||
let shared = Arc::clone(¤t);
|
||||
thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(mut stream) = stream else { continue };
|
||||
let (status, body) = match read_request(&mut stream)
|
||||
.and_then(|(head, body)| check_request(&head, &body, &expected))
|
||||
{
|
||||
Ok(Request::Page(notice)) => {
|
||||
if on_page(notice.clone()) {
|
||||
if let Ok(mut slot) = shared.lock() {
|
||||
*slot = Some(notice);
|
||||
}
|
||||
(204, String::new())
|
||||
} else {
|
||||
// `open` reads anything but 2xx as "the app did not take the page".
|
||||
(409, String::new())
|
||||
}
|
||||
}
|
||||
Ok(Request::Session) => {
|
||||
let now = shared.lock().ok().and_then(|slot| slot.clone());
|
||||
(
|
||||
200,
|
||||
serde_json::to_string(&now).unwrap_or_else(|_| "null".to_string()),
|
||||
)
|
||||
}
|
||||
Err(Refused(status, _)) => (status, String::new()),
|
||||
};
|
||||
respond(&mut stream, status, &body);
|
||||
}
|
||||
});
|
||||
Ok(AnnounceServer {
|
||||
port,
|
||||
token,
|
||||
current,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn url(&self) -> String {
|
||||
format!("http://127.0.0.1:{}/page", self.port)
|
||||
}
|
||||
|
||||
pub fn token(&self) -> &str {
|
||||
&self.token
|
||||
}
|
||||
|
||||
/// The page most recently announced, if any.
|
||||
pub fn current(&self) -> Option<PageNotice> {
|
||||
self.current.lock().ok().and_then(|slot| slot.clone())
|
||||
}
|
||||
|
||||
/// Forget the page most recently announced, so the next agent's `open`
|
||||
/// starts a session of its own instead of joining that one. New Session
|
||||
/// does this: a fresh agent's session meter starts over with it.
|
||||
pub fn forget_current(&self) {
|
||||
if let Ok(mut slot) = self.current.lock() {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// What goes on the agent's process so its `console.mjs open` shows pages
|
||||
/// here. Every value belongs to this window. `embed_origin` is the origin of
|
||||
/// the app page, so a console the agent starts allows being framed by it.
|
||||
pub fn agent_env(&self, embed_origin: &str, app_version: &str) -> Vec<(String, String)> {
|
||||
vec![
|
||||
("PLAN2CODE_IN_APP".to_string(), "1".to_string()),
|
||||
("PLAN2CODE_APP_VERSION".to_string(), app_version.to_string()),
|
||||
(
|
||||
"PLAN2CODE_EMBED_ORIGIN".to_string(),
|
||||
embed_origin.to_string(),
|
||||
),
|
||||
("PLAN2CODE_APP_ANNOUNCE".to_string(), self.url()),
|
||||
("PLAN2CODE_APP_TOKEN".to_string(), self.token.clone()),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::mpsc::channel;
|
||||
use std::sync::Mutex;
|
||||
|
||||
fn request(token: &str, body: &str) -> (String, Vec<u8>) {
|
||||
(
|
||||
format!("POST /page HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\ncontent-length: {}", body.len()),
|
||||
body.as_bytes().to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
const GOOD: &str = r#"{"url":"http://127.0.0.1:5000/s/abc/","sid":"s1","workflow":"plan"}"#;
|
||||
|
||||
#[test]
|
||||
fn accepts_a_good_notice() {
|
||||
let (head, body) = request("t", GOOD);
|
||||
let Ok(Request::Page(notice)) = check_request(&head, &body, "t") else {
|
||||
panic!("not accepted")
|
||||
};
|
||||
assert_eq!(
|
||||
(notice.sid.as_str(), notice.workflow.as_str()),
|
||||
("s1", "plan")
|
||||
);
|
||||
let get = "GET /session HTTP/1.1\r\nx-plan2code-token: t";
|
||||
assert_eq!(check_request(get, b"", "t"), Ok(Request::Session));
|
||||
assert_eq!(
|
||||
check_request(get, b"", "other"),
|
||||
Err(Refused(403, "bad token"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_wrong_or_missing_token() {
|
||||
let (head, body) = request("nope", GOOD);
|
||||
assert_eq!(
|
||||
check_request(&head, &body, "t"),
|
||||
Err(Refused(403, "bad token"))
|
||||
);
|
||||
let head = "POST /page HTTP/1.1\r\nHost: x";
|
||||
assert_eq!(
|
||||
check_request(head, GOOD.as_bytes(), "t"),
|
||||
Err(Refused(403, "bad token"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_browser_origin_and_other_routes() {
|
||||
let (head, body) = request("t", GOOD);
|
||||
let with_origin = format!("{head}\r\nOrigin: http://evil.example");
|
||||
assert_eq!(
|
||||
check_request(&with_origin, &body, "t"),
|
||||
Err(Refused(403, "not from a page"))
|
||||
);
|
||||
let other = head.replace("/page", "/other");
|
||||
assert_eq!(
|
||||
check_request(&other, &body, "t"),
|
||||
Err(Refused(404, "not found"))
|
||||
);
|
||||
let get = head.replace("POST", "GET");
|
||||
assert_eq!(
|
||||
check_request(&get, &body, "t"),
|
||||
Err(Refused(404, "not found")),
|
||||
"GET is for /session only"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_bad_body_and_a_url_that_is_not_the_console() {
|
||||
let (head, _) = request("t", "x");
|
||||
assert_eq!(
|
||||
check_request(&head, b"not json", "t"),
|
||||
Err(Refused(400, "bad body"))
|
||||
);
|
||||
for url in [
|
||||
"http://example.com/s/abc/",
|
||||
"https://127.0.0.1:5/s/a/",
|
||||
"http://127.0.0.1:5/other",
|
||||
"javascript:alert(1)",
|
||||
"http://127.0.0.1:0/s/a/",
|
||||
] {
|
||||
let body = format!(r#"{{"url":"{url}","sid":"s","workflow":"w"}}"#);
|
||||
assert_eq!(
|
||||
check_request(&head, body.as_bytes(), "t"),
|
||||
Err(Refused(400, "bad page")),
|
||||
"{url}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_differ_between_windows() {
|
||||
assert_ne!(random_token(), random_token());
|
||||
assert_eq!(random_token().len(), 32);
|
||||
assert!(same_token("abc", "abc") && !same_token("abc", "abd") && !same_token("abc", "ab"));
|
||||
}
|
||||
|
||||
fn post(port: u16, token: &str, body: &str) -> u16 {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
write!(
|
||||
stream,
|
||||
"POST /page HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\ncontent-length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.unwrap();
|
||||
let mut answer = String::new();
|
||||
stream.read_to_string(&mut answer).unwrap();
|
||||
answer.split(' ').nth(1).unwrap().parse().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_windows_hear_only_their_own_agent() {
|
||||
let (tx_a, rx_a) = channel();
|
||||
let (tx_b, rx_b) = channel();
|
||||
let (tx_a, tx_b) = (Mutex::new(tx_a), Mutex::new(tx_b));
|
||||
let a =
|
||||
AnnounceServer::start(Arc::new(move |n| tx_a.lock().unwrap().send(n).is_ok())).unwrap();
|
||||
let b =
|
||||
AnnounceServer::start(Arc::new(move |n| tx_b.lock().unwrap().send(n).is_ok())).unwrap();
|
||||
assert_ne!(a.url(), b.url());
|
||||
let port = |s: &AnnounceServer| {
|
||||
s.url()
|
||||
.rsplit_once(':')
|
||||
.unwrap()
|
||||
.1
|
||||
.trim_end_matches("/page")
|
||||
.parse::<u16>()
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
assert_eq!(post(port(&a), a.token(), GOOD), 204);
|
||||
assert_eq!(
|
||||
post(port(&b), a.token(), GOOD),
|
||||
403,
|
||||
"window A's token does nothing in window B"
|
||||
);
|
||||
assert_eq!(rx_a.recv_timeout(Duration::from_secs(3)).unwrap().sid, "s1");
|
||||
assert!(rx_b.recv_timeout(Duration::from_millis(300)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_env_names_this_windows_values() {
|
||||
let server = AnnounceServer::start(Arc::new(|_| true)).unwrap();
|
||||
let env = server.agent_env("http://127.0.0.1:1430", "3.0.0");
|
||||
let get = |key: &str| env.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone());
|
||||
assert_eq!(get("PLAN2CODE_IN_APP").as_deref(), Some("1"));
|
||||
assert_eq!(
|
||||
get("PLAN2CODE_EMBED_ORIGIN").as_deref(),
|
||||
Some("http://127.0.0.1:1430")
|
||||
);
|
||||
assert_eq!(get("PLAN2CODE_APP_VERSION").as_deref(), Some("3.0.0"));
|
||||
assert_eq!(get("PLAN2CODE_APP_ANNOUNCE"), Some(server.url()));
|
||||
assert_eq!(get("PLAN2CODE_APP_TOKEN").as_deref(), Some(server.token()));
|
||||
assert_eq!(
|
||||
get("PLAN2CODE_CONSOLE_SID"),
|
||||
None,
|
||||
"the window's session is asked for, not fixed at start"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_current_session_is_what_was_announced_last() {
|
||||
let server = AnnounceServer::start(Arc::new(|_| true)).unwrap();
|
||||
let port: u16 = server
|
||||
.url()
|
||||
.rsplit_once(':')
|
||||
.unwrap()
|
||||
.1
|
||||
.trim_end_matches("/page")
|
||||
.parse()
|
||||
.unwrap();
|
||||
let ask = |token: &str| {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
write!(stream, "GET /session HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\nConnection: close\r\n\r\n").unwrap();
|
||||
let mut answer = String::new();
|
||||
stream.read_to_string(&mut answer).unwrap();
|
||||
answer
|
||||
};
|
||||
assert!(
|
||||
ask(server.token()).ends_with("null"),
|
||||
"nothing announced yet"
|
||||
);
|
||||
assert_eq!(post(port, server.token(), GOOD), 204);
|
||||
assert!(ask(server.token()).contains(r#""sid":"s1""#));
|
||||
assert!(ask("wrong").starts_with("HTTP/1.1 403"));
|
||||
assert_eq!(server.current().unwrap().workflow, "plan");
|
||||
server.forget_current();
|
||||
assert!(
|
||||
ask(server.token()).ends_with("null"),
|
||||
"forgotten: the next open starts its own session"
|
||||
);
|
||||
assert_eq!(server.current(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_the_window_refuses_is_not_its_session() {
|
||||
// A test's throwaway console: remembered, it would steer the next
|
||||
// agent `open` away from the window's real session.
|
||||
let server = AnnounceServer::start(Arc::new(|_| false)).unwrap();
|
||||
let port: u16 = server
|
||||
.url()
|
||||
.rsplit_once(':')
|
||||
.unwrap()
|
||||
.1
|
||||
.trim_end_matches("/page")
|
||||
.parse()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
post(port, server.token(), GOOD),
|
||||
409,
|
||||
"open hears that the app did not take it"
|
||||
);
|
||||
assert_eq!(server.current(), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! The taskbar entry's attention signal. It decides which of four states the
|
||||
//! desktop app is in (busy, ready, attention, plain), which badge the platform
|
||||
//! shows for that state, whether a change into a state that wants the person
|
||||
//! should flash the window, and the pixels of the colored dot. The states and
|
||||
//! the dot colors mirror the web console's favicon. Knows nothing about Tauri.
|
||||
//! The caller turns these decisions into calls on the window.
|
||||
|
||||
/// What Plan2Code is doing, as the web console's favicon shows it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Signal {
|
||||
Busy,
|
||||
Ready,
|
||||
Attention,
|
||||
Plain,
|
||||
}
|
||||
|
||||
/// The two dot colors the taskbar badge can show.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DotColor {
|
||||
Green,
|
||||
Red,
|
||||
}
|
||||
|
||||
/// The badge a platform shows on the taskbar entry.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Badge {
|
||||
None,
|
||||
Dot(DotColor),
|
||||
Label(&'static str),
|
||||
Count(i64),
|
||||
}
|
||||
|
||||
/// The default size, in pixels, of the square dot image.
|
||||
pub const DOT_SIZE: u32 = 16;
|
||||
|
||||
const GREEN_HEX: &str = "#22c55e";
|
||||
const RED_HEX: &str = "#e5484d";
|
||||
const RING_HEX: &str = "#3b332c";
|
||||
|
||||
impl Signal {
|
||||
/// The signal named by a favicon state id ("busy", "ready", "attention"
|
||||
/// or "plain"). Any other text is `None`.
|
||||
pub fn from_id(id: &str) -> Option<Signal> {
|
||||
match id {
|
||||
"busy" => Some(Signal::Busy),
|
||||
"ready" => Some(Signal::Ready),
|
||||
"attention" => Some(Signal::Attention),
|
||||
"plain" => Some(Signal::Plain),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The badge for `signal` on the platform named by `os` (the value of
|
||||
/// `std::env::consts::OS`). When the badge is turned off, there is none.
|
||||
/// Windows shows a dot, macOS a "!" label and Linux a count of 1, and only
|
||||
/// for the states that want the person.
|
||||
pub fn badge_for(signal: Signal, os: &str, enabled: bool) -> Badge {
|
||||
if !enabled {
|
||||
return Badge::None;
|
||||
}
|
||||
match (os, signal) {
|
||||
("windows", Signal::Ready) => Badge::Dot(DotColor::Green),
|
||||
("windows", Signal::Attention) => Badge::Dot(DotColor::Red),
|
||||
("macos", Signal::Attention) => Badge::Label("!"),
|
||||
("linux", Signal::Attention) => Badge::Count(1),
|
||||
_ => Badge::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the window should flash. It does so only when flashing is on, the
|
||||
/// window is not focused, and the signal just changed into Ready or Attention.
|
||||
/// A repeat of the same signal does not flash again.
|
||||
pub fn should_flash(prev: Option<Signal>, next: Signal, focused: bool, enabled: bool) -> bool {
|
||||
enabled && !focused && matches!(next, Signal::Ready | Signal::Attention) && prev != Some(next)
|
||||
}
|
||||
|
||||
/// The dot as RGBA bytes, row by row: a filled, anti-aliased circle with a
|
||||
/// 1 px dark ring at its edge, on a transparent square of `size` pixels. The
|
||||
/// result is `size * size * 4` bytes long, with straight (not premultiplied)
|
||||
/// alpha.
|
||||
pub fn dot_rgba(color: DotColor, size: u32) -> Vec<u8> {
|
||||
let fill = parse_hex(match color {
|
||||
DotColor::Green => GREEN_HEX,
|
||||
DotColor::Red => RED_HEX,
|
||||
});
|
||||
let ring = parse_hex(RING_HEX);
|
||||
let n = size as usize;
|
||||
let mut out = vec![0u8; n * n * 4];
|
||||
let center = size as f32 / 2.0;
|
||||
let radius = center - 0.5;
|
||||
for y in 0..n {
|
||||
for x in 0..n {
|
||||
// Distance from the pixel's center to the circle's center.
|
||||
let dx = x as f32 + 0.5 - center;
|
||||
let dy = y as f32 + 0.5 - center;
|
||||
let distance = (dx * dx + dy * dy).sqrt();
|
||||
let coverage = (radius + 0.5 - distance).clamp(0.0, 1.0);
|
||||
let rgb = if distance > radius - 1.0 { ring } else { fill };
|
||||
let alpha = (coverage * 255.0).round() as u8;
|
||||
let i = (y * n + x) * 4;
|
||||
out[i..i + 4].copy_from_slice(&[rgb[0], rgb[1], rgb[2], alpha]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The three bytes of a `#rrggbb` color. A malformed pair reads as 0.
|
||||
fn parse_hex(hex: &str) -> [u8; 3] {
|
||||
let digits = hex.strip_prefix('#').unwrap_or(hex);
|
||||
let byte = |i: usize| {
|
||||
digits
|
||||
.get(i..i + 2)
|
||||
.and_then(|pair| u8::from_str_radix(pair, 16).ok())
|
||||
.unwrap_or(0)
|
||||
};
|
||||
[byte(0), byte(2), byte(4)]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SIGNALS: [Signal; 4] = [
|
||||
Signal::Busy,
|
||||
Signal::Ready,
|
||||
Signal::Attention,
|
||||
Signal::Plain,
|
||||
];
|
||||
|
||||
fn pixel(buf: &[u8], size: u32, x: u32, y: u32) -> [u8; 4] {
|
||||
let i = ((y * size + x) * 4) as usize;
|
||||
[buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_badge_follows_the_platform_table() {
|
||||
let table: [(Signal, &str, Badge); 16] = [
|
||||
(Signal::Busy, "windows", Badge::None),
|
||||
(Signal::Ready, "windows", Badge::Dot(DotColor::Green)),
|
||||
(Signal::Attention, "windows", Badge::Dot(DotColor::Red)),
|
||||
(Signal::Plain, "windows", Badge::None),
|
||||
(Signal::Busy, "macos", Badge::None),
|
||||
(Signal::Ready, "macos", Badge::None),
|
||||
(Signal::Attention, "macos", Badge::Label("!")),
|
||||
(Signal::Plain, "macos", Badge::None),
|
||||
(Signal::Busy, "linux", Badge::None),
|
||||
(Signal::Ready, "linux", Badge::None),
|
||||
(Signal::Attention, "linux", Badge::Count(1)),
|
||||
(Signal::Plain, "linux", Badge::None),
|
||||
(Signal::Busy, "freebsd", Badge::None),
|
||||
(Signal::Ready, "freebsd", Badge::None),
|
||||
(Signal::Attention, "freebsd", Badge::None),
|
||||
(Signal::Plain, "freebsd", Badge::None),
|
||||
];
|
||||
for (signal, os, want) in table {
|
||||
assert_eq!(
|
||||
badge_for(signal, os, true),
|
||||
want,
|
||||
"{signal:?} on {os}, enabled"
|
||||
);
|
||||
assert_eq!(
|
||||
badge_for(signal, os, false),
|
||||
Badge::None,
|
||||
"{signal:?} on {os}, disabled"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_id_reads_the_four_words_and_refuses_the_rest() {
|
||||
assert_eq!(Signal::from_id("busy"), Some(Signal::Busy));
|
||||
assert_eq!(Signal::from_id("ready"), Some(Signal::Ready));
|
||||
assert_eq!(Signal::from_id("attention"), Some(Signal::Attention));
|
||||
assert_eq!(Signal::from_id("plain"), Some(Signal::Plain));
|
||||
assert_eq!(Signal::from_id("sleeping"), None);
|
||||
assert_eq!(Signal::from_id("Ready"), None, "the ids are lowercase");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_into_ready_or_attention_flashes_when_unfocused() {
|
||||
assert!(should_flash(Some(Signal::Busy), Signal::Ready, false, true));
|
||||
assert!(should_flash(None, Signal::Attention, false, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_flash_while_the_window_is_focused() {
|
||||
assert!(!should_flash(Some(Signal::Busy), Signal::Ready, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_flash_for_a_repeat_of_the_same_signal() {
|
||||
assert!(!should_flash(
|
||||
Some(Signal::Ready),
|
||||
Signal::Ready,
|
||||
false,
|
||||
true
|
||||
));
|
||||
assert!(!should_flash(
|
||||
Some(Signal::Attention),
|
||||
Signal::Attention,
|
||||
false,
|
||||
true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_flash_for_busy_or_plain() {
|
||||
for prev in [None, Some(Signal::Ready), Some(Signal::Attention)] {
|
||||
assert!(
|
||||
!should_flash(prev, Signal::Busy, false, true),
|
||||
"busy from {prev:?}"
|
||||
);
|
||||
assert!(
|
||||
!should_flash(prev, Signal::Plain, false, true),
|
||||
"plain from {prev:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_flash_when_flashing_is_turned_off() {
|
||||
for signal in SIGNALS.iter().copied() {
|
||||
assert!(
|
||||
!should_flash(Some(Signal::Busy), signal, false, false),
|
||||
"{signal:?} while disabled"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_hex_reads_the_byte_pairs() {
|
||||
assert_eq!(parse_hex("#22c55e"), [0x22, 0xc5, 0x5e]);
|
||||
assert_eq!(parse_hex("e5484d"), [0xe5, 0x48, 0x4d]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_green_dot_is_a_transparent_square_with_a_filled_middle() {
|
||||
let size = DOT_SIZE;
|
||||
let buf = dot_rgba(DotColor::Green, size);
|
||||
assert_eq!(buf.len(), (size * size * 4) as usize);
|
||||
assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent");
|
||||
let center = pixel(&buf, size, 8, 8);
|
||||
assert_eq!(center[3], 255, "the middle is opaque");
|
||||
assert_eq!(
|
||||
¢er[..3],
|
||||
&parse_hex(GREEN_HEX)[..],
|
||||
"the middle is the green fill"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_red_dot_is_a_transparent_square_with_a_filled_middle() {
|
||||
let size = DOT_SIZE;
|
||||
let buf = dot_rgba(DotColor::Red, size);
|
||||
assert_eq!(buf.len(), (size * size * 4) as usize);
|
||||
assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent");
|
||||
let center = pixel(&buf, size, 8, 8);
|
||||
assert_eq!(center[3], 255, "the middle is opaque");
|
||||
assert_eq!(
|
||||
¢er[..3],
|
||||
&parse_hex(RED_HEX)[..],
|
||||
"the middle is the red fill"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fill_colors_match_the_web_console_favicon() {
|
||||
let path = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../src/web-console/public/favicon.js"
|
||||
);
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
assert!(
|
||||
text.contains(&format!("ready: \"{GREEN_HEX}\"")),
|
||||
"ready color in favicon.js"
|
||||
);
|
||||
assert!(
|
||||
text.contains(&format!("attention: \"{RED_HEX}\"")),
|
||||
"attention color in favicon.js"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
//! The restart brief: what a fresh agent needs to pick a session up where it
|
||||
//! stopped, written from the console's session files and the spec on disk. It
|
||||
//! is derived on demand and never cached. The Ask chat is left out (FR-7).
|
||||
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// How many of the person's most recent answers the brief carries.
|
||||
const RECENT_ANSWERS: usize = 10;
|
||||
|
||||
/// How many of the session's most recent `events.ndjson` lines the brief carries.
|
||||
const RECENT_EVENTS: usize = 5;
|
||||
|
||||
/// The git argument for the last five commits, one line each.
|
||||
const RECENT_COMMITS: &str = "-5";
|
||||
|
||||
/// How long the one-line next step may run before it is cut.
|
||||
const NEXT_STEP_MAX: usize = 200;
|
||||
|
||||
/// The skill a console workflow runs, as the dashboard launches it.
|
||||
pub fn skill_for_workflow(workflow: &str) -> Option<&'static str> {
|
||||
Some(match workflow {
|
||||
"init" => "plan2code-init",
|
||||
"init-update" => "plan2code-init-update",
|
||||
"pathfinder" => "plan2code-0-pathfinder",
|
||||
"plan" => "plan2code-1-plan",
|
||||
"revise-plan" => "plan2code-1b-revise-plan",
|
||||
"quick-task" => "plan2code-quick-task",
|
||||
"document" => "plan2code-2-document",
|
||||
"implement" => "plan2code-3-implement",
|
||||
"implement-review" => "plan2code-3-implement-review",
|
||||
"review" => "plan2code-review",
|
||||
"finalize" => "plan2code-4-finalize",
|
||||
"handoff" => "plan2code-handoff",
|
||||
"git" => "plan2code-git",
|
||||
"changelog" => "plan2code-changelog",
|
||||
"xray" => "plan2code-xray",
|
||||
"diagnose" => "plan2code-diagnose",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// What the repository looks like now: `git status --short`, and the last
|
||||
/// commits. `None` when the folder is not a git repository.
|
||||
pub struct GitSummary {
|
||||
pub status: String,
|
||||
pub log: String,
|
||||
}
|
||||
|
||||
pub fn git_summary(folder: &Path) -> Option<GitSummary> {
|
||||
let status = git(folder, &["status", "--short"])?;
|
||||
// A repository with no commits yet has no log: the status alone is the record.
|
||||
let log = git(folder, &["log", RECENT_COMMITS, "--oneline"]).unwrap_or_default();
|
||||
Some(GitSummary { status, log })
|
||||
}
|
||||
|
||||
/// Longest a git call may hold up the caller. The brief is built while the
|
||||
/// agent's state is locked, so a slow repository must not stall the window.
|
||||
const GIT_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
fn git(folder: &Path, args: &[&str]) -> Option<String> {
|
||||
let mut command = Command::new("git");
|
||||
command
|
||||
.arg("-C")
|
||||
.arg(folder)
|
||||
.args(args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW, as the console calls are
|
||||
}
|
||||
let mut child = command.spawn().ok()?;
|
||||
let mut out = child.stdout.take()?;
|
||||
let reader = thread::spawn(move || {
|
||||
let mut bytes = Vec::new();
|
||||
let _ = out.read_to_end(&mut bytes);
|
||||
bytes
|
||||
});
|
||||
let deadline = Instant::now() + GIT_TIMEOUT;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait().ok()? {
|
||||
break status;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
let bytes = reader.join().ok()?;
|
||||
status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&bytes).trim_end().to_string())
|
||||
}
|
||||
|
||||
/// The brief as Markdown. `state` is a session's `state.json`; `spec_dir` is
|
||||
/// the spec folder on disk, when the session has one; `git` is the repository
|
||||
/// summary, when the folder is one; `events` is the session's `events.ndjson`,
|
||||
/// oldest first.
|
||||
pub fn build_brief(
|
||||
state: &Value,
|
||||
spec_dir: Option<&Path>,
|
||||
git: Option<&GitSummary>,
|
||||
events: &[Value],
|
||||
) -> String {
|
||||
let workflow = str_field(state, "workflow").unwrap_or("");
|
||||
let skill = skill_for_workflow(workflow);
|
||||
let spec = str_field(state, "specDir");
|
||||
let mut out = String::new();
|
||||
|
||||
out.push_str("## Where you were\n\n");
|
||||
match skill {
|
||||
Some(skill) => out.push_str(&format!("- Skill: {skill} (workflow `{workflow}`)\n")),
|
||||
None => out.push_str(&format!("- Workflow: `{workflow}`\n")),
|
||||
}
|
||||
match spec {
|
||||
Some(spec) => out.push_str(&format!("- Spec: {spec}\n")),
|
||||
None => out.push_str("- Spec: none yet\n"),
|
||||
}
|
||||
out.push('\n');
|
||||
|
||||
out.push_str("## Progress\n\n");
|
||||
let headline = state.get("headline");
|
||||
let stage = headline.and_then(|h| str_field(h, "stage")).unwrap_or("");
|
||||
let cleared = headline
|
||||
.and_then(|h| h.get("cleared"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
let total = headline
|
||||
.and_then(|h| h.get("total"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
let activity = state
|
||||
.get("agent")
|
||||
.and_then(|a| str_field(a, "activity"))
|
||||
.map(str::trim)
|
||||
.filter(|a| !a.is_empty());
|
||||
if !stage.is_empty() {
|
||||
out.push_str(&format!("{stage}: {cleared} of {total} done.\n"));
|
||||
if let Some(activity) = activity {
|
||||
out.push_str(&format!("Doing: {activity}\n"));
|
||||
}
|
||||
out.push('\n');
|
||||
} else if let Some(activity) = activity {
|
||||
out.push_str(&format!("Doing: {activity}\n\n"));
|
||||
} else {
|
||||
out.push_str("No progress posted yet.\n\n");
|
||||
}
|
||||
|
||||
let items = state
|
||||
.get("items")
|
||||
.and_then(Value::as_array)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[]);
|
||||
|
||||
out.push_str("### Open questions\n\n");
|
||||
let open: Vec<&Value> = items
|
||||
.iter()
|
||||
.filter(|i| matches!(str_field(i, "status"), Some("open" | "reopened")))
|
||||
.collect();
|
||||
if open.is_empty() {
|
||||
out.push_str("None.\n\n");
|
||||
} else {
|
||||
for item in open {
|
||||
out.push_str(&format!("- {}\n", title_of(item)));
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
out.push_str("## Recent answers and decisions\n\n");
|
||||
let answered: Vec<&Value> = items
|
||||
.iter()
|
||||
.filter(|i| str_field(i, "status") == Some("answered"))
|
||||
.collect();
|
||||
let recent = &answered[answered.len().saturating_sub(RECENT_ANSWERS)..];
|
||||
if recent.is_empty() {
|
||||
out.push_str("None yet.\n\n");
|
||||
} else {
|
||||
for item in recent {
|
||||
let answer = answer_text(item);
|
||||
let answer = if answer.is_empty() {
|
||||
"answered".to_string()
|
||||
} else {
|
||||
answer
|
||||
};
|
||||
out.push_str(&format!("- {}: {answer}\n", title_of(item)));
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
if let Some(git) = git {
|
||||
out.push_str("## Git\n\n");
|
||||
out.push_str("Changes:\n\n```\n");
|
||||
out.push_str(if git.status.is_empty() {
|
||||
"clean"
|
||||
} else {
|
||||
&git.status
|
||||
});
|
||||
out.push_str("\n```\n\n");
|
||||
if !git.log.is_empty() {
|
||||
out.push_str("Last commits:\n\n```\n");
|
||||
out.push_str(&git.log);
|
||||
out.push_str("\n```\n\n");
|
||||
}
|
||||
}
|
||||
|
||||
if !events.is_empty() {
|
||||
out.push_str("## Recent activity\n\n");
|
||||
let recent = &events[events.len().saturating_sub(RECENT_EVENTS)..];
|
||||
for event in recent {
|
||||
out.push_str(&format!("- {}\n", render_event(event)));
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
out.push_str("## Next task\n\n");
|
||||
out.push_str(&next_step(spec_dir, skill));
|
||||
out.push('\n');
|
||||
out
|
||||
}
|
||||
|
||||
/// One `events.ndjson` line, as a terse line for a fresh agent. A shape this
|
||||
/// does not special-case falls back to its raw `type`.
|
||||
fn render_event(event: &Value) -> String {
|
||||
let kind = str_field(event, "type").unwrap_or("event");
|
||||
match kind {
|
||||
"post" => {
|
||||
let items = event.get("items").and_then(Value::as_u64).unwrap_or(0);
|
||||
format!("post ({items} items)")
|
||||
}
|
||||
"consume" => match str_field(event, "kind") {
|
||||
Some(kind) => format!("consume: {kind}"),
|
||||
None => "consume".to_string(),
|
||||
},
|
||||
"open" => {
|
||||
if event
|
||||
.get("resumed")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
"open (resumed)".to_string()
|
||||
} else {
|
||||
"open".to_string()
|
||||
}
|
||||
}
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one-line next step: the first open task of the spec's in-progress phase
|
||||
/// (or, failing that, the first phase not started); otherwise the skill's name;
|
||||
/// otherwise "Open the dashboard".
|
||||
pub fn next_step(spec_dir: Option<&Path>, skill: Option<&str>) -> String {
|
||||
if let Some(task) = spec_dir.and_then(open_task) {
|
||||
return cut(&task);
|
||||
}
|
||||
match skill {
|
||||
Some(skill) => format!("Continue with {skill}"),
|
||||
None => "Open the dashboard".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first `- [ ]` task line of the active phase file, as one line of text.
|
||||
fn open_task(spec_dir: &Path) -> Option<String> {
|
||||
let overview = fs::read_to_string(spec_dir.join("overview.md")).ok()?;
|
||||
let phase = active_phase(&overview)?;
|
||||
let text = fs::read_to_string(spec_dir.join(format!("phase-{phase}.md"))).ok()?;
|
||||
let line = text
|
||||
.lines()
|
||||
.map(str::trim_start)
|
||||
.find(|l| l.starts_with("- [ ]"))?;
|
||||
Some(line.trim_start_matches("- [ ]").trim().replace("**", ""))
|
||||
}
|
||||
|
||||
/// The phase number the overview marks in progress (`[/]`), else the first
|
||||
/// one not started (`[ ]`).
|
||||
fn active_phase(overview: &str) -> Option<u32> {
|
||||
let phase_of = |line: &str| {
|
||||
let rest = &line[line.find("phase-")? + "phase-".len()..];
|
||||
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
|
||||
digits.parse::<u32>().ok()
|
||||
};
|
||||
let rows = || {
|
||||
overview
|
||||
.lines()
|
||||
.map(str::trim_start)
|
||||
.filter(|l| l.starts_with("- ["))
|
||||
};
|
||||
rows()
|
||||
.find(|l| l.starts_with("- [/]"))
|
||||
.and_then(phase_of)
|
||||
.or_else(|| rows().find(|l| l.starts_with("- [ ]")).and_then(phase_of))
|
||||
}
|
||||
|
||||
fn cut(text: &str) -> String {
|
||||
let mut out: String = text.chars().take(NEXT_STEP_MAX).collect();
|
||||
if text.chars().count() > NEXT_STEP_MAX {
|
||||
out.push('…');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn str_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
|
||||
value.get(key).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
fn title_of(item: &Value) -> String {
|
||||
let title = str_field(item, "title")
|
||||
.or_else(|| str_field(item, "id"))
|
||||
.unwrap_or("(untitled)");
|
||||
title.trim().to_string()
|
||||
}
|
||||
|
||||
/// An answer as the person gave it: the option's label for a pick, plus any
|
||||
/// words they typed. Empty when the answer carries nothing to show.
|
||||
fn answer_text(item: &Value) -> String {
|
||||
let Some(answer) = item.get("answer") else {
|
||||
return String::new();
|
||||
};
|
||||
let options = item.get("options").and_then(Value::as_array);
|
||||
let label = |k: &str| {
|
||||
options
|
||||
.and_then(|list| list.iter().find(|o| str_field(o, "k") == Some(k)))
|
||||
.and_then(|o| str_field(o, "text"))
|
||||
.unwrap_or(k)
|
||||
.to_string()
|
||||
};
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
if let Some(k) = str_field(answer, "k") {
|
||||
parts.push(label(k));
|
||||
}
|
||||
if let Some(list) = answer.get("ks").and_then(Value::as_array) {
|
||||
let picks: Vec<String> = list.iter().filter_map(Value::as_str).map(label).collect();
|
||||
if !picks.is_empty() {
|
||||
parts.push(picks.join(", "));
|
||||
}
|
||||
}
|
||||
if let Some(yes) = answer.get("yes").and_then(Value::as_bool) {
|
||||
parts.push(if yes { "yes" } else { "no" }.to_string());
|
||||
}
|
||||
if let Some(verdict) = str_field(answer, "verdict") {
|
||||
parts.push(verdict.to_string());
|
||||
}
|
||||
if let Some(text) = str_field(answer, "text")
|
||||
.map(str::trim)
|
||||
.filter(|t| !t.is_empty())
|
||||
{
|
||||
parts.push(text.to_string());
|
||||
}
|
||||
parts.join("; ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn fixture(name: &str) -> std::path::PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-brief-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn mid_implement_spec() -> std::path::PathBuf {
|
||||
let spec = fixture("spec").join("specs").join("feature");
|
||||
fs::create_dir_all(&spec).unwrap();
|
||||
fs::write(
|
||||
spec.join("overview.md"),
|
||||
"- [x] [Phase 1: Foundations](./phase-1.md)\n- [/] [Phase 2: Restart](./phase-2.md)\n- [ ] [Phase 3: Later](./phase-3.md)\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(spec.join("phase-2.md"), "## Tasks\n\n- [x] **Task 2.1:** Done already\n- [ ] **Task 2.2:** Write the **reader**\n- [ ] **Task 2.3:** Later\n").unwrap();
|
||||
spec
|
||||
}
|
||||
|
||||
fn mid_implement_state() -> Value {
|
||||
json!({
|
||||
"schema": 1,
|
||||
"workflow": "implement",
|
||||
"specDir": "specs/feature",
|
||||
"headline": { "stage": "Phase 2: Restart", "cleared": 1, "total": 3 },
|
||||
"items": [
|
||||
{ "id": "q1", "title": "Which format", "status": "answered", "kind": "choice",
|
||||
"options": [{ "k": "A", "text": "Markdown" }, { "k": "B", "text": "Plain text" }],
|
||||
"answer": { "k": "A" } },
|
||||
{ "id": "q2", "title": "Keep the header", "status": "answered", "kind": "confirm", "answer": { "yes": true } },
|
||||
{ "id": "q3", "title": "Anything else?", "status": "open", "kind": "text" }
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mid_implement_session_carries_every_section() {
|
||||
let spec = mid_implement_spec();
|
||||
let git = GitSummary {
|
||||
status: " M src/lib.rs".to_string(),
|
||||
log: "abc1234 Add the reader".to_string(),
|
||||
};
|
||||
let brief = build_brief(&mid_implement_state(), Some(&spec), Some(&git), &[]);
|
||||
assert!(brief.contains("Skill: plan2code-3-implement (workflow `implement`)"));
|
||||
assert!(brief.contains("Spec: specs/feature"));
|
||||
assert!(brief.contains("Phase 2: Restart: 1 of 3 done."));
|
||||
assert!(brief.contains("### Open questions\n\n- Anything else?"));
|
||||
assert!(brief.contains("- Which format: Markdown"));
|
||||
assert!(brief.contains("- Keep the header: yes"));
|
||||
assert!(brief.contains(" M src/lib.rs"));
|
||||
assert!(brief.contains("abc1234 Add the reader"));
|
||||
assert!(brief.contains("## Next task\n\nTask 2.2: Write the reader"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brief_names_only_the_last_ten_answers() {
|
||||
let items: Vec<Value> = (0..12)
|
||||
.map(|n| json!({ "id": format!("q{n}"), "title": format!("Question {n}"), "status": "answered", "answer": { "text": format!("Answer {n}") } }))
|
||||
.collect();
|
||||
let state = json!({ "schema": 1, "workflow": "pathfinder", "items": items });
|
||||
let brief = build_brief(&state, None, None, &[]);
|
||||
assert!(!brief.contains("Question 0:"));
|
||||
assert!(!brief.contains("Question 1:"));
|
||||
assert!(brief.contains("- Question 2: Answer 2"));
|
||||
assert!(brief.contains("- Question 11: Answer 11"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pathfinder_session_without_a_spec_says_so() {
|
||||
let state = json!({ "schema": 1, "workflow": "pathfinder", "headline": { "stage": "Charting", "cleared": 2, "total": 5 } });
|
||||
let brief = build_brief(&state, None, None, &[]);
|
||||
assert!(brief.contains("Skill: plan2code-0-pathfinder"));
|
||||
assert!(brief.contains("- Spec: none yet"));
|
||||
assert!(!brief.contains("## Git"));
|
||||
assert!(brief.contains("## Next task\n\nContinue with plan2code-0-pathfinder"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_with_no_spec_and_no_skill_opens_the_dashboard() {
|
||||
let state = json!({ "schema": 1, "workflow": "dashboard" });
|
||||
assert!(
|
||||
build_brief(&state, None, None, &[]).ends_with("## Next task\n\nOpen the dashboard\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_entries_never_reach_the_brief() {
|
||||
let home = fixture("chat");
|
||||
let dir = home.join("sessions").join("s1");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(
|
||||
dir.join("state.json"),
|
||||
r#"{"schema": 1, "workflow": "implement"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
dir.join("chat.ndjson"),
|
||||
"{\"kind\":\"ask\",\"text\":\"CHAT-ONLY-WORDS\"}\n",
|
||||
)
|
||||
.unwrap();
|
||||
let session = crate::session_reader::load(&home, "s1").unwrap();
|
||||
let brief = build_brief(&session.state, None, None, &[]);
|
||||
assert!(!brief.contains("CHAT-ONLY-WORDS"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_that_is_not_a_repository_has_no_git_summary() {
|
||||
assert!(git_summary(&fixture("not-a-repo")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brief_names_what_the_agent_was_doing() {
|
||||
let state = json!({
|
||||
"schema": 1,
|
||||
"workflow": "implement",
|
||||
"headline": { "stage": "Phase 2: Restart", "cleared": 1, "total": 3 },
|
||||
"agent": { "status": "working", "activity": "Spiking Claude's context signal (Task 10.1)" },
|
||||
});
|
||||
let brief = build_brief(&state, None, None, &[]);
|
||||
assert!(brief.contains(
|
||||
"Phase 2: Restart: 1 of 3 done.\nDoing: Spiking Claude's context signal (Task 10.1)\n"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_activity_without_a_headline_still_shows() {
|
||||
let state = json!({ "schema": 1, "workflow": "implement", "agent": { "status": "working", "activity": "Reading the spec" } });
|
||||
let brief = build_brief(&state, None, None, &[]);
|
||||
assert!(brief.contains("Doing: Reading the spec\n"));
|
||||
assert!(!brief.contains("No progress posted yet."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_activity_falls_back_to_no_progress_posted() {
|
||||
let state = json!({ "schema": 1, "workflow": "implement", "agent": { "status": "idle", "activity": "" } });
|
||||
let brief = build_brief(&state, None, None, &[]);
|
||||
assert!(brief.contains("No progress posted yet."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brief_names_a_few_recent_events() {
|
||||
let state = json!({ "schema": 1, "workflow": "implement" });
|
||||
let events = vec![
|
||||
json!({ "at": "2026-10-23T01:00:00.000Z", "type": "listening", "port": 4100 }),
|
||||
json!({ "at": "2026-10-23T01:08:00.000Z", "type": "open", "resumed": true }),
|
||||
json!({ "at": "2026-10-23T01:08:47.152Z", "type": "post", "items": 3 }),
|
||||
json!({ "at": "2026-10-23T01:09:00.000Z", "type": "consume", "kind": "submit" }),
|
||||
];
|
||||
let brief = build_brief(&state, None, None, &events);
|
||||
assert!(brief.contains("## Recent activity\n\n- listening\n- open (resumed)\n- post (3 items)\n- consume: submit\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_last_five_events_are_named() {
|
||||
let state = json!({ "schema": 1, "workflow": "implement" });
|
||||
let events: Vec<Value> = (0..8)
|
||||
.map(|n| json!({ "type": "upload", "id": format!("f{n}") }))
|
||||
.collect();
|
||||
let brief = build_brief(&state, None, None, &events);
|
||||
assert_eq!(brief.matches("- upload\n").count(), RECENT_EVENTS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_events_means_no_recent_activity_section() {
|
||||
let state = json!({ "schema": 1, "workflow": "implement" });
|
||||
assert!(!build_brief(&state, None, None, &[]).contains("## Recent activity"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skill_name_maps_to_its_workflow() {
|
||||
assert_eq!(
|
||||
skill_for_workflow("quick-task"),
|
||||
Some("plan2code-quick-task")
|
||||
);
|
||||
assert_eq!(skill_for_workflow("unknown"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
//! The Node web console as a supervised child: `console.mjs open` starts a
|
||||
//! detached server and prints the session's JSON, `stop` ends it, and a plain
|
||||
//! GET on the session URL is the health check. Knows nothing about Tauri.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::session_reader;
|
||||
|
||||
/// How long a health check waits for the console before calling it dead. The
|
||||
/// server is on loopback, so anything longer is a hang, not a slow network.
|
||||
const HEALTH_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
/// The second, longer look a server gets before it is restarted, as the
|
||||
/// console's own `open` gives one: a machine busy with a test run can keep a
|
||||
/// healthy server from answering inside the first.
|
||||
const BUSY_HEALTH_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// A running console session, as `console.mjs open` reports it.
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct ConsoleSession {
|
||||
pub sid: String,
|
||||
pub url: String,
|
||||
pub pid: u32,
|
||||
pub port: u16,
|
||||
/// The console says it can be framed by the app. An older one does not
|
||||
/// print this, and its page would be refused in the frame.
|
||||
pub embed: bool,
|
||||
}
|
||||
|
||||
/// What the person is told when the installed console is too old for the app.
|
||||
pub const OLD_CONSOLE: &str =
|
||||
"The installed Plan2Code console is too old to show inside the app. Press Update skills, then try again.";
|
||||
|
||||
/// One supervised console for one project folder.
|
||||
pub struct ConsoleSupervisor {
|
||||
console_dir: PathBuf,
|
||||
project_dir: PathBuf,
|
||||
embed_origin: String,
|
||||
workflow: String,
|
||||
session: ConsoleSession,
|
||||
stopped: bool,
|
||||
}
|
||||
|
||||
fn err<E: std::fmt::Display>(e: E) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
/// A `node console.mjs ...` call with no console window on Windows: the app is
|
||||
/// a GUI program, so a bare Command would flash one open per call.
|
||||
fn node_command(console_dir: &Path) -> Command {
|
||||
let mut command = Command::new("node");
|
||||
// A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's
|
||||
// directories (Task 9.9): run `node` with the PATH that finds it anyway.
|
||||
command.env("PATH", crate::node_check::resolved_path());
|
||||
command.arg(console_dir.join("console.mjs"));
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||
}
|
||||
command
|
||||
}
|
||||
|
||||
/// The origin the app's own page has, which is what the console's embed mode
|
||||
/// must be told to allow as the frame parent. Tauri serves the page on
|
||||
/// `http://tauri.localhost` on Windows (and Android) and `tauri://localhost`
|
||||
/// on macOS and Linux.
|
||||
pub fn app_origin() -> &'static str {
|
||||
if cfg!(windows) {
|
||||
"http://tauri.localhost"
|
||||
} else {
|
||||
"tauri://localhost"
|
||||
}
|
||||
}
|
||||
|
||||
/// The origin (`scheme://host[:port]`) of the app page's own URL, which is what
|
||||
/// the console's embed mode must allow as the frame parent. In a release build
|
||||
/// that is `app_origin()`, but `tauri dev` serves the page from its own dev
|
||||
/// server on a loopback port, so the real URL is asked rather than assumed.
|
||||
pub fn origin_of(url: &str) -> Option<String> {
|
||||
let (scheme, rest) = url.split_once("://")?;
|
||||
let authority = rest.split(['/', '?', '#']).next()?;
|
||||
if authority.is_empty() || !matches!(scheme, "http" | "https" | "tauri") {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{scheme}://{authority}"))
|
||||
}
|
||||
|
||||
/// Where the installed console lives: an explicit override first (tests and
|
||||
/// dev), then the file the console keeps for the app, then the skill install.
|
||||
pub fn find_console_dir() -> Result<PathBuf, String> {
|
||||
let has_console = |dir: &Path| dir.join("console.mjs").is_file();
|
||||
if let Ok(dir) = std::env::var("PLAN2CODE_CONSOLE_DIR") {
|
||||
let dir = PathBuf::from(dir);
|
||||
if has_console(&dir) {
|
||||
return Ok(dir);
|
||||
}
|
||||
}
|
||||
// The console writes its pointer under PLAN2CODE_CONSOLE_HOME when that
|
||||
// relocates it, else under ~/.plan2code/console.
|
||||
let pointer = match std::env::var("PLAN2CODE_CONSOLE_HOME") {
|
||||
Ok(home) => PathBuf::from(home).join("console-dir"),
|
||||
Err(_) => {
|
||||
let home = std::env::home_dir().ok_or("no home folder found")?;
|
||||
home.join(".plan2code").join("console").join("console-dir")
|
||||
}
|
||||
};
|
||||
if let Ok(text) = std::fs::read_to_string(&pointer) {
|
||||
let dir = PathBuf::from(text.trim());
|
||||
if has_console(&dir) {
|
||||
return Ok(dir);
|
||||
}
|
||||
}
|
||||
let dir = std::env::home_dir()
|
||||
.ok_or("no home folder found")?
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("plan2code")
|
||||
.join("references")
|
||||
.join("web-console");
|
||||
if has_console(&dir) {
|
||||
return Ok(dir);
|
||||
}
|
||||
Err(format!(
|
||||
"the web console is not installed (looked in $PLAN2CODE_CONSOLE_DIR, {} and {})",
|
||||
pointer.display(),
|
||||
dir.display()
|
||||
))
|
||||
}
|
||||
|
||||
/// Parse the one JSON object `console.mjs open` prints on stdout.
|
||||
fn parse_open_output(stdout: &[u8]) -> Result<ConsoleSession, String> {
|
||||
let text = String::from_utf8_lossy(stdout);
|
||||
let line = text
|
||||
.lines()
|
||||
.rev()
|
||||
.find(|l| l.trim_start().starts_with('{'))
|
||||
.ok_or_else(|| format!("console open printed no JSON: {}", text.trim()))?;
|
||||
let value: serde_json::Value = serde_json::from_str(line.trim()).map_err(err)?;
|
||||
let get = |key: &str| value.get(key).and_then(|v| v.as_str().map(String::from));
|
||||
let num = |key: &str| value.get(key).and_then(|v| v.as_u64());
|
||||
Ok(ConsoleSession {
|
||||
sid: get("sid").ok_or("console open: no sid in output")?,
|
||||
url: get("url").ok_or("console open: no url in output")?,
|
||||
pid: num("pid").ok_or("console open: no pid in output")? as u32,
|
||||
port: num("port").ok_or("console open: no port in output")? as u16,
|
||||
embed: num("embed").is_some_and(|n| n >= 1),
|
||||
})
|
||||
}
|
||||
|
||||
/// Split `http://<host>:<port><path>` into its parts; the console only ever
|
||||
/// listens on loopback http.
|
||||
fn split_url(url: &str) -> Result<(String, u16, String), String> {
|
||||
let rest = url
|
||||
.strip_prefix("http://")
|
||||
.ok_or_else(|| format!("not an http url: {url}"))?;
|
||||
let (authority, path) = match rest.split_once('/') {
|
||||
Some((a, p)) => (a, format!("/{p}")),
|
||||
None => (rest, "/".to_string()),
|
||||
};
|
||||
let (host, port) = authority
|
||||
.rsplit_once(':')
|
||||
.ok_or_else(|| format!("no port in url: {url}"))?;
|
||||
let port: u16 = port
|
||||
.parse()
|
||||
.map_err(|_| format!("bad port in url: {url}"))?;
|
||||
Ok((host.to_string(), port, path))
|
||||
}
|
||||
|
||||
impl ConsoleSupervisor {
|
||||
/// Find the installed console, run `open --workflow dashboard --no-open` in
|
||||
/// the project folder with `PLAN2CODE_EMBED_ORIGIN` set, and keep the
|
||||
/// session it prints.
|
||||
pub fn start(project_dir: PathBuf, embed_origin: String) -> Result<ConsoleSupervisor, String> {
|
||||
Self::start_with_workflow(project_dir, embed_origin, "dashboard")
|
||||
}
|
||||
|
||||
/// `start` for another workflow: today only `setup`, the agent-less page
|
||||
/// the app itself opens for Set up an agent (the one exception to the
|
||||
/// app never starting a console of its own).
|
||||
pub fn start_with_workflow(
|
||||
project_dir: PathBuf,
|
||||
embed_origin: String,
|
||||
workflow: &str,
|
||||
) -> Result<ConsoleSupervisor, String> {
|
||||
let console_dir = find_console_dir()?;
|
||||
let session =
|
||||
Self::open_session(&console_dir, &project_dir, &embed_origin, None, workflow)?;
|
||||
Ok(ConsoleSupervisor {
|
||||
console_dir,
|
||||
project_dir,
|
||||
embed_origin,
|
||||
workflow: workflow.to_string(),
|
||||
session,
|
||||
stopped: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// `open` for the dashboard, or, with `resume`, the same session again on
|
||||
/// a new server (so the page and its place in a skill survive a dead server).
|
||||
/// A console the agent's `open` started and announced: this supervisor
|
||||
/// now owns its health and its stop, though it did not start it.
|
||||
pub fn adopt(
|
||||
project_dir: PathBuf,
|
||||
embed_origin: String,
|
||||
url: &str,
|
||||
sid: &str,
|
||||
) -> Result<ConsoleSupervisor, String> {
|
||||
let console_dir = find_console_dir()?;
|
||||
let (_, port, _) = split_url(url)?;
|
||||
let session = ConsoleSession {
|
||||
sid: sid.to_string(),
|
||||
url: url.to_string(),
|
||||
pid: 0,
|
||||
port,
|
||||
embed: true,
|
||||
};
|
||||
Ok(ConsoleSupervisor {
|
||||
console_dir,
|
||||
project_dir,
|
||||
embed_origin,
|
||||
workflow: "dashboard".to_string(),
|
||||
session,
|
||||
stopped: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn open_session(
|
||||
console_dir: &Path,
|
||||
project_dir: &Path,
|
||||
embed_origin: &str,
|
||||
resume: Option<&str>,
|
||||
workflow: &str,
|
||||
) -> Result<ConsoleSession, String> {
|
||||
let mut command = node_command(console_dir);
|
||||
command.arg("open");
|
||||
match resume {
|
||||
Some(sid) => command.args(["--resume", sid, "--no-open"]),
|
||||
None => command.args(["--workflow", workflow, "--no-open"]),
|
||||
};
|
||||
let output = command
|
||||
.current_dir(project_dir)
|
||||
.env("PLAN2CODE_EMBED_ORIGIN", embed_origin)
|
||||
.output()
|
||||
.map_err(err)?;
|
||||
if !output.status.success() {
|
||||
return Err(format!(
|
||||
"console open failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
));
|
||||
}
|
||||
let session = parse_open_output(&output.stdout)?;
|
||||
if !session.embed {
|
||||
// Do not leave an old console running that the frame cannot show.
|
||||
let _ = node_command(console_dir)
|
||||
.args(stop_args(&session.sid))
|
||||
.current_dir(project_dir)
|
||||
.output();
|
||||
return Err(OLD_CONSOLE.to_string());
|
||||
}
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
pub fn session(&self) -> &ConsoleSession {
|
||||
&self.session
|
||||
}
|
||||
|
||||
/// The console moved to another address or session (an announced page that
|
||||
/// is not the one this supervisor opened): health, stop and the restart
|
||||
/// brief follow it from now on.
|
||||
pub fn follow(&mut self, url: &str, sid: &str) {
|
||||
if self.session.url == url && self.session.sid == sid {
|
||||
return;
|
||||
}
|
||||
if let Ok((_, port, _)) = split_url(url) {
|
||||
self.session.port = port;
|
||||
}
|
||||
self.session.url = url.to_string();
|
||||
self.session.sid = sid.to_string();
|
||||
}
|
||||
|
||||
/// Was `stop()` called on this supervisor.
|
||||
pub fn stopped(&self) -> bool {
|
||||
self.stopped
|
||||
}
|
||||
|
||||
/// A GET on the session URL: any HTTP answer means the server is alive.
|
||||
pub fn health(&self) -> bool {
|
||||
self.health_within(HEALTH_TIMEOUT)
|
||||
}
|
||||
|
||||
fn health_within(&self, timeout: Duration) -> bool {
|
||||
if self.stopped {
|
||||
return false;
|
||||
}
|
||||
let Ok((host, port, path)) = split_url(&self.session.url) else {
|
||||
return false;
|
||||
};
|
||||
let Some(addr) = (host.as_str(), port)
|
||||
.to_socket_addrs()
|
||||
.ok()
|
||||
.and_then(|mut a| a.next())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Ok(mut stream) = TcpStream::connect_timeout(&addr, timeout) else {
|
||||
return false;
|
||||
};
|
||||
let _ = stream.set_read_timeout(Some(timeout));
|
||||
let _ = stream.set_write_timeout(Some(timeout));
|
||||
let request = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
|
||||
if stream.write_all(request.as_bytes()).is_err() {
|
||||
return false;
|
||||
}
|
||||
let mut status = [0u8; 64];
|
||||
match stream.read(&mut status) {
|
||||
Ok(n) => String::from_utf8_lossy(&status[..n]).starts_with("HTTP/"),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Health check plus a fresh `open` when the server is gone. Returns true
|
||||
/// when a new session was started. Never loops: the caller (the bar) asks
|
||||
/// and shows the outcome.
|
||||
pub fn restart_if_dead(&mut self) -> Result<bool, String> {
|
||||
if self.stopped || self.health() || self.health_within(BUSY_HEALTH_TIMEOUT) {
|
||||
return Ok(false);
|
||||
}
|
||||
let sid = self.session.sid.clone();
|
||||
let on_disk = session_on_disk(&sid);
|
||||
let (console_dir, project_dir, embed_origin, workflow) = (
|
||||
&self.console_dir,
|
||||
&self.project_dir,
|
||||
&self.embed_origin,
|
||||
&self.workflow,
|
||||
);
|
||||
self.session = resume_or_fresh(&sid, on_disk, |resume| {
|
||||
Self::open_session(console_dir, project_dir, embed_origin, resume, workflow)
|
||||
})?;
|
||||
self.stopped = false;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// `console.mjs stop --session <sid> --force`: the console's own orderly
|
||||
/// shutdown. `--force` because the app's shutdown is not the agent's ending:
|
||||
/// the session may be unfinished, and `stop` refuses a session with no finish.
|
||||
pub fn stop(&mut self) -> Result<(), String> {
|
||||
if self.stopped {
|
||||
return Ok(());
|
||||
}
|
||||
let output = node_command(&self.console_dir)
|
||||
.args(stop_args(&self.session.sid))
|
||||
.current_dir(&self.project_dir)
|
||||
.output()
|
||||
.map_err(err)?;
|
||||
self.stopped = true;
|
||||
if !output.status.success() {
|
||||
return Err(format!(
|
||||
"console stop failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the session's folder still in the console's home. Unknown (no home
|
||||
/// directory) counts as there, so the answer never throws a session away. A
|
||||
/// sid that is not a plain folder name (empty, `..`, a path) is never there.
|
||||
pub fn session_on_disk(sid: &str) -> bool {
|
||||
if Path::new(sid).file_name() != Some(std::ffi::OsStr::new(sid)) {
|
||||
return false;
|
||||
}
|
||||
session_reader::console_home()
|
||||
.is_none_or(|home| session_reader::session_dir(&home, sid).is_dir())
|
||||
}
|
||||
|
||||
/// The same session, so the page and a skill's place in it survive, tried
|
||||
/// twice. Only a session gone from disk starts a new one: falling back to a
|
||||
/// fresh dashboard while the folder is still there once swapped a build's page
|
||||
/// for an empty dashboard mid-run, and the agent went on posting to a session
|
||||
/// the window no longer showed. A failure is the bar's to report, with Retry.
|
||||
fn resume_or_fresh<F>(sid: &str, on_disk: bool, mut open: F) -> Result<ConsoleSession, String>
|
||||
where
|
||||
F: FnMut(Option<&str>) -> Result<ConsoleSession, String>,
|
||||
{
|
||||
if !on_disk {
|
||||
return open(None);
|
||||
}
|
||||
open(Some(sid)).or_else(|_| open(Some(sid)))
|
||||
}
|
||||
|
||||
impl Drop for ConsoleSupervisor {
|
||||
/// The app going away takes the console it started with it. `stop` is
|
||||
/// idempotent, so a session ended by hand just returns early here.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// The arguments of the app's own `stop`: always `--force`, since the app's
|
||||
/// shutdown is not the agent's ending and `stop` refuses a session with no finish.
|
||||
fn stop_args(sid: &str) -> [&str; 4] {
|
||||
["stop", "--session", sid, "--force"]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_apps_stop_calls_pass_force() {
|
||||
let args = stop_args("20261101-120000-abcdef");
|
||||
assert_eq!(
|
||||
args,
|
||||
["stop", "--session", "20261101-120000-abcdef", "--force"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_the_session_url() {
|
||||
let (host, port, path) = split_url("http://127.0.0.1:51617/s/abc/").unwrap();
|
||||
assert_eq!(
|
||||
(host.as_str(), port, path.as_str()),
|
||||
("127.0.0.1", 51617, "/s/abc/")
|
||||
);
|
||||
let (_, _, path) = split_url("http://localhost:9").unwrap();
|
||||
assert_eq!(path, "/");
|
||||
assert!(split_url("https://127.0.0.1:1/x").is_err());
|
||||
assert!(split_url("http://127.0.0.1/x").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn origin_comes_from_the_pages_own_url() {
|
||||
assert_eq!(
|
||||
origin_of("http://127.0.0.1:1430/index.html").as_deref(),
|
||||
Some("http://127.0.0.1:1430")
|
||||
);
|
||||
assert_eq!(
|
||||
origin_of("http://tauri.localhost/").as_deref(),
|
||||
Some("http://tauri.localhost")
|
||||
);
|
||||
assert_eq!(
|
||||
origin_of("https://tauri.localhost").as_deref(),
|
||||
Some("https://tauri.localhost")
|
||||
);
|
||||
assert_eq!(
|
||||
origin_of("tauri://localhost/index.html?x=1").as_deref(),
|
||||
Some("tauri://localhost")
|
||||
);
|
||||
assert_eq!(origin_of("file:///x"), None);
|
||||
assert_eq!(origin_of("not a url"), None);
|
||||
assert_eq!(origin_of("http:///x"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_announced_console_is_adopted_with_its_port() {
|
||||
// Only needs a console to be installed; skipped where there is none.
|
||||
let Ok(dir) = find_console_dir() else { return };
|
||||
let _ = dir;
|
||||
let mut sup = ConsoleSupervisor::adopt(
|
||||
PathBuf::from("."),
|
||||
"http://tauri.localhost".into(),
|
||||
"http://127.0.0.1:5555/s/t/",
|
||||
"sid-9",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(sup.session().port, sup.session().sid.as_str()),
|
||||
(5555, "sid-9")
|
||||
);
|
||||
assert!(sup.session().embed);
|
||||
assert!(
|
||||
ConsoleSupervisor::adopt(PathBuf::from("."), String::new(), "https://x/", "s").is_err()
|
||||
);
|
||||
sup.follow("http://127.0.0.1:6000/s/u/", "sid-10");
|
||||
assert_eq!(
|
||||
(sup.session().port, sup.session().sid.as_str()),
|
||||
(6000, "sid-10")
|
||||
);
|
||||
// Never started a server here: nothing for Drop to stop.
|
||||
sup.stopped = true;
|
||||
}
|
||||
|
||||
fn opened(sid: &str) -> ConsoleSession {
|
||||
ConsoleSession {
|
||||
sid: sid.to_string(),
|
||||
url: "http://127.0.0.1:5/s/t/".into(),
|
||||
pid: 1,
|
||||
port: 5,
|
||||
embed: true,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_plain_folder_name_can_be_a_session_on_disk() {
|
||||
// `<home>/sessions/` and `<home>` are folders too: these must not pass.
|
||||
for sid in ["", ".", "..", "../x", "a/b", "a\\b"] {
|
||||
assert!(!session_on_disk(sid), "{sid:?} counted as a session");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_resume_of_a_session_still_on_disk_never_opens_a_fresh_dashboard() {
|
||||
// A build's console that was slow to answer: swapping its page for a
|
||||
// new dashboard left the agent posting to a session nobody could see.
|
||||
let mut calls = Vec::new();
|
||||
let result = resume_or_fresh("s1", true, |resume| {
|
||||
calls.push(resume.map(str::to_string));
|
||||
Err("busy".to_string())
|
||||
});
|
||||
assert!(result.is_err(), "the failure is reported, not papered over");
|
||||
assert!(
|
||||
calls.iter().all(|c| c.as_deref() == Some("s1")),
|
||||
"only ever resumed: {calls:?}"
|
||||
);
|
||||
assert_eq!(calls.len(), 2, "the resume is tried twice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resume_that_works_the_second_time_keeps_the_session() {
|
||||
let mut tries = 0;
|
||||
let session = resume_or_fresh("s1", true, |resume| {
|
||||
tries += 1;
|
||||
assert_eq!(resume, Some("s1"));
|
||||
if tries == 1 {
|
||||
Err("busy".to_string())
|
||||
} else {
|
||||
Ok(opened("s1"))
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(session.sid, "s1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_gone_from_disk_starts_a_fresh_dashboard() {
|
||||
let mut calls = Vec::new();
|
||||
let session = resume_or_fresh("s1", false, |resume| {
|
||||
calls.push(resume.map(str::to_string));
|
||||
Ok(opened(if resume.is_some() { "s1" } else { "s2" }))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(session.sid, "s2");
|
||||
assert_eq!(calls, vec![None], "nothing on disk to resume");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_open_output() {
|
||||
let json =
|
||||
br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42,"embed":1}
|
||||
"#;
|
||||
let session = parse_open_output(json).unwrap();
|
||||
assert_eq!(
|
||||
(session.sid.as_str(), session.port, session.pid),
|
||||
("s1", 5, 42)
|
||||
);
|
||||
assert!(session.embed);
|
||||
let old = br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42}"#;
|
||||
assert!(
|
||||
!parse_open_output(old).unwrap().embed,
|
||||
"a console that does not say it embeds is too old"
|
||||
);
|
||||
assert!(parse_open_output(b"not json\n").is_err());
|
||||
assert!(parse_open_output(br#"{"ok":true,"sid":"s1"}"#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Writes a handoff the dashboard already knows how to list: a `.md` document
|
||||
//! and its `.json` record in `~/.plan2code/handoffs/`, in the shape
|
||||
//! `src/web-console/handoffs.mjs` reads (`v: 1`, the local-minute id, `usedAt`
|
||||
//! null). The console is not changed for this, so the dashboard's **Pick it up
|
||||
//! here** chip appears as it does for a handoff the Handoff skill wrote.
|
||||
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use chrono::{DateTime, Datelike, Local, SecondsFormat, Timelike, Utc};
|
||||
use serde_json::json;
|
||||
|
||||
/// `~/.plan2code/handoffs`, or `PLAN2CODE_HANDOFFS_DIR` when it is moved.
|
||||
pub fn handoffs_dir() -> Option<PathBuf> {
|
||||
if let Ok(dir) = std::env::var("PLAN2CODE_HANDOFFS_DIR") {
|
||||
return Some(PathBuf::from(dir));
|
||||
}
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("handoffs"))
|
||||
}
|
||||
|
||||
/// What the dashboard needs to resume the session the handoff came from.
|
||||
pub struct Record<'a> {
|
||||
pub title: &'a str,
|
||||
pub worktree: &'a str,
|
||||
pub project: &'a str,
|
||||
/// `specs/<name>`, or none.
|
||||
pub spec: Option<&'a str>,
|
||||
pub workflow: &'a str,
|
||||
pub skill: &'a str,
|
||||
}
|
||||
|
||||
/// Write `body` as the handoff's document and the record beside it, under an
|
||||
/// id made from `when`'s local minute. Returns the id. The record is claimed
|
||||
/// exclusively, so two writes in the same minute never share an id; a failed
|
||||
/// write leaves nothing behind.
|
||||
pub fn write(
|
||||
dir: &Path,
|
||||
when: DateTime<Local>,
|
||||
record: &Record,
|
||||
body: &str,
|
||||
) -> Result<String, String> {
|
||||
validate(record)?;
|
||||
fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
let base = format!(
|
||||
"{:04}-{:02}-{:02}-{:02}{:02}-handoff",
|
||||
when.year(),
|
||||
when.month(),
|
||||
when.day(),
|
||||
when.hour(),
|
||||
when.minute()
|
||||
);
|
||||
let written = when
|
||||
.with_timezone(&Utc)
|
||||
.to_rfc3339_opts(SecondsFormat::Millis, true);
|
||||
for n in 1.. {
|
||||
let id = if n == 1 {
|
||||
base.clone()
|
||||
} else {
|
||||
format!("{base}-{n}")
|
||||
};
|
||||
let md = dir.join(format!("{id}.md"));
|
||||
let json_file = dir.join(format!("{id}.json"));
|
||||
if md.exists() {
|
||||
continue;
|
||||
}
|
||||
let mut claim = match OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&json_file)
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e.to_string()),
|
||||
};
|
||||
let meta = json!({
|
||||
"v": 1,
|
||||
"id": id,
|
||||
"title": record.title,
|
||||
"worktree": record.worktree,
|
||||
"project": record.project,
|
||||
"spec": record.spec,
|
||||
"workflow": record.workflow,
|
||||
"skill": record.skill,
|
||||
"written": written,
|
||||
"fromStop": false,
|
||||
"usedAt": null,
|
||||
});
|
||||
let text = serde_json::to_string_pretty(&meta).map_err(|e| e.to_string())? + "\n";
|
||||
if let Err(e) = claim.write_all(text.as_bytes()) {
|
||||
let _ = fs::remove_file(&json_file);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
if let Err(e) = write_document(&md, &title_line(record.title), body) {
|
||||
let _ = fs::remove_file(&json_file);
|
||||
return Err(e);
|
||||
}
|
||||
return Ok(id);
|
||||
}
|
||||
unreachable!("the id loop only ends by returning")
|
||||
}
|
||||
|
||||
fn write_document(md: &Path, heading: &str, body: &str) -> Result<(), String> {
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(md)
|
||||
.map_err(|e| e.to_string())?;
|
||||
file.write_all(format!("{heading}\n\n{body}").as_bytes())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn title_line(title: &str) -> String {
|
||||
format!("# Handoff: {title}")
|
||||
}
|
||||
|
||||
/// Delete a handoff the person has not picked up (its record has no `usedAt`),
|
||||
/// both files. A picked-up one, or one already gone, is left alone.
|
||||
pub fn retire_if_unused(dir: &Path, id: &str) -> Result<(), String> {
|
||||
let json_file = dir.join(format!("{id}.json"));
|
||||
let Ok(text) = fs::read_to_string(&json_file) else {
|
||||
return Ok(());
|
||||
};
|
||||
let used = serde_json::from_str::<serde_json::Value>(&text)
|
||||
.ok()
|
||||
.is_some_and(|meta| !meta["usedAt"].is_null());
|
||||
if used {
|
||||
return Ok(());
|
||||
}
|
||||
for file in [json_file, dir.join(format!("{id}.md"))] {
|
||||
match fs::remove_file(&file) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The same rules the console applies to the record, so a bad field is refused
|
||||
/// here rather than written and then ignored.
|
||||
fn validate(record: &Record) -> Result<(), String> {
|
||||
let lower_dashes =
|
||||
|s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c == '-');
|
||||
if !lower_dashes(record.workflow) {
|
||||
return Err(format!(
|
||||
"workflow must be lowercase letters and dashes, got {:?}",
|
||||
record.workflow
|
||||
));
|
||||
}
|
||||
let skill_ok = !record.skill.is_empty()
|
||||
&& record
|
||||
.skill
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
|
||||
if !skill_ok {
|
||||
return Err(format!(
|
||||
"skill must be a skill name, got {:?}",
|
||||
record.skill
|
||||
));
|
||||
}
|
||||
if let Some(spec) = record.spec {
|
||||
let name = spec.strip_prefix("specs/");
|
||||
if name.is_none_or(|n| {
|
||||
n.is_empty() || n == "." || n == ".." || n.contains('/') || n.contains('\\')
|
||||
}) {
|
||||
return Err(format!("spec must be specs/<name>, got {spec:?}"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The clock's local time, for the id. Tests pass their own.
|
||||
pub fn now() -> DateTime<Local> {
|
||||
Local::now()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::TimeZone;
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-handoff-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
fn record() -> Record<'static> {
|
||||
Record {
|
||||
title: "Restart of plan2code-3-implement",
|
||||
worktree: "C:\\git\\plan2code",
|
||||
project: "C:\\git\\plan2code",
|
||||
spec: Some("specs/feature"),
|
||||
workflow: "implement",
|
||||
skill: "plan2code-3-implement",
|
||||
}
|
||||
}
|
||||
|
||||
fn at(hour: u32, minute: u32) -> DateTime<Local> {
|
||||
Local
|
||||
.with_ymd_and_hms(2026, 10, 21, hour, minute, 0)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_record_has_the_shape_the_dashboard_reads() {
|
||||
let dir = fixture("shape");
|
||||
let id = write(&dir, at(13, 52), &record(), "## Next task\n\nTask 5.2").unwrap();
|
||||
assert_eq!(id, "2026-10-21-1352-handoff");
|
||||
let meta: serde_json::Value =
|
||||
serde_json::from_str(&fs::read_to_string(dir.join(format!("{id}.json"))).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(meta["v"], 1);
|
||||
assert_eq!(meta["id"], id.as_str());
|
||||
assert_eq!(meta["workflow"], "implement");
|
||||
assert_eq!(meta["skill"], "plan2code-3-implement");
|
||||
assert_eq!(meta["spec"], "specs/feature");
|
||||
assert_eq!(meta["fromStop"], false);
|
||||
assert!(meta["usedAt"].is_null());
|
||||
assert!(meta["written"].as_str().unwrap().ends_with('Z'));
|
||||
let doc = fs::read_to_string(dir.join(format!("{id}.md"))).unwrap();
|
||||
assert!(doc.starts_with("# Handoff: Restart of plan2code-3-implement\n\n"));
|
||||
assert!(doc.contains("## Next task"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_write_in_the_same_minute_takes_the_next_id() {
|
||||
let dir = fixture("clash");
|
||||
let first = write(&dir, at(9, 0), &record(), "one").unwrap();
|
||||
let second = write(&dir, at(9, 0), &record(), "two").unwrap();
|
||||
assert_eq!(first, "2026-10-21-0900-handoff");
|
||||
assert_eq!(second, "2026-10-21-0900-handoff-2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_workflow_is_refused_before_anything_is_written() {
|
||||
let dir = fixture("bad");
|
||||
let mut bad = record();
|
||||
bad.workflow = "Implement";
|
||||
assert!(write(&dir, at(9, 0), &bad, "x").is_err());
|
||||
assert!(!dir.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unused_handoff_is_retired_and_a_picked_up_one_is_kept() {
|
||||
let dir = fixture("retire");
|
||||
let unused = write(&dir, at(10, 0), &record(), "one").unwrap();
|
||||
let used = write(&dir, at(10, 1), &record(), "two").unwrap();
|
||||
fs::write(
|
||||
dir.join(format!("{used}.json")),
|
||||
r#"{"v":1,"usedAt":"2026-10-21T10:02:00.000Z"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
retire_if_unused(&dir, &unused).unwrap();
|
||||
retire_if_unused(&dir, &used).unwrap();
|
||||
assert!(!dir.join(format!("{unused}.json")).exists());
|
||||
assert!(!dir.join(format!("{unused}.md")).exists());
|
||||
assert!(dir.join(format!("{used}.json")).exists());
|
||||
assert!(dir.join(format!("{used}.md")).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spec_must_be_one_folder_under_specs() {
|
||||
let mut bad = record();
|
||||
bad.spec = Some("specs/a/b");
|
||||
assert!(validate(&bad).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//! The parts of the app that tests reach directly.
|
||||
|
||||
pub mod agent_manager;
|
||||
pub mod agents;
|
||||
pub mod announce;
|
||||
pub mod attention;
|
||||
pub mod brief;
|
||||
pub mod console_supervisor;
|
||||
pub mod handoff;
|
||||
pub mod loop_commit;
|
||||
pub mod loop_driver;
|
||||
pub mod loop_notify;
|
||||
pub mod loop_report;
|
||||
pub mod loop_tools;
|
||||
pub mod models;
|
||||
pub mod node_check;
|
||||
pub mod project;
|
||||
pub mod pty_host;
|
||||
pub mod quit_prompt;
|
||||
pub mod restart_brief;
|
||||
pub mod session_reader;
|
||||
pub mod settings;
|
||||
#[cfg(windows)]
|
||||
pub mod task_dialog;
|
||||
pub mod versions;
|
||||
@@ -0,0 +1,866 @@
|
||||
//! The commit step of the Implementation Loop: its order, and nothing else.
|
||||
//!
|
||||
//! A passed phase goes through five calls, in this order: `prepare` (everything
|
||||
//! that can fail, before any file is touched), `stage_and_check` (stage, then
|
||||
//! refuse a secret or an oversized file), `mark` (save the files, mark the
|
||||
//! phase done, write the approval line), `commit` (stage the marked files and
|
||||
//! commit) and, when the commit fails, `undo` (put the saved text back). The
|
||||
//! driver decides what to say and where to stop; this module only does the work
|
||||
//! and names the failure.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::loop_driver::{with_approval_line, write_atomic};
|
||||
use crate::loop_report::LoopReport;
|
||||
use crate::loop_tools;
|
||||
|
||||
/// What `prepare` settled before any file was touched.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Prepared {
|
||||
pub message: String,
|
||||
pub phase_file: PathBuf,
|
||||
}
|
||||
|
||||
/// The phase file named by a row of `specs.mjs status`, as a path under
|
||||
/// `<project>/<spec>/`. Refuses a name that is missing, empty, climbs out of
|
||||
/// the folder (`..`, a separator, a drive letter) or does not exist.
|
||||
pub fn phase_file(project: &Path, spec: &str, entry: &Value) -> Result<PathBuf, String> {
|
||||
let file = entry["file"].as_str().unwrap_or("").trim();
|
||||
if file.is_empty() {
|
||||
return Err("the spec names no phase file for this phase".to_string());
|
||||
}
|
||||
let unsafe_name = file.contains("..")
|
||||
|| file.contains('/')
|
||||
|| file.contains('\\')
|
||||
|| file.contains('\0')
|
||||
|| file.chars().nth(1) == Some(':');
|
||||
if unsafe_name {
|
||||
return Err(format!(
|
||||
"the phase file name {file} is not a plain file name"
|
||||
));
|
||||
}
|
||||
let path = project.join(spec).join(file);
|
||||
if !path.is_file() {
|
||||
return Err(format!("the phase file {file} does not exist in {spec}"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Everything that can fail before a file changes: the commit message and the
|
||||
/// phase file. Nothing is written.
|
||||
pub fn prepare(
|
||||
project: &Path,
|
||||
spec: &str,
|
||||
entry: &Value,
|
||||
subject: &str,
|
||||
) -> Result<Prepared, String> {
|
||||
let phase_file = phase_file(project, spec, entry)?;
|
||||
let message = loop_tools::commit_message(project, subject)
|
||||
.map_err(|e| format!("the commit message was refused: {e}"))?;
|
||||
Ok(Prepared {
|
||||
message,
|
||||
phase_file,
|
||||
})
|
||||
}
|
||||
|
||||
/// The text of the two files `specs.mjs mark` changes, before and after the
|
||||
/// loop wrote them.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Marked {
|
||||
/// The phase file before the mark, and as the loop left it.
|
||||
pub saved: String,
|
||||
pub written: String,
|
||||
/// The same for `overview.md`, whose checkbox the mark flips.
|
||||
pub overview: PathBuf,
|
||||
pub overview_saved: String,
|
||||
pub overview_written: String,
|
||||
}
|
||||
|
||||
fn read(file: &Path) -> Result<String, String> {
|
||||
std::fs::read_to_string(file).map_err(|e| format!("{} could not be read ({e})", file.display()))
|
||||
}
|
||||
|
||||
/// Why `mark` failed, and whether the files could be put back. When they could
|
||||
/// not, the phase may be left marked done and the driver must say so.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct MarkFailure {
|
||||
pub message: String,
|
||||
pub put_back_failed: bool,
|
||||
}
|
||||
|
||||
/// Mark the phase done and write the approval line, keeping the text of both
|
||||
/// files so `undo` can take it back. On any failure both files are put back
|
||||
/// before the error is returned.
|
||||
pub fn mark(
|
||||
prepared: &Prepared,
|
||||
project: &Path,
|
||||
spec: &str,
|
||||
phase: u32,
|
||||
approval: &str,
|
||||
) -> Result<Marked, MarkFailure> {
|
||||
let plain = |message: String| MarkFailure {
|
||||
message,
|
||||
put_back_failed: false,
|
||||
};
|
||||
let overview = project.join(spec).join("overview.md");
|
||||
let saved = read(&prepared.phase_file).map_err(plain)?;
|
||||
let overview_saved = read(&overview).map_err(plain)?;
|
||||
let fail = |message: String| {
|
||||
let phase_back = write_atomic(&prepared.phase_file, &saved);
|
||||
let overview_back = write_atomic(&overview, &overview_saved);
|
||||
MarkFailure {
|
||||
put_back_failed: phase_back.is_err() || overview_back.is_err(),
|
||||
message,
|
||||
}
|
||||
};
|
||||
let run = loop_tools::specs_mark_done(project, spec, phase);
|
||||
if !run.ok {
|
||||
return Err(fail(run.output.trim().to_string()));
|
||||
}
|
||||
let written = read(&prepared.phase_file)
|
||||
.map(|text| with_approval_line(&text, approval))
|
||||
.and_then(|text| {
|
||||
write_atomic(&prepared.phase_file, &text)
|
||||
.map(|()| text)
|
||||
.map_err(|e| format!("the approval line could not be written ({e})"))
|
||||
})
|
||||
.map_err(&fail)?;
|
||||
let overview_written = read(&overview).map_err(&fail)?;
|
||||
Ok(Marked {
|
||||
saved,
|
||||
written,
|
||||
overview,
|
||||
overview_saved,
|
||||
overview_written,
|
||||
})
|
||||
}
|
||||
|
||||
/// Take the mark back: both files get their saved text again, but only while
|
||||
/// both still hold what the loop wrote, so an edit the person made in between
|
||||
/// is never overwritten. Nothing is written unless both can be restored, so the
|
||||
/// mark is either fully off or fully on; the error names each file that could
|
||||
/// not be.
|
||||
pub fn undo(prepared: &Prepared, marked: &Marked) -> Result<(), String> {
|
||||
let files = [
|
||||
(&prepared.phase_file, &marked.saved, &marked.written),
|
||||
(
|
||||
&marked.overview,
|
||||
&marked.overview_saved,
|
||||
&marked.overview_written,
|
||||
),
|
||||
];
|
||||
let name = |file: &Path| {
|
||||
file.file_name()
|
||||
.map_or_else(String::new, |n| n.to_string_lossy().into_owned())
|
||||
};
|
||||
let changed: Vec<String> = files
|
||||
.iter()
|
||||
.filter(|(file, _, written)| std::fs::read_to_string(file).ok().as_ref() != Some(*written))
|
||||
.map(|(file, _, _)| name(file))
|
||||
.collect();
|
||||
if !changed.is_empty() {
|
||||
return Err(format!(
|
||||
"{} changed since the loop wrote it, so it was not restored",
|
||||
changed.join(" and ")
|
||||
));
|
||||
}
|
||||
for (file, saved, _) in files {
|
||||
write_atomic(file, saved)
|
||||
.map_err(|e| format!("{} could not be restored ({e})", name(file)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Which call failed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Stage {
|
||||
Add,
|
||||
Commit,
|
||||
}
|
||||
|
||||
/// A failed `git add` or `git commit`, with what it printed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CommitFailure {
|
||||
pub stage: Stage,
|
||||
pub first_line: String,
|
||||
pub output: String,
|
||||
}
|
||||
|
||||
/// The first non-empty line of `output`, trimmed, at most 160 characters.
|
||||
pub fn first_line(output: &str) -> String {
|
||||
let line = output
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find(|l| !l.is_empty())
|
||||
.unwrap_or("");
|
||||
if line.chars().count() > 160 {
|
||||
let cut: String = line.chars().take(157).collect();
|
||||
format!("{cut}...")
|
||||
} else {
|
||||
line.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest file the loop will commit.
|
||||
pub const MAX_STAGED_BYTES: u64 = 5 * 1024 * 1024;
|
||||
|
||||
/// File-name suffixes of a key or certificate.
|
||||
const SECRET_SUFFIXES: [&str; 5] = [".pem", ".key", ".p12", ".pfx", ".keystore"];
|
||||
/// Names an `.env` file may carry and still be committed: a template.
|
||||
const ENV_TEMPLATES: [&str; 3] = [".example", ".sample", ".template"];
|
||||
/// Private-key files with no suffix.
|
||||
const KEY_NAMES: [&str; 2] = ["id_rsa", "id_ed25519"];
|
||||
|
||||
/// Why a staged file must not be committed, or `None`. Only the file name is
|
||||
/// read (the part after the last separator, any case), so a folder named `.env`
|
||||
/// does not match and `environment.md` or `monkey.txt` does not either.
|
||||
pub fn denied(path: &str) -> Option<&'static str> {
|
||||
let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
|
||||
let name = name.to_lowercase();
|
||||
if name == ".env"
|
||||
|| (name.starts_with(".env.") && !ENV_TEMPLATES.iter().any(|suffix| name.ends_with(suffix)))
|
||||
{
|
||||
return Some("an environment file");
|
||||
}
|
||||
if SECRET_SUFFIXES.iter().any(|suffix| name.ends_with(suffix)) {
|
||||
return Some("a key or certificate");
|
||||
}
|
||||
if KEY_NAMES.contains(&name.as_str()) {
|
||||
return Some("a private key");
|
||||
}
|
||||
if name == "credentials.json" || name.starts_with("secrets.") {
|
||||
return Some("a credentials file");
|
||||
}
|
||||
if name.ends_with(".loop-tmp") {
|
||||
return Some("a temporary file of the loop");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A staged file and its size on disk.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StagedFile {
|
||||
pub path: String,
|
||||
pub bytes: u64,
|
||||
}
|
||||
|
||||
/// Whether the file is over `MAX_STAGED_BYTES`.
|
||||
pub fn too_big(file: &StagedFile) -> bool {
|
||||
file.bytes > MAX_STAGED_BYTES
|
||||
}
|
||||
|
||||
/// Staged files the loop refuses to commit, by their names.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StagedProblem {
|
||||
pub files: Vec<String>,
|
||||
pub why: &'static str,
|
||||
/// Set when the files could not be taken out of the index again: git's
|
||||
/// first line. They are still staged.
|
||||
pub left_staged: Option<String>,
|
||||
}
|
||||
|
||||
/// Why `stage_and_check` stopped: `git add` itself failed, or the staged list
|
||||
/// holds something that must not be committed (and was unstaged again).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum StageError {
|
||||
Add(CommitFailure),
|
||||
Problem(StagedProblem),
|
||||
}
|
||||
|
||||
/// Stage everything and look at the list before anything is marked. Any
|
||||
/// secret-looking or oversized file takes everything out of the index again and
|
||||
/// returns every offending path.
|
||||
pub fn stage_and_check(project: &Path) -> Result<(), StageError> {
|
||||
let added = loop_tools::git_add_all(project);
|
||||
if !added.ok {
|
||||
return Err(StageError::Add(CommitFailure {
|
||||
stage: Stage::Add,
|
||||
first_line: first_line(&added.output),
|
||||
output: added.output,
|
||||
}));
|
||||
}
|
||||
let staged = loop_tools::git_staged(project).map_err(|output| {
|
||||
StageError::Add(CommitFailure {
|
||||
stage: Stage::Add,
|
||||
first_line: first_line(&output),
|
||||
output,
|
||||
})
|
||||
})?;
|
||||
// Staged names are relative to the repository's top folder.
|
||||
let top = loop_tools::git_toplevel(project).unwrap_or_else(|| project.to_path_buf());
|
||||
let mut secrets = false;
|
||||
let mut big = false;
|
||||
let mut files = Vec::new();
|
||||
for path in staged {
|
||||
// A deleted file is gone from the tree: it counts as 0 bytes.
|
||||
let bytes = std::fs::symlink_metadata(top.join(&path)).map_or(0, |m| m.len());
|
||||
let file = StagedFile { path, bytes };
|
||||
let is_secret = denied(&file.path).is_some();
|
||||
let is_big = too_big(&file);
|
||||
if is_secret || is_big {
|
||||
secrets |= is_secret;
|
||||
big |= is_big;
|
||||
files.push(file.path);
|
||||
}
|
||||
}
|
||||
if files.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let unstaged = loop_tools::git_unstage_all(project);
|
||||
let left_staged = (!unstaged.ok).then(|| first_line(&unstaged.output));
|
||||
let why = match (secrets, big) {
|
||||
(true, true) => "look like secrets or are over 5 MB",
|
||||
(true, false) => "look like secrets",
|
||||
_ => "are over 5 MB",
|
||||
};
|
||||
Err(StageError::Problem(StagedProblem {
|
||||
files,
|
||||
why,
|
||||
left_staged,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Commit what `stage_and_check` staged, plus the two files the mark changed
|
||||
/// since: the phase file and `overview.md`. The short hash of the new commit.
|
||||
/// `limit` is the commit's own time limit, for a slow hook.
|
||||
pub fn commit(
|
||||
project: &Path,
|
||||
prepared: &Prepared,
|
||||
marked: &Marked,
|
||||
limit: Duration,
|
||||
) -> Result<Option<String>, CommitFailure> {
|
||||
let added = loop_tools::git_add_paths(project, &[&prepared.phase_file, &marked.overview]);
|
||||
if !added.ok {
|
||||
return Err(CommitFailure {
|
||||
stage: Stage::Add,
|
||||
first_line: first_line(&added.output),
|
||||
output: added.output,
|
||||
});
|
||||
}
|
||||
let done = loop_tools::git_commit_with(project, &prepared.message, limit);
|
||||
if !done.ok {
|
||||
// A cut-off commit says so on its last line, after whatever a hook
|
||||
// printed first; lead with that.
|
||||
let cut_off = done
|
||||
.output
|
||||
.lines()
|
||||
.last()
|
||||
.filter(|line| line.starts_with("(stopped after"))
|
||||
.map(|line| {
|
||||
format!(
|
||||
"the commit was {} (a hook ran too long)",
|
||||
line.trim_matches(|c| c == '(' || c == ')')
|
||||
)
|
||||
});
|
||||
return Err(CommitFailure {
|
||||
stage: Stage::Commit,
|
||||
first_line: cut_off.unwrap_or_else(|| first_line(&done.output)),
|
||||
output: done.output,
|
||||
});
|
||||
}
|
||||
Ok(loop_tools::git_head_short(project))
|
||||
}
|
||||
|
||||
/// Take what a failed commit left staged out of the index, so a commit the
|
||||
/// person makes by hand does not carry a mark the loop took back.
|
||||
pub fn unstage(project: &Path) -> Option<String> {
|
||||
let unstaged = loop_tools::git_unstage_all(project);
|
||||
(!unstaged.ok).then(|| first_line(&unstaged.output))
|
||||
}
|
||||
|
||||
/// The phases the spec shows done (`done`) that the commit log does not hold:
|
||||
/// one the loop built whose recorded commit is gone from the history, and the
|
||||
/// phase a failed undo left marked. A phase the loop never recorded is trusted
|
||||
/// (the person built it).
|
||||
pub fn marks_without_commits(
|
||||
project: &Path,
|
||||
_spec: &str,
|
||||
done: &[u32],
|
||||
report: &LoopReport,
|
||||
) -> Vec<u32> {
|
||||
let mut missing: Vec<u32> = report
|
||||
.passed()
|
||||
.iter()
|
||||
.filter(|entry| done.contains(&entry.phase))
|
||||
.filter(|entry| {
|
||||
entry
|
||||
.commit
|
||||
.as_deref()
|
||||
.is_some_and(|hash| !loop_tools::git_commit_exists(project, hash))
|
||||
})
|
||||
.map(|entry| entry.phase)
|
||||
.collect();
|
||||
if let Some(left) = &report.marked_not_committed {
|
||||
if done.contains(&left.phase) && !missing.contains(&left.phase) {
|
||||
missing.push(left.phase);
|
||||
}
|
||||
}
|
||||
missing.sort_unstable();
|
||||
missing
|
||||
}
|
||||
|
||||
/// With commit on, the phases `status` shows done that have no commit behind
|
||||
/// them (see `marks_without_commits`). With commit off a mark is trusted.
|
||||
/// Reads only: nothing is written until the person has confirmed the Start.
|
||||
pub fn unbacked_marks(
|
||||
project: &Path,
|
||||
spec: &str,
|
||||
status: &Value,
|
||||
report: &LoopReport,
|
||||
commit: bool,
|
||||
) -> Vec<u32> {
|
||||
if !commit {
|
||||
return Vec::new();
|
||||
}
|
||||
let done: Vec<u32> = status["phases"]
|
||||
.as_array()
|
||||
.map(|all| {
|
||||
all.iter()
|
||||
.filter(|p| crate::loop_driver::checklist_done(p))
|
||||
.filter_map(|p| u32::try_from(p["number"].as_u64()?).ok())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
marks_without_commits(project, spec, &done, report)
|
||||
}
|
||||
|
||||
/// Open each of `phases` again through `specs.mjs`: `open` first, which also
|
||||
/// sets a Complete phase file back to In Progress, then `in-progress`.
|
||||
pub fn reopen(project: &Path, spec: &str, phases: &[u32]) -> Result<(), String> {
|
||||
for &n in phases {
|
||||
for to in ["open", "in-progress"] {
|
||||
let run = loop_tools::specs_mark(project, spec, n, to);
|
||||
if !run.ok {
|
||||
return Err(format!(
|
||||
"Phase {n} is marked done with no commit, and could not be opened again: {}",
|
||||
first_line(&run.output)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn temp_spec(name: &str) -> (PathBuf, PathBuf) {
|
||||
let base = std::env::temp_dir().join(format!(
|
||||
"plan2code-loop-commit-{name}-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let spec = base.join("specs/lunch");
|
||||
std::fs::create_dir_all(&spec).unwrap();
|
||||
(base, spec)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_line_skips_blanks_and_is_cut_at_160_characters() {
|
||||
assert_eq!(first_line("\n \n lint says no \nsecond"), "lint says no");
|
||||
assert_eq!(first_line(""), "");
|
||||
let long = "x".repeat(300);
|
||||
let line = first_line(&long);
|
||||
assert_eq!(line.chars().count(), 160);
|
||||
assert!(line.ends_with("..."));
|
||||
assert_eq!(first_line(&"y".repeat(160)).chars().count(), 160);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_file_must_be_a_plain_name_that_exists() {
|
||||
let (base, spec) = temp_spec("names");
|
||||
std::fs::write(spec.join("phase-2.md"), "x").unwrap();
|
||||
std::fs::write(base.join("secret.md"), "x").unwrap();
|
||||
let ok = phase_file(&base, "specs/lunch", &json!({ "file": "phase-2.md" }));
|
||||
assert_eq!(ok.unwrap(), spec.join("phase-2.md"));
|
||||
for (entry, word) in [
|
||||
(json!({}), "no phase file"),
|
||||
(json!({ "file": "" }), "no phase file"),
|
||||
(json!({ "file": " " }), "no phase file"),
|
||||
(json!({ "file": "../../secret.md" }), "plain file name"),
|
||||
(json!({ "file": "sub/phase-2.md" }), "plain file name"),
|
||||
(json!({ "file": "sub\\phase-2.md" }), "plain file name"),
|
||||
(json!({ "file": "C:phase-2.md" }), "plain file name"),
|
||||
(json!({ "file": "phase-9.md" }), "does not exist"),
|
||||
] {
|
||||
let err = phase_file(&base, "specs/lunch", &entry).unwrap_err();
|
||||
assert!(err.contains(word), "{entry}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
const OVERVIEW: &str =
|
||||
"# Lunch - Overview\n\n## Phase Checklist\n\n- [/] [Phase 2: P2](./phase-2.md)\n";
|
||||
const PHASE: &str = "# Phase 2: P2\n\n**Status:** In Progress\n\n## Tasks\n\n- [x] **Task 2.1:** First\n\n## Phase Completion Summary\n\nBuilt it.\n";
|
||||
|
||||
fn marked_spec(name: &str) -> (PathBuf, Prepared) {
|
||||
let (base, spec) = temp_spec(name);
|
||||
std::fs::write(spec.join("overview.md"), OVERVIEW).unwrap();
|
||||
std::fs::write(spec.join("phase-2.md"), PHASE).unwrap();
|
||||
let prepared = Prepared {
|
||||
message: "Add it\n\nAI Assisted".to_string(),
|
||||
phase_file: spec.join("phase-2.md"),
|
||||
};
|
||||
(base, prepared)
|
||||
}
|
||||
|
||||
fn node_ready() -> bool {
|
||||
loop_tools::skill_script("specs.mjs").is_some()
|
||||
&& std::process::Command::new("node")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.is_ok_and(|out| out.status.success())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mark_writes_the_approval_line_and_undo_puts_both_files_back() {
|
||||
if !node_ready() {
|
||||
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
|
||||
return;
|
||||
}
|
||||
let (base, prepared) = marked_spec("undo");
|
||||
let marked = mark(&prepared, &base, "specs/lunch", 2, "Approved by the loop.").unwrap();
|
||||
let overview = std::fs::read_to_string(&marked.overview).unwrap();
|
||||
assert!(overview.contains("[x] [Phase 2"), "{overview}");
|
||||
let phase = std::fs::read_to_string(&prepared.phase_file).unwrap();
|
||||
assert!(phase.contains("Approved by the loop."), "{phase}");
|
||||
assert_eq!(phase, marked.written);
|
||||
undo(&prepared, &marked).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&prepared.phase_file).unwrap(),
|
||||
PHASE
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(&marked.overview).unwrap(), OVERVIEW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_will_not_overwrite_an_edit_made_since_and_names_the_file() {
|
||||
if !node_ready() {
|
||||
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
|
||||
return;
|
||||
}
|
||||
let (base, prepared) = marked_spec("edited");
|
||||
let marked = mark(&prepared, &base, "specs/lunch", 2, "Approved.").unwrap();
|
||||
let mut edited = marked.written.clone();
|
||||
edited.push_str("\nMy own note.\n");
|
||||
std::fs::write(&prepared.phase_file, &edited).unwrap();
|
||||
let err = undo(&prepared, &marked).unwrap_err();
|
||||
assert!(err.contains("phase-2.md"), "{err}");
|
||||
assert!(!err.contains("overview.md"), "{err}");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&prepared.phase_file).unwrap(),
|
||||
edited,
|
||||
"the edit stays"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&marked.overview).unwrap(),
|
||||
marked.overview_written,
|
||||
"nothing is restored unless both files can be"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_refuses_an_unsafe_phase_file_before_anything_is_touched() {
|
||||
let (base, prepared) = marked_spec("prepare");
|
||||
for file in ["../../secret.md", "", "phase-9.md"] {
|
||||
let err =
|
||||
prepare(&base, "specs/lunch", &json!({ "file": file }), "Add it").unwrap_err();
|
||||
assert!(!err.is_empty());
|
||||
}
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&prepared.phase_file).unwrap(),
|
||||
PHASE
|
||||
);
|
||||
let overview = base.join("specs/lunch/overview.md");
|
||||
assert_eq!(std::fs::read_to_string(overview).unwrap(), OVERVIEW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_are_found_with_commit_on_and_reopened_only_when_asked() {
|
||||
if !node_ready() {
|
||||
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
|
||||
return;
|
||||
}
|
||||
let (base, prepared) = marked_spec("reopen");
|
||||
mark(&prepared, &base, "specs/lunch", 2, "Approved.").unwrap();
|
||||
let status = loop_tools::specs_status(&base, "specs/lunch").unwrap();
|
||||
assert_eq!(status["phases"][0]["marker"], "x");
|
||||
let mut report = LoopReport::new("specs/lunch", "now");
|
||||
report.marked_not_committed = Some(crate::loop_report::MarkedNotCommitted {
|
||||
phase: 2,
|
||||
file: "phase-2.md".into(),
|
||||
});
|
||||
// Commit off: a mark is trusted.
|
||||
assert!(unbacked_marks(&base, "specs/lunch", &status, &report, false).is_empty());
|
||||
// Commit on: the saved fact names the phase, and finding it writes nothing.
|
||||
let found = unbacked_marks(&base, "specs/lunch", &status, &report, true);
|
||||
assert_eq!(found, vec![2]);
|
||||
let still = loop_tools::specs_status(&base, "specs/lunch").unwrap();
|
||||
assert_eq!(still["phases"][0]["marker"], "x");
|
||||
// Reopening sets the overview and the phase file's Status back.
|
||||
reopen(&base, "specs/lunch", &found).unwrap();
|
||||
let after = loop_tools::specs_status(&base, "specs/lunch").unwrap();
|
||||
assert_eq!(after["phases"][0]["marker"], "/");
|
||||
let phase = std::fs::read_to_string(&prepared.phase_file).unwrap();
|
||||
assert!(phase.contains("**Status:** In Progress"), "{phase}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_mark_leaves_both_files_as_they_were() {
|
||||
if !node_ready() {
|
||||
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
|
||||
return;
|
||||
}
|
||||
let (base, prepared) = marked_spec("failed-mark");
|
||||
// Phase 9 is not in the overview, so the script refuses.
|
||||
let err = mark(&prepared, &base, "specs/lunch", 9, "Approved.").unwrap_err();
|
||||
assert!(!err.message.is_empty());
|
||||
assert!(!err.put_back_failed);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&prepared.phase_file).unwrap(),
|
||||
PHASE
|
||||
);
|
||||
let overview = base.join("specs/lunch/overview.md");
|
||||
assert_eq!(std::fs::read_to_string(overview).unwrap(), OVERVIEW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_that_names_a_marked_phase_is_rebuilt_only_when_the_spec_shows_it_done() {
|
||||
let (base, _) = temp_spec("marks");
|
||||
let mut report = LoopReport::new("specs/lunch", "now");
|
||||
report.marked_not_committed = Some(crate::loop_report::MarkedNotCommitted {
|
||||
phase: 3,
|
||||
file: "phase-3.md".into(),
|
||||
});
|
||||
assert_eq!(
|
||||
marks_without_commits(&base, "specs/lunch", &[1, 3], &report),
|
||||
vec![3]
|
||||
);
|
||||
assert!(marks_without_commits(&base, "specs/lunch", &[1], &report).is_empty());
|
||||
}
|
||||
|
||||
fn git_in(repo: &Path, args: &[&str]) -> String {
|
||||
let out = std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(repo)
|
||||
.output()
|
||||
.expect("run git");
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"git {args:?}: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
fn git_ready() -> bool {
|
||||
let found = std::process::Command::new("git")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.is_ok_and(|out| out.status.success());
|
||||
if !found {
|
||||
assert!(std::env::var_os("CI").is_none(), "git is not on PATH");
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secret_looking_names_are_denied_and_templates_are_not() {
|
||||
for name in [
|
||||
".env",
|
||||
".env.local",
|
||||
".env.production",
|
||||
".ENV",
|
||||
"a/b/.env",
|
||||
"server.pem",
|
||||
"tls.KEY",
|
||||
"cert.p12",
|
||||
"cert.pfx",
|
||||
"release.keystore",
|
||||
"id_rsa",
|
||||
"home/.ssh/id_ed25519",
|
||||
"credentials.json",
|
||||
"config\\credentials.json",
|
||||
"secrets.yml",
|
||||
"Secrets.json",
|
||||
"x/y.loop-tmp",
|
||||
] {
|
||||
assert!(denied(name).is_some(), "{name} should be denied");
|
||||
}
|
||||
for name in [
|
||||
".env.example",
|
||||
".env.production.example",
|
||||
".env.local.sample",
|
||||
".env.sample",
|
||||
".env.template",
|
||||
"app/.env.EXAMPLE",
|
||||
"environment.md",
|
||||
"monkey.txt",
|
||||
"keyboard.rs",
|
||||
"id_rsa.pub",
|
||||
"my-credentials.json.md",
|
||||
"secretsauce.md",
|
||||
"src/.env/readme.md",
|
||||
"tmp.loop-tmp.md",
|
||||
] {
|
||||
assert_eq!(denied(name), None, "{name} should be allowed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_is_too_big_only_over_five_megabytes() {
|
||||
let file = |bytes| StagedFile {
|
||||
path: "a.bin".into(),
|
||||
bytes,
|
||||
};
|
||||
assert!(!too_big(&file(0)));
|
||||
assert!(!too_big(&file(MAX_STAGED_BYTES)));
|
||||
assert!(too_big(&file(MAX_STAGED_BYTES + 1)));
|
||||
}
|
||||
|
||||
fn init_repo(name: &str) -> PathBuf {
|
||||
let (base, _) = temp_spec(name);
|
||||
git_in(&base, &["init", "-q"]);
|
||||
for (key, value) in [
|
||||
("user.name", "Loop Test"),
|
||||
("user.email", "loop@example.com"),
|
||||
("commit.gpgsign", "false"),
|
||||
("core.autocrlf", "false"),
|
||||
("core.hooksPath", ".git/hooks"),
|
||||
] {
|
||||
git_in(&base, &["config", key, value]);
|
||||
}
|
||||
base
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_stops_on_every_secret_and_oversized_file_and_unstages_all() {
|
||||
if !git_ready() {
|
||||
return;
|
||||
}
|
||||
let repo = init_repo("stage-problem");
|
||||
std::fs::write(repo.join("ok.txt"), "fine").unwrap();
|
||||
std::fs::write(repo.join(".env"), "KEY=1").unwrap();
|
||||
std::fs::write(repo.join(".env.example"), "KEY=").unwrap();
|
||||
std::fs::create_dir_all(repo.join("sub")).unwrap();
|
||||
std::fs::write(repo.join("sub/server.pem"), "x").unwrap();
|
||||
let big = std::fs::File::create(repo.join("big.bin")).unwrap();
|
||||
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
|
||||
// No commit yet: unstaging must work without a HEAD.
|
||||
let Err(StageError::Problem(problem)) = stage_and_check(&repo) else {
|
||||
panic!("expected a problem");
|
||||
};
|
||||
let mut files = problem.files.clone();
|
||||
files.sort();
|
||||
assert_eq!(files, vec![".env", "big.bin", "sub/server.pem"]);
|
||||
assert_eq!(problem.why, "look like secrets or are over 5 MB");
|
||||
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
|
||||
|
||||
// Once the offenders are gone, the same call stages the rest.
|
||||
std::fs::remove_file(repo.join(".env")).unwrap();
|
||||
std::fs::remove_file(repo.join("big.bin")).unwrap();
|
||||
std::fs::remove_file(repo.join("sub/server.pem")).unwrap();
|
||||
stage_and_check(&repo).expect("a clean list passes");
|
||||
let staged = git_in(&repo, &["diff", "--cached", "--name-only"]);
|
||||
assert!(staged.contains("ok.txt") && staged.contains(".env.example"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_ordinary_file_passes_and_a_big_one_alone_says_so() {
|
||||
if !git_ready() {
|
||||
return;
|
||||
}
|
||||
let repo = init_repo("stage-deleted");
|
||||
std::fs::write(repo.join("a.txt"), "a").unwrap();
|
||||
git_in(&repo, &["add", "-A"]);
|
||||
git_in(&repo, &["commit", "-q", "-m", "First"]);
|
||||
std::fs::remove_file(repo.join("a.txt")).unwrap();
|
||||
stage_and_check(&repo).expect("a deletion of an ordinary file passes");
|
||||
git_in(&repo, &["reset", "-q"]);
|
||||
let big = std::fs::File::create(repo.join("huge.dat")).unwrap();
|
||||
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
|
||||
let Err(StageError::Problem(problem)) = stage_and_check(&repo) else {
|
||||
panic!("expected a problem");
|
||||
};
|
||||
assert_eq!(problem.files, vec!["huge.dat"]);
|
||||
assert_eq!(problem.why, "are over 5 MB");
|
||||
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_stages_the_marked_files_but_leaves_an_ignored_spec_folder_alone() {
|
||||
if !git_ready() || !node_ready() {
|
||||
assert!(
|
||||
std::env::var_os("CI").is_none(),
|
||||
"git or node is not on PATH"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let repo = init_repo("commit-ignored");
|
||||
std::fs::write(repo.join(".gitignore"), "specs/\n").unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "a").unwrap();
|
||||
let spec = repo.join("specs/lunch");
|
||||
std::fs::create_dir_all(&spec).unwrap();
|
||||
std::fs::write(spec.join("overview.md"), OVERVIEW).unwrap();
|
||||
std::fs::write(spec.join("phase-2.md"), PHASE).unwrap();
|
||||
let prepared = Prepared {
|
||||
message: "Add it\n\nAI Assisted".to_string(),
|
||||
phase_file: spec.join("phase-2.md"),
|
||||
};
|
||||
stage_and_check(&repo).unwrap();
|
||||
let marked = mark(&prepared, &repo, "specs/lunch", 2, "Approved.").unwrap();
|
||||
let head = commit(&repo, &prepared, &marked, Duration::from_secs(30)).unwrap();
|
||||
assert!(head.is_some());
|
||||
let shown = git_in(&repo, &["show", "--name-only", "--format=%s", "HEAD"]);
|
||||
assert!(shown.contains("a.txt"), "{shown}");
|
||||
assert!(!shown.contains("specs/"), "{shown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recorded_commit_hash_is_checked_against_the_history() {
|
||||
if !git_ready() {
|
||||
return;
|
||||
}
|
||||
let (base, _) = temp_spec("hashes");
|
||||
git_in(&base, &["init", "-q"]);
|
||||
for (key, value) in [
|
||||
("user.name", "Loop Test"),
|
||||
("user.email", "loop@example.com"),
|
||||
("commit.gpgsign", "false"),
|
||||
] {
|
||||
git_in(&base, &["config", key, value]);
|
||||
}
|
||||
std::fs::write(base.join("a.txt"), "a").unwrap();
|
||||
git_in(&base, &["add", "-A"]);
|
||||
git_in(&base, &["commit", "-q", "-m", "First"]);
|
||||
let real = git_in(&base, &["rev-parse", "--short", "HEAD"]);
|
||||
assert!(loop_tools::git_commit_exists(&base, &real));
|
||||
assert!(!loop_tools::git_commit_exists(&base, "deadbee"));
|
||||
assert!(!loop_tools::git_commit_exists(&base, ""));
|
||||
assert!(!loop_tools::git_commit_exists(&base, "--all"));
|
||||
assert!(!loop_tools::git_commit_exists(&base, "HEAD"));
|
||||
|
||||
let entry = |phase: u32, commit: Option<&str>| crate::loop_report::ReportEntry {
|
||||
phase,
|
||||
commit: commit.map(str::to_string),
|
||||
..crate::loop_report::ReportEntry::default()
|
||||
};
|
||||
let mut report = LoopReport::new("specs/lunch", "now");
|
||||
report.entries.push(entry(2, Some(real.as_str())));
|
||||
report.entries.push(entry(3, Some("deadbee")));
|
||||
// Built with commit off: no hash, so nothing to check.
|
||||
report.entries.push(entry(4, None));
|
||||
// Never recorded by the loop (built by hand): trusted.
|
||||
let done = [1, 2, 3, 4];
|
||||
assert_eq!(
|
||||
marks_without_commits(&base, "specs/lunch", &done, &report),
|
||||
vec![3]
|
||||
);
|
||||
// A phase the spec no longer shows done is not listed.
|
||||
assert!(marks_without_commits(&base, "specs/lunch", &[2], &report).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
//! The Implementation Loop's notification to a web address the person chose,
|
||||
//! when it needs them or ends: a plain GET with the message in the query
|
||||
//! string, or a POST in the shape a chat service's webhook wants. The kind, the
|
||||
//! address and the name come from `loop-setup.json` and the app names them in
|
||||
//! its own Start confirm; the message is written by the loop. A failed call
|
||||
//! never changes what the loop does, and its reason never repeats the address,
|
||||
//! which may hold a token.
|
||||
|
||||
use reqwest::{blocking::Client, header::CONTENT_TYPE, redirect::Policy, Url};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::Duration;
|
||||
|
||||
/// How the message reaches the address. To add a service: a variant here, its
|
||||
/// body in `request_for`, its words in `describe`, and its row in the setup
|
||||
/// screen's `NOTIFY_KINDS` and `loop-setup.mjs`'s list.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum NotifyKind {
|
||||
/// A GET with the message in a query string parameter the person names.
|
||||
#[default]
|
||||
Query,
|
||||
/// A POST of a JSON object with the message in a field the person names.
|
||||
Json,
|
||||
Discord,
|
||||
Slack,
|
||||
Teams,
|
||||
GoogleChat,
|
||||
}
|
||||
|
||||
impl NotifyKind {
|
||||
/// Whether the person names the parameter or field that holds the message.
|
||||
pub fn uses_param(self) -> bool {
|
||||
matches!(self, NotifyKind::Query | NotifyKind::Json)
|
||||
}
|
||||
}
|
||||
|
||||
pub const DEFAULT_PARAM: &str = "message";
|
||||
const MAX_URL: usize = 2000;
|
||||
const MAX_PARAM: usize = 64;
|
||||
const CALL_LIMIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Whether `url` is an http or https address the app may call: printable ASCII
|
||||
/// (anything else percent-encoded), a host, and no user name or password.
|
||||
pub fn valid_url(url: &str) -> bool {
|
||||
if url.len() > MAX_URL || !url.chars().all(|c| ('!'..='~').contains(&c)) {
|
||||
return false;
|
||||
}
|
||||
let lower = url.to_ascii_lowercase();
|
||||
let Some(rest) = lower
|
||||
.strip_prefix("http://")
|
||||
.or_else(|| lower.strip_prefix("https://"))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
|
||||
!authority.is_empty()
|
||||
&& !authority.contains('@')
|
||||
&& Url::parse(url).is_ok_and(|u| u.host_str().is_some())
|
||||
}
|
||||
|
||||
/// Whether `name` can stand as a query parameter's name without being encoded.
|
||||
pub fn valid_param(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name.len() <= MAX_PARAM
|
||||
&& name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '~'))
|
||||
}
|
||||
|
||||
fn encode(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for byte in text.bytes() {
|
||||
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
|
||||
out.push(char::from(byte));
|
||||
} else {
|
||||
out.push_str(&format!("%{byte:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `url` with `param=message` in its query. The address's other parameters and
|
||||
/// fragment stay; a parameter of the same name is replaced.
|
||||
pub fn target_url(url: &str, param: &str, message: &str) -> String {
|
||||
let (rest, fragment) = match url.split_once('#') {
|
||||
Some((rest, fragment)) => (rest, Some(fragment)),
|
||||
None => (url, None),
|
||||
};
|
||||
let (base, query) = rest.split_once('?').unwrap_or((rest, ""));
|
||||
let mut pairs: Vec<String> = query
|
||||
.split('&')
|
||||
.filter(|pair| !pair.is_empty() && pair.split('=').next() != Some(param))
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
pairs.push(format!("{param}={}", encode(message)));
|
||||
let mut out = format!("{base}?{}", pairs.join("&"));
|
||||
if let Some(fragment) = fragment {
|
||||
out.push('#');
|
||||
out.push_str(fragment);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the setup's notification fields can be used, for an address that is set.
|
||||
pub fn valid_setup(kind: NotifyKind, url: &str, param: &str) -> bool {
|
||||
valid_url(url) && (!kind.uses_param() || valid_param(param))
|
||||
}
|
||||
|
||||
/// Slack treats these three as its own markup in message text.
|
||||
fn slack_escaped(text: &str) -> String {
|
||||
text.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
}
|
||||
|
||||
/// The address to call and, for a POST, the JSON body.
|
||||
pub fn request_for(
|
||||
kind: NotifyKind,
|
||||
url: &str,
|
||||
param: &str,
|
||||
message: &str,
|
||||
) -> (String, Option<Value>) {
|
||||
let body = match kind {
|
||||
NotifyKind::Query => return (target_url(url, param, message), None),
|
||||
NotifyKind::Json => json!({ param: message }),
|
||||
// No mentions, whatever a spec is called: this must never ping a channel.
|
||||
NotifyKind::Discord => json!({ "content": message, "allowed_mentions": { "parse": [] } }),
|
||||
NotifyKind::Slack => json!({ "text": slack_escaped(message) }),
|
||||
NotifyKind::GoogleChat => json!({ "text": message }),
|
||||
// A Teams workflow's "when a webhook request is received" trigger.
|
||||
NotifyKind::Teams => json!({
|
||||
"type": "message",
|
||||
"attachments": [{
|
||||
"contentType": "application/vnd.microsoft.card.adaptive",
|
||||
"contentUrl": null,
|
||||
"content": {
|
||||
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
|
||||
"type": "AdaptiveCard",
|
||||
"version": "1.4",
|
||||
"body": [{ "type": "TextBlock", "text": message, "wrap": true }],
|
||||
},
|
||||
}],
|
||||
}),
|
||||
};
|
||||
(url.to_string(), Some(body))
|
||||
}
|
||||
|
||||
/// The Start confirm's words for what the app will do.
|
||||
pub fn describe(kind: NotifyKind, url: &str, param: &str) -> String {
|
||||
match kind {
|
||||
NotifyKind::Query => format!("the app calls: {url} with a message in {param}"),
|
||||
NotifyKind::Json => format!("the app posts to: {url} with a message in {param}"),
|
||||
NotifyKind::Discord => format!("the app posts to Discord at: {url}"),
|
||||
NotifyKind::Slack => format!("the app posts to Slack at: {url}"),
|
||||
NotifyKind::Teams => format!("the app posts to Microsoft Teams at: {url}"),
|
||||
NotifyKind::GoogleChat => format!("the app posts to Google Chat at: {url}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send the message, within ten seconds. Any 2xx answer counts as sent. The
|
||||
/// error is safe to show: it never holds the address.
|
||||
pub fn send(kind: NotifyKind, url: &str, param: &str, message: &str) -> Result<(), String> {
|
||||
let client = Client::builder()
|
||||
.timeout(CALL_LIMIT)
|
||||
.redirect(Policy::limited(5))
|
||||
.build()
|
||||
.map_err(|_| "the app could not prepare the call".to_string())?;
|
||||
let (address, body) = request_for(kind, url, param, message);
|
||||
let request = match body {
|
||||
None => client.get(address),
|
||||
Some(body) => client
|
||||
.post(address)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.body(body.to_string()),
|
||||
};
|
||||
let response = request.send().map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
"it did not answer within 10 seconds".to_string()
|
||||
} else if e.is_connect() {
|
||||
"the app could not connect to it".to_string()
|
||||
} else {
|
||||
"the call failed".to_string()
|
||||
}
|
||||
})?;
|
||||
let status = response.status();
|
||||
if status.is_success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("it answered {}", status.as_u16()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::thread;
|
||||
|
||||
/// Answer one request with `status` on a local port; gives back the whole request.
|
||||
fn one_call(status: &'static str) -> (String, thread::JoinHandle<String>) {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let handle = thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut request = String::new();
|
||||
let mut buf = [0u8; 4096];
|
||||
loop {
|
||||
let n = stream.read(&mut buf).unwrap();
|
||||
request.push_str(&String::from_utf8_lossy(&buf[..n]));
|
||||
let Some((head, body)) = request.split_once("\r\n\r\n") else {
|
||||
continue;
|
||||
};
|
||||
let length = head
|
||||
.lines()
|
||||
.find_map(|l| {
|
||||
l.to_ascii_lowercase()
|
||||
.strip_prefix("content-length: ")
|
||||
.map(str::to_string)
|
||||
})
|
||||
.and_then(|l| l.parse::<usize>().ok())
|
||||
.unwrap_or(0);
|
||||
if n == 0 || body.len() >= length {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let answer =
|
||||
format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(answer.as_bytes()).unwrap();
|
||||
request
|
||||
});
|
||||
(format!("http://127.0.0.1:{port}/hook?team=a"), handle)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_http_and_https_addresses_with_a_host_are_valid() {
|
||||
for good in [
|
||||
"http://example.com",
|
||||
"https://example.com/hook?x=1#top",
|
||||
"HTTPS://EXAMPLE.COM/a%20b",
|
||||
"http://127.0.0.1:8080/",
|
||||
] {
|
||||
assert!(valid_url(good), "{good}");
|
||||
}
|
||||
for bad in [
|
||||
"",
|
||||
"example.com",
|
||||
"ftp://example.com",
|
||||
"file:///c:/x",
|
||||
"javascript:alert(1)",
|
||||
"https:/example.com",
|
||||
"https://",
|
||||
"https://?x=1",
|
||||
"https://exa mple.com",
|
||||
"https://example.com/é",
|
||||
"https://me:secret@example.com/",
|
||||
"https://example.com/\nx",
|
||||
] {
|
||||
assert!(!valid_url(bad), "{bad}");
|
||||
}
|
||||
assert!(!valid_url(&format!(
|
||||
"https://e.com/{}",
|
||||
"x".repeat(MAX_URL)
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_name_needs_no_encoding() {
|
||||
for good in ["message", "msg_1", "a-b.c~d", "M"] {
|
||||
assert!(valid_param(good), "{good}");
|
||||
}
|
||||
for bad in ["", "a b", "a=b", "a&b", "a?b", "a#b", "a%20b", "é", "[x]"] {
|
||||
assert!(!valid_param(bad), "{bad}");
|
||||
}
|
||||
assert!(!valid_param(&"x".repeat(MAX_PARAM + 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_message_lands_encoded_in_the_query_beside_what_is_there() {
|
||||
assert_eq!(
|
||||
target_url("https://e.com/hook", "message", "a b&c=d/é"),
|
||||
"https://e.com/hook?message=a%20b%26c%3Dd%2F%C3%A9"
|
||||
);
|
||||
assert_eq!(
|
||||
target_url("https://e.com/hook?t=1&x=2#top", "msg", "hi"),
|
||||
"https://e.com/hook?t=1&x=2&msg=hi#top"
|
||||
);
|
||||
assert_eq!(
|
||||
target_url("https://e.com/?msg=old&t=1", "msg", "new"),
|
||||
"https://e.com/?t=1&msg=new",
|
||||
"a parameter of the same name is replaced"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_call_is_a_get_with_the_message_in_the_query() {
|
||||
let (url, server) = one_call("200 OK");
|
||||
assert_eq!(send(NotifyKind::Query, &url, "message", "all done"), Ok(()));
|
||||
assert_eq!(
|
||||
server.join().unwrap().lines().next().unwrap(),
|
||||
"GET /hook?team=a&message=all%20done HTTP/1.1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_webhook_gets_a_post_of_json_at_the_address_as_given() {
|
||||
let (url, server) = one_call("204 No Content");
|
||||
assert_eq!(
|
||||
send(NotifyKind::Discord, &url, "ignored", "all done"),
|
||||
Ok(())
|
||||
);
|
||||
let request = server.join().unwrap();
|
||||
assert_eq!(
|
||||
request.lines().next().unwrap(),
|
||||
"POST /hook?team=a HTTP/1.1"
|
||||
);
|
||||
assert!(request
|
||||
.to_ascii_lowercase()
|
||||
.contains("content-type: application/json"));
|
||||
let (_, body) = request.split_once("\r\n\r\n").unwrap();
|
||||
let body: Value = serde_json::from_str(body).unwrap();
|
||||
assert_eq!(body["content"], "all done");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_service_gets_the_shape_it_wants() {
|
||||
let body = |kind, message| {
|
||||
request_for(kind, "https://e.com/x", "note", message)
|
||||
.1
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(body(NotifyKind::Json, "hi"), json!({ "note": "hi" }));
|
||||
assert_eq!(
|
||||
body(NotifyKind::Discord, "@everyone hi"),
|
||||
json!({ "content": "@everyone hi", "allowed_mentions": { "parse": [] } }),
|
||||
"a mention in a spec's name pings nobody"
|
||||
);
|
||||
assert_eq!(
|
||||
body(NotifyKind::Slack, "a <b> & c"),
|
||||
json!({ "text": "a <b> & c" })
|
||||
);
|
||||
assert_eq!(body(NotifyKind::GoogleChat, "hi"), json!({ "text": "hi" }));
|
||||
let teams = body(NotifyKind::Teams, "hi");
|
||||
assert_eq!(teams["type"], "message");
|
||||
let attachment = &teams["attachments"][0];
|
||||
assert_eq!(
|
||||
attachment["contentType"],
|
||||
"application/vnd.microsoft.card.adaptive"
|
||||
);
|
||||
assert_eq!(attachment["content"]["type"], "AdaptiveCard");
|
||||
assert_eq!(attachment["content"]["body"][0]["text"], "hi");
|
||||
assert_eq!(
|
||||
request_for(NotifyKind::Slack, "https://e.com/x", "n", "m").0,
|
||||
"https://e.com/x"
|
||||
);
|
||||
assert_eq!(
|
||||
request_for(NotifyKind::Query, "https://e.com/x", "n", "m"),
|
||||
("https://e.com/x?n=m".to_string(), None)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kind_reads_by_its_saved_name_and_only_some_need_a_name() {
|
||||
for (name, kind) in [
|
||||
("query", NotifyKind::Query),
|
||||
("json", NotifyKind::Json),
|
||||
("discord", NotifyKind::Discord),
|
||||
("slack", NotifyKind::Slack),
|
||||
("teams", NotifyKind::Teams),
|
||||
("google-chat", NotifyKind::GoogleChat),
|
||||
] {
|
||||
assert_eq!(
|
||||
serde_json::from_value::<NotifyKind>(json!(name)).unwrap(),
|
||||
kind
|
||||
);
|
||||
}
|
||||
assert!(valid_setup(NotifyKind::Slack, "https://e.com/", "a b"));
|
||||
assert!(!valid_setup(NotifyKind::Query, "https://e.com/", "a b"));
|
||||
assert!(!valid_setup(NotifyKind::Json, "https://e.com/", ""));
|
||||
assert!(!valid_setup(NotifyKind::Slack, "e.com", "message"));
|
||||
}
|
||||
|
||||
// Needs the internet, so only by hand: `cargo test live_https -- --ignored`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn live_https_reaches_a_real_certificate() {
|
||||
assert_eq!(
|
||||
send(NotifyKind::Query, "https://example.com/", "message", "test"),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_call_says_why_without_the_address() {
|
||||
let (url, server) = one_call("503 Service Unavailable");
|
||||
assert_eq!(
|
||||
send(NotifyKind::Query, &url, "message", "x"),
|
||||
Err("it answered 503".to_string())
|
||||
);
|
||||
server.join().unwrap();
|
||||
|
||||
// A port nothing listens on.
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
drop(listener);
|
||||
let err = send(
|
||||
NotifyKind::Slack,
|
||||
&format!("http://127.0.0.1:{port}/secret-token"),
|
||||
"message",
|
||||
"x",
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(!err.contains("secret-token"), "{err}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
//! The Implementation Loop's report: everything the loop did on the person's
|
||||
//! behalf, across stops and resumes, until every phase is built.
|
||||
//!
|
||||
//! While a build is under way the report lives in `loop-reports.json` in the
|
||||
//! console's folder, saved after every phase, retry and stop. It cannot live in
|
||||
//! the project yet: a file there would dirty the tree, and Resume needs a clean
|
||||
//! one to commit each phase. When the last phase is built it is written to
|
||||
//! `specs/<feature>/LOOP-SUMMARY-<date>.md` and its entry here goes away.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::loop_driver::{fold_key, write_atomic, Finding, Outcome};
|
||||
|
||||
pub const REPORTS_FILE: &str = "loop-reports.json";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum EntryResult {
|
||||
#[default]
|
||||
Passed,
|
||||
Stopped,
|
||||
Retried,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Assumption {
|
||||
pub task: String,
|
||||
pub note: String,
|
||||
}
|
||||
|
||||
/// One thing that happened to a phase, in the order it happened.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ReportEntry {
|
||||
pub at: String,
|
||||
pub phase: u32,
|
||||
pub name: String,
|
||||
pub result: EntryResult,
|
||||
/// Why it stopped or was retried; empty for a phase that passed.
|
||||
pub line: String,
|
||||
pub commit: Option<String>,
|
||||
pub subject: String,
|
||||
pub summary: String,
|
||||
pub tests: String,
|
||||
/// Whether the phase got as far as reporting; false for a crash or a stop mid-build.
|
||||
pub reported: bool,
|
||||
pub review_ran: bool,
|
||||
pub fixed: Vec<Finding>,
|
||||
pub skipped: Vec<Finding>,
|
||||
pub left_open: Vec<Finding>,
|
||||
pub assumed: Vec<Assumption>,
|
||||
pub blocked: Vec<String>,
|
||||
pub conflicts: Vec<String>,
|
||||
pub decisions: Vec<String>,
|
||||
/// Things the app noticed that did not stop the phase (leftover Suggestions).
|
||||
pub warnings: Vec<String>,
|
||||
pub retries: u32,
|
||||
/// What the phase ran on, with Set strength per phase on: "Thrifty",
|
||||
/// "Balanced", "Best" or "Match my session" (the word a retry stepped up
|
||||
/// to, for a retry); empty with the toggle off.
|
||||
pub strength: String,
|
||||
/// The model it ran on, with the effort folded in ("sonnet, low").
|
||||
pub model: String,
|
||||
}
|
||||
|
||||
impl ReportEntry {
|
||||
/// An entry's review, tasks and decisions, from the phase's report.
|
||||
pub fn with_outcome(mut self, outcome: &Outcome) -> ReportEntry {
|
||||
self.reported = true;
|
||||
self.subject.clone_from(&outcome.subject);
|
||||
self.summary.clone_from(&outcome.summary);
|
||||
self.tests = match &outcome.tests {
|
||||
Some(t) if !t.summary.is_empty() => t.summary.clone(),
|
||||
Some(t) if t.passed => "passed".to_string(),
|
||||
Some(t) if t.ran => "failed".to_string(),
|
||||
_ => "not reported".to_string(),
|
||||
};
|
||||
if let Some(review) = &outcome.review {
|
||||
self.review_ran = review.ran;
|
||||
self.fixed.clone_from(&review.fixed);
|
||||
self.left_open.clone_from(&review.unfixed);
|
||||
if let Some(triage) = &review.triage {
|
||||
self.skipped.clone_from(&triage.skipped);
|
||||
}
|
||||
}
|
||||
self.blocked.clone_from(&outcome.tasks.blocked);
|
||||
self.conflicts.clone_from(&outcome.conflicts);
|
||||
self.decisions.clone_from(&outcome.decisions);
|
||||
for task in &outcome.tasks.assumed {
|
||||
if !self.assumed.iter().any(|a| &a.task == task) {
|
||||
self.assumed.push(Assumption {
|
||||
task: task.clone(),
|
||||
note: String::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A phase the loop marked done whose commit failed and whose mark could not be
|
||||
/// taken back: it survives an app restart, so Resume can rebuild the phase.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct MarkedNotCommitted {
|
||||
pub phase: u32,
|
||||
pub file: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct LoopReport {
|
||||
pub spec: String,
|
||||
pub started: String,
|
||||
pub entries: Vec<ReportEntry>,
|
||||
pub marked_not_committed: Option<MarkedNotCommitted>,
|
||||
}
|
||||
|
||||
impl LoopReport {
|
||||
pub fn new(spec: &str, started: &str) -> LoopReport {
|
||||
LoopReport {
|
||||
spec: spec.to_string(),
|
||||
started: started.to_string(),
|
||||
entries: Vec::new(),
|
||||
marked_not_committed: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_marked(&mut self, phase: u32, file: &str) {
|
||||
self.marked_not_committed = Some(MarkedNotCommitted {
|
||||
phase,
|
||||
file: file.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn clear_marked(&mut self) {
|
||||
self.marked_not_committed = None;
|
||||
}
|
||||
|
||||
/// Each phase's latest pass, by phase number.
|
||||
pub fn passed(&self) -> Vec<&ReportEntry> {
|
||||
let mut seen: Vec<&ReportEntry> = Vec::new();
|
||||
for entry in self
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| e.result == EntryResult::Passed)
|
||||
{
|
||||
seen.retain(|e| e.phase != entry.phase);
|
||||
seen.push(entry);
|
||||
}
|
||||
seen.sort_by_key(|e| e.phase);
|
||||
seen
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- the store
|
||||
|
||||
fn key(project: &Path, spec: &str) -> String {
|
||||
format!("{}|{spec}", fold_key(project))
|
||||
}
|
||||
|
||||
fn read_store(home: &Path) -> Value {
|
||||
std::fs::read_to_string(home.join(REPORTS_FILE))
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
|
||||
.filter(|store| store["schema"].as_u64() == Some(1) && store["reports"].is_object())
|
||||
.unwrap_or_else(|| json!({ "schema": 1, "reports": {} }))
|
||||
}
|
||||
|
||||
/// The report under way for this spec, if a build of it has not finished.
|
||||
pub fn load(home: &Path, project: &Path, spec: &str) -> Option<LoopReport> {
|
||||
let store = read_store(home);
|
||||
serde_json::from_value(store["reports"].get(key(project, spec))?.clone()).ok()
|
||||
}
|
||||
|
||||
pub fn save(home: &Path, project: &Path, report: &LoopReport) -> Result<(), String> {
|
||||
let mut store = read_store(home);
|
||||
store["reports"][key(project, &report.spec)] = json!(report);
|
||||
write_atomic(&home.join(REPORTS_FILE), &store.to_string())
|
||||
}
|
||||
|
||||
pub fn remove(home: &Path, project: &Path, spec: &str) -> Result<(), String> {
|
||||
let mut store = read_store(home);
|
||||
let gone = store["reports"]
|
||||
.as_object_mut()
|
||||
.and_then(|all| all.remove(&key(project, spec)));
|
||||
if gone.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
write_atomic(&home.join(REPORTS_FILE), &store.to_string())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------ the phase file
|
||||
|
||||
/// The `[?]` tasks in a phase file and their `Assumed:` notes: on the task's own
|
||||
/// line or on an indented line under it.
|
||||
pub fn assumptions_in(phase_text: &str) -> Vec<Assumption> {
|
||||
let mut found: Vec<Assumption> = Vec::new();
|
||||
let mut open = false;
|
||||
for line in phase_text.lines() {
|
||||
let trimmed = line.trim_start();
|
||||
let indented = trimmed.len() < line.len();
|
||||
if let Some(rest) = trimmed.strip_prefix("- [?]") {
|
||||
found.push(Assumption {
|
||||
task: task_id(rest),
|
||||
note: note_in(rest).unwrap_or_default(),
|
||||
});
|
||||
open = true;
|
||||
} else if !indented {
|
||||
open = false;
|
||||
} else if open {
|
||||
if let (Some(last), Some(note)) = (found.last_mut(), note_in(trimmed)) {
|
||||
if last.note.is_empty() {
|
||||
last.note = note;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn note_in(text: &str) -> Option<String> {
|
||||
let (_, note) = text.split_once("Assumed:")?;
|
||||
let note = note.trim().trim_end_matches("**").trim();
|
||||
(!note.is_empty()).then(|| note.to_string())
|
||||
}
|
||||
|
||||
/// `2.4` from ` **Task 2.4:** Do it`; the line itself when it names no task.
|
||||
fn task_id(rest: &str) -> String {
|
||||
let id = rest.split_once("Task ").and_then(|(_, after)| {
|
||||
let id: String = after
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_digit() || *c == '.')
|
||||
.collect();
|
||||
(!id.is_empty()).then(|| id.trim_end_matches('.').to_string())
|
||||
});
|
||||
id.unwrap_or_else(|| rest.trim().to_string())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------- the markdown
|
||||
|
||||
fn cell(text: &str) -> String {
|
||||
text.replace('|', "\\|").replace(['\r', '\n'], " ")
|
||||
}
|
||||
|
||||
fn finding_line(f: &Finding) -> String {
|
||||
let file = if f.file.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" (`{}`)", cell(&f.file))
|
||||
};
|
||||
format!("- {}: {}{file}", f.level.word(), cell(&f.title))
|
||||
}
|
||||
|
||||
fn section(md: &mut String, title: &str, lines: &[String], none: &str) {
|
||||
md.push_str(&format!("\n**{title}**\n\n"));
|
||||
if lines.is_empty() {
|
||||
md.push_str(none);
|
||||
md.push('\n');
|
||||
} else {
|
||||
md.push_str(&lines.join("\n"));
|
||||
md.push('\n');
|
||||
}
|
||||
}
|
||||
|
||||
fn entry_markdown(md: &mut String, e: &ReportEntry) {
|
||||
let word = match e.result {
|
||||
EntryResult::Passed => "built",
|
||||
EntryResult::Stopped => "stopped",
|
||||
EntryResult::Retried => "retried",
|
||||
};
|
||||
md.push_str(&format!(
|
||||
"\n### Phase {}: {} ({word}, {})\n\n",
|
||||
e.phase,
|
||||
cell(&e.name),
|
||||
e.at
|
||||
));
|
||||
if !e.line.is_empty() {
|
||||
md.push_str(&format!("{}\n\n", cell(&e.line)));
|
||||
}
|
||||
if let Some(commit) = &e.commit {
|
||||
md.push_str(&format!("- Commit: `{commit}` {}\n", cell(&e.subject)));
|
||||
} else if e.result == EntryResult::Passed {
|
||||
md.push_str("- Commit: not committed\n");
|
||||
}
|
||||
if !e.strength.is_empty() {
|
||||
let on = if e.model.is_empty() {
|
||||
e.strength.clone()
|
||||
} else {
|
||||
format!("{} ({})", e.strength, e.model)
|
||||
};
|
||||
md.push_str(&format!("- Ran on: {}\n", cell(&on)));
|
||||
}
|
||||
if e.retries > 0 {
|
||||
md.push_str(&format!("- Retries: {}\n", e.retries));
|
||||
}
|
||||
if !e.warnings.is_empty() {
|
||||
let notes: Vec<String> = e.warnings.iter().map(|w| cell(w)).collect();
|
||||
md.push_str(&format!("- Warnings: {}\n", notes.join("; ")));
|
||||
}
|
||||
if !e.reported {
|
||||
md.push_str(
|
||||
"- The agent ended before reporting, so its review and decisions are unknown.\n",
|
||||
);
|
||||
} else {
|
||||
md.push_str(&format!("- Summary: {}\n", cell(&e.summary)));
|
||||
md.push_str(&format!("- Tests: {}\n", cell(&e.tests)));
|
||||
}
|
||||
if !e.blocked.is_empty() {
|
||||
md.push_str(&format!("- Blocked tasks: {}\n", e.blocked.join(", ")));
|
||||
}
|
||||
for conflict in &e.conflicts {
|
||||
md.push_str(&format!("- Spec conflict: {}\n", cell(conflict)));
|
||||
}
|
||||
let assumed: Vec<String> = e
|
||||
.assumed
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let note = if a.note.is_empty() {
|
||||
"(no note in the phase file)"
|
||||
} else {
|
||||
&a.note
|
||||
};
|
||||
format!("- Task {}: {}", cell(&a.task), cell(note))
|
||||
})
|
||||
.collect();
|
||||
if e.reported || !assumed.is_empty() {
|
||||
section(md, "Assumptions it made", &assumed, "None.");
|
||||
}
|
||||
if !e.reported {
|
||||
return;
|
||||
}
|
||||
let decisions: Vec<String> = e
|
||||
.decisions
|
||||
.iter()
|
||||
.map(|d| format!("- {}", cell(d)))
|
||||
.collect();
|
||||
section(
|
||||
md,
|
||||
"Other decisions it reported",
|
||||
&decisions,
|
||||
"None reported.",
|
||||
);
|
||||
if !e.review_ran {
|
||||
md.push_str("\n**Review:** did not run.\n");
|
||||
return;
|
||||
}
|
||||
let fixed: Vec<String> = e.fixed.iter().map(finding_line).collect();
|
||||
section(md, "Findings it fixed", &fixed, "None.");
|
||||
let skipped: Vec<String> = e
|
||||
.skipped
|
||||
.iter()
|
||||
.map(|f| {
|
||||
format!(
|
||||
"{}: {}",
|
||||
finding_line(f),
|
||||
cell(f.reason.as_deref().unwrap_or("(no reason given)"))
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
section(md, "Findings it chose not to fix", &skipped, "None.");
|
||||
let left: Vec<String> = e.left_open.iter().map(finding_line).collect();
|
||||
section(md, "Findings left open", &left, "None.");
|
||||
}
|
||||
|
||||
/// The report's body: the table of phases and every entry, oldest first.
|
||||
pub fn body_markdown(report: &LoopReport) -> String {
|
||||
let mut md = String::from(
|
||||
"Everything below comes from each phase's report, as its agent wrote it, except the \
|
||||
task marks, the quick check and the commits, which the app checked or made itself. \
|
||||
An agent can only report the decisions it noticed making.\n",
|
||||
);
|
||||
let passed = report.passed();
|
||||
if !passed.is_empty() {
|
||||
md.push_str(
|
||||
"\n## Phases\n\n| Phase | Commit | Subject | Fixed | Not fixed | Left open | Assumed | Other decisions | Retries |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
|
||||
);
|
||||
for e in &passed {
|
||||
md.push_str(&format!(
|
||||
"| Phase {}: {} | {} | {} | {} | {} | {} | {} | {} | {} |\n",
|
||||
e.phase,
|
||||
cell(&e.name),
|
||||
e.commit.as_deref().unwrap_or("not committed"),
|
||||
cell(&e.subject),
|
||||
e.fixed.len(),
|
||||
e.skipped.len(),
|
||||
e.left_open.len(),
|
||||
e.assumed.len(),
|
||||
e.decisions.len(),
|
||||
e.retries,
|
||||
));
|
||||
}
|
||||
}
|
||||
md.push_str("\n## What happened, in order\n");
|
||||
if report.entries.is_empty() {
|
||||
md.push_str("\nNo phase has finished or stopped yet.\n");
|
||||
}
|
||||
for entry in &report.entries {
|
||||
entry_markdown(&mut md, entry);
|
||||
}
|
||||
md
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::loop_driver::FixLevel;
|
||||
|
||||
fn finding(title: &str, reason: Option<&str>) -> Finding {
|
||||
Finding {
|
||||
level: FixLevel::Warning,
|
||||
title: title.into(),
|
||||
file: "src/y.js".into(),
|
||||
reason: reason.map(str::to_string),
|
||||
}
|
||||
}
|
||||
|
||||
fn entry(phase: u32, result: EntryResult) -> ReportEntry {
|
||||
ReportEntry {
|
||||
at: "2026-11-01 10:00".into(),
|
||||
phase,
|
||||
name: format!("P{phase}"),
|
||||
result,
|
||||
..ReportEntry::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_store_keeps_a_report_per_project_and_spec_until_it_is_removed() {
|
||||
let home = std::env::temp_dir().join(format!("plan2code-report-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let (a, b) = (Path::new("C:/one"), Path::new("C:/two"));
|
||||
assert_eq!(load(&home, a, "specs/x"), None);
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
report.entries.push(entry(1, EntryResult::Passed));
|
||||
save(&home, a, &report).unwrap();
|
||||
save(&home, b, &LoopReport::new("specs/x", "later")).unwrap();
|
||||
assert_eq!(load(&home, a, "specs/x").unwrap(), report);
|
||||
assert_eq!(load(&home, a, "specs/other"), None);
|
||||
remove(&home, a, "specs/x").unwrap();
|
||||
assert_eq!(load(&home, a, "specs/x"), None);
|
||||
assert_eq!(load(&home, b, "specs/x").unwrap().started, "later");
|
||||
remove(&home, a, "specs/x").unwrap();
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_store_reads_as_empty_and_is_replaced() {
|
||||
let home =
|
||||
std::env::temp_dir().join(format!("plan2code-report-bad-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::write(home.join(REPORTS_FILE), "not json").unwrap();
|
||||
assert_eq!(load(&home, Path::new("C:/one"), "specs/x"), None);
|
||||
let report = LoopReport::new("specs/x", "now");
|
||||
save(&home, Path::new("C:/one"), &report).unwrap();
|
||||
assert_eq!(load(&home, Path::new("C:/one"), "specs/x").unwrap(), report);
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assumptions_come_from_the_task_line_or_the_line_under_it() {
|
||||
let text = "# Phase 2\n\n- [x] **Task 2.1:** Done\n - Assumed: not this one\n- [?] **Task 2.2:** Pick a store\n - Test: through the route\n - Assumed: SQLite, since the spec names no store\n- [?] **Task 2.3:** Pick a port. Assumed: 8080\n- [?] **Task 2.4:** No note\n\n## Notes\n\nAssumed: not under a task\n";
|
||||
assert_eq!(
|
||||
assumptions_in(text),
|
||||
vec![
|
||||
Assumption {
|
||||
task: "2.2".into(),
|
||||
note: "SQLite, since the spec names no store".into()
|
||||
},
|
||||
Assumption {
|
||||
task: "2.3".into(),
|
||||
note: "8080".into()
|
||||
},
|
||||
Assumption {
|
||||
task: "2.4".into(),
|
||||
note: String::new()
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_report_lists_every_kind_of_decision_with_its_reason() {
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
let mut built = entry(2, EntryResult::Passed);
|
||||
built.reported = true;
|
||||
built.review_ran = true;
|
||||
built.commit = Some("a1b2c3d".into());
|
||||
built.subject = "Add | the driver".into();
|
||||
built.summary = "Built it".into();
|
||||
built.tests = "14 pass".into();
|
||||
built.fixed.push(finding("Null check", None));
|
||||
built
|
||||
.skipped
|
||||
.push(finding("Rename", Some("Outside this phase")));
|
||||
built.left_open.push(finding("Name the timer", None));
|
||||
built.assumed.push(Assumption {
|
||||
task: "2.2".into(),
|
||||
note: "SQLite".into(),
|
||||
});
|
||||
built.assumed.push(Assumption {
|
||||
task: "2.3".into(),
|
||||
note: String::new(),
|
||||
});
|
||||
built
|
||||
.decisions
|
||||
.push("Kept the old route for callers".into());
|
||||
built.retries = 1;
|
||||
report.entries.push(built);
|
||||
let md = body_markdown(&report);
|
||||
assert!(
|
||||
md.contains("| Phase 2: P2 | a1b2c3d | Add \\| the driver | 1 | 1 | 1 | 2 | 1 | 1 |")
|
||||
);
|
||||
assert!(md.contains("- warning: Null check (`src/y.js`)"));
|
||||
assert!(md.contains("- warning: Rename (`src/y.js`): Outside this phase"));
|
||||
assert!(md.contains("- warning: Name the timer (`src/y.js`)"));
|
||||
assert!(md.contains("- Task 2.2: SQLite"));
|
||||
assert!(md.contains("- Task 2.3: (no note in the phase file)"));
|
||||
assert!(md.contains("- Kept the old route for callers"));
|
||||
assert!(md.contains("- Tests: 14 pass"));
|
||||
assert!(md.contains("- Retries: 1"));
|
||||
assert!(!md.contains('\u{2014}'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_that_never_reported_says_so_and_keeps_what_the_file_shows() {
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
let mut stopped = entry(3, EntryResult::Stopped);
|
||||
stopped.line = "Phase 3 stopped: the agent crashed".into();
|
||||
stopped.assumed.push(Assumption {
|
||||
task: "3.1".into(),
|
||||
note: "Port 8080".into(),
|
||||
});
|
||||
report.entries.push(stopped);
|
||||
let md = body_markdown(&report);
|
||||
assert!(md.contains("Phase 3 stopped: the agent crashed"));
|
||||
assert!(md.contains("its review and decisions are unknown"));
|
||||
assert!(md.contains("- Task 3.1: Port 8080"));
|
||||
assert!(!md.contains("Findings it fixed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_pass_is_the_phases_row_and_earlier_attempts_stay_in_the_story() {
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
report.entries.push(entry(1, EntryResult::Stopped));
|
||||
let mut first = entry(1, EntryResult::Passed);
|
||||
first.subject = "first".into();
|
||||
report.entries.push(first);
|
||||
report.entries.push(entry(2, EntryResult::Passed));
|
||||
let mut again = entry(1, EntryResult::Passed);
|
||||
again.subject = "again".into();
|
||||
report.entries.push(again);
|
||||
let passed = report.passed();
|
||||
assert_eq!(passed.len(), 2);
|
||||
assert_eq!(passed[0].phase, 1);
|
||||
assert_eq!(passed[0].subject, "again");
|
||||
assert_eq!(passed[1].phase, 2);
|
||||
assert_eq!(body_markdown(&report).matches("### Phase 1").count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warnings_show_under_the_phase_and_an_old_store_loads_without_them() {
|
||||
let mut e = entry(2, EntryResult::Passed);
|
||||
e.warnings = vec!["2 Suggestions left unfixed".into(), "a | b".into()];
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
report.entries.push(e);
|
||||
let md = body_markdown(&report);
|
||||
assert!(
|
||||
md.contains("- Warnings: 2 Suggestions left unfixed; a \\| b"),
|
||||
"{md}"
|
||||
);
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
report.entries.push(entry(3, EntryResult::Passed));
|
||||
assert!(!body_markdown(&report).contains("Warnings"));
|
||||
let old: ReportEntry = serde_json::from_str(r#"{"phase":4,"name":"P4"}"#).unwrap();
|
||||
assert!(old.warnings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_line_says_what_it_ran_on_and_an_old_store_says_nothing() {
|
||||
let mut thrifty = entry(2, EntryResult::Passed);
|
||||
thrifty.strength = "Thrifty".into();
|
||||
thrifty.model = "sonnet, low".into();
|
||||
let mut matched = entry(3, EntryResult::Passed);
|
||||
matched.strength = "Match my session".into();
|
||||
matched.model = "opus".into();
|
||||
let mut bare = entry(4, EntryResult::Passed);
|
||||
bare.strength = "Best".into();
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
report.entries = vec![thrifty, matched, bare, entry(5, EntryResult::Passed)];
|
||||
let md = body_markdown(&report);
|
||||
assert!(md.contains("- Ran on: Thrifty (sonnet, low)"), "{md}");
|
||||
assert!(md.contains("- Ran on: Match my session (opus)"), "{md}");
|
||||
assert!(
|
||||
md.contains(
|
||||
"- Ran on: Best
|
||||
"
|
||||
),
|
||||
"{md}"
|
||||
);
|
||||
assert_eq!(md.matches("Ran on").count(), 3, "toggle off adds nothing");
|
||||
let old: ReportEntry = serde_json::from_str(r#"{"phase":4,"name":"P4"}"#).unwrap();
|
||||
assert!(old.strength.is_empty() && old.model.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,802 @@
|
||||
//! The commands the Implementation Loop runs on its own: the spec scripts, git,
|
||||
//! the console's `post` and the person's quick check. Each call has a time
|
||||
//! limit and keeps its output. No shell runs here except the quick check, whose
|
||||
//! text comes only from `loop-setup.json` (never from a page message).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::console_supervisor::find_console_dir;
|
||||
|
||||
/// What a finished (or stopped) call left behind.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ToolRun {
|
||||
pub ok: bool,
|
||||
pub code: Option<i32>,
|
||||
pub output: String,
|
||||
}
|
||||
|
||||
/// Output kept per call: the tail, which is where a failure says why.
|
||||
const OUTPUT_LIMIT: usize = 200 * 1024;
|
||||
|
||||
/// What a stop says when too many files are staged to check.
|
||||
pub const STAGED_TOO_LONG: &str =
|
||||
"too many changed files to check: add generated folders to .gitignore, then Resume";
|
||||
|
||||
/// Output kept for the staged-file list the commit gate checks (far above any real list).
|
||||
const STAGED_LIST_LIMIT: usize = 64 * 1024 * 1024;
|
||||
|
||||
/// The limit for node and git calls.
|
||||
pub const QUICK_LIMIT: Duration = Duration::from_secs(60);
|
||||
/// The limit for the person's quick check.
|
||||
pub const CHECK_LIMIT: Duration = Duration::from_secs(15 * 60);
|
||||
|
||||
const POLL: Duration = Duration::from_millis(25);
|
||||
|
||||
/// Appends `bytes`, dropping from the front when over `limit`.
|
||||
fn append_tail(buf: &mut Vec<u8>, bytes: &[u8], limit: usize) {
|
||||
buf.extend_from_slice(bytes);
|
||||
if buf.len() > limit {
|
||||
let excess = buf.len() - limit;
|
||||
buf.drain(..excess);
|
||||
}
|
||||
}
|
||||
|
||||
fn pump<R: Read + Send + 'static>(
|
||||
mut source: R,
|
||||
sink: Arc<Mutex<Vec<u8>>>,
|
||||
keep: Keep,
|
||||
cut: Arc<AtomicBool>,
|
||||
) -> thread::JoinHandle<()> {
|
||||
thread::spawn(move || {
|
||||
let mut chunk = [0u8; 8192];
|
||||
loop {
|
||||
match source.read(&mut chunk) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
if let Ok(mut buf) = sink.lock() {
|
||||
match keep {
|
||||
Keep::Tail(cap) => append_tail(&mut buf, &chunk[..n], cap),
|
||||
Keep::Head(cap) => {
|
||||
let room = cap.saturating_sub(buf.len()).min(n);
|
||||
buf.extend_from_slice(&chunk[..room]);
|
||||
if room < n {
|
||||
cut.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Run `cmd` to its end or `limit`, with `stdin` written when given. Stdout and
|
||||
/// stderr share one kept `output`. The child is killed when the limit passes.
|
||||
fn run_limited(cmd: Command, stdin: Option<&str>, limit: Duration) -> ToolRun {
|
||||
run_limited_with(cmd, stdin, limit, true)
|
||||
}
|
||||
|
||||
/// `run_limited`, with stderr dropped when `keep_stderr` is false: a list read
|
||||
/// from stdout must not be mixed with a warning git printed beside it.
|
||||
fn run_limited_with(
|
||||
cmd: Command,
|
||||
stdin: Option<&str>,
|
||||
limit: Duration,
|
||||
keep_stderr: bool,
|
||||
) -> ToolRun {
|
||||
run_capped(cmd, stdin, limit, keep_stderr, Keep::Tail(OUTPUT_LIMIT)).0
|
||||
}
|
||||
|
||||
/// Which part of a long output a call keeps.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Keep {
|
||||
/// The last `n` bytes, where a failure says why.
|
||||
Tail(usize),
|
||||
/// The first `n` bytes; anything after is read and dropped, and the call
|
||||
/// reports it was cut. For a list a safety check must read whole.
|
||||
Head(usize),
|
||||
}
|
||||
|
||||
/// `run_limited_with` with the part kept chosen, and whether output was dropped.
|
||||
fn run_capped(
|
||||
mut cmd: Command,
|
||||
stdin: Option<&str>,
|
||||
limit: Duration,
|
||||
keep_stderr: bool,
|
||||
keep: Keep,
|
||||
) -> (ToolRun, bool) {
|
||||
let cut = Arc::new(AtomicBool::new(false));
|
||||
cmd.env("PATH", crate::node_check::resolved_path());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
// Its own process group, so a timeout can end every descendant at once.
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
cmd.stdin(if stdin.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::null()
|
||||
})
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(if keep_stderr {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::null()
|
||||
});
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(child) => child,
|
||||
Err(e) => {
|
||||
return (
|
||||
ToolRun {
|
||||
ok: false,
|
||||
code: None,
|
||||
output: format!("could not start: {e}"),
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
};
|
||||
let sink = Arc::new(Mutex::new(Vec::new()));
|
||||
let readers = [
|
||||
child
|
||||
.stdout
|
||||
.take()
|
||||
.map(|s| pump(s, Arc::clone(&sink), keep, Arc::clone(&cut))),
|
||||
child
|
||||
.stderr
|
||||
.take()
|
||||
.map(|s| pump(s, Arc::clone(&sink), keep, Arc::clone(&cut))),
|
||||
];
|
||||
if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) {
|
||||
// A child that exits before reading closes the pipe: not an error here.
|
||||
let _ = pipe.write_all(text.as_bytes());
|
||||
}
|
||||
let pid = child.id();
|
||||
let started = Instant::now();
|
||||
let mut timed_out = false;
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break Some(status),
|
||||
Ok(None) => {
|
||||
if started.elapsed() >= limit {
|
||||
timed_out = true;
|
||||
kill_tree(pid);
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break None;
|
||||
}
|
||||
thread::sleep(POLL);
|
||||
}
|
||||
Err(_) => break None,
|
||||
}
|
||||
};
|
||||
// A descendant that outlives the child can keep the pipes open: wait a
|
||||
// short grace for the readers, then leave them behind.
|
||||
let grace = Instant::now() + Duration::from_secs(3);
|
||||
for reader in readers.into_iter().flatten() {
|
||||
while !reader.is_finished() && Instant::now() < grace {
|
||||
thread::sleep(POLL);
|
||||
}
|
||||
if reader.is_finished() {
|
||||
let _ = reader.join();
|
||||
}
|
||||
}
|
||||
let mut output = sink
|
||||
.lock()
|
||||
.map(|buf| String::from_utf8_lossy(&buf).into_owned())
|
||||
.unwrap_or_default();
|
||||
if timed_out {
|
||||
if !output.is_empty() && !output.ends_with('\n') {
|
||||
output.push('\n');
|
||||
}
|
||||
output.push_str(&format!("(stopped after {})", describe_limit(limit)));
|
||||
}
|
||||
(
|
||||
ToolRun {
|
||||
ok: status.is_some_and(|s| s.success()),
|
||||
code: status.and_then(|s| s.code()),
|
||||
output,
|
||||
},
|
||||
cut.load(Ordering::Relaxed),
|
||||
)
|
||||
}
|
||||
|
||||
/// "1 minute", "15 minutes", "2 seconds".
|
||||
fn describe_limit(limit: Duration) -> String {
|
||||
let secs = limit.as_secs();
|
||||
let (n, unit) = if secs >= 60 {
|
||||
(secs / 60, "minute")
|
||||
} else {
|
||||
(secs.max(1), "second")
|
||||
};
|
||||
format!("{n} {unit}{}", if n == 1 { "" } else { "s" })
|
||||
}
|
||||
|
||||
/// End a call's whole process tree, not just the program it started.
|
||||
fn kill_tree(pid: u32) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
let _ = Command::new("taskkill")
|
||||
.args(["/PID", &pid.to_string(), "/T", "/F"])
|
||||
.creation_flags(0x08000000)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
// The child leads its own process group (see run_limited): a negative
|
||||
// pid ends the whole group, grandchildren included.
|
||||
if let Ok(pgid) = i32::try_from(pid) {
|
||||
// SAFETY: kill(2) takes plain integers and touches no memory.
|
||||
unsafe {
|
||||
libc::kill(-pgid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn node_script(script: &Path, project: &Path, args: &[&str]) -> Command {
|
||||
let mut cmd = Command::new("node");
|
||||
cmd.arg(script).args(args).current_dir(project);
|
||||
cmd
|
||||
}
|
||||
|
||||
fn git(project: &Path, args: &[&str]) -> Command {
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.args(args).current_dir(project);
|
||||
cmd
|
||||
}
|
||||
|
||||
/// A skill script (`specs.mjs`, `commit-msg.mjs`): beside the console's skill
|
||||
/// first (`<console dir>/../../scripts/`), then the Implement skills' own.
|
||||
pub fn skill_script(name: &str) -> Option<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
// Tests run the repository's own scripts, so they need no installed skill
|
||||
// (CI has none) and cannot drift from the source.
|
||||
#[cfg(test)]
|
||||
candidates.push(
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../src/skill-scripts")
|
||||
.join(name),
|
||||
);
|
||||
if let Ok(console) = find_console_dir() {
|
||||
if let Some(skill) = console.parent().and_then(Path::parent) {
|
||||
candidates.push(skill.join("scripts").join(name));
|
||||
}
|
||||
}
|
||||
if let Some(home) = std::env::home_dir() {
|
||||
let skills = home.join(".agents").join("skills");
|
||||
for skill in ["plan2code-3-implement", "plan2code-3-implement-review"] {
|
||||
candidates.push(skills.join(skill).join("scripts").join(name));
|
||||
}
|
||||
}
|
||||
candidates.into_iter().find(|path| path.is_file())
|
||||
}
|
||||
|
||||
fn script_or_err(name: &str) -> Result<PathBuf, String> {
|
||||
skill_script(name).ok_or_else(|| format!("the Plan2Code skill script {name} is not installed"))
|
||||
}
|
||||
|
||||
/// `specs.mjs status <spec>`, parsed.
|
||||
pub fn specs_status(project: &Path, spec: &str) -> Result<serde_json::Value, String> {
|
||||
let script = script_or_err("specs.mjs")?;
|
||||
let run = run_limited(
|
||||
node_script(&script, project, &["status", spec]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
);
|
||||
parse_json_object(&run)
|
||||
}
|
||||
|
||||
/// `specs.mjs mark <spec> --phase N --to done`.
|
||||
pub fn specs_mark_done(project: &Path, spec: &str, phase: u32) -> ToolRun {
|
||||
specs_mark(project, spec, phase, "done")
|
||||
}
|
||||
|
||||
/// `specs.mjs mark <spec> --phase N --to <to>` (`in-progress` reopens a phase).
|
||||
pub fn specs_mark(project: &Path, spec: &str, phase: u32, to: &str) -> ToolRun {
|
||||
let script = match script_or_err("specs.mjs") {
|
||||
Ok(script) => script,
|
||||
Err(output) => {
|
||||
return ToolRun {
|
||||
ok: false,
|
||||
code: None,
|
||||
output,
|
||||
}
|
||||
}
|
||||
};
|
||||
let phase = phase.to_string();
|
||||
run_limited(
|
||||
node_script(
|
||||
&script,
|
||||
project,
|
||||
&["mark", spec, "--phase", &phase, "--to", to],
|
||||
),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
)
|
||||
}
|
||||
|
||||
/// `commit-msg.mjs --subject <subject> --add-all`: the checked message. The
|
||||
/// script's own subject checks are the only ones.
|
||||
pub fn commit_message(project: &Path, subject: &str) -> Result<String, String> {
|
||||
let script = script_or_err("commit-msg.mjs")?;
|
||||
let run = run_limited(
|
||||
node_script(&script, project, &["--subject", subject, "--add-all"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
);
|
||||
parse_commit_msg(&run.output)
|
||||
}
|
||||
|
||||
/// What `commit-msg.mjs` printed, read without a shell: its `message` when
|
||||
/// `ok`, otherwise its error, otherwise whatever it printed.
|
||||
fn parse_commit_msg(stdout: &str) -> Result<String, String> {
|
||||
let run = ToolRun {
|
||||
ok: true,
|
||||
code: Some(0),
|
||||
output: stdout.to_string(),
|
||||
};
|
||||
let value = parse_json_object(&run).map_err(|_| stdout.trim().to_string())?;
|
||||
if value["ok"].as_bool() == Some(true) {
|
||||
if let Some(message) = value["message"].as_str() {
|
||||
return Ok(message.to_string());
|
||||
}
|
||||
}
|
||||
// `error` is a machine code; `message` is the human text.
|
||||
Err(value["message"]
|
||||
.as_str()
|
||||
.or_else(|| value["error"].as_str())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| stdout.trim().to_string()))
|
||||
}
|
||||
|
||||
pub fn git_add_all(project: &Path) -> ToolRun {
|
||||
run_limited(git(project, &["add", "-A"]), None, QUICK_LIMIT)
|
||||
}
|
||||
|
||||
/// `git commit -F -` with the message on stdin: no shell, nothing quoted.
|
||||
pub fn git_commit(project: &Path, message: &str) -> ToolRun {
|
||||
git_commit_with(project, message, QUICK_LIMIT)
|
||||
}
|
||||
|
||||
/// `git_commit` with its own time limit: a slow hook is not killed at the
|
||||
/// limit of the quick calls.
|
||||
pub fn git_commit_with(project: &Path, message: &str, limit: Duration) -> ToolRun {
|
||||
run_limited(git(project, &["commit", "-F", "-"]), Some(message), limit)
|
||||
}
|
||||
|
||||
/// `git add -- <paths>`: stage exactly these files. A path git ignores (a
|
||||
/// `specs/` folder in `.gitignore`) is left out, as `git add -A` leaves it out,
|
||||
/// not refused.
|
||||
pub fn git_add_paths(project: &Path, paths: &[&Path]) -> ToolRun {
|
||||
let wanted: Vec<&Path> = paths
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|path| {
|
||||
let mut cmd = git(project, &["check-ignore", "-q", "--"]);
|
||||
cmd.arg(path);
|
||||
!run_limited(cmd, None, QUICK_LIMIT).ok
|
||||
})
|
||||
.collect();
|
||||
if wanted.is_empty() {
|
||||
return ToolRun {
|
||||
ok: true,
|
||||
code: Some(0),
|
||||
output: String::new(),
|
||||
};
|
||||
}
|
||||
let mut cmd = git(project, &["add", "--"]);
|
||||
cmd.args(wanted);
|
||||
run_limited(cmd, None, QUICK_LIMIT)
|
||||
}
|
||||
|
||||
/// The names of the staged files, as `git diff --cached --name-only -z` prints
|
||||
/// them: NUL-separated, so no path is quoted.
|
||||
pub fn git_staged(project: &Path) -> Result<Vec<String>, String> {
|
||||
git_staged_capped(project, STAGED_LIST_LIMIT)
|
||||
}
|
||||
|
||||
/// `git_staged` with the size the list may reach. The secret and size gate
|
||||
/// reads every staged name, so a list over the cap fails closed rather than
|
||||
/// being checked in part.
|
||||
fn git_staged_capped(project: &Path, cap: usize) -> Result<Vec<String>, String> {
|
||||
let (run, cut) = run_capped(
|
||||
git(project, &["diff", "--cached", "--name-only", "-z"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
false,
|
||||
Keep::Head(cap),
|
||||
);
|
||||
if !run.ok {
|
||||
return Err(run.output.trim().to_string());
|
||||
}
|
||||
if cut {
|
||||
return Err(STAGED_TOO_LONG.to_string());
|
||||
}
|
||||
Ok(split_nul(&run.output))
|
||||
}
|
||||
|
||||
fn split_nul(text: &str) -> Vec<String> {
|
||||
text.split('\0')
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The repository's top folder: staged names are relative to it, not to
|
||||
/// `project`, which may be a subfolder.
|
||||
pub fn git_toplevel(project: &Path) -> Option<PathBuf> {
|
||||
let run = run_limited_with(
|
||||
git(project, &["rev-parse", "--show-toplevel"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
false,
|
||||
);
|
||||
let top = run.output.trim();
|
||||
(run.ok && !top.is_empty()).then(|| PathBuf::from(top))
|
||||
}
|
||||
|
||||
/// Whether `HEAD` names a commit (false in a repository with no commit yet).
|
||||
fn git_has_head(project: &Path) -> bool {
|
||||
run_limited(
|
||||
git(project, &["rev-parse", "--verify", "-q", "HEAD"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
)
|
||||
.ok
|
||||
}
|
||||
|
||||
/// Take everything out of the index again; the files keep their contents.
|
||||
pub fn git_unstage_all(project: &Path) -> ToolRun {
|
||||
if git_has_head(project) {
|
||||
run_limited(git(project, &["reset", "-q"]), None, QUICK_LIMIT)
|
||||
} else {
|
||||
// Before a first commit there is no HEAD to reset to.
|
||||
run_limited(
|
||||
git(project, &["rm", "-r", "--cached", "-q", ":/"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The branch `HEAD` is on: `Ok(None)` for a detached HEAD, an error when
|
||||
/// `project` is not a git repository.
|
||||
pub fn git_branch(project: &Path) -> Result<Option<String>, String> {
|
||||
let run = run_limited(
|
||||
git(project, &["symbolic-ref", "--short", "-q", "HEAD"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
);
|
||||
let name = run.output.trim();
|
||||
if run.ok && !name.is_empty() {
|
||||
return Ok(Some(name.to_string()));
|
||||
}
|
||||
// `symbolic-ref -q` exits 1 and prints nothing for a detached HEAD; any
|
||||
// other failure (not a repository, git missing) prints something.
|
||||
if run.code == Some(1) && name.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
Err(name.to_string())
|
||||
}
|
||||
|
||||
/// Whether `hash` names a commit in this repository.
|
||||
pub fn git_commit_exists(project: &Path, hash: &str) -> bool {
|
||||
if hash.is_empty() || !hash.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return false;
|
||||
}
|
||||
let target = format!("{hash}^{{commit}}");
|
||||
run_limited(
|
||||
git(project, &["cat-file", "-e", &target]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
)
|
||||
.ok
|
||||
}
|
||||
|
||||
pub fn git_head_short(project: &Path) -> Option<String> {
|
||||
let run = run_limited(
|
||||
git(project, &["rev-parse", "--short", "HEAD"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
);
|
||||
let hash = run.output.trim();
|
||||
(run.ok && !hash.is_empty()).then(|| hash.to_string())
|
||||
}
|
||||
|
||||
/// The full hash of `HEAD`, when there is a commit.
|
||||
pub fn git_head_full(project: &Path) -> Option<String> {
|
||||
let run = run_limited(git(project, &["rev-parse", "HEAD"]), None, QUICK_LIMIT);
|
||||
let hash = run.output.trim();
|
||||
(run.ok && !hash.is_empty()).then(|| hash.to_string())
|
||||
}
|
||||
|
||||
/// The paths `git status --porcelain=v1 -z` lists (renames name the new path).
|
||||
pub fn git_status_porcelain(project: &Path) -> Result<Vec<String>, String> {
|
||||
let run = run_limited_with(
|
||||
git(project, &["status", "--porcelain=v1", "-z"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
false,
|
||||
);
|
||||
if !run.ok {
|
||||
return Err(run.output.trim().to_string());
|
||||
}
|
||||
Ok(parse_porcelain(&run.output))
|
||||
}
|
||||
|
||||
/// Read `git status --porcelain=v1 -z`: NUL-separated records of `XY path`, no
|
||||
/// quoting. A rename or copy record is followed by one more field, the old
|
||||
/// path, which is skipped (the new path is the one listed).
|
||||
pub fn parse_porcelain(text: &str) -> Vec<String> {
|
||||
let mut paths = Vec::new();
|
||||
let mut fields = text.split('\0');
|
||||
while let Some(record) = fields.next() {
|
||||
let mut chars = record.chars();
|
||||
let (Some(x), Some(y), Some(' ')) = (chars.next(), chars.next(), chars.next()) else {
|
||||
continue;
|
||||
};
|
||||
let Some(path) = record.get(x.len_utf8() + y.len_utf8() + 1..) else {
|
||||
continue;
|
||||
};
|
||||
if path.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if matches!(x, 'R' | 'C') || matches!(y, 'R' | 'C') {
|
||||
fields.next();
|
||||
}
|
||||
paths.push(path.to_string());
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
/// `node console.mjs post --session <sid> --file -` with `patch` on stdin.
|
||||
pub fn console_post(console_dir: &Path, sid: &str, patch: &serde_json::Value) -> ToolRun {
|
||||
let mut cmd = Command::new("node");
|
||||
cmd.arg(console_dir.join("console.mjs"))
|
||||
.args(["post", "--session", sid, "--file", "-"]);
|
||||
run_limited(cmd, Some(&patch.to_string()), QUICK_LIMIT)
|
||||
}
|
||||
|
||||
/// `node console.mjs open --resume <sid> --no-open --workflow <workflow>`: the
|
||||
/// console holding a session again after it went away, without a browser.
|
||||
pub fn console_resume(console_dir: &Path, sid: &str, workflow: &str) -> ToolRun {
|
||||
let mut cmd = Command::new("node");
|
||||
cmd.arg(console_dir.join("console.mjs")).args([
|
||||
"open",
|
||||
"--resume",
|
||||
sid,
|
||||
"--no-open",
|
||||
"--workflow",
|
||||
workflow,
|
||||
]);
|
||||
run_limited(cmd, None, QUICK_LIMIT)
|
||||
}
|
||||
|
||||
/// The person's quick check through the platform shell, in `project`.
|
||||
pub fn quick_check(project: &Path, command: &str, limit: Duration) -> ToolRun {
|
||||
let mut cmd;
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd = Command::new("cmd");
|
||||
// Raw, so a quoted argument reaches cmd.exe as typed (the usual
|
||||
// argument quoting would turn each quote into a backslash-quote).
|
||||
cmd.arg("/C").raw_arg(command);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
cmd = Command::new("sh");
|
||||
cmd.args(["-c", command]);
|
||||
}
|
||||
cmd.current_dir(project);
|
||||
run_limited(cmd, None, limit)
|
||||
}
|
||||
|
||||
fn parse_json_object(run: &ToolRun) -> Result<serde_json::Value, String> {
|
||||
let text = run.output.trim();
|
||||
// Stderr shares the output: take the first line that starts the object.
|
||||
let start = text.find('{').unwrap_or(0);
|
||||
// Only the first value counts: stderr lines may trail the object.
|
||||
let first = serde_json::Deserializer::from_str(&text[start..])
|
||||
.into_iter::<serde_json::Value>()
|
||||
.next();
|
||||
match first {
|
||||
Some(Ok(value)) if value.is_object() => Ok(value),
|
||||
_ => Err(if text.is_empty() {
|
||||
"the tool printed nothing".to_string()
|
||||
} else {
|
||||
text.to_string()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_capped_run_keeps_the_part_asked_for_and_says_when_output_was_cut() {
|
||||
if Command::new("node").arg("--version").output().is_err() {
|
||||
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
|
||||
return;
|
||||
}
|
||||
fn run(keep: Keep, text: &str) -> (ToolRun, bool) {
|
||||
let mut cmd = Command::new("node");
|
||||
cmd.args(["-e", &format!("process.stdout.write('{text}')")]);
|
||||
run_capped(cmd, None, QUICK_LIMIT, false, keep)
|
||||
}
|
||||
let (tail, tail_cut) = run(Keep::Tail(4), "aaaabbbb");
|
||||
assert!(tail.ok);
|
||||
assert_eq!(tail.output, "bbbb");
|
||||
assert!(!tail_cut, "a tail keeper never reports a cut");
|
||||
let (head, head_cut) = run(Keep::Head(4), "aaaabbbb");
|
||||
assert_eq!(head.output, "aaaa");
|
||||
assert!(head_cut);
|
||||
let (whole, whole_cut) = run(Keep::Head(8), "aaaabbbb");
|
||||
assert_eq!(whole.output, "aaaabbbb");
|
||||
assert!(!whole_cut);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_staged_list_over_the_cap_is_refused_not_checked_in_part() {
|
||||
if Command::new("git").arg("--version").output().is_err() {
|
||||
assert!(std::env::var_os("CI").is_none(), "git is not on PATH");
|
||||
return;
|
||||
}
|
||||
let repo =
|
||||
std::env::temp_dir().join(format!("plan2code-staged-cap-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&repo);
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
let git_in = |args: &[&str]| {
|
||||
let status = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(&repo)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "git {args:?}");
|
||||
};
|
||||
git_in(&["init", "-q"]);
|
||||
for name in [".env", "a.txt", "b.txt"] {
|
||||
std::fs::write(repo.join(name), "x").unwrap();
|
||||
}
|
||||
git_in(&["add", "-A"]);
|
||||
// A cap below the list's size: refused, never a list missing its first names.
|
||||
assert_eq!(
|
||||
git_staged_capped(&repo, 8),
|
||||
Err(STAGED_TOO_LONG.to_string())
|
||||
);
|
||||
let all = git_staged_capped(&repo, 1024).unwrap();
|
||||
assert_eq!(all, [".env", "a.txt", "b.txt"]);
|
||||
let _ = std::fs::remove_dir_all(&repo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_commit_message_is_read_from_the_scripts_output_without_a_shell() {
|
||||
let ok = r#"{"ok":true,"subject":"Add it","message":"Add it\n\nAI Assisted"}"#;
|
||||
assert_eq!(parse_commit_msg(ok).unwrap(), "Add it\n\nAI Assisted");
|
||||
// Stderr noise before the object does not matter.
|
||||
let noisy = format!("warning: something\n{ok}\n");
|
||||
assert_eq!(parse_commit_msg(&noisy).unwrap(), "Add it\n\nAI Assisted");
|
||||
assert_eq!(
|
||||
parse_commit_msg(r#"{"ok":false,"error":"subject too long"}"#).unwrap_err(),
|
||||
"subject too long"
|
||||
);
|
||||
assert_eq!(
|
||||
parse_commit_msg(r#"{"ok":false,"message":"no subject"}"#).unwrap_err(),
|
||||
"no subject"
|
||||
);
|
||||
assert_eq!(
|
||||
parse_commit_msg("not json at all\n").unwrap_err(),
|
||||
"not json at all"
|
||||
);
|
||||
assert!(parse_commit_msg("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_as_the_script_really_prints_it_reads_as_its_message() {
|
||||
let real = "{\n \"ok\": false,\n \"error\": \"unsafe-subject\",\n \"message\": \"The subject has a double quote.\",\n \"next\": \"Rephrase.\"\n}\nerror: The subject has a double quote.\nnext: Rephrase.\n";
|
||||
assert_eq!(
|
||||
parse_commit_msg(real).unwrap_err(),
|
||||
"The subject has a double quote."
|
||||
);
|
||||
// ok without a message is still an error, never an empty commit.
|
||||
assert!(parse_commit_msg(r#"{"ok":true}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kept_output_is_the_tail() {
|
||||
let mut buf = Vec::new();
|
||||
append_tail(&mut buf, b"0123456789", 6);
|
||||
append_tail(&mut buf, b"AB", 6);
|
||||
assert_eq!(buf, b"6789AB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn porcelain_lists_paths_and_the_new_name_of_a_rename() {
|
||||
let text = " M src/a.rs\0?? new file.txt\0R new.rs\0old.rs\0A \"quoted\".txt\0";
|
||||
assert_eq!(
|
||||
parse_porcelain(text),
|
||||
vec!["src/a.rs", "new file.txt", "new.rs", "\"quoted\".txt"]
|
||||
);
|
||||
assert!(parse_porcelain("").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renames_old_path_is_never_read_as_a_record() {
|
||||
// The old path could look like a record; it is skipped by position.
|
||||
let text = "R new.rs\0 M fake.rs\0 M real.rs\0";
|
||||
assert_eq!(parse_porcelain(text), vec!["new.rs", "real.rs"]);
|
||||
// A work-tree rename (intent-to-add) carries the old path too.
|
||||
assert_eq!(parse_porcelain(" R new.rs\0 M fake.rs\0"), vec!["new.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_names_are_split_on_nul() {
|
||||
assert_eq!(
|
||||
split_nul("a b.txt\0dir/c.rs\0"),
|
||||
vec!["a b.txt", "dir/c.rs"]
|
||||
);
|
||||
assert!(split_nul("").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_that_outlives_its_limit_is_stopped_and_says_so() {
|
||||
#[cfg(windows)]
|
||||
let cmd = {
|
||||
let mut c = Command::new("ping");
|
||||
c.args(["-n", "30", "127.0.0.1"]);
|
||||
c
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let cmd = {
|
||||
let mut c = Command::new("sleep");
|
||||
c.arg("30");
|
||||
c
|
||||
};
|
||||
let run = run_limited(cmd, None, Duration::from_millis(300));
|
||||
assert!(!run.ok);
|
||||
assert!(run.output.ends_with("(stopped after 1 second)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_reaches_the_child_and_its_output_is_kept() {
|
||||
#[cfg(windows)]
|
||||
let cmd = {
|
||||
let mut c = Command::new("findstr");
|
||||
c.arg("x*");
|
||||
c
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let cmd = Command::new("cat");
|
||||
let run = run_limited(cmd, Some("hello loop\n"), Duration::from_secs(10));
|
||||
assert!(run.ok, "{}", run.output);
|
||||
assert!(run.output.contains("hello loop"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_json_object_in_mixed_output_is_parsed() {
|
||||
let run = ToolRun {
|
||||
ok: true,
|
||||
code: Some(0),
|
||||
output: "warning: noise\n{\"ok\":true,\"n\":1}\n".to_string(),
|
||||
};
|
||||
assert_eq!(parse_json_object(&run).unwrap()["n"], 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
//! The launch card's model menu for a built-in agent: the same list the
|
||||
//! `plan2code` launcher's model question offers (`listModels` in
|
||||
//! `src/launcher/plan2code.js`). The shipped `bin/models.json` (refreshed by
|
||||
//! every install, and baked in here as the fallback) comes first, then the
|
||||
//! user's own additions in `~/.plan2code/models.json` (written by User
|
||||
//! Preferences) whose ids the shipped list does not already have. Custom
|
||||
//! agents never come through here: their menu is their own `models` in
|
||||
//! agents.json.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::agents::CustomModel;
|
||||
|
||||
/// The shipped model menu, baked in beside agents.json so the launch card
|
||||
/// still offers a list when the installed `bin/models.json` cannot be read.
|
||||
const BAKED_MODELS: &str = include_str!("../../../src/launcher/models.json");
|
||||
|
||||
/// The shipped `bin/models.json`: `PLAN2CODE_MODELS_DIR/bin/models.json` when
|
||||
/// the tests relocate the models home, else the launcher's own
|
||||
/// `~/.plan2code/bin/models.json` (`PLAN2CODE_LAUNCHER_DIR` still honored).
|
||||
fn shipped_models_file() -> Option<PathBuf> {
|
||||
if let Ok(dir) = std::env::var("PLAN2CODE_MODELS_DIR") {
|
||||
return Some(PathBuf::from(dir).join("bin").join("models.json"));
|
||||
}
|
||||
crate::versions::launcher_dir().map(|dir| dir.join("models.json"))
|
||||
}
|
||||
|
||||
/// The user's `models.json`: `PLAN2CODE_MODELS_DIR/models.json` when set, else
|
||||
/// `~/.plan2code/models.json` (the same file the console's User Preferences
|
||||
/// writes, `USER_MODELS_FILE` in files.mjs).
|
||||
fn user_models_file() -> Option<PathBuf> {
|
||||
if let Ok(dir) = std::env::var("PLAN2CODE_MODELS_DIR") {
|
||||
return Some(PathBuf::from(dir).join("models.json"));
|
||||
}
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("models.json"))
|
||||
}
|
||||
|
||||
/// `[{ id, label }]` from a parsed models file for one agent; anything
|
||||
/// malformed is skipped (`modelEntries` in plan2code.js: an entry needs a
|
||||
/// non-empty string `id` and a string `label`; a blank label is no label).
|
||||
fn model_entries(file: &Value, cli_id: &str) -> Vec<CustomModel> {
|
||||
let mut models = Vec::new();
|
||||
let Some(items) = file.get(cli_id).and_then(Value::as_array) else {
|
||||
return models;
|
||||
};
|
||||
for item in items {
|
||||
let Some(id) = item.get("id").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
let id = id.trim();
|
||||
if id.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(label) = item.get("label").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
let label = label.trim();
|
||||
models.push(CustomModel {
|
||||
id: id.to_string(),
|
||||
label: (!label.is_empty()).then(|| label.to_string()),
|
||||
});
|
||||
}
|
||||
models
|
||||
}
|
||||
|
||||
/// The shipped list first, then the user's additions the shipped list does not
|
||||
/// already have (`mergeModels` in plan2code.js).
|
||||
fn merge_models(shipped: Vec<CustomModel>, user: Vec<CustomModel>) -> Vec<CustomModel> {
|
||||
let mut seen: HashSet<String> = shipped.iter().map(|m| m.id.clone()).collect();
|
||||
let mut out = shipped;
|
||||
out.extend(user.into_iter().filter(|m| seen.insert(m.id.clone())));
|
||||
out
|
||||
}
|
||||
|
||||
fn read_json(file: &Path) -> Option<Value> {
|
||||
serde_json::from_str(&std::fs::read_to_string(file).ok()?).ok()
|
||||
}
|
||||
|
||||
/// One built-in's menu from explicit file paths, so tests never touch the real
|
||||
/// home. A shipped file that is missing or will not parse falls back to the
|
||||
/// baked list; a user file the same way means no additions.
|
||||
fn models_for(
|
||||
cli_id: &str,
|
||||
shipped_file: Option<&Path>,
|
||||
user_file: Option<&Path>,
|
||||
) -> Vec<CustomModel> {
|
||||
let shipped = shipped_file
|
||||
.and_then(read_json)
|
||||
.or_else(|| serde_json::from_str(BAKED_MODELS).ok())
|
||||
.unwrap_or(Value::Null);
|
||||
let user = user_file.and_then(read_json).unwrap_or(Value::Null);
|
||||
merge_models(
|
||||
model_entries(&shipped, cli_id),
|
||||
model_entries(&user, cli_id),
|
||||
)
|
||||
}
|
||||
|
||||
/// The launch card's model menu for the built-in `cli_id` (empty when it has
|
||||
/// none, like the launcher's skipped question; `models` on a custom agent's
|
||||
/// agents.json entry covers customs).
|
||||
pub fn models_for_builtin(cli_id: &str) -> Vec<CustomModel> {
|
||||
models_for(
|
||||
cli_id,
|
||||
shipped_models_file().as_deref(),
|
||||
user_models_file().as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The loop's strength words, lightest first (`STRENGTH_ORDER` in
|
||||
/// src/web-console/strengths.mjs).
|
||||
pub const STRENGTH_ORDER: [&str; 3] = ["thrifty", "balanced", "best"];
|
||||
|
||||
/// One strength's model, and the effort when the agent takes one.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StrengthRow {
|
||||
pub model: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub effort: Option<String>,
|
||||
}
|
||||
|
||||
/// A row as the resolver keeps it, or None when it is not usable: the model
|
||||
/// must be a string in `models`; an effort survives only when the agent takes
|
||||
/// one and it is low, medium or high (`validRow` in strengths.mjs).
|
||||
fn valid_strength_row(
|
||||
row: Option<&Value>,
|
||||
models: &[String],
|
||||
has_effort: bool,
|
||||
) -> Option<StrengthRow> {
|
||||
let row = row?.as_object()?;
|
||||
let model = row.get("model")?.as_str()?;
|
||||
if !models.iter().any(|m| m == model) {
|
||||
return None;
|
||||
}
|
||||
let effort = row
|
||||
.get("effort")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|e| has_effort && matches!(*e, "low" | "medium" | "high"))
|
||||
.map(str::to_string);
|
||||
Some(StrengthRow {
|
||||
model: model.to_string(),
|
||||
effort,
|
||||
})
|
||||
}
|
||||
|
||||
/// `{ thrifty?, balanced?, best? }` for one agent from the shipped and the
|
||||
/// user's `strengths` objects (each keyed by agent id): per word the user's row
|
||||
/// if it is valid, else the shipped row if it is valid; a word with neither is
|
||||
/// left out. The twin of `resolveStrengths` in strengths.mjs, held to
|
||||
/// scripts/fixtures/strength-cases.json.
|
||||
pub fn resolve_strengths(
|
||||
shipped: &Value,
|
||||
user: &Value,
|
||||
agent: &str,
|
||||
models: &[String],
|
||||
has_effort: bool,
|
||||
) -> BTreeMap<String, StrengthRow> {
|
||||
let mut resolved = BTreeMap::new();
|
||||
for word in STRENGTH_ORDER {
|
||||
let row = valid_strength_row(
|
||||
user.get(agent).and_then(|a| a.get(word)),
|
||||
models,
|
||||
has_effort,
|
||||
)
|
||||
.or_else(|| {
|
||||
valid_strength_row(
|
||||
shipped.get(agent).and_then(|a| a.get(word)),
|
||||
models,
|
||||
has_effort,
|
||||
)
|
||||
});
|
||||
if let Some(row) = row {
|
||||
resolved.insert(word.to_string(), row);
|
||||
}
|
||||
}
|
||||
resolved
|
||||
}
|
||||
|
||||
/// The first mapped word after `word` in `STRENGTH_ORDER`, else None
|
||||
/// (`nextStrength` in strengths.mjs).
|
||||
pub fn next_strength(resolved: &BTreeMap<String, StrengthRow>, word: &str) -> Option<String> {
|
||||
let at = STRENGTH_ORDER.iter().position(|w| *w == word)?;
|
||||
STRENGTH_ORDER[at + 1..]
|
||||
.iter()
|
||||
.find(|w| resolved.contains_key(**w))
|
||||
.map(|w| w.to_string())
|
||||
}
|
||||
|
||||
/// `strengths_for` from explicit file paths, so tests never touch the real
|
||||
/// home. The shipped file falls back to the baked list, like `models_for`.
|
||||
fn strengths_from(
|
||||
agent: &str,
|
||||
models: &[String],
|
||||
has_effort: bool,
|
||||
shipped_file: Option<&Path>,
|
||||
user_file: Option<&Path>,
|
||||
) -> BTreeMap<String, StrengthRow> {
|
||||
let shipped = shipped_file
|
||||
.and_then(read_json)
|
||||
.or_else(|| serde_json::from_str(BAKED_MODELS).ok())
|
||||
.unwrap_or(Value::Null);
|
||||
let user = user_file.and_then(read_json).unwrap_or(Value::Null);
|
||||
resolve_strengths(
|
||||
shipped.get("strengths").unwrap_or(&Value::Null),
|
||||
user.get("strengths").unwrap_or(&Value::Null),
|
||||
agent,
|
||||
models,
|
||||
has_effort,
|
||||
)
|
||||
}
|
||||
|
||||
/// What each strength word maps to for the built-in `agent`, from the same
|
||||
/// shipped and user files as `models_for_builtin`. `models` is the ids of the
|
||||
/// agent's menu; a row naming a model outside it reads unmapped.
|
||||
pub fn strengths_for(
|
||||
agent: &str,
|
||||
models: &[String],
|
||||
has_effort: bool,
|
||||
) -> BTreeMap<String, StrengthRow> {
|
||||
strengths_from(
|
||||
agent,
|
||||
models,
|
||||
has_effort,
|
||||
shipped_models_file().as_deref(),
|
||||
user_models_file().as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn model(id: &str, label: Option<&str>) -> CustomModel {
|
||||
CustomModel {
|
||||
id: id.to_string(),
|
||||
label: label.map(str::to_string),
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("models-test-{}-{tag}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("bin")).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_entries_keeps_only_id_and_label_pairs() {
|
||||
let file = json!({
|
||||
"_note": "not a list",
|
||||
"claude": [
|
||||
{ "id": "sonnet", "label": "Sonnet - latest" },
|
||||
{ "id": "opus" },
|
||||
{ "id": " ", "label": "blank id" },
|
||||
{ "label": "no id" },
|
||||
"not an object",
|
||||
{ "id": "haiku", "label": " " },
|
||||
{ "id": "fable", "label": "Fable" }
|
||||
]
|
||||
});
|
||||
assert_eq!(
|
||||
model_entries(&file, "claude"),
|
||||
vec![
|
||||
model("sonnet", Some("Sonnet - latest")),
|
||||
model("haiku", None),
|
||||
model("fable", Some("Fable")),
|
||||
]
|
||||
);
|
||||
assert!(model_entries(&file, "codex").is_empty());
|
||||
assert!(model_entries(&Value::Null, "claude").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_models_appends_only_the_user_ids_the_shipped_list_lacks() {
|
||||
let shipped = vec![model("a", Some("A")), model("b", Some("B"))];
|
||||
let user = vec![
|
||||
model("b", Some("user's B")),
|
||||
model("c", Some("C")),
|
||||
model("c", Some("dupe")),
|
||||
];
|
||||
assert_eq!(
|
||||
merge_models(shipped, user),
|
||||
vec![
|
||||
model("a", Some("A")),
|
||||
model("b", Some("B")),
|
||||
model("c", Some("C"))
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_for_merges_the_shipped_and_user_files() {
|
||||
let dir = temp_dir("merge");
|
||||
std::fs::write(
|
||||
dir.join("bin").join("models.json"),
|
||||
r#"{ "claude": [{ "id": "sonnet", "label": "Sonnet" }] }"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.join("models.json"),
|
||||
r#"{ "claude": [
|
||||
{ "id": "sonnet", "label": "ignored dupe" },
|
||||
{ "id": "my-new", "label": "Mine" }
|
||||
] }"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
models_for(
|
||||
"claude",
|
||||
Some(&dir.join("bin").join("models.json")),
|
||||
Some(&dir.join("models.json"))
|
||||
),
|
||||
vec![
|
||||
model("sonnet", Some("Sonnet")),
|
||||
model("my-new", Some("Mine"))
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_for_falls_back_to_the_baked_list() {
|
||||
// No shipped file at all (or one that will not parse): the baked copy
|
||||
// of src/launcher/models.json still offers its list.
|
||||
let dir = temp_dir("baked");
|
||||
let missing = dir.join("bin").join("models.json");
|
||||
let baked = models_for("claude", Some(&missing), Some(&missing));
|
||||
assert_eq!(baked.first().map(|m| m.id.as_str()), Some("default"));
|
||||
assert!(baked.len() > 1);
|
||||
std::fs::write(&missing, "{ nope").unwrap();
|
||||
assert!(models_for("claude", Some(&missing), Some(&missing)).len() > 1);
|
||||
assert!(models_for("nonesuch", Some(&missing), Some(&missing)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_for_ignores_an_unreadable_user_file() {
|
||||
let dir = temp_dir("user");
|
||||
let shipped = dir.join("bin").join("models.json");
|
||||
let user = dir.join("models.json");
|
||||
std::fs::write(
|
||||
&shipped,
|
||||
r#"{ "claude": [{ "id": "sonnet", "label": "S" }] }"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(&user, "{ nope").unwrap();
|
||||
assert_eq!(
|
||||
models_for("claude", Some(&shipped), Some(&user)),
|
||||
vec![model("sonnet", Some("S"))]
|
||||
);
|
||||
assert_eq!(
|
||||
models_for("claude", Some(&shipped), None),
|
||||
vec![model("sonnet", Some("S"))]
|
||||
);
|
||||
}
|
||||
|
||||
/// Every case in the shared strength fixture: the same file drives
|
||||
/// scripts/test-web-console-strengths.mjs, so the console's resolver and
|
||||
/// this one stay the one rule.
|
||||
#[test]
|
||||
fn the_shared_strength_cases_all_resolve_the_same() {
|
||||
let cases: Value = serde_json::from_str(include_str!(
|
||||
"../../../scripts/fixtures/strength-cases.json"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(cases["schema"], 1);
|
||||
let list = cases["cases"].as_array().unwrap();
|
||||
assert!(list.len() >= 10);
|
||||
for case in list {
|
||||
let name = case["name"].as_str().unwrap();
|
||||
let agent = case["agent"].as_str().unwrap();
|
||||
let models: Vec<String> = case["models"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|m| m.as_str().unwrap().to_string())
|
||||
.collect();
|
||||
// The fixture holds one agent's rows; the resolver reads them by agent id.
|
||||
let wrap = |rows: &Value| json!({ agent: rows.clone() });
|
||||
let resolved = resolve_strengths(
|
||||
&wrap(&case["shipped"]),
|
||||
&wrap(&case["user"]),
|
||||
agent,
|
||||
&models,
|
||||
case["hasEffort"].as_bool().unwrap(),
|
||||
);
|
||||
let got = serde_json::to_value(&resolved).unwrap();
|
||||
assert_eq!(got, case["expect"]["resolved"], "{name}: resolved");
|
||||
for word in STRENGTH_ORDER {
|
||||
let want = case["expect"]["next"][word].as_str().map(str::to_string);
|
||||
assert_eq!(
|
||||
next_strength(&resolved, word),
|
||||
want,
|
||||
"{name}: next after {word}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_strength_of_an_unknown_word_is_none() {
|
||||
let mut resolved = BTreeMap::new();
|
||||
resolved.insert(
|
||||
"best".to_string(),
|
||||
StrengthRow {
|
||||
model: "x".to_string(),
|
||||
effort: None,
|
||||
},
|
||||
);
|
||||
assert_eq!(next_strength(&resolved, "cheap"), None);
|
||||
assert_eq!(
|
||||
next_strength(&resolved, "thrifty"),
|
||||
Some("best".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strengths_for_reads_the_shipped_and_user_files() {
|
||||
let dir = temp_dir("strengths");
|
||||
let shipped = dir.join("bin").join("models.json");
|
||||
let user = dir.join("models.json");
|
||||
std::fs::write(
|
||||
&shipped,
|
||||
r#"{ "claude": [{ "id": "sonnet", "label": "S" }, { "id": "opus", "label": "O" }],
|
||||
"strengths": { "claude": {
|
||||
"thrifty": { "model": "sonnet", "effort": "low" },
|
||||
"best": { "model": "opus", "effort": "medium" } } } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
&user,
|
||||
r#"{ "strengths": { "claude": { "best": { "model": "sonnet", "effort": "high" } } } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
let models = vec!["sonnet".to_string(), "opus".to_string()];
|
||||
let got = strengths_from("claude", &models, true, Some(&shipped), Some(&user));
|
||||
assert_eq!(got["thrifty"].model, "sonnet");
|
||||
assert_eq!(got["best"].model, "sonnet");
|
||||
assert_eq!(got["best"].effort.as_deref(), Some("high"));
|
||||
assert!(!got.contains_key("balanced"));
|
||||
// No user file: the shipped rows alone.
|
||||
let got = strengths_from("claude", &models, true, Some(&shipped), None);
|
||||
assert_eq!(got["best"].model, "opus");
|
||||
// An agent with no rows anywhere has none.
|
||||
assert!(strengths_from("codex", &models, false, Some(&shipped), Some(&user)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_baked_copy_ships_the_claude_and_devin_strengths() {
|
||||
let dir = temp_dir("baked-strengths");
|
||||
let missing = dir.join("bin").join("models.json");
|
||||
let ids = |agent: &str| -> Vec<String> {
|
||||
models_for(agent, Some(&missing), Some(&missing))
|
||||
.into_iter()
|
||||
.map(|m| m.id)
|
||||
.collect()
|
||||
};
|
||||
let claude = strengths_from(
|
||||
"claude",
|
||||
&ids("claude"),
|
||||
true,
|
||||
Some(&missing),
|
||||
Some(&missing),
|
||||
);
|
||||
assert_eq!(claude.len(), 3);
|
||||
let devin = strengths_from(
|
||||
"devin",
|
||||
&ids("devin"),
|
||||
false,
|
||||
Some(&missing),
|
||||
Some(&missing),
|
||||
);
|
||||
assert_eq!(devin.len(), 3);
|
||||
assert!(strengths_from(
|
||||
"codex",
|
||||
&ids("codex"),
|
||||
false,
|
||||
Some(&missing),
|
||||
Some(&missing)
|
||||
)
|
||||
.is_empty());
|
||||
}
|
||||
|
||||
/// A `strengths` key beside the agents' lists is never read as a model
|
||||
/// list: the menus come out as they did without it.
|
||||
#[test]
|
||||
fn a_strengths_key_leaves_the_model_menus_unchanged() {
|
||||
let dir = temp_dir("strengths-menu");
|
||||
let shipped = dir.join("bin").join("models.json");
|
||||
let user = dir.join("models.json");
|
||||
std::fs::write(
|
||||
&shipped,
|
||||
r#"{ "claude": [{ "id": "sonnet", "label": "S" }],
|
||||
"strengths": { "claude": { "best": { "model": "sonnet" } } } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
&user,
|
||||
r#"{ "claude": [{ "id": "mine", "label": "M" }],
|
||||
"strengths": { "claude": { "best": { "model": "mine" } } } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
models_for("claude", Some(&shipped), Some(&user)),
|
||||
vec![model("sonnet", Some("S")), model("mine", Some("M"))]
|
||||
);
|
||||
assert!(models_for("strengths", Some(&shipped), Some(&user)).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
//! The Node 18+ check (FR-13). The console and the skills run on Node, so the
|
||||
//! app refuses to start without it and says what to install.
|
||||
//!
|
||||
//! An app started from the Dock, Finder or a `.desktop` file, rather than a
|
||||
//! terminal, inherits a minimal PATH: none of nvm, Homebrew or Volta's
|
||||
//! directories, which a login shell's own profile adds. `resolved_path`
|
||||
//! (Task 9.9) is what every process this app spawns (the console, an update,
|
||||
//! an agent CLI) should run with, not the bare inherited one; `node_check`,
|
||||
//! `console_supervisor`, `versions` and `agents` all use it.
|
||||
|
||||
use std::process::Command;
|
||||
use std::sync::Mutex;
|
||||
|
||||
pub const MIN_NODE_MAJOR: u32 = 18;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum NodeStatus {
|
||||
Ok(String),
|
||||
TooOld(String),
|
||||
Missing,
|
||||
}
|
||||
|
||||
/// Major version from `node --version` output such as `v20.11.1`.
|
||||
pub fn parse_node_major(output: &str) -> Option<u32> {
|
||||
let text = output.trim().strip_prefix('v')?;
|
||||
text.split('.').next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// Classify the output of `node --version`.
|
||||
pub fn classify(output: &str) -> NodeStatus {
|
||||
let version = output.trim().to_string();
|
||||
match parse_node_major(output) {
|
||||
Some(major) if major >= MIN_NODE_MAJOR => NodeStatus::Ok(version),
|
||||
Some(_) => NodeStatus::TooOld(version),
|
||||
None => NodeStatus::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check_node() -> NodeStatus {
|
||||
match Command::new("node")
|
||||
.env("PATH", resolved_path())
|
||||
.arg("--version")
|
||||
.output()
|
||||
{
|
||||
Ok(out) if out.status.success() => classify(&String::from_utf8_lossy(&out.stdout)),
|
||||
_ => NodeStatus::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
/// `--node <path>` or `--node=<path>`: the launcher's own `node`, already
|
||||
/// resolved under the person's real shell. Only its directory is used here,
|
||||
/// so it joins the PATH the normal way rather than replacing every lookup.
|
||||
fn node_override_dir(args: &[String]) -> Option<String> {
|
||||
let mut i = 1; // args[0] is the program name
|
||||
while i < args.len() {
|
||||
let value = if args[i] == "--node" {
|
||||
args.get(i + 1).cloned()
|
||||
} else {
|
||||
args[i].strip_prefix("--node=").map(str::to_string)
|
||||
};
|
||||
if let Some(path) = value.filter(|v| !v.is_empty()) {
|
||||
return std::path::Path::new(&path)
|
||||
.parent()
|
||||
.map(|dir| dir.to_string_lossy().into_owned());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The login shell's own PATH: running it as a login shell sources
|
||||
/// `.zprofile`, `.bash_profile` or `.profile`, which a GUI launch never does.
|
||||
/// Windows sets PATH outside any shell's startup files, so this is unix only.
|
||||
#[cfg(unix)]
|
||||
fn login_shell_path() -> Option<String> {
|
||||
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
|
||||
let out = Command::new(&shell)
|
||||
.args(["-lc", "echo $PATH"])
|
||||
.output()
|
||||
.ok()?;
|
||||
let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
(out.status.success() && !path.is_empty()).then_some(path)
|
||||
}
|
||||
|
||||
static RESOLVED_PATH: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
/// The PATH every process this app spawns should run with: an explicit
|
||||
/// `--node`'s directory first, then (macOS and Linux) the login shell's own
|
||||
/// PATH, then this process's own PATH, each included only once. Worked out
|
||||
/// once per launch, and again only on `refresh_path`.
|
||||
pub fn resolved_path() -> String {
|
||||
let mut cached = RESOLVED_PATH.lock().unwrap_or_else(|e| e.into_inner());
|
||||
cached.get_or_insert_with(|| build_path(false)).clone()
|
||||
}
|
||||
|
||||
/// Work the PATH out again, for "Check again" after an agent CLI was
|
||||
/// installed: an installer may have added a folder (the login shell's
|
||||
/// profile on macOS and Linux, the saved user or system PATH on Windows)
|
||||
/// that this process's own PATH has never had.
|
||||
pub fn refresh_path() {
|
||||
let fresh = build_path(true);
|
||||
*RESOLVED_PATH.lock().unwrap_or_else(|e| e.into_inner()) = Some(fresh);
|
||||
}
|
||||
|
||||
fn build_path(fresh: bool) -> String {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let inherited = std::env::var("PATH").unwrap_or_default();
|
||||
let mut parts = Vec::new();
|
||||
if let Some(dir) = node_override_dir(&args) {
|
||||
parts.push(dir);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
if let Some(login) = login_shell_path() {
|
||||
parts.push(login);
|
||||
}
|
||||
// This process's PATH is whatever its parent had, which is stale when
|
||||
// that parent (a terminal, the launcher) started before an installer
|
||||
// added a folder: a custom agent was then offered only some of the time.
|
||||
// A refresh puts the saved PATH first; at start it only fills in after
|
||||
// the inherited one, so that keeps its order.
|
||||
#[cfg(windows)]
|
||||
let saved = saved_windows_path();
|
||||
#[cfg(windows)]
|
||||
if fresh {
|
||||
parts.extend(saved.clone());
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = fresh;
|
||||
if !inherited.is_empty() {
|
||||
parts.push(inherited);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if !fresh {
|
||||
parts.extend(saved);
|
||||
}
|
||||
parts.join(if cfg!(windows) { ";" } else { ":" })
|
||||
}
|
||||
|
||||
/// The system then the user PATH as saved in the registry, with `%NAME%`
|
||||
/// expanded: what a newly opened terminal would get.
|
||||
#[cfg(windows)]
|
||||
fn saved_windows_path() -> Vec<String> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
let keys = [
|
||||
r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
|
||||
r"HKCU\Environment",
|
||||
];
|
||||
keys.iter()
|
||||
.filter_map(|key| {
|
||||
let out = Command::new("reg")
|
||||
.args(["query", key, "/v", "Path"])
|
||||
.creation_flags(0x0800_0000) // CREATE_NO_WINDOW
|
||||
.output()
|
||||
.ok()?;
|
||||
let value = parse_reg_query_value(&String::from_utf8_lossy(&out.stdout))?;
|
||||
Some(expand_percent_vars(&value, |name| std::env::var(name).ok()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The value from `reg query <key> /v <name>` output: the text after the
|
||||
/// `REG_SZ` or `REG_EXPAND_SZ` column on its line.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn parse_reg_query_value(output: &str) -> Option<String> {
|
||||
output.lines().find_map(|line| {
|
||||
let (_, rest) = line
|
||||
.split_once("REG_EXPAND_SZ")
|
||||
.or_else(|| line.split_once("REG_SZ"))?;
|
||||
let value = rest.trim();
|
||||
(!value.is_empty()).then(|| value.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// The saved system and user PATH as one PATH string (Windows only): what a
|
||||
/// newly opened terminal gets, kept apart from the process PATH so the agent
|
||||
/// lookup can answer `saved-path`. "" elsewhere / when tests ask it off
|
||||
/// (PLAN2CODE_NO_SAVED_PATH, as the launcher's addSavedWindowsPath() honors).
|
||||
pub fn saved_path_value() -> String {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if std::env::var_os("PLAN2CODE_NO_SAVED_PATH").is_some_and(|v| !v.is_empty()) {
|
||||
return String::new();
|
||||
}
|
||||
saved_windows_path().join(";")
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// `%NAME%` replaced with `lookup(NAME)`; an unknown name stays as written.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
pub(crate) fn expand_percent_vars(text: &str, lookup: impl Fn(&str) -> Option<String>) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = text;
|
||||
while let Some(start) = rest.find('%') {
|
||||
out.push_str(&rest[..start]);
|
||||
let after = &rest[start + 1..];
|
||||
match after.find('%') {
|
||||
Some(end) if end > 0 => match lookup(&after[..end]) {
|
||||
Some(value) => {
|
||||
out.push_str(&value);
|
||||
rest = &after[end + 1..];
|
||||
}
|
||||
None => {
|
||||
out.push('%');
|
||||
rest = after;
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
out.push('%');
|
||||
rest = after;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// Where `node` actually resolves, with `resolved_path`: for the first-run
|
||||
/// checklist to name (Task 9.9), not for `check_node` itself to decide with.
|
||||
pub fn node_binary_path() -> Option<String> {
|
||||
let (program, arg) = if cfg!(windows) {
|
||||
("where", "node")
|
||||
} else {
|
||||
("which", "node")
|
||||
};
|
||||
let out = Command::new(program)
|
||||
.env("PATH", resolved_path())
|
||||
.arg(arg)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.lines()
|
||||
.next()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
/// The plain message shown when the check fails; `None` when Node is fine.
|
||||
pub fn problem_message(status: &NodeStatus) -> Option<String> {
|
||||
match status {
|
||||
NodeStatus::Ok(_) => None,
|
||||
NodeStatus::TooOld(v) => Some(format!(
|
||||
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and this computer has {v}.\n\nInstall the current LTS release from https://nodejs.org and start Plan2Code again."
|
||||
)),
|
||||
NodeStatus::Missing => Some(format!(
|
||||
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and it was not found.\n\nInstall the current LTS release from https://nodejs.org and start Plan2Code again."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn accepts_node_18_and_newer() {
|
||||
assert_eq!(classify("v18.0.0\n"), NodeStatus::Ok("v18.0.0".into()));
|
||||
assert_eq!(classify("v20.11.1"), NodeStatus::Ok("v20.11.1".into()));
|
||||
assert_eq!(classify("v24.12.0\r\n"), NodeStatus::Ok("v24.12.0".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_node_older_than_18() {
|
||||
assert_eq!(classify("v16.20.2"), NodeStatus::TooOld("v16.20.2".into()));
|
||||
assert_eq!(classify("v17.9.1"), NodeStatus::TooOld("v17.9.1".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn treats_garbage_as_missing() {
|
||||
assert_eq!(classify("not a version"), NodeStatus::Missing);
|
||||
assert_eq!(classify(""), NodeStatus::Missing);
|
||||
assert_eq!(classify("v"), NodeStatus::Missing);
|
||||
assert_eq!(classify("vx.1.2"), NodeStatus::Missing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_only_for_a_problem() {
|
||||
assert!(problem_message(&NodeStatus::Ok("v20.0.0".into())).is_none());
|
||||
assert!(problem_message(&NodeStatus::Missing)
|
||||
.unwrap()
|
||||
.contains("nodejs.org"));
|
||||
assert!(problem_message(&NodeStatus::TooOld("v16.0.0".into()))
|
||||
.unwrap()
|
||||
.contains("v16.0.0"));
|
||||
}
|
||||
|
||||
fn args(list: &[&str]) -> Vec<String> {
|
||||
std::iter::once("plan2code-app")
|
||||
.chain(list.iter().copied())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_node_override_names_its_directory_in_both_forms() {
|
||||
let want = if cfg!(windows) {
|
||||
"C:\\nvm\\v20"
|
||||
} else {
|
||||
"/home/x/.nvm/v20"
|
||||
};
|
||||
let bin = if cfg!(windows) {
|
||||
"C:\\nvm\\v20\\node.exe"
|
||||
} else {
|
||||
"/home/x/.nvm/v20/node"
|
||||
};
|
||||
assert_eq!(
|
||||
node_override_dir(&args(&["--node", bin])).as_deref(),
|
||||
Some(want)
|
||||
);
|
||||
assert_eq!(
|
||||
node_override_dir(&args(&[&format!("--node={bin}")])).as_deref(),
|
||||
Some(want)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_override_or_a_missing_value_is_none() {
|
||||
assert_eq!(node_override_dir(&args(&[])), None);
|
||||
assert_eq!(node_override_dir(&args(&["--node"])), None);
|
||||
assert_eq!(node_override_dir(&args(&["--node="])), None);
|
||||
assert_eq!(node_override_dir(&args(&["--agent", "claude"])), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_saved_path_out_of_reg_query_output() {
|
||||
let out = "\r\nHKEY_CURRENT_USER\\Environment\r\n Path REG_EXPAND_SZ %USERPROFILE%\\.local\\bin;C:\\Tools\r\n\r\n";
|
||||
assert_eq!(
|
||||
parse_reg_query_value(out).as_deref(),
|
||||
Some("%USERPROFILE%\\.local\\bin;C:\\Tools")
|
||||
);
|
||||
let plain = "HKEY_LOCAL_MACHINE\\x\r\n Path REG_SZ C:\\Windows\r\n";
|
||||
assert_eq!(parse_reg_query_value(plain).as_deref(), Some("C:\\Windows"));
|
||||
assert_eq!(
|
||||
parse_reg_query_value(
|
||||
"ERROR: The system was unable to find the specified registry key or value.\r\n"
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expands_known_percent_names_and_keeps_the_rest() {
|
||||
let lookup = |name: &str| (name == "USERPROFILE").then(|| "C:\\Users\\sam".to_string());
|
||||
assert_eq!(
|
||||
expand_percent_vars("%USERPROFILE%\\.local\\bin;C:\\x", lookup),
|
||||
"C:\\Users\\sam\\.local\\bin;C:\\x"
|
||||
);
|
||||
assert_eq!(
|
||||
expand_percent_vars("%NOPE%\\bin;%USERPROFILE%", lookup),
|
||||
"%NOPE%\\bin;C:\\Users\\sam"
|
||||
);
|
||||
assert_eq!(expand_percent_vars("50%", lookup), "50%");
|
||||
assert_eq!(expand_percent_vars("a%%b", lookup), "a%%b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_path_keeps_this_process_path() {
|
||||
refresh_path();
|
||||
let inherited = std::env::var("PATH").unwrap_or_default();
|
||||
assert!(resolved_path().ends_with(&inherited));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
//! Which project folder the app works on: the folder the launcher passes in,
|
||||
//! else the one the launcher remembers, else the person picks. The launcher's
|
||||
//! memory is `~/.plan2code/launcher.json` (`lastFolder`, `lastCli`), shared so
|
||||
//! the app and `plan2code` agree on both.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::agents;
|
||||
|
||||
/// Where the project folder came from, in the order it is tried.
|
||||
#[derive(Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProjectSource {
|
||||
Argument,
|
||||
Remembered,
|
||||
Picked,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ProjectDir {
|
||||
pub dir: PathBuf,
|
||||
pub source: ProjectSource,
|
||||
}
|
||||
|
||||
fn err<E: std::fmt::Display>(e: E) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
fn launcher_file() -> Option<PathBuf> {
|
||||
Some(
|
||||
std::env::home_dir()?
|
||||
.join(".plan2code")
|
||||
.join("launcher.json"),
|
||||
)
|
||||
}
|
||||
|
||||
fn read_launcher() -> serde_json::Map<String, serde_json::Value> {
|
||||
launcher_file()
|
||||
.and_then(|file| std::fs::read_to_string(file).ok())
|
||||
.and_then(|text| serde_json::from_str(&text).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The folder the launcher remembers, when it is still a directory.
|
||||
fn remembered_folder() -> Option<PathBuf> {
|
||||
let dir = PathBuf::from(read_launcher().get("lastFolder")?.as_str()?);
|
||||
dir.is_dir().then_some(dir)
|
||||
}
|
||||
|
||||
/// The id of the agent the launcher last ran (it may be a custom one). The
|
||||
/// bar's picker starts on it until the app has a choice of its own
|
||||
/// (`settings.rs`); a caller ignores an id that no longer resolves.
|
||||
pub fn remembered_agent() -> Option<String> {
|
||||
Some(read_launcher().get("lastCli")?.as_str()?.to_string()).filter(|id| !id.is_empty())
|
||||
}
|
||||
|
||||
/// `--project <dir>`, `--project=<dir>` or the first bare argument: the folder
|
||||
/// the launcher passed in when it started the app.
|
||||
fn argument_folder(args: &[String]) -> Option<PathBuf> {
|
||||
let mut i = 1; // args[0] is the program name
|
||||
while i < args.len() {
|
||||
let arg = &args[i];
|
||||
if arg == "--agent" || arg == "--model" {
|
||||
// Their values are not folders, even when a folder of that name exists.
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if arg == "--project" {
|
||||
i += 1;
|
||||
if i < args.len() {
|
||||
let dir = PathBuf::from(&args[i]);
|
||||
return dir.is_dir().then_some(dir);
|
||||
}
|
||||
} else if let Some(dir) = arg.strip_prefix("--project=") {
|
||||
let dir = PathBuf::from(dir);
|
||||
return dir.is_dir().then_some(dir);
|
||||
} else if !arg.starts_with('-') {
|
||||
let dir = PathBuf::from(arg);
|
||||
return dir.is_dir().then_some(dir);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// What the launcher chose before it opened the app: `--agent <id>` and `--model <id>` (or the
|
||||
/// `=` forms). An unknown agent or a missing value is ignored, and a model only counts beside
|
||||
/// an agent, since a model name belongs to one agent.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct LaunchChoice {
|
||||
/// An agent id, built-in or custom; resolved at use through `agents::find_agent`.
|
||||
pub agent: Option<String>,
|
||||
pub model: Option<String>,
|
||||
}
|
||||
|
||||
fn flag_value(args: &[String], flag: &str) -> Option<String> {
|
||||
let prefix = format!("{flag}=");
|
||||
let mut i = 1;
|
||||
while i < args.len() {
|
||||
let arg = &args[i];
|
||||
if arg == flag {
|
||||
return args
|
||||
.get(i + 1)
|
||||
.filter(|v| !v.is_empty() && !v.starts_with('-'))
|
||||
.cloned();
|
||||
}
|
||||
if let Some(value) = arg.strip_prefix(&prefix) {
|
||||
return (!value.is_empty()).then(|| value.to_string());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn launch_choice(args: &[String]) -> LaunchChoice {
|
||||
launch_choice_in(args, agents::agents_file().as_deref())
|
||||
}
|
||||
|
||||
/// `launch_choice` with the custom agents read from `agents_file` (`None`: built-ins only).
|
||||
pub fn launch_choice_in(args: &[String], agents_file: Option<&Path>) -> LaunchChoice {
|
||||
let agent = flag_value(args, "--agent")
|
||||
.map(|id| id.to_lowercase())
|
||||
.filter(|id| agents::find_agent_in(id, agents_file).is_some());
|
||||
let model = agent.as_ref().and_then(|_| flag_value(args, "--model"));
|
||||
LaunchChoice { agent, model }
|
||||
}
|
||||
|
||||
/// The folder to open on: the launcher's argument wins, then its memory, then
|
||||
/// nothing (the page asks with the folder picker).
|
||||
pub fn resolve(args: &[String]) -> Option<ProjectDir> {
|
||||
if let Some(dir) = argument_folder(args) {
|
||||
return Some(ProjectDir {
|
||||
dir,
|
||||
source: ProjectSource::Argument,
|
||||
});
|
||||
}
|
||||
remembered_folder().map(|dir| ProjectDir {
|
||||
dir,
|
||||
source: ProjectSource::Remembered,
|
||||
})
|
||||
}
|
||||
|
||||
/// A folder the person picked becomes the remembered one, so the next start
|
||||
/// (app or launcher) opens on it. The launcher's other keys are kept.
|
||||
pub fn remember_folder(dir: &Path) -> Result<ProjectDir, String> {
|
||||
let file = launcher_file().ok_or("no home folder found")?;
|
||||
let mut state = read_launcher();
|
||||
state.insert(
|
||||
"lastFolder".to_string(),
|
||||
serde_json::Value::String(dir.to_string_lossy().into_owned()),
|
||||
);
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(err)?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&serde_json::Value::Object(state)).map_err(err)?;
|
||||
crate::loop_driver::write_atomic(&file, &json)?;
|
||||
Ok(ProjectDir {
|
||||
dir: dir.to_path_buf(),
|
||||
source: ProjectSource::Picked,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn launch_choice(args: &[String]) -> LaunchChoice {
|
||||
launch_choice_in(args, None)
|
||||
}
|
||||
|
||||
fn args(list: &[&str]) -> Vec<String> {
|
||||
std::iter::once("plan2code-app")
|
||||
.chain(list.iter().copied())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_choice_reads_agent_and_model_in_both_forms() {
|
||||
let want = LaunchChoice {
|
||||
agent: Some("codex".to_string()),
|
||||
model: Some("gpt-5".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
launch_choice(&args(&[
|
||||
"--project",
|
||||
".",
|
||||
"--agent",
|
||||
"codex",
|
||||
"--model",
|
||||
"gpt-5"
|
||||
])),
|
||||
want
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent=codex", "--model=gpt-5"])),
|
||||
want
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "CODEX", "--model", "gpt-5"])),
|
||||
want
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_alone_is_a_choice_and_a_model_alone_is_not() {
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "claude"])),
|
||||
LaunchChoice {
|
||||
agent: Some("claude".to_string()),
|
||||
model: None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--model", "opus"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_agent_or_a_missing_value_is_ignored() {
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "emacs", "--model", "x"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(launch_choice(&args(&["--agent"])), LaunchChoice::default());
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "--model", "x"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent=", "--model=x"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(launch_choice(&args(&[])), LaunchChoice::default());
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "devin", "--model"])),
|
||||
LaunchChoice {
|
||||
agent: Some("devin".to_string()),
|
||||
model: None
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_agent_id_is_accepted_when_the_file_names_it() {
|
||||
let dir = std::env::temp_dir().join(format!("p2c-project-custom-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("agents.json");
|
||||
std::fs::write(
|
||||
&file,
|
||||
r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose"}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let want = LaunchChoice {
|
||||
agent: Some("goose".into()),
|
||||
model: Some("m1".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
launch_choice_in(&args(&["--agent", "goose", "--model", "m1"]), Some(&file)),
|
||||
want
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice_in(&args(&["--agent", "other", "--model", "m1"]), Some(&file)),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice_in(&args(&["--agent", "goose"]), None),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_agent_and_model_values_are_never_taken_for_a_folder() {
|
||||
// A folder named like the agent exists right here, so a bare-argument reading would pick it.
|
||||
let cwd = std::env::temp_dir().join(format!("p2c-project-args-{}", std::process::id()));
|
||||
std::fs::create_dir_all(cwd.join("codex")).unwrap();
|
||||
let named = cwd.join("codex").to_string_lossy().into_owned();
|
||||
let found = argument_folder(&args(&["--agent", &named, "--model", &named]));
|
||||
assert_eq!(found, None);
|
||||
// Beside --project, the folder wins as before.
|
||||
let found = argument_folder(&args(&["--project", &named, "--agent", "codex"]));
|
||||
assert_eq!(found, Some(cwd.join("codex")));
|
||||
let _ = std::fs::remove_dir_all(&cwd);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
//! A command running in a pseudo-terminal, so full-screen agent programs see a
|
||||
//! real terminal. Knows nothing about Tauri: output goes to a callback.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
#[cfg(unix)]
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use portable_pty::{native_pty_system, Child, ChildKiller, CommandBuilder, MasterPty, PtySize};
|
||||
|
||||
/// Output is sent to the page at most once per this long, so a flood of text
|
||||
/// does not stall the web view.
|
||||
pub const BATCH_INTERVAL: Duration = Duration::from_millis(16);
|
||||
|
||||
/// On macOS and Linux the kill is a hang-up signal, which a program can ignore.
|
||||
/// This long after it, a command that is still running is killed outright.
|
||||
#[cfg(unix)]
|
||||
const HANGUP_GRACE: Duration = Duration::from_secs(2);
|
||||
|
||||
/// What to run, where, and how big the terminal starts.
|
||||
pub struct StartOptions {
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
pub cwd: Option<PathBuf>,
|
||||
pub cols: u16,
|
||||
pub rows: u16,
|
||||
}
|
||||
|
||||
/// A running command in a pseudo-terminal.
|
||||
pub struct PtyHost {
|
||||
master: Mutex<Box<dyn MasterPty + Send>>,
|
||||
writer: Mutex<Box<dyn Write + Send>>,
|
||||
child: Arc<Mutex<Box<dyn Child + Send + Sync>>>,
|
||||
killer: Mutex<Box<dyn ChildKiller + Send + Sync>>,
|
||||
#[cfg(unix)]
|
||||
pid: Option<u32>,
|
||||
/// Set once the command has been waited for, so a late kill never signals
|
||||
/// a process id that may have been given to something else.
|
||||
#[cfg(unix)]
|
||||
exited: Arc<AtomicBool>,
|
||||
/// A Windows Job Object the spawned process was assigned to, so ending
|
||||
/// it (`kill`, or this host simply being dropped) ends every process
|
||||
/// still in it, not just the one directly spawned: a `cmd /c` npm shim's
|
||||
/// real agent process is a child of that child, invisible to a plain
|
||||
/// `TerminateProcess`. A raw handle value, not `HANDLE`, so the struct
|
||||
/// stays `Send`. `None` when the job could not be made; `kill` then
|
||||
/// falls back to ending just the one process, as before.
|
||||
#[cfg(windows)]
|
||||
job: Option<usize>,
|
||||
}
|
||||
|
||||
fn size(cols: u16, rows: u16) -> PtySize {
|
||||
PtySize {
|
||||
rows,
|
||||
cols,
|
||||
pixel_width: 0,
|
||||
pixel_height: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn err<E: std::fmt::Display>(e: E) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
impl PtyHost {
|
||||
/// Start the command. `on_output` gets the output in chunks, at most one per
|
||||
/// `BATCH_INTERVAL`, until the command's output ends.
|
||||
pub fn start<F>(options: StartOptions, mut on_output: F) -> Result<PtyHost, String>
|
||||
where
|
||||
F: FnMut(Vec<u8>) + Send + 'static,
|
||||
{
|
||||
let pair = native_pty_system()
|
||||
.openpty(size(options.cols, options.rows))
|
||||
.map_err(err)?;
|
||||
|
||||
let mut command = CommandBuilder::new(&options.program);
|
||||
command.args(&options.args);
|
||||
// What the agent CLIs expect from a terminal that can show color.
|
||||
command.env("TERM", "xterm-256color");
|
||||
command.env("COLORTERM", "truecolor");
|
||||
for (key, value) in &options.env {
|
||||
command.env(key, value);
|
||||
}
|
||||
if let Some(cwd) = &options.cwd {
|
||||
command.cwd(cwd);
|
||||
}
|
||||
let child = pair.slave.spawn_command(command).map_err(err)?;
|
||||
// The child holds its own end; keeping ours open would stop the reader
|
||||
// from ever seeing the end of the output.
|
||||
drop(pair.slave);
|
||||
|
||||
let mut reader = pair.master.try_clone_reader().map_err(err)?;
|
||||
let writer = pair.master.take_writer().map_err(err)?;
|
||||
let killer = child.clone_killer();
|
||||
#[cfg(unix)]
|
||||
let pid = child.process_id();
|
||||
#[cfg(windows)]
|
||||
let job = windows_job::assign(child.as_ref());
|
||||
|
||||
// One thread reads as fast as the terminal produces; another gathers
|
||||
// what arrived into one send per interval.
|
||||
let (tx, rx) = mpsc::channel::<Vec<u8>>();
|
||||
thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
match reader.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
if tx.send(buf[..n].to_vec()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
thread::spawn(move || {
|
||||
// Blocks for the first chunk, then collects until the interval is up.
|
||||
while let Ok(first) = rx.recv() {
|
||||
let mut batch = first;
|
||||
let deadline = Instant::now() + BATCH_INTERVAL;
|
||||
loop {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
break;
|
||||
}
|
||||
match rx.recv_timeout(left) {
|
||||
Ok(more) => batch.extend_from_slice(&more),
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => break,
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => {
|
||||
on_output(batch);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
on_output(batch);
|
||||
}
|
||||
});
|
||||
|
||||
Ok(PtyHost {
|
||||
master: Mutex::new(pair.master),
|
||||
writer: Mutex::new(writer),
|
||||
child: Arc::new(Mutex::new(child)),
|
||||
killer: Mutex::new(killer),
|
||||
#[cfg(unix)]
|
||||
pid,
|
||||
#[cfg(unix)]
|
||||
exited: Arc::new(AtomicBool::new(false)),
|
||||
#[cfg(windows)]
|
||||
job,
|
||||
})
|
||||
}
|
||||
|
||||
/// Send keystrokes (or pasted text) to the command.
|
||||
pub fn write(&self, bytes: &[u8]) -> Result<(), String> {
|
||||
let mut writer = self.writer.lock().map_err(err)?;
|
||||
writer.write_all(bytes).map_err(err)?;
|
||||
writer.flush().map_err(err)
|
||||
}
|
||||
|
||||
/// Tell the command the terminal changed size.
|
||||
pub fn resize(&self, cols: u16, rows: u16) -> Result<(), String> {
|
||||
self.master
|
||||
.lock()
|
||||
.map_err(err)?
|
||||
.resize(size(cols, rows))
|
||||
.map_err(err)
|
||||
}
|
||||
|
||||
/// End the command. Safe to call while `wait` is blocked in another thread.
|
||||
pub fn kill(&self) -> Result<(), String> {
|
||||
let result = self.killer.lock().map_err(err)?.kill().map_err(err);
|
||||
// The job object, when there is one, ends the whole process tree:
|
||||
// killing just the directly spawned process (above) leaves a
|
||||
// `cmd /c` npm shim's real agent process running.
|
||||
#[cfg(windows)]
|
||||
if let Some(job) = self.job {
|
||||
windows_job::terminate(job);
|
||||
}
|
||||
// portable-pty 0.9 on Windows has the TerminateProcess result inverted: it
|
||||
// returns Err (a stale error) when the kill worked and Ok when it failed, so
|
||||
// its answer says nothing there.
|
||||
if cfg!(windows) {
|
||||
return Ok(());
|
||||
}
|
||||
// portable-pty only sends SIGHUP on macOS and Linux; follow it with
|
||||
// SIGKILL if the command is still there after the grace period.
|
||||
#[cfg(unix)]
|
||||
if let Some(pid) = self.pid {
|
||||
let exited = Arc::clone(&self.exited);
|
||||
thread::spawn(move || {
|
||||
thread::sleep(HANGUP_GRACE);
|
||||
if !exited.load(Ordering::SeqCst) {
|
||||
// SAFETY: plain signal to a process id the command still holds.
|
||||
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
|
||||
}
|
||||
});
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Block until the command ends and return its exit code. A command ended by
|
||||
/// a signal reports 1.
|
||||
pub fn wait(&self) -> Result<u32, String> {
|
||||
self.wait_described().map(|(code, _)| code)
|
||||
}
|
||||
|
||||
/// Like `wait`, with the name of the signal that ended the command, when
|
||||
/// there was one (macOS and Linux).
|
||||
pub fn wait_described(&self) -> Result<(u32, Option<String>), String> {
|
||||
let child = Arc::clone(&self.child);
|
||||
let mut child = child.lock().map_err(err)?;
|
||||
let status = child.wait().map_err(err)?;
|
||||
#[cfg(unix)]
|
||||
self.exited.store(true, Ordering::SeqCst);
|
||||
Ok((status.exit_code(), status.signal().map(str::to_string)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Closing the job's last handle ends every process still in it (`job` was
|
||||
/// made with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`): a safety net for a host
|
||||
/// dropped without `kill` ever being called, on top of `kill`'s own explicit
|
||||
/// `TerminateJobObject`.
|
||||
#[cfg(windows)]
|
||||
impl Drop for PtyHost {
|
||||
fn drop(&mut self) {
|
||||
if let Some(job) = self.job {
|
||||
windows_job::close(job);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Windows Job Object groups a spawned process with every process it goes
|
||||
/// on to spawn itself (a child joins its parent's job automatically, unless
|
||||
/// it asks to break away, which `cmd /c` does not), so ending the job ends
|
||||
/// the whole tree. Nothing here calls back into `PtyHost`.
|
||||
#[cfg(windows)]
|
||||
mod windows_job {
|
||||
use portable_pty::Child;
|
||||
use std::os::windows::io::RawHandle;
|
||||
use winapi::shared::minwindef::DWORD;
|
||||
use winapi::shared::ntdef::HANDLE;
|
||||
use winapi::um::handleapi::CloseHandle;
|
||||
use winapi::um::jobapi2::{
|
||||
AssignProcessToJobObject, CreateJobObjectW, SetInformationJobObject, TerminateJobObject,
|
||||
};
|
||||
use winapi::um::winnt::{
|
||||
JobObjectExtendedLimitInformation, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
};
|
||||
|
||||
/// Create a job, set it to kill everything in it when its last handle
|
||||
/// closes, and assign `child` to it. `None` on any failure (an older
|
||||
/// Windows without nested-job support, say): `kill` then falls back to
|
||||
/// ending just the one process, as it always did.
|
||||
pub fn assign(child: &(dyn Child + Send + Sync)) -> Option<usize> {
|
||||
let process: RawHandle = child.as_raw_handle()?;
|
||||
unsafe {
|
||||
let job = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null());
|
||||
if job.is_null() {
|
||||
return None;
|
||||
}
|
||||
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();
|
||||
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
let set = SetInformationJobObject(
|
||||
job,
|
||||
JobObjectExtendedLimitInformation,
|
||||
&mut info as *mut _ as *mut _,
|
||||
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as DWORD,
|
||||
);
|
||||
if set == 0 || AssignProcessToJobObject(job, process as HANDLE) == 0 {
|
||||
CloseHandle(job);
|
||||
return None;
|
||||
}
|
||||
Some(job as usize)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn terminate(job: usize) {
|
||||
unsafe {
|
||||
TerminateJobObject(job as HANDLE, 1);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn close(job: usize) {
|
||||
unsafe {
|
||||
CloseHandle(job as HANDLE);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! The words the quit check shows while an agent runs. Most of the time the
|
||||
//! agent is not mid-step at all but waiting on the person's answer in the web
|
||||
//! console, so the check reads the page's last taskbar signal (attention.rs)
|
||||
//! and says which case it is. Anything it cannot be sure of is the working
|
||||
//! case, the safer warning. While the Implementation Loop builds a phase the
|
||||
//! words are the loop's own (`loop_quit_prompt`). Knows nothing about Tauri;
|
||||
//! main.rs shows it.
|
||||
|
||||
use crate::attention::Signal;
|
||||
|
||||
/// Whether quitting would stop the agent partway through something.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum QuitCase {
|
||||
/// The person's move, or nothing left to do: nothing is half done.
|
||||
Waiting,
|
||||
/// Busy, quiet for too long, gone, or not known yet.
|
||||
Working,
|
||||
}
|
||||
|
||||
/// Everything the box says.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct QuitPrompt {
|
||||
pub case: QuitCase,
|
||||
pub title: String,
|
||||
pub heading: String,
|
||||
pub message: String,
|
||||
pub quit: String,
|
||||
pub stay: String,
|
||||
}
|
||||
|
||||
fn words(case: QuitCase, heading: &str, message: &str, quit: &str) -> QuitPrompt {
|
||||
QuitPrompt {
|
||||
case,
|
||||
title: "Plan2Code".to_string(),
|
||||
heading: heading.to_string(),
|
||||
message: message.to_string(),
|
||||
quit: quit.to_string(),
|
||||
stay: "Stay".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The prompt for the page's last signal (`None` before the page has sent one).
|
||||
pub fn quit_prompt(last: Option<Signal>) -> QuitPrompt {
|
||||
match last {
|
||||
Some(Signal::Ready | Signal::Plain) => words(
|
||||
QuitCase::Waiting,
|
||||
"Done for now?",
|
||||
"Your agent is just waiting on your next answer. Quit and this session ends.",
|
||||
"Quit",
|
||||
),
|
||||
Some(Signal::Busy | Signal::Attention) | None => words(
|
||||
QuitCase::Working,
|
||||
"Leave while your agent is busy?",
|
||||
"If you quit now, the agent stops mid-step. Everything it has saved so far stays put.",
|
||||
"Quit and stop it",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// "Phase 1", "Phases 1 and 2", "Phases 1, 2 and 3".
|
||||
fn phase_list(committed: &[u32]) -> String {
|
||||
let numbers: Vec<String> = committed.iter().map(u32::to_string).collect();
|
||||
match numbers.as_slice() {
|
||||
[] => String::new(),
|
||||
[one] => format!("Phase {one}"),
|
||||
[init @ .., last] => format!("Phases {} and {last}", init.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The words for quitting while the Implementation Loop builds a phase.
|
||||
/// `committed` lists the phase numbers already committed.
|
||||
pub fn loop_quit_prompt(phase: u32, phases: u32, committed: &[u32]) -> QuitPrompt {
|
||||
let done = match committed.len() {
|
||||
0 => "No phase is committed yet".to_string(),
|
||||
1 => format!("{} is committed", phase_list(committed)),
|
||||
_ => format!("{} are committed", phase_list(committed)),
|
||||
};
|
||||
words(
|
||||
QuitCase::Working,
|
||||
"Stop the loop and quit?",
|
||||
&format!(
|
||||
"Phase {phase} of {phases} is mid-build. {done}; this phase's changes stay uncommitted."
|
||||
),
|
||||
"Quit and stop the loop",
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_persons_move_and_nothing_left_are_the_waiting_case() {
|
||||
assert_eq!(quit_prompt(Some(Signal::Ready)).case, QuitCase::Waiting);
|
||||
assert_eq!(quit_prompt(Some(Signal::Plain)).case, QuitCase::Waiting);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_attention_and_unknown_are_the_working_case() {
|
||||
assert_eq!(quit_prompt(Some(Signal::Busy)).case, QuitCase::Working);
|
||||
assert_eq!(
|
||||
quit_prompt(Some(Signal::Attention)).case,
|
||||
QuitCase::Working,
|
||||
"attention covers a quiet agent that may still be mid-step"
|
||||
);
|
||||
assert_eq!(quit_prompt(None).case, QuitCase::Working);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_case_has_its_own_words() {
|
||||
let waiting = quit_prompt(Some(Signal::Ready));
|
||||
assert_eq!(waiting.heading, "Done for now?");
|
||||
assert_eq!(waiting.quit, "Quit");
|
||||
let working = quit_prompt(Some(Signal::Busy));
|
||||
assert_eq!(working.heading, "Leave while your agent is busy?");
|
||||
assert_eq!(working.quit, "Quit and stop it");
|
||||
assert!(working.message.contains("mid-step"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stay_is_never_mistaken_for_quit() {
|
||||
for last in [None, Some(Signal::Busy), Some(Signal::Ready)] {
|
||||
let prompt = quit_prompt(last);
|
||||
assert_eq!(prompt.stay, "Stay");
|
||||
assert_ne!(prompt.stay, prompt.quit);
|
||||
assert_eq!(prompt.title, "Plan2Code");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_text_carries_an_em_dash() {
|
||||
let mut all = vec![loop_quit_prompt(2, 4, &[1]), loop_quit_prompt(1, 4, &[])];
|
||||
all.extend([None, Some(Signal::Busy), Some(Signal::Ready)].map(quit_prompt));
|
||||
for p in all {
|
||||
for text in [&p.title, &p.heading, &p.message, &p.quit, &p.stay] {
|
||||
assert!(!text.contains('\u{2014}'), "{text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_loop_wording_names_what_is_committed() {
|
||||
let none = loop_quit_prompt(1, 4, &[]);
|
||||
assert_eq!(none.heading, "Stop the loop and quit?");
|
||||
assert_eq!(none.title, "Plan2Code");
|
||||
assert_eq!(none.quit, "Quit and stop the loop");
|
||||
assert_eq!(none.stay, "Stay");
|
||||
assert_eq!(none.case, QuitCase::Working);
|
||||
assert_eq!(
|
||||
none.message,
|
||||
"Phase 1 of 4 is mid-build. No phase is committed yet; this phase's changes stay uncommitted."
|
||||
);
|
||||
assert_eq!(
|
||||
loop_quit_prompt(2, 4, &[1]).message,
|
||||
"Phase 2 of 4 is mid-build. Phase 1 is committed; this phase's changes stay uncommitted."
|
||||
);
|
||||
assert_eq!(
|
||||
loop_quit_prompt(3, 4, &[1, 2]).message,
|
||||
"Phase 3 of 4 is mid-build. Phases 1 and 2 are committed; this phase's changes stay uncommitted."
|
||||
);
|
||||
assert_eq!(
|
||||
loop_quit_prompt(4, 4, &[1, 2, 3]).message,
|
||||
"Phase 4 of 4 is mid-build. Phases 1, 2 and 3 are committed; this phase's changes stay uncommitted."
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
//! What a Restart leaves for the dashboard: the restart brief, written as a
|
||||
//! pick-up handoff, so the fresh agent (which starts on the plain `/plan2code`
|
||||
//! prompt and lands on the dashboard) finds the chip waiting. Nothing new is
|
||||
//! stored anywhere: the brief is built from the session's files each time.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use chrono::{DateTime, Local};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::brief;
|
||||
use crate::handoff;
|
||||
use crate::session_reader;
|
||||
|
||||
pub const READY_NOTE: &str = "Brief ready on the dashboard";
|
||||
|
||||
/// The handoff the last Restart wrote. The next Restart retires it if the person
|
||||
/// has not picked it up, so unused briefs do not pile up as chips.
|
||||
static LAST_BRIEF: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
/// Write the brief for session `sid` as a handoff. Returns the handoff's id,
|
||||
/// or `None` when there is nothing worth picking up: a workflow with no mapped
|
||||
/// skill (the dashboard, or one not yet known), whose only next step would be
|
||||
/// "Open the dashboard" where the fresh agent lands anyway, and a session that
|
||||
/// finished, whose finished screen already named what comes next, and one
|
||||
/// that has posted nothing yet (no spec, progress, activity or questions),
|
||||
/// whose brief would only repeat the skill's name. A session
|
||||
/// that names no worktree is an error, not a `None`, since that is a broken
|
||||
/// session rather than an empty one.
|
||||
pub fn leave_brief(
|
||||
console_home: &Path,
|
||||
handoffs: &Path,
|
||||
sid: &str,
|
||||
when: DateTime<Local>,
|
||||
) -> Result<Option<String>, String> {
|
||||
let session = session_reader::load(console_home, sid).map_err(|e| e.to_string())?;
|
||||
let state = &session.state;
|
||||
let workflow = text(state, "workflow").unwrap_or("");
|
||||
let Some(skill) = brief::skill_for_workflow(workflow) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if finished(state) || empty(state) {
|
||||
return Ok(None);
|
||||
}
|
||||
let worktree = text(state, "worktree").ok_or("the session names no worktree")?;
|
||||
let project = text(state, "project").unwrap_or(worktree);
|
||||
let spec = text(state, "specDir").filter(|s| valid_spec(s));
|
||||
let spec_dir = spec.map(|s| Path::new(worktree).join(s));
|
||||
let git = brief::git_summary(Path::new(worktree));
|
||||
let events = session_reader::read_ndjson(&session.dir.join("events.ndjson"));
|
||||
let body = brief::build_brief(state, spec_dir.as_deref(), git.as_ref(), &events);
|
||||
let title = match spec {
|
||||
Some(spec) => format!("Restart of {skill} on {spec}"),
|
||||
None => format!("Restart of {skill}"),
|
||||
};
|
||||
let record = handoff::Record {
|
||||
title: &title,
|
||||
worktree,
|
||||
project,
|
||||
spec,
|
||||
workflow,
|
||||
skill,
|
||||
};
|
||||
handoff::write(handoffs, when, &record, &body).map(Some)
|
||||
}
|
||||
|
||||
/// The bar's line for a Restart on session `sid`, written to the real console
|
||||
/// and handoff folders. `None` when there was nothing to leave.
|
||||
pub fn note_for_restart(sid: &str) -> Option<String> {
|
||||
let console_home = session_reader::console_home()?;
|
||||
let handoffs = handoff::handoffs_dir()?;
|
||||
match leave_brief(&console_home, &handoffs, sid, handoff::now()) {
|
||||
Ok(Some(id)) => {
|
||||
let previous = LAST_BRIEF
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut last| last.replace(id.clone()));
|
||||
if let Some(previous) = previous.filter(|p| *p != id) {
|
||||
let _ = handoff::retire_if_unused(&handoffs, &previous);
|
||||
}
|
||||
Some(READY_NOTE.to_string())
|
||||
}
|
||||
Ok(None) => None,
|
||||
Err(why) => Some(format!("The brief could not be written: {why}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn text<'a>(state: &'a Value, key: &str) -> Option<&'a str> {
|
||||
state
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// The session posted a `finish` that is not a pause. A pause's headline starts
|
||||
/// with "Paused" (the page's `finishPaused`) and keeps a place worth picking up.
|
||||
fn finished(state: &Value) -> bool {
|
||||
let Some(finish) = state.get("finish").filter(|f| f.is_object()) else {
|
||||
return false;
|
||||
};
|
||||
let headline = finish
|
||||
.get("headline")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.trim_start();
|
||||
!headline
|
||||
.get(..6)
|
||||
.is_some_and(|word| word.eq_ignore_ascii_case("paused"))
|
||||
}
|
||||
|
||||
/// Nothing a fresh agent could pick up beyond the skill's name.
|
||||
fn empty(state: &Value) -> bool {
|
||||
let stage = state.get("headline").and_then(|h| text(h, "stage"));
|
||||
let activity = state
|
||||
.get("agent")
|
||||
.and_then(|a| text(a, "activity"))
|
||||
.filter(|a| !a.trim().is_empty());
|
||||
let items = state
|
||||
.get("items")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| !items.is_empty());
|
||||
text(state, "specDir").is_none() && stage.is_none() && activity.is_none() && !items
|
||||
}
|
||||
|
||||
fn valid_spec(spec: &str) -> bool {
|
||||
spec.strip_prefix("specs/").is_some_and(|name| {
|
||||
!name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\'])
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::TimeZone;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-restart-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A console home with one session on `workflow`, and a project with a spec.
|
||||
fn session(name: &str, workflow: &str, spec: Option<&str>) -> (PathBuf, PathBuf, PathBuf) {
|
||||
let root = fixture(name);
|
||||
let home = root.join("console");
|
||||
let project = root.join("project");
|
||||
let dir = home.join("sessions").join("s1");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::create_dir_all(&project).unwrap();
|
||||
let state = serde_json::json!({
|
||||
"schema": 1,
|
||||
"workflow": workflow,
|
||||
"specDir": spec,
|
||||
"worktree": project.to_string_lossy(),
|
||||
"project": project.to_string_lossy(),
|
||||
"headline": { "stage": "Phase 5: Restart brief", "cleared": 4, "total": 11 },
|
||||
"items": [],
|
||||
});
|
||||
fs::write(dir.join("state.json"), state.to_string()).unwrap();
|
||||
(home, project, root.join("handoffs"))
|
||||
}
|
||||
|
||||
fn when() -> DateTime<Local> {
|
||||
Local.with_ymd_and_hms(2026, 10, 21, 14, 5, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mid_implement_session_leaves_a_pick_up_the_dashboard_lists() {
|
||||
let (home, project, handoffs) = session("pickup", "implement", Some("specs/feature"));
|
||||
let spec = project.join("specs").join("feature");
|
||||
fs::create_dir_all(&spec).unwrap();
|
||||
fs::write(
|
||||
spec.join("overview.md"),
|
||||
"- [/] [Phase 5: Restart](./phase-5.md)\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
spec.join("phase-5.md"),
|
||||
"- [ ] **Task 5.1:** Create the reader\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let id = leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.expect("a handoff");
|
||||
assert_eq!(id, "2026-10-21-1405-handoff");
|
||||
let record: Value =
|
||||
serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(record["workflow"], "implement");
|
||||
assert_eq!(record["spec"], "specs/feature");
|
||||
let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap();
|
||||
assert!(doc.contains("## Next task\n\nTask 5.1: Create the reader"));
|
||||
assert!(doc.contains("Phase 5: Restart brief: 4 of 11 done."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dashboard_session_leaves_nothing() {
|
||||
let (home, _, handoffs) = session("dashboard", "dashboard", None);
|
||||
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
|
||||
assert!(!handoffs.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skill_that_has_posted_nothing_leaves_nothing() {
|
||||
let (home, _, handoffs) = session("blank", "quick-task", None);
|
||||
let file = home.join("sessions").join("s1").join("state.json");
|
||||
let mut state: Value = serde_json::from_str(&fs::read_to_string(&file).unwrap()).unwrap();
|
||||
state["headline"] = Value::Null;
|
||||
fs::write(&file, state.to_string()).unwrap();
|
||||
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_session_leaves_nothing_but_a_paused_one_does() {
|
||||
let (home, _, handoffs) = session("finished", "implement", Some("specs/feature"));
|
||||
let file = home.join("sessions").join("s1").join("state.json");
|
||||
let mut state: Value = serde_json::from_str(&fs::read_to_string(&file).unwrap()).unwrap();
|
||||
state["finish"] = serde_json::json!({ "headline": "Phase 5 is built", "dashboard": true });
|
||||
fs::write(&file, state.to_string()).unwrap();
|
||||
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
|
||||
|
||||
state["finish"] = serde_json::json!({ "headline": "Paused at Phase 5" });
|
||||
fs::write(&file, state.to_string()).unwrap();
|
||||
assert!(leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brief_carries_the_agent_activity_and_recent_events() {
|
||||
let (home, _project, handoffs) = session("activity", "implement", None);
|
||||
let dir = home.join("sessions").join("s1");
|
||||
let mut state: Value =
|
||||
serde_json::from_str(&fs::read_to_string(dir.join("state.json")).unwrap()).unwrap();
|
||||
state["agent"] = serde_json::json!({ "status": "working", "activity": "Spiking Claude's context signal (Task 10.1)" });
|
||||
fs::write(dir.join("state.json"), state.to_string()).unwrap();
|
||||
fs::write(
|
||||
dir.join("events.ndjson"),
|
||||
"{\"at\":\"2026-10-23T01:08:47.152Z\",\"type\":\"post\",\"items\":0}\n{\"at\":\"2026-10-23T01:09:00.000Z\",\"type\":\"consume\",\"kind\":\"submit\"}\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let id = leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.expect("a handoff");
|
||||
let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap();
|
||||
assert!(doc.contains("Doing: Spiking Claude's context signal (Task 10.1)"));
|
||||
assert!(doc.contains("## Recent activity\n\n- post (0 items)\n- consume: submit\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_does_not_exist_is_an_error_not_a_brief() {
|
||||
let (home, _, handoffs) = session("missing", "implement", None);
|
||||
assert!(leave_brief(&home, &handoffs, "nope", when()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spec_that_is_not_one_folder_is_left_out_of_the_record() {
|
||||
let (home, _, handoffs) = session("badspec", "pathfinder", Some("specs/a/b"));
|
||||
let id = leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let record: Value =
|
||||
serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap())
|
||||
.unwrap();
|
||||
assert!(record["spec"].is_null());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Reads a console session's files without disturbing them. The console owns
|
||||
//! `~/.plan2code/console/sessions/<sid>/`: this module only opens files for
|
||||
//! reading. It never creates, locks, renames or removes anything there, so the
|
||||
//! console's own writes are never blocked by the app (NFR-3).
|
||||
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::thread::sleep;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// The one session schema this reader understands (`state.json`'s `schema`).
|
||||
pub const SCHEMA: u64 = 1;
|
||||
|
||||
/// How many times a locked `state.json` is tried again. The console renames
|
||||
/// the file while it writes, so Windows can refuse a read for a moment.
|
||||
const LOCKED_RETRIES: u32 = 5;
|
||||
const RETRY_EVERY: Duration = Duration::from_millis(50);
|
||||
|
||||
/// Windows: ERROR_SHARING_VIOLATION and ERROR_LOCK_VIOLATION.
|
||||
const WINDOWS_SHARING: [i32; 2] = [32, 33];
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ReadError {
|
||||
/// The file is not there.
|
||||
Missing(PathBuf),
|
||||
/// Still locked after every retry.
|
||||
Busy,
|
||||
/// Some other read failure.
|
||||
Unreadable(String),
|
||||
/// Not a JSON object.
|
||||
Malformed(String),
|
||||
/// A schema this app does not read.
|
||||
Schema(u64),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ReadError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ReadError::Missing(file) => write!(f, "{} is missing", file.display()),
|
||||
ReadError::Busy => write!(f, "session busy: the console is still writing its state"),
|
||||
ReadError::Unreadable(why) => write!(f, "could not read the session: {why}"),
|
||||
ReadError::Malformed(why) => write!(f, "the session file is not valid: {why}"),
|
||||
ReadError::Schema(found) => {
|
||||
write!(
|
||||
f,
|
||||
"session schema {found} is not supported (this app reads schema {SCHEMA})"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's `state.json`, read once. Nothing else in the session folder is
|
||||
/// read here: the Ask chat lives in `chat.ndjson` and stays out of the brief.
|
||||
pub struct Session {
|
||||
pub dir: PathBuf,
|
||||
pub state: Value,
|
||||
}
|
||||
|
||||
/// `~/.plan2code/console`, or `PLAN2CODE_CONSOLE_HOME` when the console is
|
||||
/// relocated (the same rule the console and the supervisor follow).
|
||||
pub fn console_home() -> Option<PathBuf> {
|
||||
if let Ok(home) = std::env::var("PLAN2CODE_CONSOLE_HOME") {
|
||||
return Some(PathBuf::from(home));
|
||||
}
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("console"))
|
||||
}
|
||||
|
||||
/// `<console home>/sessions/<sid>`.
|
||||
pub fn session_dir(console_home: &Path, sid: &str) -> PathBuf {
|
||||
console_home.join("sessions").join(sid)
|
||||
}
|
||||
|
||||
/// Open and parse the session `sid` under `console_home`.
|
||||
pub fn load(console_home: &Path, sid: &str) -> Result<Session, ReadError> {
|
||||
let dir = session_dir(console_home, sid);
|
||||
let text = read_with_retry(&dir.join("state.json"), |file| {
|
||||
std::fs::read_to_string(file)
|
||||
})?;
|
||||
let state = parse_state(&text)?;
|
||||
Ok(Session { dir, state })
|
||||
}
|
||||
|
||||
/// Read `file` through `read`. A locked file (a sharing or permission error) is
|
||||
/// tried again up to `LOCKED_RETRIES` times, `RETRY_EVERY` apart; then the
|
||||
/// session is reported busy. `read` is a parameter so a test can stand in a
|
||||
/// reader that fails a few times.
|
||||
pub fn read_with_retry<F>(file: &Path, mut read: F) -> Result<String, ReadError>
|
||||
where
|
||||
F: FnMut(&Path) -> io::Result<String>,
|
||||
{
|
||||
let mut retries = 0;
|
||||
loop {
|
||||
match read(file) {
|
||||
Ok(text) => return Ok(text),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
return Err(ReadError::Missing(file.to_path_buf()))
|
||||
}
|
||||
Err(e) if is_locked(&e) => {
|
||||
if retries == LOCKED_RETRIES {
|
||||
return Err(ReadError::Busy);
|
||||
}
|
||||
retries += 1;
|
||||
sleep(RETRY_EVERY);
|
||||
}
|
||||
Err(e) => return Err(ReadError::Unreadable(e.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_locked(e: &io::Error) -> bool {
|
||||
e.kind() == io::ErrorKind::PermissionDenied
|
||||
|| e.raw_os_error()
|
||||
.is_some_and(|code| WINDOWS_SHARING.contains(&code))
|
||||
}
|
||||
|
||||
/// Parse `state.json` text: a JSON object whose `schema` is `SCHEMA`.
|
||||
pub fn parse_state(text: &str) -> Result<Value, ReadError> {
|
||||
let state: Value =
|
||||
serde_json::from_str(text).map_err(|e| ReadError::Malformed(e.to_string()))?;
|
||||
if !state.is_object() {
|
||||
return Err(ReadError::Malformed("not a JSON object".to_string()));
|
||||
}
|
||||
let schema = state
|
||||
.get("schema")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or_else(|| ReadError::Malformed("no schema number".to_string()))?;
|
||||
if schema != SCHEMA {
|
||||
return Err(ReadError::Schema(schema));
|
||||
}
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
/// Each line of a `.ndjson` file that parses as JSON, in order. A partial last
|
||||
/// line (the console was mid-write) does not parse and is dropped; so is any
|
||||
/// other line that does not parse. A missing file has no lines.
|
||||
pub fn read_ndjson(file: &Path) -> Vec<Value> {
|
||||
match std::fs::read_to_string(file) {
|
||||
Ok(text) => parse_ndjson(&text),
|
||||
Err(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_ndjson(text: &str) -> Vec<Value> {
|
||||
text.lines()
|
||||
.filter(|line| !line.trim().is_empty())
|
||||
.filter_map(|line| serde_json::from_str(line).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-reader-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
const STATE: &str =
|
||||
r#"{"schema": 1, "sid": "s1", "workflow": "implement", "specDir": "specs/x"}"#;
|
||||
|
||||
#[test]
|
||||
fn a_complete_session_loads() {
|
||||
let home = fixture("complete");
|
||||
let dir = session_dir(&home, "s1");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("state.json"), STATE).unwrap();
|
||||
let session = load(&home, "s1").unwrap();
|
||||
assert_eq!(session.state["workflow"], "implement");
|
||||
assert_eq!(session.dir, dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_last_line_is_dropped() {
|
||||
let lines = parse_ndjson("{\"a\":1}\n{\"b\":2}\n{\"c\":");
|
||||
assert_eq!(
|
||||
lines,
|
||||
vec![serde_json::json!({"a": 1}), serde_json::json!({"b": 2})]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_ndjson_file_has_no_lines() {
|
||||
assert!(read_ndjson(&fixture("no-ndjson").join("events.ndjson")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_state_file_is_reported() {
|
||||
let home = fixture("missing");
|
||||
match load(&home, "nope") {
|
||||
Err(ReadError::Missing(file)) => assert!(file.ends_with("state.json")),
|
||||
other => panic!("expected Missing, got {:?}", other.map(|s| s.dir)),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_schema_is_rejected_with_a_clear_message() {
|
||||
let err = parse_state(r#"{"schema": 2}"#).unwrap_err();
|
||||
assert_eq!(err, ReadError::Schema(2));
|
||||
assert!(err.to_string().contains("schema 2 is not supported"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_file_that_frees_up_on_the_third_retry_is_read() {
|
||||
let tries = Cell::new(0);
|
||||
let text = read_with_retry(Path::new("state.json"), |_| {
|
||||
tries.set(tries.get() + 1);
|
||||
if tries.get() < 4 {
|
||||
Err(io::Error::from(io::ErrorKind::PermissionDenied))
|
||||
} else {
|
||||
Ok(STATE.to_string())
|
||||
}
|
||||
});
|
||||
assert_eq!(text.unwrap(), STATE);
|
||||
assert_eq!(tries.get(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_stays_locked_is_busy_not_a_failure() {
|
||||
let tries = Cell::new(0);
|
||||
let result = read_with_retry(Path::new("state.json"), |_| {
|
||||
tries.set(tries.get() + 1);
|
||||
Err(io::Error::from_raw_os_error(32))
|
||||
});
|
||||
assert_eq!(result, Err(ReadError::Busy));
|
||||
assert_eq!(tries.get(), LOCKED_RETRIES + 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
//! The app's own settings file, `~/.plan2code/app.json`. It holds what only the
|
||||
//! app remembers (today: the agent last picked in the bar). The console's
|
||||
//! folders under `~/.plan2code/console/` are never written to from here.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const LAST_AGENT_KEY: &str = "lastAgent";
|
||||
const TERM_DOCK_KEY: &str = "termDock";
|
||||
const TERM_FRACTION_KEY: &str = "termFraction";
|
||||
const TERM_COLLAPSED_KEY: &str = "termCollapsed";
|
||||
const FIRST_RUN_DONE_KEY: &str = "firstRunDone";
|
||||
const TASKBAR_SIGNAL_KEY: &str = "taskbarSignal";
|
||||
|
||||
/// The terminal pane's remembered shape: which edge it docks to, how much of
|
||||
/// the window it takes (a fraction, not collapsed or maximized), and whether
|
||||
/// it was left collapsed.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
|
||||
pub struct TermPanelSettings {
|
||||
pub dock: String,
|
||||
pub fraction: f64,
|
||||
pub collapsed: bool,
|
||||
}
|
||||
|
||||
pub const DEFAULT_TERM_DOCK: &str = "bottom";
|
||||
pub const DEFAULT_TERM_FRACTION: f64 = 0.25;
|
||||
const TERM_FRACTION_MIN: f64 = 0.05;
|
||||
const TERM_FRACTION_MAX: f64 = 0.9;
|
||||
|
||||
pub fn settings_file() -> Option<PathBuf> {
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("app.json"))
|
||||
}
|
||||
|
||||
fn read(file: &Path) -> serde_json::Map<String, serde_json::Value> {
|
||||
std::fs::read_to_string(file)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str(&text).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The agent id saved in `file` (built-in or custom). Whether it still
|
||||
/// resolves is the caller's check (`agents::find_agent`).
|
||||
pub fn load_last_agent(file: &Path) -> Option<String> {
|
||||
Some(read(file).get(LAST_AGENT_KEY)?.as_str()?.to_string()).filter(|id| !id.is_empty())
|
||||
}
|
||||
|
||||
/// Save the pick, keeping any other key the file holds.
|
||||
pub fn save_last_agent(file: &Path, id: &str) -> Result<(), String> {
|
||||
let mut settings = read(file);
|
||||
settings.insert(
|
||||
LAST_AGENT_KEY.to_string(),
|
||||
serde_json::Value::String(id.to_string()),
|
||||
);
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
/// The terminal pane's shape, from the file or the defaults. A dock other
|
||||
/// than `bottom` or `right`, or a fraction outside its range, is the default.
|
||||
pub fn load_term_panel(file: &Path) -> TermPanelSettings {
|
||||
let settings = read(file);
|
||||
let dock = settings
|
||||
.get(TERM_DOCK_KEY)
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|d| *d == "bottom" || *d == "right")
|
||||
.unwrap_or(DEFAULT_TERM_DOCK)
|
||||
.to_string();
|
||||
let fraction = settings
|
||||
.get(TERM_FRACTION_KEY)
|
||||
.and_then(|v| v.as_f64())
|
||||
.filter(|f| (TERM_FRACTION_MIN..=TERM_FRACTION_MAX).contains(f))
|
||||
.unwrap_or(DEFAULT_TERM_FRACTION);
|
||||
let collapsed = settings
|
||||
.get(TERM_COLLAPSED_KEY)
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
TermPanelSettings {
|
||||
dock,
|
||||
fraction,
|
||||
collapsed,
|
||||
}
|
||||
}
|
||||
|
||||
/// Save the terminal pane's shape, keeping any other key the file holds. An
|
||||
/// invalid dock or an out-of-range fraction is rejected rather than saved.
|
||||
pub fn save_term_panel(
|
||||
file: &Path,
|
||||
dock: &str,
|
||||
fraction: f64,
|
||||
collapsed: bool,
|
||||
) -> Result<(), String> {
|
||||
if dock != "bottom" && dock != "right" {
|
||||
return Err(format!("unknown dock: {dock}"));
|
||||
}
|
||||
if !(TERM_FRACTION_MIN..=TERM_FRACTION_MAX).contains(&fraction) {
|
||||
return Err(format!("fraction out of range: {fraction}"));
|
||||
}
|
||||
let mut settings = read(file);
|
||||
settings.insert(
|
||||
TERM_DOCK_KEY.to_string(),
|
||||
serde_json::Value::String(dock.to_string()),
|
||||
);
|
||||
settings.insert(
|
||||
TERM_FRACTION_KEY.to_string(),
|
||||
serde_json::Number::from_f64(fraction)
|
||||
.map(serde_json::Value::Number)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
);
|
||||
settings.insert(
|
||||
TERM_COLLAPSED_KEY.to_string(),
|
||||
serde_json::Value::Bool(collapsed),
|
||||
);
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
/// Whether the first-run checklist has already passed once. Once it has,
|
||||
/// later launches go straight to the launch card (Task 9.4).
|
||||
pub fn load_first_run_done(file: &Path) -> bool {
|
||||
read(file)
|
||||
.get(FIRST_RUN_DONE_KEY)
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Remember that the checklist passed, keeping any other key the file holds.
|
||||
pub fn save_first_run_done(file: &Path) -> Result<(), String> {
|
||||
let mut settings = read(file);
|
||||
settings.insert(
|
||||
FIRST_RUN_DONE_KEY.to_string(),
|
||||
serde_json::Value::Bool(true),
|
||||
);
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
/// Whether the taskbar entry shows when Plan2Code needs the person (the
|
||||
/// Desktop app switch in the console's User Preferences). On unless the file
|
||||
/// says `false`; anything but a boolean reads as on.
|
||||
pub fn load_taskbar_signal(file: &Path) -> bool {
|
||||
read(file)
|
||||
.get(TASKBAR_SIGNAL_KEY)
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Save the switch, keeping any other key the file holds.
|
||||
pub fn save_taskbar_signal(file: &Path, on: bool) -> Result<(), String> {
|
||||
let mut settings = read(file);
|
||||
settings.insert(TASKBAR_SIGNAL_KEY.to_string(), serde_json::Value::Bool(on));
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
fn write(file: &Path, settings: serde_json::Map<String, serde_json::Value>) -> Result<(), String> {
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&serde_json::Value::Object(settings))
|
||||
.map_err(|e| e.to_string())?;
|
||||
crate::loop_driver::write_atomic(file, &json)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_file(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-settings-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir.join("app.json")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_has_no_choice() {
|
||||
assert_eq!(load_last_agent(&temp_file("missing")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_choice_round_trips_and_other_keys_survive() {
|
||||
let file = temp_file("round-trip");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"other": 1}"#).unwrap();
|
||||
save_last_agent(&file, "devin").unwrap();
|
||||
assert_eq!(load_last_agent(&file), Some("devin".to_string()));
|
||||
save_last_agent(&file, "goose").unwrap();
|
||||
assert_eq!(
|
||||
load_last_agent(&file),
|
||||
Some("goose".to_string()),
|
||||
"a custom id round-trips"
|
||||
);
|
||||
assert!(std::fs::read_to_string(&file)
|
||||
.unwrap()
|
||||
.contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_id_is_returned_as_stored_and_the_caller_checks_it() {
|
||||
let file = temp_file("unknown");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"lastAgent": "nope"}"#).unwrap();
|
||||
assert_eq!(load_last_agent(&file), Some("nope".to_string()));
|
||||
assert!(crate::agents::find_agent_in("nope", None).is_none());
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_term_panel_defaults_to_bottom_at_a_quarter() {
|
||||
let want = TermPanelSettings {
|
||||
dock: "bottom".into(),
|
||||
fraction: 0.25,
|
||||
collapsed: false,
|
||||
};
|
||||
assert_eq!(load_term_panel(&temp_file("term-missing")), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_term_panel_round_trips_and_other_keys_survive() {
|
||||
let file = temp_file("term-round-trip");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"other": 1}"#).unwrap();
|
||||
save_term_panel(&file, "right", 0.4, true).unwrap();
|
||||
assert_eq!(
|
||||
load_term_panel(&file),
|
||||
TermPanelSettings {
|
||||
dock: "right".into(),
|
||||
fraction: 0.4,
|
||||
collapsed: true
|
||||
}
|
||||
);
|
||||
assert!(std::fs::read_to_string(&file)
|
||||
.unwrap()
|
||||
.contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_dock_or_an_out_of_range_fraction_is_refused() {
|
||||
let file = temp_file("term-bad-save");
|
||||
assert!(save_term_panel(&file, "top", 0.3, false).is_err());
|
||||
assert!(save_term_panel(&file, "bottom", 0.0, false).is_err());
|
||||
assert!(save_term_panel(&file, "bottom", 1.0, false).is_err());
|
||||
assert!(!file.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_run_is_not_done_until_it_is_saved() {
|
||||
let file = temp_file("first-run");
|
||||
assert!(!load_first_run_done(&file));
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"other": 1}"#).unwrap();
|
||||
save_first_run_done(&file).unwrap();
|
||||
assert!(load_first_run_done(&file));
|
||||
assert!(std::fs::read_to_string(&file)
|
||||
.unwrap()
|
||||
.contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_taskbar_signal_is_on_until_it_is_switched_off() {
|
||||
assert!(load_taskbar_signal(&temp_file("taskbar-missing")));
|
||||
let file = temp_file("taskbar");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"other": 1, "taskbarSignal": "no"}"#).unwrap();
|
||||
assert!(load_taskbar_signal(&file), "not a boolean reads as on");
|
||||
save_taskbar_signal(&file, false).unwrap();
|
||||
assert!(!load_taskbar_signal(&file));
|
||||
save_taskbar_signal(&file, true).unwrap();
|
||||
assert!(load_taskbar_signal(&file));
|
||||
assert!(std::fs::read_to_string(&file)
|
||||
.unwrap()
|
||||
.contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_dock_or_out_of_range_fraction_on_disk_reads_as_the_default() {
|
||||
let file = temp_file("term-bad-load");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"termDock": "top", "termFraction": 5}"#).unwrap();
|
||||
let loaded = load_term_panel(&file);
|
||||
assert_eq!(loaded.dock, "bottom");
|
||||
assert_eq!(loaded.fraction, 0.25);
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! The quit check's box on Windows, drawn with TaskDialog directly. The dialog
|
||||
//! plugin has no heading, always makes its first button the default, and
|
||||
//! leaves Windows to copy the body's icon into the title bar, so the same
|
||||
//! warning showed twice. Here the heading is the question, Stay is the default
|
||||
//! (Enter, Esc and the close button all keep the app open), and the title bar
|
||||
//! wears the app's own icon. The words come from quit_prompt.rs.
|
||||
|
||||
use crate::quit_prompt::{QuitCase, QuitPrompt};
|
||||
use std::ptr;
|
||||
use winapi::shared::basetsd::LONG_PTR;
|
||||
use winapi::shared::minwindef::{LPARAM, UINT, WPARAM};
|
||||
use winapi::shared::ntdef::HRESULT;
|
||||
use winapi::shared::windef::HWND;
|
||||
use winapi::shared::winerror::S_OK;
|
||||
use winapi::um::commctrl::{
|
||||
TaskDialogIndirect, TASKDIALOGCONFIG, TASKDIALOG_BUTTON, TDF_ALLOW_DIALOG_CANCELLATION,
|
||||
TDF_POSITION_RELATIVE_TO_WINDOW, TDN_CREATED, TD_INFORMATION_ICON, TD_WARNING_ICON,
|
||||
};
|
||||
use winapi::um::winuser::{
|
||||
GetClassLongPtrW, SendMessageW, GCLP_HICONSM, ICON_BIG, ICON_SMALL, ICON_SMALL2, WM_GETICON,
|
||||
WM_SETICON,
|
||||
};
|
||||
|
||||
const ID_QUIT: i32 = 100;
|
||||
const ID_STAY: i32 = 101;
|
||||
|
||||
fn wide(text: &str) -> Vec<u16> {
|
||||
text.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
|
||||
// Once the box exists, give its title bar the parent window's icon instead of
|
||||
// the copy of the body's icon Windows puts there.
|
||||
unsafe extern "system" fn on_event(
|
||||
hwnd: HWND,
|
||||
msg: UINT,
|
||||
_wparam: WPARAM,
|
||||
_lparam: LPARAM,
|
||||
parent: LONG_PTR,
|
||||
) -> HRESULT {
|
||||
if msg == TDN_CREATED {
|
||||
let parent = parent as HWND;
|
||||
let mut icon = SendMessageW(parent, WM_GETICON, ICON_SMALL2 as WPARAM, 0);
|
||||
if icon == 0 {
|
||||
icon = GetClassLongPtrW(parent, GCLP_HICONSM) as isize;
|
||||
}
|
||||
SendMessageW(hwnd, WM_SETICON, ICON_SMALL as WPARAM, icon);
|
||||
SendMessageW(hwnd, WM_SETICON, ICON_BIG as WPARAM, icon);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Shows the box over `parent` and blocks until it closes. True only when
|
||||
/// Quit was pressed; anything else (Stay, Esc, the close button, a failure to
|
||||
/// show the box) keeps the app open.
|
||||
pub fn ask(parent: HWND, prompt: &QuitPrompt) -> bool {
|
||||
let title = wide(&prompt.title);
|
||||
let heading = wide(&prompt.heading);
|
||||
let message = wide(&prompt.message);
|
||||
let quit = wide(&prompt.quit);
|
||||
let stay = wide(&prompt.stay);
|
||||
let buttons = [
|
||||
TASKDIALOG_BUTTON {
|
||||
nButtonID: ID_QUIT,
|
||||
pszButtonText: quit.as_ptr(),
|
||||
},
|
||||
TASKDIALOG_BUTTON {
|
||||
nButtonID: ID_STAY,
|
||||
pszButtonText: stay.as_ptr(),
|
||||
},
|
||||
];
|
||||
let icon = match prompt.case {
|
||||
QuitCase::Waiting => TD_INFORMATION_ICON,
|
||||
QuitCase::Working => TD_WARNING_ICON,
|
||||
};
|
||||
|
||||
// SAFETY: every pointer in the config points at a local above that
|
||||
// outlives the blocking TaskDialogIndirect call, and an all-zero
|
||||
// TASKDIALOGCONFIG is the documented "nothing set" for every other field.
|
||||
unsafe {
|
||||
let mut config: TASKDIALOGCONFIG = std::mem::zeroed();
|
||||
config.cbSize = std::mem::size_of::<TASKDIALOGCONFIG>() as UINT;
|
||||
config.hwndParent = parent;
|
||||
config.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW;
|
||||
config.pszWindowTitle = title.as_ptr();
|
||||
*config.u1.pszMainIcon_mut() = icon;
|
||||
config.pszMainInstruction = heading.as_ptr();
|
||||
config.pszContent = message.as_ptr();
|
||||
config.cButtons = buttons.len() as UINT;
|
||||
config.pButtons = buttons.as_ptr();
|
||||
config.nDefaultButton = ID_STAY;
|
||||
config.pfCallback = Some(on_event);
|
||||
config.lpCallbackData = parent as LONG_PTR;
|
||||
|
||||
let mut pressed = 0;
|
||||
let result = TaskDialogIndirect(&config, &mut pressed, ptr::null_mut(), ptr::null_mut());
|
||||
result == S_OK && pressed == ID_QUIT
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//! Whether the app and the installed skills are on the same Plan2Code version, and the
|
||||
//! one-click way to bring them level. The app's own version is the one in `tauri.conf.json`
|
||||
//! (Tauri reads it into the package info); the skills' version is the `version.json` the
|
||||
//! installer writes beside the launcher in `~/.plan2code/bin/` on every install and update.
|
||||
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
/// How long `run_update` lets the installer run before giving up on it.
|
||||
pub const UPDATE_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct VersionStatus {
|
||||
pub app: String,
|
||||
/// The installed skills' version, or none when it cannot be read.
|
||||
pub skills: Option<String>,
|
||||
/// True only when both are readable `X.Y.Z` versions and they differ: an unknown version is
|
||||
/// never a reason to nag.
|
||||
pub mismatch: bool,
|
||||
/// Only meaningful when `mismatch` is true: the skills are ahead of this app, so another
|
||||
/// Update skills run cannot fix it (a newer app is what is missing), as against the usual
|
||||
/// case of the skills sitting behind the app.
|
||||
pub skills_ahead: bool,
|
||||
}
|
||||
|
||||
/// `~/.plan2code/bin`, or `PLAN2CODE_LAUNCHER_DIR` when it is set (tests only, the same
|
||||
/// convention `PLAN2CODE_CONSOLE_HOME` and `PLAN2CODE_APP_AGENT_BIN` already use).
|
||||
pub(crate) fn launcher_dir() -> Option<PathBuf> {
|
||||
if let Ok(dir) = std::env::var("PLAN2CODE_LAUNCHER_DIR") {
|
||||
return Some(PathBuf::from(dir));
|
||||
}
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("bin"))
|
||||
}
|
||||
|
||||
/// `X.Y.Z` as three numbers; anything else (a pre-release tag, a missing part) is none.
|
||||
fn parse(version: &str) -> Option<(u64, u64, u64)> {
|
||||
let mut parts = version.trim().split('.');
|
||||
let triple = (
|
||||
parts.next()?.parse().ok()?,
|
||||
parts.next()?.parse().ok()?,
|
||||
parts.next()?.parse().ok()?,
|
||||
);
|
||||
parts.next().is_none().then_some(triple)
|
||||
}
|
||||
|
||||
/// The `version` field of a `version.json` file.
|
||||
pub fn version_in(file: &Path) -> Option<String> {
|
||||
let text = std::fs::read_to_string(file).ok()?;
|
||||
let json: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
json.get("version")?.as_str().map(str::to_string)
|
||||
}
|
||||
|
||||
/// The skills' version as the installer last wrote it.
|
||||
pub fn installed_skills_version() -> Option<String> {
|
||||
version_in(&launcher_dir()?.join("version.json"))
|
||||
}
|
||||
|
||||
pub fn status(app: &str, skills: Option<String>) -> VersionStatus {
|
||||
let (mismatch, skills_ahead) = match (parse(app), skills.as_deref().and_then(parse)) {
|
||||
(Some(a), Some(s)) => (a != s, s > a),
|
||||
_ => (false, false),
|
||||
};
|
||||
VersionStatus {
|
||||
app: app.to_string(),
|
||||
skills,
|
||||
mismatch,
|
||||
skills_ahead,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the existing installer's update (`plan2code update`, through the launcher's own copy),
|
||||
/// which brings the skills, the launcher and the app level. Pinned to the release tag `app_version`
|
||||
/// names, not `main`, so Update skills never pulls in work the app does not know about yet. Blocks
|
||||
/// until it ends or `UPDATE_TIMEOUT` passes, whichever comes first; the page asks for it with a
|
||||
/// click, never on its own. `on_line` is called with each line of output as it is produced, for a
|
||||
/// live progress readout. Returns the installer's last non-empty line on success.
|
||||
pub fn run_update(app_version: &str, on_line: impl FnMut(&str)) -> Result<String, String> {
|
||||
run_update_within(app_version, UPDATE_TIMEOUT, on_line)
|
||||
}
|
||||
|
||||
/// `run_update`, with the timeout as a parameter so a test can use a short one instead of
|
||||
/// `UPDATE_TIMEOUT`'s real five minutes.
|
||||
fn run_update_within(
|
||||
app_version: &str,
|
||||
timeout: Duration,
|
||||
mut on_line: impl FnMut(&str),
|
||||
) -> Result<String, String> {
|
||||
let launcher = launcher_dir()
|
||||
.ok_or("no home folder found")?
|
||||
.join("plan2code.js");
|
||||
if !launcher.is_file() {
|
||||
return Err(format!(
|
||||
"the plan2code command is not installed ({} is missing)",
|
||||
launcher.display()
|
||||
));
|
||||
}
|
||||
let mut command = Command::new("node");
|
||||
// A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's
|
||||
// directories (Task 9.9): the update script itself shells out to `npx`
|
||||
// and `git`, which need a PATH that finds them too.
|
||||
command.env("PATH", crate::node_check::resolved_path());
|
||||
command
|
||||
.arg(&launcher)
|
||||
.arg("update")
|
||||
.arg("--tag")
|
||||
.arg(format!("v{app_version}"))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW, as the console calls are
|
||||
}
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|e| format!("could not run node: {e}"))?;
|
||||
let stdout = child.stdout.take().ok_or("no stdout from the update")?;
|
||||
let stderr = child.stderr.take().ok_or("no stderr from the update")?;
|
||||
let (tx, rx) = mpsc::channel::<String>();
|
||||
let err_tx = tx.clone();
|
||||
let out_thread = std::thread::spawn(move || {
|
||||
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
|
||||
if tx.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let err_thread = std::thread::spawn(move || {
|
||||
for line in BufReader::new(stderr).lines().map_while(Result::ok) {
|
||||
if err_tx.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let deadline = Instant::now() + timeout;
|
||||
let poll = Duration::from_millis(200).min(timeout);
|
||||
let mut last_line = String::new();
|
||||
loop {
|
||||
match rx.recv_timeout(poll) {
|
||||
Ok(line) => {
|
||||
if !line.trim().is_empty() {
|
||||
last_line = line.clone();
|
||||
}
|
||||
on_line(&line);
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) if Instant::now() < deadline => continue,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(format!("the update timed out after {}s", timeout.as_secs()));
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
let _ = out_thread.join();
|
||||
let _ = err_thread.join();
|
||||
let status = child.wait().map_err(|e| e.to_string())?;
|
||||
if status.success() {
|
||||
Ok(last_line)
|
||||
} else {
|
||||
Err(format!("the update did not finish: {last_line}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_file(name: &str, content: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("p2c-versions-{}-{name}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("version.json");
|
||||
std::fs::write(&file, content).unwrap();
|
||||
file
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_versions_do_not_mismatch() {
|
||||
let s = status("3.0.0", Some("3.0.0".into()));
|
||||
assert_eq!(
|
||||
s,
|
||||
VersionStatus {
|
||||
app: "3.0.0".into(),
|
||||
skills: Some("3.0.0".into()),
|
||||
mismatch: false,
|
||||
skills_ahead: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_versions_mismatch_in_either_direction() {
|
||||
assert!(status("3.0.0", Some("2.11.0".into())).mismatch);
|
||||
assert!(status("3.0.0", Some("3.1.0".into())).mismatch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skills_ahead_names_which_direction_the_mismatch_runs() {
|
||||
assert!(!status("3.0.0", Some("2.11.0".into())).skills_ahead);
|
||||
assert!(status("3.0.0", Some("3.1.0".into())).skills_ahead);
|
||||
assert!(!status("3.0.0", Some("3.0.0".into())).skills_ahead);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_or_odd_version_never_mismatches() {
|
||||
assert!(!status("3.0.0", None).mismatch);
|
||||
assert!(!status("3.0.0", Some("3.0.0-beta".into())).mismatch);
|
||||
assert!(!status("3.0", Some("3.0.0".into())).mismatch);
|
||||
assert!(!status("3.0.0", Some("".into())).mismatch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_version_field_of_a_version_file() {
|
||||
let file = temp_file("ok", r#"{ "name": "Plan2Code", "version": "2.11.0" }"#);
|
||||
assert_eq!(version_in(&file).as_deref(), Some("2.11.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_broken_version_file_reads_as_none() {
|
||||
let missing = std::env::temp_dir()
|
||||
.join("p2c-versions-does-not-exist")
|
||||
.join("version.json");
|
||||
assert_eq!(version_in(&missing), None);
|
||||
assert_eq!(version_in(&temp_file("broken", "{ not json")), None);
|
||||
assert_eq!(version_in(&temp_file("nover", r#"{ "name": "x" }"#)), None);
|
||||
}
|
||||
|
||||
// `PLAN2CODE_LAUNCHER_DIR` is process-global, so these tests serialize on it.
|
||||
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Points `launcher_dir()` at a fresh folder holding a fake `plan2code.js` (plain Node
|
||||
/// source, no quoting needed), runs `body`, then restores the environment.
|
||||
fn with_fake_launcher<T>(name: &str, script: &str, body: impl FnOnce() -> T) -> T {
|
||||
let _guard = ENV_LOCK.lock().unwrap();
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"p2c-versions-launcher-{}-{name}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("plan2code.js"), script).unwrap();
|
||||
std::env::set_var("PLAN2CODE_LAUNCHER_DIR", &dir);
|
||||
let result = body();
|
||||
std::env::remove_var("PLAN2CODE_LAUNCHER_DIR");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_update_streams_lines_live_and_returns_the_last_one_on_success() {
|
||||
let lines = std::sync::Mutex::new(Vec::<String>::new());
|
||||
let result =
|
||||
with_fake_launcher("ok", "console.log('line1'); console.log('line2');", || {
|
||||
run_update_within("9.9.9", Duration::from_secs(60), |line| {
|
||||
lines.lock().unwrap().push(line.to_string())
|
||||
})
|
||||
});
|
||||
assert_eq!(result, Ok("line2".to_string()));
|
||||
assert_eq!(
|
||||
*lines.lock().unwrap(),
|
||||
vec!["line1".to_string(), "line2".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_update_pins_the_install_to_the_app_s_own_release_tag() {
|
||||
let result = with_fake_launcher(
|
||||
"tag",
|
||||
"console.log(process.argv.slice(2).join(' '));",
|
||||
|| run_update_within("9.9.9", Duration::from_secs(60), |_| {}),
|
||||
);
|
||||
assert_eq!(result, Ok("update --tag v9.9.9".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_update_fails_with_the_installer_s_own_last_line() {
|
||||
let result = with_fake_launcher("fail", "console.log('oops'); process.exit(1);", || {
|
||||
run_update_within("9.9.9", Duration::from_secs(60), |_| {})
|
||||
});
|
||||
assert_eq!(result, Err("the update did not finish: oops".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_update_gives_up_after_its_timeout_and_kills_the_child() {
|
||||
let result = with_fake_launcher("hang", "setInterval(() => {}, 1000);", || {
|
||||
run_update_within("9.9.9", Duration::from_millis(300), |_| {})
|
||||
});
|
||||
assert_eq!(result, Err("the update timed out after 0s".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_launcher_is_an_error_not_a_panic() {
|
||||
let result = with_fake_launcher("missing", "", || {
|
||||
std::fs::remove_file(launcher_dir().unwrap().join("plan2code.js")).unwrap();
|
||||
run_update_within("9.9.9", Duration::from_secs(60), |_| {})
|
||||
});
|
||||
assert!(result.unwrap_err().contains("is missing"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Plan2Code",
|
||||
"version": "3.0.0",
|
||||
"identifier": "com.plan2code.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../ui",
|
||||
"beforeDevCommand": "node scripts/vendor.mjs",
|
||||
"beforeBuildCommand": "node scripts/vendor.mjs"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "Plan2Code",
|
||||
"width": 1280,
|
||||
"height": 800,
|
||||
"maximized": true,
|
||||
"url": "index.html"
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src ipc: http://ipc.localhost; frame-src http://127.0.0.1:*; object-src 'none'; base-uri 'none'",
|
||||
"dangerousDisableAssetCspModification": ["style-src"]
|
||||
},
|
||||
"withGlobalTauri": true
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
//! The agent lifecycle against the fake agent in a real pseudo-terminal. Real
|
||||
//! agents are never started here: `PLAN2CODE_APP_AGENT_BIN` points every agent
|
||||
//! kind at the fake one.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{channel, Receiver, RecvTimeoutError};
|
||||
use std::sync::{Arc, Mutex, Once};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentSnapshot, AgentState};
|
||||
use plan2code_app_lib::agents::{
|
||||
agent_launch_spec, builtin_entry, parse_agents_file, Agent, PermissionMode, AGENT_BIN_ENV,
|
||||
};
|
||||
|
||||
mod common;
|
||||
use common::process_alive;
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(20);
|
||||
const READY: &str = "FAKE-AGENT ready";
|
||||
|
||||
struct Harness {
|
||||
manager: AgentManager,
|
||||
rx: Receiver<AgentEvent>,
|
||||
/// Everything the agents printed, in order.
|
||||
seen: String,
|
||||
/// Every state change, in order.
|
||||
states: Vec<AgentSnapshot>,
|
||||
/// How many of `states` `wait_state` has already looked at.
|
||||
cursor: usize,
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
fn new() -> Harness {
|
||||
static BIN: Once = Once::new();
|
||||
BIN.call_once(|| std::env::set_var(AGENT_BIN_ENV, common::fake_agent()));
|
||||
let (tx, rx) = channel();
|
||||
let tx = Mutex::new(tx);
|
||||
let sink = Arc::new(move |event| {
|
||||
let _ = tx.lock().unwrap().send(event);
|
||||
});
|
||||
Harness {
|
||||
manager: AgentManager::new(PathBuf::from("."), sink),
|
||||
rx,
|
||||
seen: String::new(),
|
||||
states: Vec::new(),
|
||||
cursor: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&mut self, event: AgentEvent) {
|
||||
match event {
|
||||
AgentEvent::Output(bytes) => {
|
||||
let text = String::from_utf8_lossy(&bytes).into_owned();
|
||||
// Windows' pseudo-terminal asks where the cursor is (ESC [ 6 n)
|
||||
// and holds the output until told, as xterm does on its own.
|
||||
for _ in text.matches("[6n") {
|
||||
self.manager.input(b"\x1b[1;1R").unwrap();
|
||||
}
|
||||
self.seen.push_str(&text);
|
||||
}
|
||||
AgentEvent::State(snapshot) => self.states.push(snapshot),
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle events for `how_long`, answering the terminal's questions.
|
||||
fn pump_for(&mut self, how_long: Duration) {
|
||||
let deadline = Instant::now() + how_long;
|
||||
loop {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
match self.rx.recv_timeout(left) {
|
||||
Ok(event) => self.take(event),
|
||||
Err(_) => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for_output(&mut self, needle: &str, times: usize) {
|
||||
let deadline = Instant::now() + TIMEOUT;
|
||||
while self.seen.matches(needle).count() < times {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
match self.rx.recv_timeout(left) {
|
||||
Ok(event) => self.take(event),
|
||||
Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => {
|
||||
panic!("never saw {needle:?} {times} time(s); got {:?}", self.seen)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next state change (after the last one this returned) that matches.
|
||||
fn wait_state(
|
||||
&mut self,
|
||||
what: &str,
|
||||
matches: impl Fn(&AgentSnapshot) -> bool,
|
||||
) -> AgentSnapshot {
|
||||
let deadline = Instant::now() + TIMEOUT;
|
||||
loop {
|
||||
while self.cursor < self.states.len() {
|
||||
let snapshot = self.states[self.cursor].clone();
|
||||
self.cursor += 1;
|
||||
if matches(&snapshot) {
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
match self.rx.recv_timeout(left) {
|
||||
Ok(event) => self.take(event),
|
||||
Err(_) => panic!("never saw the state {what}; got {:?}", self.states),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start_and_wait_ready(&mut self) {
|
||||
self.manager
|
||||
.start(
|
||||
Agent::Builtin(builtin_entry("claude").unwrap()),
|
||||
None,
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
None,
|
||||
)
|
||||
.expect("start the fake agent");
|
||||
self.wait_for_output(READY, 1);
|
||||
}
|
||||
|
||||
fn type_line(&self, line: &str) {
|
||||
self.manager.input(format!("{line}\r").as_bytes()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn is_running(snapshot: &AgentSnapshot) -> bool {
|
||||
snapshot.state == AgentState::Running
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_start_while_running_is_refused() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
let generation = h.manager.snapshot().generation;
|
||||
|
||||
let refused = h.manager.start(
|
||||
Agent::Builtin(builtin_entry("devin").unwrap()),
|
||||
None,
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
None,
|
||||
);
|
||||
assert!(refused.is_err(), "a second start must be refused");
|
||||
let after = h.manager.snapshot();
|
||||
assert_eq!(after.state, AgentState::Running);
|
||||
assert_eq!(
|
||||
after.generation, generation,
|
||||
"the running agent was replaced"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_keeps_the_previous_agent_kind_mode_model_and_effort() {
|
||||
let mut h = Harness::new();
|
||||
h.manager
|
||||
.start(
|
||||
Agent::Builtin(builtin_entry("codex").unwrap()),
|
||||
Some("gpt-5".to_string()),
|
||||
Some("high".to_string()),
|
||||
PermissionMode::Checked,
|
||||
None,
|
||||
)
|
||||
.expect("start the fake agent");
|
||||
h.wait_for_output(READY, 1);
|
||||
let before = h.manager.snapshot();
|
||||
assert_eq!(before.kind, Some("codex".to_string()));
|
||||
assert_eq!(before.mode, Some(PermissionMode::Checked));
|
||||
assert_eq!(
|
||||
h.manager.model_and_effort(),
|
||||
(Some("gpt-5".to_string()), Some("high".to_string()))
|
||||
);
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
let after = h.manager.snapshot();
|
||||
assert_eq!(
|
||||
after.kind,
|
||||
Some("codex".to_string()),
|
||||
"restart must keep the same agent"
|
||||
);
|
||||
assert_eq!(
|
||||
after.mode,
|
||||
Some(PermissionMode::Checked),
|
||||
"restart must keep the same permission mode"
|
||||
);
|
||||
assert_eq!(
|
||||
h.manager.model_and_effort(),
|
||||
(Some("gpt-5".to_string()), Some("high".to_string())),
|
||||
"restart must keep the same model and effort"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_between_steps_replaces_the_agent_at_once() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
let generation = h.manager.snapshot().generation;
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
|
||||
let now = h.manager.snapshot();
|
||||
assert_eq!(now.state, AgentState::Running);
|
||||
assert!(now.generation > generation, "a fresh agent was not started");
|
||||
h.wait_for_output(READY, 2);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_mid_step_kills_the_step_at_once_instead_of_waiting_for_it() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
h.type_line("STEP 30");
|
||||
h.wait_for_output("working 1/30", 1);
|
||||
|
||||
let started = Instant::now();
|
||||
h.manager.restart().unwrap();
|
||||
|
||||
// Running again straight away: no wait for the step to finish.
|
||||
h.wait_state("Running again", is_running);
|
||||
h.wait_for_output(READY, 2);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(5),
|
||||
"restart must not wait on the step; took {:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
assert!(
|
||||
!h.seen.contains("STEP DONE"),
|
||||
"the step should have been cut short, not finished"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_that_exits_by_itself_ends_with_its_code_and_nothing_restarts() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
h.type_line("EXIT 7");
|
||||
|
||||
let ended = h.wait_state("Ended", |s| matches!(s.state, AgentState::Ended { .. }));
|
||||
match &ended.state {
|
||||
AgentState::Ended { reason } => assert!(reason.contains('7'), "reason was {reason:?}"),
|
||||
other => panic!("expected Ended, got {other:?}"),
|
||||
}
|
||||
|
||||
// Nothing starts without a press.
|
||||
h.pump_for(Duration::from_millis(1500));
|
||||
assert!(matches!(
|
||||
h.manager.snapshot().state,
|
||||
AgentState::Ended { .. }
|
||||
));
|
||||
assert_eq!(
|
||||
h.seen.matches(READY).count(),
|
||||
1,
|
||||
"an agent started by itself"
|
||||
);
|
||||
assert!(!h.manager.is_active());
|
||||
|
||||
// A press of Restart starts a fresh one on the same brief.
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
assert_eq!(h.manager.snapshot().state, AgentState::Running);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quitting_with_a_running_agent_stops_it() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
assert!(h.manager.is_active());
|
||||
h.type_line("PID");
|
||||
h.wait_for_output("PID ", 1);
|
||||
let pid = h
|
||||
.seen
|
||||
.rsplit("PID ")
|
||||
.next()
|
||||
.unwrap()
|
||||
.trim_start()
|
||||
.split(|c: char| !c.is_ascii_digit())
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse::<u32>()
|
||||
.expect("the agent's pid");
|
||||
assert!(
|
||||
process_alive(pid),
|
||||
"the agent should be running before the stop"
|
||||
);
|
||||
|
||||
h.manager.stop();
|
||||
|
||||
assert!(!process_alive(pid), "the agent's process outlived stop()");
|
||||
|
||||
assert_eq!(h.manager.snapshot().state, AgentState::Idle);
|
||||
assert!(!h.manager.is_active());
|
||||
// The stopped agent does not come back or print again.
|
||||
let before = h.seen.len();
|
||||
h.pump_for(Duration::from_millis(1000));
|
||||
assert!(
|
||||
!h.seen[before..].contains(READY),
|
||||
"an agent started after the stop"
|
||||
);
|
||||
assert!(
|
||||
h.manager.restart().is_err(),
|
||||
"there is nothing left to restart"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_replay_buffer_holds_recent_output_and_clears_on_a_fresh_agent() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
let replay = String::from_utf8_lossy(&h.manager.replay()).into_owned();
|
||||
assert!(
|
||||
replay.contains(READY),
|
||||
"replay should hold what was just printed; got {replay:?}"
|
||||
);
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
let replay = String::from_utf8_lossy(&h.manager.replay()).into_owned();
|
||||
assert_eq!(
|
||||
replay.matches(READY).count(),
|
||||
1,
|
||||
"a fresh agent's replay must not carry the old one's output"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restart_runs_the_brief_hook_and_the_bar_gets_its_note() {
|
||||
let mut h = Harness::new();
|
||||
let runs = Arc::new(Mutex::new(0));
|
||||
let counter = Arc::clone(&runs);
|
||||
h.manager.set_before_fresh(Arc::new(move || {
|
||||
*counter.lock().unwrap() += 1;
|
||||
Some("Brief ready on the dashboard".to_string())
|
||||
}));
|
||||
h.start_and_wait_ready();
|
||||
assert_eq!(*runs.lock().unwrap(), 0, "a first start leaves no brief");
|
||||
assert_eq!(h.manager.snapshot().brief_note, None);
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
*runs.lock().unwrap(),
|
||||
1,
|
||||
"the restart did not run the brief once"
|
||||
);
|
||||
assert_eq!(
|
||||
h.manager.snapshot().brief_note.as_deref(),
|
||||
Some("Brief ready on the dashboard")
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_agent_gets_the_in_app_signal_and_a_restart_keeps_it() {
|
||||
let mut h = Harness::new();
|
||||
h.manager.set_env(vec![
|
||||
("PLAN2CODE_IN_APP".to_string(), "1".to_string()),
|
||||
(
|
||||
"PLAN2CODE_CONSOLE_SID".to_string(),
|
||||
"sid-window-a".to_string(),
|
||||
),
|
||||
]);
|
||||
h.start_and_wait_ready();
|
||||
h.type_line("ENV PLAN2CODE_IN_APP");
|
||||
h.wait_for_output("ENV PLAN2CODE_IN_APP=1", 1);
|
||||
h.type_line("ENV PLAN2CODE_CONSOLE_SID");
|
||||
h.wait_for_output("ENV PLAN2CODE_CONSOLE_SID=sid-window-a", 1);
|
||||
|
||||
// The signal changes with the console; a Restart starts on the newest.
|
||||
h.manager.set_env(vec![(
|
||||
"PLAN2CODE_CONSOLE_SID".to_string(),
|
||||
"sid-window-b".to_string(),
|
||||
)]);
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
h.type_line("ENV PLAN2CODE_CONSOLE_SID");
|
||||
h.wait_for_output("ENV PLAN2CODE_CONSOLE_SID=sid-window-b", 1);
|
||||
h.type_line("ENV PLAN2CODE_IN_APP");
|
||||
h.wait_for_output("ENV PLAN2CODE_IN_APP=\r", 1);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_with_no_signal_set_gets_none() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
h.type_line("ENV PLAN2CODE_IN_APP");
|
||||
h.wait_for_output("ENV PLAN2CODE_IN_APP=", 1);
|
||||
assert!(!h.seen.contains("ENV PLAN2CODE_IN_APP=1"));
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_agent_runs_the_override_too_and_restart_keeps_its_id() {
|
||||
let mut h = Harness::new();
|
||||
// Its command is nowhere on PATH: the override replaces it, as for a built-in.
|
||||
let (mut agents, warnings) = parse_agents_file(
|
||||
r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose-not-installed","bypassArgs":["--yes"]}]}"#,
|
||||
);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let goose = Agent::Custom(agents.remove(0));
|
||||
let spec = agent_launch_spec(
|
||||
&goose,
|
||||
&std::env::temp_dir(),
|
||||
Some("m"),
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
"/plan2code",
|
||||
);
|
||||
assert_eq!(PathBuf::from(&spec.program), common::fake_agent());
|
||||
assert!(spec.args.is_empty());
|
||||
h.manager
|
||||
.start(goose, None, None, PermissionMode::Checked, None)
|
||||
.expect("start the custom agent");
|
||||
h.wait_for_output(READY, 1);
|
||||
assert_eq!(h.manager.snapshot().kind, Some("goose".to_string()));
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
assert_eq!(
|
||||
h.manager.snapshot().kind,
|
||||
Some("goose".to_string()),
|
||||
"restart must keep the custom agent"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_start_runs_on_its_model_and_env_and_leaves_the_launch_choice_alone() {
|
||||
let mut h = Harness::new();
|
||||
h.manager
|
||||
.start(
|
||||
Agent::Builtin(builtin_entry("claude").unwrap()),
|
||||
Some("opus".to_string()),
|
||||
Some("high".to_string()),
|
||||
PermissionMode::Checked,
|
||||
None,
|
||||
)
|
||||
.expect("start the fake agent");
|
||||
h.wait_for_output(READY, 1);
|
||||
|
||||
h.manager
|
||||
.start_phase_on(
|
||||
"/plan2code phase".to_string(),
|
||||
"sonnet".to_string(),
|
||||
Some("low".to_string()),
|
||||
vec![("PLAN2CODE_LOOP_STRENGTH".to_string(), "thrifty".to_string())],
|
||||
)
|
||||
.expect("start the phase on its strength");
|
||||
h.wait_for_output(READY, 2);
|
||||
// The agent-bin override drops every argument, so the fake agent sees the
|
||||
// env only; the model is checked through the stored choice below.
|
||||
h.type_line("ENV PLAN2CODE_LOOP_STRENGTH");
|
||||
h.wait_for_output("ENV PLAN2CODE_LOOP_STRENGTH=thrifty", 1);
|
||||
|
||||
// The stored choice, kind and mode are what they were.
|
||||
let (kind, model, effort, mode) = h.manager.launch_choice().unwrap();
|
||||
assert_eq!(kind.id(), "claude");
|
||||
assert_eq!(model.as_deref(), Some("opus"));
|
||||
assert_eq!(effort.as_deref(), Some("high"));
|
||||
assert_eq!(mode, PermissionMode::Checked);
|
||||
|
||||
// The next plain start runs on the original choice, with no strength.
|
||||
h.manager
|
||||
.start_fresh("/plan2code next".to_string())
|
||||
.unwrap();
|
||||
h.wait_for_output(READY, 3);
|
||||
h.type_line("ENV PLAN2CODE_LOOP_STRENGTH");
|
||||
h.wait_for_output("ENV PLAN2CODE_LOOP_STRENGTH=\r", 1);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_start_with_no_launch_choice_is_refused() {
|
||||
let h = Harness::new();
|
||||
let refused = h
|
||||
.manager
|
||||
.start_phase_on("p".to_string(), "sonnet".to_string(), None, Vec::new());
|
||||
assert!(refused.is_err());
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Shared by the integration tests: where the fake agent program is, and
|
||||
//! whether a process id is still alive.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::sync::Once;
|
||||
|
||||
/// Is a process with this id still there? Asks the operating system.
|
||||
#[allow(dead_code)]
|
||||
pub fn process_alive(pid: u32) -> bool {
|
||||
if cfg!(windows) {
|
||||
let out = Command::new("tasklist")
|
||||
.args(["/FI", &format!("PID eq {pid}"), "/NH"])
|
||||
.output()
|
||||
.unwrap();
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.split_whitespace()
|
||||
.any(|word| word == pid.to_string())
|
||||
} else {
|
||||
Command::new("kill")
|
||||
.args(["-0", &pid.to_string()])
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fake_agent() -> PathBuf {
|
||||
// `cargo test` does not build another package's program, so build it once.
|
||||
static BUILD: Once = Once::new();
|
||||
BUILD.call_once(|| {
|
||||
let status = Command::new(env!("CARGO"))
|
||||
.args(["build", "-p", "fake-agent"])
|
||||
.status()
|
||||
.expect("run cargo");
|
||||
assert!(status.success(), "could not build the fake agent");
|
||||
});
|
||||
// The test binary is in target/<profile>/deps; the fake agent is one up.
|
||||
let exe = std::env::current_exe().unwrap();
|
||||
let path = exe
|
||||
.parent()
|
||||
.and_then(|deps| deps.parent())
|
||||
.unwrap()
|
||||
.join(format!("fake-agent{}", std::env::consts::EXE_SUFFIX));
|
||||
assert!(
|
||||
path.exists(),
|
||||
"{} is missing after building the fake agent",
|
||||
path.display()
|
||||
);
|
||||
path
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! The supervisor against the real console: a temp project, no agent, no
|
||||
//! Tauri. `PLAN2CODE_CONSOLE_DIR` points the lookup at the repo's own console
|
||||
//! source and `PLAN2CODE_CONSOLE_HOME` keeps the sessions out of the user's
|
||||
//! real console folder. Skipped entirely when node is not on PATH.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use plan2code_app_lib::console_supervisor::{app_origin, ConsoleSupervisor};
|
||||
|
||||
fn have_node() -> bool {
|
||||
Command::new("node")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn repo_console_dir() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console")
|
||||
}
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("p2c-sup-{name}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn setup() -> Option<PathBuf> {
|
||||
if !have_node() {
|
||||
eprintln!("skipping: node is not on PATH");
|
||||
return None;
|
||||
}
|
||||
let console = repo_console_dir();
|
||||
assert!(
|
||||
console.join("console.mjs").is_file(),
|
||||
"console source missing at {}",
|
||||
console.display()
|
||||
);
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console);
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_HOME", temp_dir("home"));
|
||||
std::env::set_var("PLAN2CODE_NO_BROWSER", "1");
|
||||
// Run inside the desktop app, the agent's in-app variables would have this
|
||||
// console announce itself to the live window and take it over.
|
||||
for name in [
|
||||
"PLAN2CODE_IN_APP",
|
||||
"PLAN2CODE_APP_ANNOUNCE",
|
||||
"PLAN2CODE_APP_TOKEN",
|
||||
"PLAN2CODE_CONSOLE_SID",
|
||||
] {
|
||||
std::env::remove_var(name);
|
||||
}
|
||||
Some(temp_dir("project"))
|
||||
}
|
||||
|
||||
fn kill_pid(pid: u32) {
|
||||
#[cfg(windows)]
|
||||
let _ = Command::new("taskkill")
|
||||
.args(["/PID", &pid.to_string(), "/F"])
|
||||
.output();
|
||||
#[cfg(not(windows))]
|
||||
let _ = Command::new("kill").args(["-9", &pid.to_string()]).output();
|
||||
}
|
||||
|
||||
/// The detached server can take a beat to bind or die; ask until `want` holds.
|
||||
fn until_health(sup: &ConsoleSupervisor, want: bool) -> bool {
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
while Instant::now() < deadline {
|
||||
if sup.health() == want {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starts_answers_and_stops() {
|
||||
let Some(project) = setup() else { return };
|
||||
let mut sup = ConsoleSupervisor::start(project, app_origin().to_string()).expect("start");
|
||||
assert!(!sup.session().sid.is_empty());
|
||||
assert!(sup.session().url.starts_with("http://127.0.0.1:"));
|
||||
assert!(sup.session().pid > 0);
|
||||
assert!(until_health(&sup, true), "the console URL never answered");
|
||||
|
||||
sup.stop().expect("stop");
|
||||
assert!(
|
||||
until_health(&sup, false),
|
||||
"the console still answered after stop()"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_killed_console_is_dead_and_restarts() {
|
||||
let Some(project) = setup() else { return };
|
||||
let mut sup = ConsoleSupervisor::start(project, app_origin().to_string()).expect("start");
|
||||
assert!(until_health(&sup, true), "the console URL never answered");
|
||||
let first_sid = sup.session().sid.clone();
|
||||
|
||||
kill_pid(sup.session().pid);
|
||||
assert!(
|
||||
until_health(&sup, false),
|
||||
"a killed console still looked alive"
|
||||
);
|
||||
|
||||
assert!(
|
||||
sup.restart_if_dead().expect("restart"),
|
||||
"restart_if_dead did nothing"
|
||||
);
|
||||
assert_eq!(
|
||||
sup.session().sid,
|
||||
first_sid,
|
||||
"a dead console comes back on the same session, so its page and place survive"
|
||||
);
|
||||
assert!(
|
||||
until_health(&sup, true),
|
||||
"the restarted console never answered"
|
||||
);
|
||||
sup.stop().expect("stop");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_live_console_is_not_restarted() {
|
||||
let Some(project) = setup() else { return };
|
||||
let mut sup = ConsoleSupervisor::start(project, app_origin().to_string()).expect("start");
|
||||
assert!(until_health(&sup, true), "the console URL never answered");
|
||||
assert!(!sup.restart_if_dead().expect("restart check"));
|
||||
sup.stop().expect("stop");
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! The PTY host against the fake agent in a real pseudo-terminal. Real agents
|
||||
//! are never started here.
|
||||
|
||||
use std::sync::mpsc::{channel, Receiver, RecvTimeoutError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use plan2code_app_lib::pty_host::{PtyHost, StartOptions};
|
||||
|
||||
mod common;
|
||||
use common::fake_agent;
|
||||
|
||||
fn start_fake() -> (PtyHost, Receiver<Vec<u8>>) {
|
||||
let (tx, rx) = channel();
|
||||
let host = PtyHost::start(
|
||||
StartOptions {
|
||||
program: fake_agent().to_string_lossy().into_owned(),
|
||||
args: vec![],
|
||||
env: vec![],
|
||||
cwd: None,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
},
|
||||
move |bytes| {
|
||||
let _ = tx.send(bytes);
|
||||
},
|
||||
)
|
||||
.expect("start the fake agent");
|
||||
(host, rx)
|
||||
}
|
||||
|
||||
/// Collect output until `needle` appears; panic with what arrived if it does not.
|
||||
/// Windows' pseudo-terminal asks where the cursor is (ESC [ 6 n) and holds the
|
||||
/// output until it is told, as a real terminal such as xterm does on its own.
|
||||
fn wait_for(host: &PtyHost, rx: &Receiver<Vec<u8>>, seen: &mut String, needle: &str) {
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
while !seen.contains(needle) {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
match rx.recv_timeout(left) {
|
||||
Ok(bytes) => {
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
for _ in text.matches("[6n") {
|
||||
host.write(b"[1;1R").unwrap();
|
||||
}
|
||||
seen.push_str(&text);
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => {
|
||||
panic!("never saw {needle:?}; got {seen:?}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn banner_arrives() {
|
||||
let (host, rx) = start_fake();
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready");
|
||||
host.kill().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_line_is_echoed() {
|
||||
let (host, rx) = start_fake();
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready");
|
||||
host.write(b"hello there\r").unwrap();
|
||||
wait_for(&host, &rx, &mut seen, "echo: hello there");
|
||||
host.kill().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_reaches_the_child() {
|
||||
let (host, rx) = start_fake();
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "SIZE 80x24");
|
||||
host.resize(100, 30).unwrap();
|
||||
wait_for(&host, &rx, &mut seen, "SIZE 100x30");
|
||||
host.kill().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_code_is_returned() {
|
||||
let (host, rx) = start_fake();
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready");
|
||||
host.write(b"EXIT 3\r").unwrap();
|
||||
assert_eq!(host.wait().unwrap(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kill_ends_a_running_step() {
|
||||
let (host, rx) = start_fake();
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready");
|
||||
host.write(b"STEP 30\r").unwrap();
|
||||
wait_for(&host, &rx, &mut seen, "working 1/30");
|
||||
let started = Instant::now();
|
||||
host.kill().unwrap();
|
||||
host.wait().unwrap();
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(10),
|
||||
"kill took too long"
|
||||
);
|
||||
}
|
||||
|
||||
/// An npm `.cmd` shim: `cmd.exe` is the directly spawned process, the real
|
||||
/// program (here, the fake agent) its grandchild. `kill` must end both, not
|
||||
/// just `cmd.exe` (Task 9.8).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn kill_ends_a_cmd_wrapped_grandchild_too() {
|
||||
use common::process_alive;
|
||||
use plan2code_app_lib::agents::windows_command;
|
||||
use std::fs;
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-pty-cmdshim-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let shim = dir.join("shim.cmd");
|
||||
fs::write(
|
||||
&shim,
|
||||
format!("@echo off\r\n\"{}\" %*\r\n", fake_agent().display()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let (program, args) = windows_command("shim", vec![], &dir.to_string_lossy());
|
||||
let path = format!(
|
||||
"{};{}",
|
||||
dir.to_string_lossy(),
|
||||
std::env::var("PATH").unwrap_or_default()
|
||||
);
|
||||
let (tx, rx) = channel();
|
||||
let host = PtyHost::start(
|
||||
// `cmd /c shim.cmd` is a bare name: like a real npm shim, cmd.exe
|
||||
// only finds it on PATH, never by the current directory alone.
|
||||
StartOptions {
|
||||
program,
|
||||
args,
|
||||
env: vec![("PATH".to_string(), path)],
|
||||
cwd: None,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
},
|
||||
move |bytes| {
|
||||
let _ = tx.send(bytes);
|
||||
},
|
||||
)
|
||||
.expect("start the cmd-wrapped fake agent");
|
||||
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready");
|
||||
host.write(b"PID\r").unwrap();
|
||||
wait_for(&host, &rx, &mut seen, "PID ");
|
||||
let pid: u32 = seen
|
||||
.rsplit("PID ")
|
||||
.next()
|
||||
.unwrap()
|
||||
.trim_start()
|
||||
.split(|c: char| !c.is_ascii_digit())
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("the grandchild's pid");
|
||||
assert!(
|
||||
process_alive(pid),
|
||||
"the grandchild should be running before kill"
|
||||
);
|
||||
|
||||
host.kill().unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while process_alive(pid) && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
assert!(!process_alive(pid), "the grandchild outlived kill()");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' ipc: http://ipc.localhost; frame-src http://127.0.0.1:*; object-src 'none'; base-uri 'none'">
|
||||
<title>Plan2Code</title>
|
||||
<link rel="stylesheet" href="vendor/xterm.css">
|
||||
<style>
|
||||
html, body { margin: 0; height: 100%; font-family: system-ui, sans-serif; background: #1e1e1e; color: #ddd; }
|
||||
body { display: flex; flex-direction: column; overflow: hidden; }
|
||||
|
||||
/* The console's dark tokens and its default highlight (Ocean). app.js sets
|
||||
the four accent ones to the person's own highlight once the console page
|
||||
says which it is, and keeps them for the next launch. */
|
||||
:root {
|
||||
--panel: #201d1a; --panel-2: #262220; --ink: #f0ece5; --ink-2: #b6afa3; --ink-3: #8b8376; --rule-2: #46403a;
|
||||
--accent: #619fe5; --accent-soft: #1a2533; --accent-ink: #0c1117; --accent-line: #3d5978;
|
||||
}
|
||||
|
||||
#bar { flex: none; border-bottom: 1px solid #444; }
|
||||
/* The console's top bar buttons (.btn small ghost), sized to this bar:
|
||||
quiet until hovered, then in the highlight color. New Session is the
|
||||
one that is often the next step, so it wears the highlight outline at
|
||||
rest, like the console's standby buttons. */
|
||||
#bar button {
|
||||
appearance: none; font: inherit; font-size: 12px; font-weight: 600; line-height: 1.2;
|
||||
padding: 4px 10px; border-radius: 8px; cursor: pointer;
|
||||
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink-2);
|
||||
transition: background 0.12s, border-color 0.12s, color 0.12s;
|
||||
}
|
||||
#bar button:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); background: var(--panel-2); }
|
||||
#bar button:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
#bar button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
#bar #agent-restart { background: transparent; border-color: var(--accent-line); color: var(--accent); }
|
||||
#bar #agent-restart:hover:not(:disabled) { background: var(--accent-soft); border-color: var(--accent); }
|
||||
#bar-row { height: 34px; flex: none; display: flex; align-items: center; gap: 10px; padding: 0 10px; font-size: 12px; white-space: nowrap; overflow-x: auto; overflow-y: hidden; }
|
||||
#bar [hidden] { display: none !important; }
|
||||
/* The project and agent menus' triggers: plain text until hovered, a
|
||||
caret saying there is more behind them. */
|
||||
#bar .bar-menu { display: inline-flex; align-items: center; gap: 6px; flex: none; border-color: transparent; background: transparent; color: var(--ink); padding: 4px 8px; }
|
||||
#bar .bar-menu:hover:not(:disabled), #bar .bar-menu[aria-expanded="true"] { background: var(--panel-2); border-color: transparent; color: var(--ink); }
|
||||
.bar-caret { color: var(--ink-3); font-size: 10px; }
|
||||
#project-name { max-width: 220px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.agent-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: #666; }
|
||||
.agent-dot.is-ok { background: #6a9955; }
|
||||
.agent-dot.is-warn { background: #d7ba7d; }
|
||||
#agent-ended { color: var(--ink-3); font-weight: 400; }
|
||||
#agent-bypass { flex: none; font-size: 11px; font-weight: 600; line-height: 1.3; padding: 0 7px; border-radius: 999px; border: 1px solid #d7ba7d; color: #d7ba7d; }
|
||||
#agent-none { color: var(--ink-3); }
|
||||
#agent-status { color: var(--ink-3); overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 320px; }
|
||||
#agent-status.is-error { color: #f48771; }
|
||||
/* The Implementation Loop, for as long as one runs: the loudest thing in the
|
||||
window on purpose. The accent says it is working; amber says it needs you. */
|
||||
#loop-banner {
|
||||
--banner-color: var(--accent); --banner-bg: var(--accent-soft); --banner-line: var(--accent-line);
|
||||
flex: none; display: flex; flex-wrap: wrap; align-items: center; gap: 8px 20px;
|
||||
padding: 10px 14px 10px 16px; font-size: 13px; color: var(--ink);
|
||||
background: var(--banner-bg); border-bottom: 1px solid var(--banner-line); box-shadow: inset 4px 0 0 var(--banner-color);
|
||||
}
|
||||
#loop-banner[hidden] { display: none; }
|
||||
#loop-banner[data-tone="waiting"] { --banner-color: #e5a93c; --banner-bg: #3a2b10; --banner-line: #7a5a1e; }
|
||||
#loop-now { flex: 1 1 320px; min-width: 0; display: grid; gap: 3px; }
|
||||
#loop-headline { display: flex; align-items: center; gap: 9px; }
|
||||
#loop-dot { flex: none; width: 10px; height: 10px; border-radius: 50%; background: var(--banner-color); animation: loop-pulse 1.8s ease-in-out infinite; }
|
||||
#loop-banner[data-tone="waiting"] #loop-dot { animation-duration: 0.9s; }
|
||||
@keyframes loop-pulse { 0%, 100% { box-shadow: 0 0 0 0 transparent; opacity: 1; } 50% { box-shadow: 0 0 0 5px color-mix(in srgb, var(--banner-color) 30%, transparent); opacity: 0.75; } }
|
||||
#loop-title { margin: 0; font-size: 15px; font-weight: 700; line-height: 1.25; }
|
||||
#loop-detail { margin: 0; color: var(--ink-2); overflow-wrap: anywhere; }
|
||||
#loop-progress { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; margin-top: 3px; color: var(--ink-3); font-size: 12px; }
|
||||
#loop-pips { display: flex; flex-wrap: wrap; gap: 3px; }
|
||||
.loop-pip { width: 16px; height: 5px; border-radius: 3px; background: var(--rule-2); }
|
||||
.loop-pip.done { background: var(--banner-color); }
|
||||
.loop-pip.current { background: var(--banner-color); animation: loop-pip 1.8s ease-in-out infinite; }
|
||||
@keyframes loop-pip { 50% { opacity: 0.4; } }
|
||||
#loop-spec { color: var(--ink-2); font-weight: 600; }
|
||||
#loop-elapsed { font-variant-numeric: tabular-nums; }
|
||||
#loop-retries { color: #f48771; }
|
||||
#loop-actions { flex: none; display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
#loop-actions button {
|
||||
appearance: none; font: inherit; font-size: 12.5px; font-weight: 600; line-height: 1.2;
|
||||
padding: 6px 12px; border-radius: 8px; cursor: pointer;
|
||||
border: 1px solid var(--banner-line); background: var(--panel); color: var(--ink);
|
||||
}
|
||||
#loop-actions button:hover:not(:disabled) { border-color: var(--banner-color); background: var(--panel-2); }
|
||||
#loop-actions button:disabled { cursor: default; opacity: 0.65; }
|
||||
#loop-actions button:focus-visible { outline: 2px solid var(--banner-color); outline-offset: 2px; }
|
||||
#loop-actions #loop-error { align-self: center; max-width: 320px; color: #f48771; font-size: 12.5px; overflow-wrap: anywhere; }
|
||||
#loop-actions [hidden] { display: none; }
|
||||
#loop-actions #loop-stop-now { color: #f48771; }
|
||||
#loop-actions #loop-stop-now:hover:not(:disabled) { border-color: #f48771; }
|
||||
@media (prefers-reduced-motion: reduce) { #loop-dot, .loop-pip.current { animation: none; } }
|
||||
#bar-grow { flex: 1; min-width: 0; }
|
||||
/* The one next step for the console or the skills, at the right end. */
|
||||
#next-step { display: flex; align-items: center; gap: 8px; flex: none; }
|
||||
#next-step-text { overflow: hidden; text-overflow: ellipsis; max-width: 320px; }
|
||||
#next-step-text.is-ok { color: #6a9955; }
|
||||
#next-step-text.is-warn { color: #d7ba7d; }
|
||||
#next-step-text.is-err { color: #f48771; }
|
||||
#next-step-text.is-busy::before {
|
||||
content: ""; display: inline-block; width: 8px; height: 8px; margin-right: 6px; vertical-align: -1px;
|
||||
border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: bar-spin 0.8s linear infinite;
|
||||
}
|
||||
@keyframes bar-spin { to { transform: rotate(360deg); } }
|
||||
#bar #next-step-button { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
#bar #next-step-button:hover:not(:disabled) { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); filter: brightness(1.12); }
|
||||
#next-step-more { color: var(--ink-3); font-size: 11px; border-bottom: 1px dotted var(--ink-3); cursor: help; }
|
||||
/* The menus sit outside the scrolling row (fixed, placed under their
|
||||
trigger by app.js), so the row's overflow never clips them. */
|
||||
.bar-dropdown {
|
||||
position: fixed; z-index: 20; min-width: 240px; max-width: 380px; padding: 6px; box-sizing: border-box;
|
||||
font-size: 12px; background: var(--panel); border: 1px solid var(--rule-2); border-radius: 8px; box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
.bar-dropdown-head { margin: 0; padding: 4px 8px 8px; color: var(--ink-3); line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.bar-dropdown-head b { color: var(--ink); font-weight: 600; }
|
||||
.bar-dropdown-head .is-warn { color: #d7ba7d; }
|
||||
#bar .bar-dropdown button {
|
||||
display: block; width: 100%; text-align: left; font-weight: 400; padding: 6px 8px; border: 0; border-radius: 6px;
|
||||
background: transparent; color: var(--ink);
|
||||
}
|
||||
#bar .bar-dropdown button:hover:not(:disabled), #bar .bar-dropdown button:focus-visible { background: var(--panel-2); color: var(--accent); }
|
||||
|
||||
#workspace { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
#workspace.dock-right { flex-direction: row; }
|
||||
|
||||
#dashboard { flex: 1; min-height: 0; min-width: 0; position: relative; }
|
||||
/* An Activities game in full screen: the console's frame over the whole
|
||||
window, the bar and the terminal left as they are underneath. */
|
||||
body.console-full #console-frame { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 1000; }
|
||||
#console-frame { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: #1e1e1e; }
|
||||
#dashboard-state { position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; background: #1e1e1e; text-align: center; padding: 16px; box-sizing: border-box; }
|
||||
#dashboard-state[hidden] { display: none; }
|
||||
#dashboard-state-text { margin: 0; max-width: 60ch; overflow-wrap: anywhere; color: #bbb; }
|
||||
#dashboard-state-planny[hidden] { display: none; }
|
||||
/* Drawn and colored like the console's own Planny (styles/planny.css):
|
||||
an outlined shell, the star eye, a lip of a smile, round hands. */
|
||||
#dashboard-state-planny { width: 104px; height: auto; overflow: visible; }
|
||||
#dashboard-state-planny :is(.ps-shell, .ps-smile, .ps-arm path, .ps-mug, .ps-handle) {
|
||||
fill: none; stroke: var(--ink-2); stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round;
|
||||
}
|
||||
#dashboard-state-planny .ps-shell { fill: var(--panel-2); }
|
||||
#dashboard-state-planny .ps-smile { stroke-width: 0.9; }
|
||||
#dashboard-state-planny .ps-arm path { stroke-width: 1.2; }
|
||||
#dashboard-state-planny :is(.ps-arm circle, .ps-foot) { fill: var(--ink-2); stroke: none; }
|
||||
#dashboard-state-planny .ps-eye { fill: var(--ink); }
|
||||
#dashboard-state-planny .ps-mug { fill: var(--panel-2); stroke-width: 1; }
|
||||
#dashboard-state-planny .ps-handle { stroke-width: 0.9; }
|
||||
#dashboard-state-planny .ps-coffee { fill: #9a6b47; }
|
||||
#dashboard-state-planny .ps-steam path {
|
||||
fill: none; stroke: var(--ink-3); stroke-width: 0.7; stroke-linecap: round;
|
||||
animation: ps-steam 2.4s ease-in-out infinite; opacity: 0;
|
||||
}
|
||||
#dashboard-state-planny .ps-steam path:nth-child(2) { animation-delay: 0.8s; }
|
||||
#dashboard-state-planny .ps-steam path:nth-child(3) { animation-delay: 1.6s; }
|
||||
@keyframes ps-steam {
|
||||
0% { opacity: 0; transform: translateY(1px); }
|
||||
35% { opacity: 0.9; }
|
||||
100% { opacity: 0; transform: translateY(-2.4px); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
#dashboard-state-planny .ps-steam path { animation: none; opacity: 0.8; }
|
||||
}
|
||||
/* The console's buttons (.btn, with .primary for the way forward): the
|
||||
one action wears the highlight, Cancel is a plain button. */
|
||||
#dashboard-state-actions { display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; }
|
||||
#dashboard-state-actions button {
|
||||
appearance: none; font: inherit; font-size: 13.5px; font-weight: 600; line-height: 1.2;
|
||||
padding: 7px 13px; border-radius: 8px; cursor: pointer;
|
||||
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink);
|
||||
transition: filter 0.12s, background 0.12s;
|
||||
}
|
||||
#dashboard-state-actions button:hover { background: var(--panel-2); }
|
||||
#dashboard-state-actions button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
#dashboard-state-actions #dashboard-state-button { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
#dashboard-state-actions #dashboard-state-button:hover { background: var(--accent); filter: brightness(1.08); }
|
||||
#dashboard-state-actions button[hidden] { display: none; }
|
||||
|
||||
#launch-card {
|
||||
position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column;
|
||||
align-items: stretch; justify-content: center; gap: 10px; background: #1e1e1e;
|
||||
padding: 24px; box-sizing: border-box; width: min(360px, 100%); margin: 0 auto;
|
||||
}
|
||||
#launch-card[hidden] { display: none; }
|
||||
#launch-card h2 { margin: 0 0 6px; font-size: 17px; text-align: center; }
|
||||
#launch-card label { font-size: 12px; color: #9ab; }
|
||||
#launch-card select, #launch-card input[type="text"] {
|
||||
width: 100%; box-sizing: border-box; margin: 4px 0 2px; padding: 6px 8px;
|
||||
background: #2a2a2a; color: #ddd; border: 1px solid #555; border-radius: 4px; font: inherit;
|
||||
}
|
||||
#launch-missing { margin: 0; font-size: 12px; color: #d7ba7d; }
|
||||
#launch-notice { margin: 0; font-size: 12px; color: #9ab; }
|
||||
#launch-notice[hidden] { display: none; }
|
||||
/* Set up an agent, shown wherever the app says "no agent". */
|
||||
.setup-agent-btn { font: inherit; font-size: 12px; margin-top: 4px; padding: 3px 10px; cursor: pointer;
|
||||
background: var(--accent); color: var(--accent-ink); border: 1px solid var(--accent); border-radius: 4px; }
|
||||
/* The way out of the setup page, over its frame. */
|
||||
#setup-close { position: absolute; top: 10px; right: 10px; z-index: 2; font: inherit; font-size: 12px;
|
||||
padding: 4px 10px; border-radius: 6px; cursor: pointer; border: 1px solid var(--rule-2);
|
||||
background: var(--panel); color: var(--ink); }
|
||||
#setup-close:hover { background: var(--panel-2); }
|
||||
#setup-close[hidden] { display: none; }
|
||||
#launch-missing code { color: #ddd; }
|
||||
#launch-agents-warning { margin: 0; font-size: 12px; color: #d7ba7d; white-space: pre-line; }
|
||||
#launch-agents-warning[hidden] { display: none; }
|
||||
.agent-explainer { margin: 0; font-size: 12px; line-height: 1.5; }
|
||||
.agent-explainer ul { margin: 4px 0; padding-left: 18px; }
|
||||
.agent-explainer code { color: #ddd; }
|
||||
.agent-explainer button, #launch-missing button { font: inherit; font-size: 12px; margin-left: 6px; padding: 1px 8px; cursor: pointer; }
|
||||
.agent-explainer .agent-link, #launch-missing .agent-link { background: none; border: 0; padding: 0; color: #75beff; text-decoration: underline; }
|
||||
#launch-effort-row[hidden], #launch-model-row[hidden] { display: none; }
|
||||
#launch-bypass-row { display: flex; align-items: center; gap: 8px; color: #ccc; font-size: 13px; cursor: pointer; }
|
||||
#launch-bypass-row input { margin: 0; }
|
||||
#launch-bypass-warning { margin: 0; font-size: 12px; color: #d7ba7d; }
|
||||
#launch-bypass-warning[hidden] { display: none; }
|
||||
#launch-start {
|
||||
margin-top: 6px; padding: 8px; background: #2d6a4f; color: #fff; border: 0; border-radius: 4px;
|
||||
font: inherit; font-weight: 600; cursor: pointer;
|
||||
}
|
||||
#launch-start:hover { background: #357a5c; }
|
||||
#launch-start:disabled { background: #444; color: #888; cursor: not-allowed; }
|
||||
|
||||
#first-run {
|
||||
position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column;
|
||||
align-items: stretch; justify-content: center; gap: 14px; background: #1e1e1e;
|
||||
padding: 24px; box-sizing: border-box; width: min(420px, 100%); margin: 0 auto;
|
||||
}
|
||||
#first-run[hidden] { display: none; }
|
||||
#first-run h2 { margin: 0; font-size: 17px; text-align: center; }
|
||||
#first-run-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.first-run-row { display: flex; align-items: flex-start; gap: 8px; font-size: 13px; }
|
||||
.first-run-mark { flex: none; width: 16px; text-align: center; font-weight: 700; }
|
||||
.first-run-row.is-pass .first-run-mark { color: #6a9955; }
|
||||
.first-run-row.is-fail .first-run-mark { color: #d7ba7d; }
|
||||
.first-run-body { flex: 1; min-width: 0; }
|
||||
.first-run-title { color: #ddd; }
|
||||
.first-run-detail { color: #9ab; font-size: 12px; margin-top: 2px; }
|
||||
.first-run-detail code { color: #ddd; }
|
||||
.first-run-row button {
|
||||
margin-top: 4px; background: none; border: 1px solid #555; color: #ccc; border-radius: 3px;
|
||||
font: inherit; font-size: 12px; padding: 3px 8px; cursor: pointer;
|
||||
}
|
||||
.first-run-row button:hover { background: #333; }
|
||||
#first-run-start {
|
||||
margin-top: 6px; padding: 8px; background: #2d6a4f; color: #fff; border: 0; border-radius: 4px;
|
||||
font: inherit; font-weight: 600; cursor: pointer;
|
||||
}
|
||||
#first-run-start:hover { background: #357a5c; }
|
||||
#first-run-start:disabled { background: #444; color: #888; cursor: not-allowed; }
|
||||
|
||||
#term-handle { flex: none; background: #2a2a2a; }
|
||||
#term-handle:hover { background: #3d3d3d; }
|
||||
#term-handle[hidden] { display: none; }
|
||||
#workspace:not(.dock-right) #term-handle { height: 6px; cursor: row-resize; }
|
||||
#workspace.dock-right #term-handle { width: 6px; cursor: col-resize; }
|
||||
|
||||
#term-panel { flex: none; display: flex; flex-direction: column; min-height: 0; min-width: 0; }
|
||||
#workspace:not(.dock-right) #term-panel { border-top: 1px solid #444; }
|
||||
#workspace.dock-right #term-panel { border-left: 1px solid #444; }
|
||||
#term-panel.collapsed { height: 28px !important; }
|
||||
#workspace.dock-right #term-panel.collapsed { width: 28px !important; height: auto !important; }
|
||||
#term-panel.collapsed #term { display: none; }
|
||||
#term-toolbar { flex: none; display: flex; align-items: center; gap: 6px; padding: 3px 6px; background: #252525; font-size: 11px; }
|
||||
#workspace.dock-right #term-toolbar { flex-direction: column; align-items: stretch; }
|
||||
#term-toolbar-spacer { flex: 1; min-height: 0; }
|
||||
#term-toolbar button {
|
||||
background: none; border: 1px solid #555; color: #ccc; border-radius: 3px;
|
||||
font-size: 11px; padding: 2px 6px; cursor: pointer; font-family: inherit;
|
||||
}
|
||||
#term-toolbar button:hover { background: #333; }
|
||||
#term-toolbar button[aria-pressed="true"] { color: #fff; border-color: #888; }
|
||||
#term-panel.collapsed #term-dock, #term-panel.collapsed #term-maximize { display: none; }
|
||||
/* Docked right and collapsed, the panel is a 28px-wide strip: "View Agent
|
||||
Terminal" does not fit sideways, so it reads top-to-bottom instead, rotated the
|
||||
same way a reader would turn the panel to read it. */
|
||||
#workspace.dock-right #term-panel.collapsed #term-toolbar { padding: 6px 2px; align-items: center; }
|
||||
#workspace.dock-right #term-panel.collapsed #term-collapse {
|
||||
writing-mode: vertical-rl; text-orientation: mixed; padding: 6px 2px;
|
||||
}
|
||||
#term-badge { color: #d7ba7d; font-size: 14px; line-height: 1; }
|
||||
#term-badge[hidden] { display: none; }
|
||||
#term { flex: 1; min-height: 0; min-width: 0; padding: 4px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header id="bar">
|
||||
<div id="bar-row">
|
||||
<button id="project-menu-button" class="bar-menu" aria-haspopup="menu" aria-expanded="false" aria-controls="project-menu" hidden><span id="project-name"></span><span class="bar-caret" aria-hidden="true">▾</span></button>
|
||||
<!-- Whenever an agent exists, running or ended, just left of its menu. -->
|
||||
<button id="agent-restart" hidden>New Session</button>
|
||||
<button id="agent-menu-button" class="bar-menu" aria-haspopup="menu" aria-expanded="false" aria-controls="agent-menu" hidden><span id="agent-dot" class="agent-dot" aria-hidden="true"></span><span id="agent-name"></span><span id="agent-ended" hidden>ended</span><span id="agent-bypass" title="Permission checks are off: the agent runs commands and changes files without asking" hidden>checks off</span><span class="bar-caret" aria-hidden="true">▾</span></button>
|
||||
<span id="agent-none">No agent</span>
|
||||
<span id="agent-status" role="status"></span>
|
||||
<span id="bar-grow"></span>
|
||||
<!-- The console's or the skills' one next step (meter.js barNextSteps), when there is one. -->
|
||||
<span id="next-step" role="status" hidden>
|
||||
<span id="next-step-text"></span>
|
||||
<button id="next-step-button" hidden></button>
|
||||
<span id="next-step-more" hidden></span>
|
||||
</span>
|
||||
</div>
|
||||
<div id="project-menu" class="bar-dropdown" role="menu" aria-label="Project" hidden>
|
||||
<p class="bar-dropdown-head">Project<br><b id="project-path"></b></p>
|
||||
<button id="change-project" role="menuitem">Change project...</button>
|
||||
</div>
|
||||
<div id="agent-menu" class="bar-dropdown" role="menu" aria-label="Agent" hidden>
|
||||
<p id="agent-menu-head" class="bar-dropdown-head"></p>
|
||||
<button id="change-agent" role="menuitem" hidden>Change agent...</button>
|
||||
</div>
|
||||
</header>
|
||||
<!-- The Implementation Loop, while one runs (app.js loop-state, meter.js loopBanner). -->
|
||||
<section id="loop-banner" aria-label="Implementation Loop" hidden>
|
||||
<div id="loop-now">
|
||||
<div role="status" aria-live="polite">
|
||||
<div id="loop-headline"><span id="loop-dot" aria-hidden="true"></span><p id="loop-title"></p></div>
|
||||
<p id="loop-detail"></p>
|
||||
</div>
|
||||
<div id="loop-progress">
|
||||
<span id="loop-pips" aria-hidden="true"></span>
|
||||
<span id="loop-spec"></span>
|
||||
<span id="loop-elapsed"></span>
|
||||
<span id="loop-retries" hidden></span>
|
||||
<span id="loop-hint"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="loop-actions">
|
||||
<button id="loop-stop-after" type="button">Stop after this phase</button>
|
||||
<button id="loop-stop-now" type="button">Stop now</button>
|
||||
<span id="loop-error" role="alert" hidden></span>
|
||||
<button id="loop-retry" type="button" hidden>Retry</button>
|
||||
</div>
|
||||
</section>
|
||||
<div id="workspace">
|
||||
<main id="dashboard">
|
||||
<iframe id="console-frame" title="Plan2Code console dashboard" allow="clipboard-write"></iframe>
|
||||
<button id="setup-close" type="button" hidden>Back</button>
|
||||
<div id="dashboard-state" hidden>
|
||||
<!-- Planny on a coffee break: shown only before a New Session press,
|
||||
the one state here that is a question rather than a status. The
|
||||
console's own Planny (shell, star eye, smile, feet, resting left
|
||||
arm) with the right arm reaching out to a steaming mug. -->
|
||||
<svg id="dashboard-state-planny" viewBox="0 7 29 23" aria-hidden="true" focusable="false" hidden>
|
||||
<rect class="ps-foot" x="5.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
|
||||
<rect class="ps-foot" x="12.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
|
||||
<rect class="ps-shell" x="3" y="7" width="16" height="20" rx="3.2" />
|
||||
<path class="ps-eye" d="M11 10.95 L11.79 12.91 L13.9 13.06 L12.28 14.42 L12.79 16.47 L11 15.35 L9.21 16.47 L9.72 14.42 L8.1 13.06 L10.21 12.91 Z" />
|
||||
<path class="ps-smile" d="M8.3 18.4 Q11 21 13.7 18.4" />
|
||||
<g class="ps-arm"><path d="M3 18 L1.3 21" /><circle cx="1.3" cy="21" r="0.85" /></g>
|
||||
<g class="ps-steam">
|
||||
<path d="M23 17.3 q-0.6 -0.9 0 -1.8 t0 -1.8" />
|
||||
<path d="M24.4 17.1 q0.6 -0.9 0 -1.8 t0 -1.8" />
|
||||
<path d="M25.8 17.3 q-0.6 -0.9 0 -1.8 t0 -1.8" />
|
||||
</g>
|
||||
<g class="ps-arm"><path d="M19 18 L21.6 20.6" /><circle cx="21.6" cy="20.6" r="0.85" /></g>
|
||||
<path class="ps-handle" d="M26.7 19.6 h0.3 a1.15 1.15 0 0 1 0 2.3 h-0.3" />
|
||||
<rect class="ps-mug" x="22.4" y="18.4" width="4.3" height="4.6" rx="0.8" />
|
||||
<rect class="ps-coffee" x="23" y="19" width="3.1" height="0.8" rx="0.35" />
|
||||
</svg>
|
||||
<p id="dashboard-state-text"></p>
|
||||
<span id="dashboard-state-actions">
|
||||
<button id="dashboard-state-button" hidden></button>
|
||||
<button id="dashboard-state-cancel" hidden>Cancel</button>
|
||||
</span>
|
||||
</div>
|
||||
<div id="first-run" hidden>
|
||||
<h2>Before you start</h2>
|
||||
<ul id="first-run-list"></ul>
|
||||
<button id="first-run-start" type="button" disabled>Start</button>
|
||||
</div>
|
||||
<form id="launch-card" hidden>
|
||||
<h2>Start an agent</h2>
|
||||
<label for="launch-agent">Agent</label>
|
||||
<select id="launch-agent">
|
||||
<option value="claude">Claude Code</option>
|
||||
<option value="devin">Devin</option>
|
||||
<option value="codex">Codex</option>
|
||||
</select>
|
||||
<p id="launch-notice" hidden></p>
|
||||
<p id="launch-missing" hidden></p>
|
||||
<p id="launch-agents-warning" hidden></p>
|
||||
<div id="launch-model-row">
|
||||
<label for="launch-model">Model</label>
|
||||
<select id="launch-model"></select>
|
||||
</div>
|
||||
<div id="launch-effort-row">
|
||||
<label for="launch-effort">Effort</label>
|
||||
<select id="launch-effort"></select>
|
||||
</div>
|
||||
<label id="launch-bypass-row">
|
||||
<input id="launch-bypass" type="checkbox" checked>
|
||||
Turn permission checks off for this agent
|
||||
</label>
|
||||
<p id="launch-bypass-warning">Permission checks will be off: the agent can run commands and change files without asking first.</p>
|
||||
<button id="launch-start" type="submit">Start agent</button>
|
||||
</form>
|
||||
</main>
|
||||
<div id="term-handle" title="Drag to resize the terminal panel"></div>
|
||||
<section id="term-panel">
|
||||
<div id="term-toolbar">
|
||||
<span id="term-badge" title="The agent has been quiet a while" hidden>●</span>
|
||||
<span id="term-toolbar-spacer"></span>
|
||||
<button id="term-dock" type="button">Dock right</button>
|
||||
<button id="term-maximize" type="button" aria-pressed="false">Maximize</button>
|
||||
<button id="term-collapse" type="button" aria-pressed="false">Collapse</button>
|
||||
</div>
|
||||
<div id="term"></div>
|
||||
</section>
|
||||
</div>
|
||||
<script src="vendor/xterm.js"></script>
|
||||
<script src="vendor/addon-fit.js"></script>
|
||||
<script type="module" src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||