Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2b43d1188 | ||
|
|
94063fc0a9 | ||
|
|
3e22d53bf5 | ||
|
|
7a9f56a452 | ||
|
|
37f2735294 | ||
|
|
1d146cce6f | ||
|
|
5f91fb665f | ||
|
|
4d05b4f6f6 | ||
|
|
3155298fea | ||
|
|
a4644d533b | ||
|
|
b73a4cebe7 | ||
|
|
efc96e91c2 | ||
|
|
442904e6f2 | ||
|
|
c1f41e4a82 | ||
|
|
72043e20fc | ||
|
|
bdc4decbb4 | ||
|
|
cb6468577d | ||
|
|
0de630603b | ||
|
|
26013db54f | ||
|
|
e00769b56a | ||
|
|
a5a3a81c5f | ||
|
|
681c4a4b85 | ||
|
|
7a4b7c6db8 | ||
|
|
086c735c65 | ||
|
|
d4adb53a3a | ||
|
|
2075d235d8 | ||
|
|
452d8e3895 | ||
|
|
d32925cccf | ||
|
|
f8b54ef708 | ||
|
|
124beb46db | ||
|
|
1121157938 | ||
|
|
e3aba0a637 | ||
|
|
3edb4468a8 | ||
|
|
699a827cae | ||
|
|
765e374584 | ||
|
|
2ab57d9a7e | ||
|
|
17dffac1ea | ||
|
|
36843e4bc9 | ||
|
|
33a0dbd34a | ||
|
|
80ae3decdd | ||
|
|
caef9a0ee3 | ||
|
|
72c827dddf | ||
|
|
498e09bb15 | ||
|
|
68d1f82a2e | ||
|
|
fdf43b197f | ||
|
|
7e2c824d4f | ||
|
|
8890c3ad13 | ||
|
|
f328406bb5 | ||
|
|
6114914dd6 | ||
|
|
4932ad4162 | ||
|
|
a3b117dafc | ||
|
|
3469a74cc1 | ||
|
|
b639c8945d | ||
|
|
9cd39f6ce8 | ||
|
|
d4cfd32c9a | ||
|
|
8215b7a9c5 | ||
|
|
3dfd44ba88 | ||
|
|
3414a19ce6 | ||
|
|
50a78a6917 | ||
|
|
1877ca1fa7 | ||
|
|
57bda29db8 | ||
|
|
3343762c70 | ||
|
|
342da7c353 | ||
|
|
da105160a8 | ||
|
|
977e462e76 | ||
|
|
57134cf36e | ||
|
|
c19a072a3a | ||
|
|
cd8a1be568 | ||
|
|
f968aeded8 | ||
|
|
fb71a02756 | ||
|
|
c8e65f12a6 | ||
|
|
739e56c5cf | ||
|
|
ade74cd636 | ||
|
|
48830c1afb | ||
|
|
b65481cb24 | ||
|
|
7d54941b75 | ||
|
|
5cbc6edce2 | ||
|
|
6b93bcb4c5 | ||
|
|
d49f2d5792 | ||
|
|
bfb47f3a8e | ||
|
|
cb86034de9 | ||
|
|
0d7c2e140b | ||
|
|
eefa7082ed | ||
|
|
8acd7b9d9f | ||
|
|
f026d3eebc | ||
|
|
1b3360dc99 | ||
|
|
16a736a2a9 | ||
|
|
8663eba113 | ||
|
|
f40ddf5f8e | ||
|
|
57e32ab64f | ||
|
|
483c3055b2 | ||
|
|
ca1e137a54 | ||
|
|
a7506952c8 | ||
|
|
dd7d8eff2d | ||
|
|
b9c6d87a2d | ||
|
|
94d53d1152 | ||
|
|
0037bde2aa | ||
|
|
1d88d787a3 | ||
|
|
987f7b8b04 | ||
|
|
9bc0cfe652 | ||
|
|
044d41ad06 | ||
|
|
b08b385e76 | ||
|
|
61b3050174 | ||
|
|
7b57d70e31 | ||
|
|
832cb1637b | ||
|
|
6290f66d03 | ||
|
|
f8f9896d38 | ||
|
|
be24b0a8dc | ||
|
|
34204d9993 | ||
|
|
3e6566af4f | ||
|
|
1183919964 | ||
|
|
f0a60da2e2 | ||
|
|
5d0f2c6380 | ||
|
|
495f0cc3f6 | ||
|
|
ed220c3c7d | ||
|
|
8e700d485c | ||
|
|
8f87dcce67 | ||
|
|
9e6949ec60 | ||
|
|
36ee3343a0 | ||
|
|
f1e0de5f2d | ||
|
|
b941c3fdb8 | ||
|
|
b79aed8569 | ||
|
|
ec61e9c2ca | ||
|
|
1d75934e45 | ||
|
|
882caa1d12 | ||
|
|
1301aa1b40 | ||
|
|
e3ed8e80f2 | ||
|
|
7b3266e7d8 | ||
|
|
bc6e2863dc |
No files matched your search
@@ -0,0 +1,403 @@
|
|||||||
|
# Architecture
|
||||||
|
> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.
|
||||||
|
|
||||||
|
## Directory Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
plan2code/
|
||||||
|
├── src/ # Source workflow prompts (14 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
|
||||||
|
│ │ ├── github-issues.md # Issue-backed map (loaded only when Backend is github)
|
||||||
|
│ │ ├── grilling.md # Folded-in grilling + domain-modeling
|
||||||
|
│ │ ├── questions.md # On-disk question-file format + markers
|
||||||
|
│ │ ├── 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 behaviour (quick-task, implement, implement-review)
|
||||||
|
│ │ └── helper-strength.md # How strong a model and how much effort each helper gets (pathfinder, quick-task, implement, implement-review, review)
|
||||||
|
│ ├── 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-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)
|
||||||
|
├── 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)
|
||||||
|
│ ├── 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, routes.mjs, static.mjs, cmd-*.mjs, picker.mjs, and the by-job files (files, sessions, patches, scan, inbox, workspace, settings)
|
||||||
|
│ ├── 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 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, web-console-test-helpers.mjs # Web console suites, split by area (the page tests are `-page-*`, the source shape `-shape`), and their shared setup
|
||||||
|
│ ├── 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
|
||||||
|
│ └── 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
|
||||||
|
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
|
||||||
|
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/, plan2code-model-update/
|
||||||
|
├── .github/ISSUE_TEMPLATE/ # bug.yml, idea.yml, config.yml (target of the console's feedback button)
|
||||||
|
├── .readme/ # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, autonomous-loop.md, metrics.md, status-line.md, test-bot.md)
|
||||||
|
├── 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)
|
||||||
|
├── install.js # Interactive installer (Node.js)
|
||||||
|
├── package.json # Root package (husky only, private: true)
|
||||||
|
├── version.json # Version metadata
|
||||||
|
├── CHANGELOG.md, QUICK-REFERENCE.md, LICENSE
|
||||||
|
├── .gitattributes, .editorconfig # Pin LF (see Code Style & Gotchas)
|
||||||
|
├── prototypes/, specs--completed/, dist/ # Local only, gitignored: design prototypes, archived specs, stale pre-2.2 build output. Ignore root dist/.
|
||||||
|
└── README.md # User documentation
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Files
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `install.js` | Interactive installer — builds `skills/` from `src/`, then delegates installation to the skills CLI |
|
||||||
|
| `src/plan2code-*.md` | Source workflow prompts (the "source of truth") |
|
||||||
|
| `skills/` | Generated Agent Skills, gitignored build output regenerated by the installer (and `npm run build:skills`) before every `skills add` |
|
||||||
|
| `scripts/validate-char-count.js` | Pre-commit validator ensuring all source prompts ≤ 20,000 chars |
|
||||||
|
| `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`). 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 |
|
||||||
|
| `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 |
|
||||||
|
| 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 (`{ "schema": 1, "agents": [...] }`). The web console is its only writer (User Preferences → Agents, 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), 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. A bad file or entry is skipped with a warning, never a crash. Until the feature is finalized, the rules are written out in `specs/agent-setup-and-taskbar-attention/PLAN-DRAFT-20261025.md` section 4.4.
|
||||||
|
|
||||||
|
## Workflow Prompts (in `src/`)
|
||||||
|
|
||||||
|
| File | Step | Purpose |
|
||||||
|
|------|------|---------|
|
||||||
|
| `plan2code.md` | — | The dashboard: opens the web console's skill menu and launches the picked skill into its own session |
|
||||||
|
| `plan2code-init.md` | Init | Generate AGENTS.md as index + `.agents-docs/` section files (progressive discovery) |
|
||||||
|
| `plan2code-init-update.md` | Update | Update AGENTS.md with learnings; detects and routes edits to `.agents-docs/` files |
|
||||||
|
| `plan2code-0-pathfinder.md` | 0 | Chart a foggy idea as a map (local files, or GitHub Issues) of decision questions under `specs/<idea>/pathfinder/`, resolve them one at a time, hand a seeded PLAN-DRAFT to Step 1 |
|
||||||
|
| `plan2code-quick-task.md` | quick | Lightweight planning for small tasks (standalone — not a pipeline step) |
|
||||||
|
| `plan2code-1-plan.md` | 1 | Requirements analysis & architecture |
|
||||||
|
| `plan2code-1b-revise-plan.md` | 1b | Mid-implementation revisions |
|
||||||
|
| `plan2code-2-document.md` | 2 | Create implementation specs |
|
||||||
|
| `plan2code-3-implement.md` | 3 | Execute implementation (phase by phase) |
|
||||||
|
| `plan2code-3-implement-review.md` | 3 | Execute one phase, run focused review and fixes, then request approval |
|
||||||
|
| `plan2code-review.md` | review | Post-implementation comprehensive review, analysed 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-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-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
|
||||||
|
|
||||||
|
Workflow files follow a strict naming pattern:
|
||||||
|
- **The hub:** `plan2code.md` (bare name — `bare: true` in `SOURCE_PROMPTS`, no suffix; it is the dashboard the rest hang off, not a step)
|
||||||
|
- **Utilities:** `plan2code-<name>.md` (single dash)
|
||||||
|
- **Numbered steps:** `plan2code-<N>-<name>.md` (single dash, number, single dash)
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
- `plan2code-init.md` (utility)
|
||||||
|
- `plan2code-1-plan.md` (step 1)
|
||||||
|
- `plan2code-1b-revise-plan.md` (step 1b)
|
||||||
|
|
||||||
|
## Reference Files
|
||||||
|
|
||||||
|
Some workflows use companion reference files for depth that 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/`). 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.
|
||||||
|
|
||||||
|
Reference files are NOT subject to the 20,000 character limit. The review workflow pioneered this pattern (`verification-protocol`, `dimensions`, `false-positives`, `session-end`); the init-update workflow also uses it (`ai-agent-file-sync` for its Step 7), `plan2code-4-finalize.md` uses it for STEP 6.5 (`community-feedback-submission`), and `plan2code-0-pathfinder.md` leans on it hardest (`brief`, `chart`, `github-issues`, `grilling`, `questions`, `resolve`, `handoff`, `trail` — the orchestrator is a dispatcher, the depth lives in the references). Other workflows can adopt it when a source file carries detail that is only needed some of the time. The implement-review skill is a generated composition: `additionalReferences` in `SOURCE_PROMPTS` packages the canonical implement prompt, review prompt, and review reference directory into its own `references/` directory so those workflows are reused without source duplication.
|
||||||
|
|
||||||
|
## Skill Scripts
|
||||||
|
|
||||||
|
Anything a workflow step decides with one correct answer (parsing a spec's checkboxes, rebuilding Pathfinder's map markers, the commit message, which AI config files exist) lives in a script the agent runs, not in prose it follows. Prose keeps the judgment.
|
||||||
|
|
||||||
|
| Source | Ships to | How |
|
||||||
|
|---|---|---|
|
||||||
|
| `src/skill-scripts/<name>.mjs` | `skills/<skill>/scripts/<name>.mjs` | Shared: a skill lists the ones it runs in `scripts: [...]` on its `SOURCE_PROMPTS` entry. Skills install independently, so each gets its own copy |
|
||||||
|
| `src/skill-scripts/common.mjs` | every skill that has scripts | `SHARED_SCRIPTS_ALWAYS` in `install.js` |
|
||||||
|
| `src/<source>-scripts/<name>.mjs` | `skills/<skill>/scripts/<name>.mjs` | A skill's own scripts, mirroring `-references/`. A name that collides with a shared script is a build error |
|
||||||
|
| `version.json` (repo root) | `skills/<skill>/scripts/version.json` | Copied at build, so an installed skill can report its version |
|
||||||
|
|
||||||
|
| 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/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 | Review Mode's git fallback: files, lines, doc share, base branch |
|
||||||
|
| `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 |
|
||||||
|
| `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.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`. 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/`)
|
||||||
|
|
||||||
|
Maintainer-only skills committed to the repo but deliberately excluded from the generated `skills/` product artifact:
|
||||||
|
|
||||||
|
- `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.
|
||||||
|
- `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 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, 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. `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/`), `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) |
|
||||||
|
| `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 |
|
||||||
|
| `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` |
|
||||||
|
| `inbox.mjs` | the Quick question chat's inbox beside the card slot |
|
||||||
|
| `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 → 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/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/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry |
|
||||||
|
| `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 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/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: looks, sounds and the launcher's model menus |
|
||||||
|
| `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/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` | Colours, 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` (18 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; The git board sits right after Watching a build), `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). No module-scope DOM, so `node --test` covers it |
|
||||||
|
| `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/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) and `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all). Nothing outside a frame |
|
||||||
|
| `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, 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 } } }`) 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/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 |
|
||||||
|
| `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. 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 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 `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, `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`). 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), 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 `screens/help-dialog.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/` (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.
|
||||||
|
- **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`). `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.
|
||||||
|
- **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 `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 `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.
|
||||||
|
- **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, 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.
|
||||||
|
- **`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 greyed, 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 five 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 `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` | 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.** `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` | 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-subagents.md`.
|
||||||
|
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or the loop's marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
|
||||||
|
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `routes.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `sessions.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
|
||||||
|
- **Answers carry their terminal token.** Each item ships `fallbackText` and `token`, so a click resolves to the literal word the prompt already expects (`approved`, `a`, `skip`). No workflow needs a second code path, and declining the console degrades to prose with nothing lost.
|
||||||
|
- **A build tells the page how long silence is normal.** The page calls a working agent stuck after two minutes without a post, which is right for a conversation and wrong for a twenty-minute build task. `agent.quietMinutes` (1 to 60, counted only while `working`) stretches the stuck, adrift and Send-grace thresholds; `quietLimitMs()` in `answers.js` is the one rule.
|
||||||
|
- **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.
|
||||||
|
- **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 never the agent's.** `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 } } }`, 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:** eleven, 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) and `/notepad/tab/last` (`{ id }`), 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 ten 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` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **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/notepad.js` binds every save and picture to the tab it was made in (a switch waits for the save, and stays put when it cannot), `public/notepad-tabs.js` draws the bar, and `public/notepad.js` holds the name, order and delete rules as pure code. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labelled "Notebook for <folder>"Line 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 (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 `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 18 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 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`, `-git`, `-qa`, `-speed`, `-hardening`). 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/`:** 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.
|
||||||
|
|
||||||
|
## Status Line
|
||||||
|
|
||||||
|
Optional Claude Code status bar living in `src/statusline-claude/`. Three-line bar beside a Planny icon: two content lines with a dashed rule between, showing model (+ effort), project/worktree, branch, uncommitted diff stats, session duration + cost, context window usage, and plan/quota usage.
|
||||||
|
|
||||||
|
**Design constraints:**
|
||||||
|
- **Zero runtime dependencies** — `statusline.js` is self-contained (config loader, git helpers, formatters, render). Copied verbatim to `~/.claude/plan2code-statusline.js` on install; no bundler step.
|
||||||
|
- **Stdin-driven** — all data comes from Claude Code's stdin JSON (`model`, `workspace`, `context_window`, `rate_limits`, `cost`). No API calls, no auth, no background processes.
|
||||||
|
- **Silent failure** — outer `try/catch` around `main()` plus `process.exit(0)` on missing stdin guarantees the script never crashes the CLI. All git ops are timeout-bounded (1.5s) and non-git workspaces short-circuit via `isGitRepo()` (walks up to 10 parent dirs looking for `.git`).
|
||||||
|
- **Atomic settings writes** — installer writes `~/.claude/settings.json` via temp file + rename so a crash never leaves the file truncated.
|
||||||
|
- **Custom-config respect** — installer detects non-plan2code `statusLine` entries, prompts before replacing, and backs up to `statusline-previous.json`. Uninstall only removes `settings.statusLine` if it points to the plan2code bundle.
|
||||||
|
|
||||||
|
**Layout:**
|
||||||
|
|
||||||
|
```
|
||||||
|
src/statusline-claude/
|
||||||
|
├── statusline.js # Self-contained: config, git, formatters, render
|
||||||
|
├── statusline-config.json # Default config template
|
||||||
|
└── README.md # User docs: install, config, debugging
|
||||||
|
```
|
||||||
|
|
||||||
|
**Adaptive plan-usage display:** the formatter auto-selects between `5h/7d` rate-limit percentages (Pro/Max/Teams — when `rate_limits` present in stdin) and `Nk in · Nk out` session-token counts (Bedrock/Vertex/PAYG — when `rate_limits` absent). Segment is hidden when neither shape is available.
|
||||||
|
|
||||||
|
**Installer integration** lives in `install.js` under the `STATUS LINE INSTALLATION` section (`installStatusLine`, `uninstallStatusLine`). Included in Advanced → `E` (Everything); also available individually via Advanced → `S`.
|
||||||
|
|
||||||
|
## 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):
|
||||||
|
|
||||||
|
| 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) |
|
||||||
|
|
||||||
|
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it exits 127 and prints `SKILL_STEPS`: how to install an agent, `cd` into the project, and type `/plan2code` (`$plan2code` in Codex). An uninstalled `--cli` pick prints that CLI's own steps after its error (its install command, `cd` into the project, then `plan2code --cli <id>` or its prompt). `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. `plan2code update` is the one subcommand: it is never forwarded and opens no agent, it runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists. On every other start, before spawning the CLI, it prints one line when a newer release is out (`Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`), compared against `~/.plan2code/bin/version.json` and read from the console's cached release check (`~/.plan2code/console/update-check.json`); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
|
||||||
|
|
||||||
|
**Design constraints:**
|
||||||
|
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. Beside it go `update-check.mjs` (the web console's release check, for the terminal notice) and a `version.json` (the installed version). (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||||
|
- **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`.
|
||||||
|
- **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.
|
||||||
|
|
||||||
|
**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):
|
||||||
|
|
||||||
|
| OS | File | Runs |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Windows | `Plan2Code.lnk` (written by `WScript.Shell`) | `pwsh.exe` (else Windows PowerShell) `-NoLogo -ExecutionPolicy Bypass -File "<bin>\plan2code.ps1" --pick-folder`, icon `src/launcher/plan2code.ico` (the web console's Peek-a-boo favicon, 16–256 px) copied to `~/.plan2code/bin/plan2code.ico` |
|
||||||
|
| macOS | `Plan2Code.command` (0755) | `exec "<bin>/plan2code" --pick-folder` in Terminal |
|
||||||
|
| Linux | `plan2code.desktop` (0755, `Terminal=true`, `gio … metadata::trusted`) | `"<bin>/plan2code" --pick-folder`, `Icon=` the web console's `favicon.png` copied to `~/.plan2code/bin/plan2code.png` |
|
||||||
|
|
||||||
|
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. 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 exactly those, 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.
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Code Style & Gotchas
|
||||||
|
> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.
|
||||||
|
|
||||||
|
## Code Style
|
||||||
|
|
||||||
|
- **install.js:** CommonJS, Node.js built-ins only (no external deps), ANSI colors via `COLORS` constant, readline-based prompts
|
||||||
|
- **plan2code-loop, plan2code-metrics & plan2code-bot:** TypeScript + ESM, built with tsup (target ES2022, moduleResolution: bundler)
|
||||||
|
- External deps (loop, metrics): `@inquirer/prompts`, `chalk`, `execa`, `fs-extra`, `ora`
|
||||||
|
- External deps (bot): `@anthropic-ai/claude-agent-sdk`, `chalk`, `fs-extra`, `ora`
|
||||||
|
- Interactive CLI via `@inquirer/prompts` (select, input, confirm)
|
||||||
|
- **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.
|
||||||
|
|
||||||
|
## Gotchas / Pitfalls
|
||||||
|
|
||||||
|
- **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).
|
||||||
|
- **`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 `\|`.
|
||||||
|
- **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-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`, 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 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/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.
|
||||||
|
- **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.
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
# Development Commands
|
||||||
|
> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.
|
||||||
|
|
||||||
|
## Common Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install dev dependencies (sets up husky pre-commit hooks only; each sub-package
|
||||||
|
# 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
|
||||||
|
node install.js
|
||||||
|
|
||||||
|
# Regenerate skills/ from src/ (non-interactive)
|
||||||
|
npm run build:skills
|
||||||
|
|
||||||
|
# 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-<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.
|
||||||
|
# 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)
|
||||||
|
|
||||||
|
# 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 Loop
|
||||||
|
cd plan2code-loop && npm install # First time setup
|
||||||
|
cd plan2code-loop && npm run build # Build the CLI
|
||||||
|
|
||||||
|
# Plan2Code Metrics
|
||||||
|
cd plan2code-metrics && npm install # First time setup
|
||||||
|
cd plan2code-metrics && npm run build # Build the CLI
|
||||||
|
cd plan2code-metrics && npm test # vitest (aggregator, community, improver)
|
||||||
|
|
||||||
|
# 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/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.
|
||||||
|
|
||||||
|
## 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/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_CONSOLE_TRACE` | Set to `1` on `open` to print a start-up step timeline to stderr. |
|
||||||
|
|
||||||
|
## Installer Menu Options
|
||||||
|
|
||||||
|
**Main menu:**
|
||||||
|
|
||||||
|
| 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) |
|
||||||
|
| `A` | Open the ADVANCED sub-menu |
|
||||||
|
| `Q` | Quit |
|
||||||
|
|
||||||
|
**ADVANCED sub-menu (`A`):**
|
||||||
|
|
||||||
|
| 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) |
|
||||||
|
| `Q` | Return to main menu |
|
||||||
|
|
||||||
|
## Non-Interactive Flags
|
||||||
|
|
||||||
|
`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, statusline, loop, metrics, bot), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx |
|
||||||
|
|
||||||
|
## How the Installer Works
|
||||||
|
|
||||||
|
1. **Builds `skills/` from `src/`** — one Agent Skill per source prompt, including uncommitted source edits.
|
||||||
|
2. **Checks the skills CLI is reachable** with `npx --yes skills --version`.
|
||||||
|
3. **Sweeps pre-2.2 install paths** and removes installed `plan2code-*` skills so renamed or retired prompts cannot survive as orphans.
|
||||||
|
4. **Delegates installation** to `npx --yes skills add "<repo>/skills" -g -s <skill names> -y`.
|
||||||
|
5. **Installs the global `plan2code` command** (only when step 4 succeeded). Advanced → `L` runs the same flow without `-g` and without the launcher.
|
||||||
|
|
||||||
|
The skills CLI owns distribution from step 4 onward. It stores canonical skills under `~/.agents/skills/` and links them into agents that maintain their own skill directory. Plan2Code no longer maintains platform-specific output formats.
|
||||||
|
|
||||||
|
**Invocation choices:**
|
||||||
|
|
||||||
|
| Choice | Reason |
|
||||||
|
|--------|--------|
|
||||||
|
| Explicit space-separated `-s <names>` | Avoids shell expansion and prevents unrelated directories under `skills/` from being installed. |
|
||||||
|
| No `-a` / `--agent '*'` | Uses the CLI's supported default agent set instead of requesting incompatible scope/agent combinations. |
|
||||||
|
| Captured output | Suppresses the CLI's duplicated banners while preserving real failures; unsupported-scope noise is filtered. |
|
||||||
|
|
||||||
|
## Skill Format
|
||||||
|
|
||||||
|
| Item | Value |
|
||||||
|
|------|-------|
|
||||||
|
| Path | `skills/<skill-name>/SKILL.md` |
|
||||||
|
| Skill name | `generateSkillName(prompt)`, such as `plan2code-1-plan` or `plan2code-init` |
|
||||||
|
| Frontmatter | `name`, `description`, `disable-model-invocation: true` |
|
||||||
|
| Reference files | `skills/<skill-name>/references/<path>`, copied from `src/<prompt>-references/` and `additionalReferences` (any file type; every skill bundles `web-console/` plus a copy of `version.json`) |
|
||||||
|
| Scripts | `skills/<skill-name>/scripts/<file>.mjs`, plus `common.mjs` and a generated `version.json` (see Skill Scripts in the architecture doc) |
|
||||||
|
|
||||||
|
`disable-model-invocation: true` is unconditional because these workflows are user-initiated. Agents that do not recognize the field ignore it.
|
||||||
|
|
||||||
|
## Editing Workflow Prompts
|
||||||
|
|
||||||
|
See the `skills/` build-artifact gotcha in [Code Style & Gotchas](./AGENTS-code-style.md).
|
||||||
|
|
||||||
|
1. Edit the source file under `src/`.
|
||||||
|
2. Run `npm run build:skills`.
|
||||||
|
3. Test the workflow in an AI tool.
|
||||||
|
4. `skills/` is gitignored, so only the `src/` change is committed.
|
||||||
|
5. Never edit `skills/` by hand because the next build overwrites it.
|
||||||
|
|
||||||
|
## 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/` (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 `greyed`. 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`.
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# 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,89 @@
|
|||||||
|
# Plan2Code Metrics
|
||||||
|
> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.
|
||||||
|
|
||||||
|
A recursive self-improvement toolchain for plan2code contributors. Collects run metrics, aggregates by prompt generation, diagnoses weak steps via AI, and proposes surgical prompt edits.
|
||||||
|
|
||||||
|
## Metrics Data Flow
|
||||||
|
|
||||||
|
```
|
||||||
|
Collect → Aggregate → Analyze → Improve → Apply
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **Collector** reads project artifacts (`specs/<feature>/`) → writes `RunMetrics` JSON per run
|
||||||
|
2. **Aggregator** groups runs by prompt SHA fingerprint (cohorts) → `aggregated.json`
|
||||||
|
3. **Analyzer** invokes AI with aggregated metrics + prompt contents → diagnosis markdown
|
||||||
|
4. **Improver** invokes AI with diagnosis → validated `PromptEdit[]` proposals (char limit + verbatim checks)
|
||||||
|
5. **Applier** shows interactive diffs → patches `src/plan2code-*.md` files
|
||||||
|
|
||||||
|
## Metrics Commands
|
||||||
|
|
||||||
|
Run `plan2code-metrics` (fully interactive, no flags). Build and test commands: see [Development Commands](./AGENTS-development-commands.md).
|
||||||
|
|
||||||
|
## Metrics CLI Menu
|
||||||
|
|
||||||
|
| Option | Action |
|
||||||
|
|--------|--------|
|
||||||
|
| Collect | Read spec artifacts → run JSON |
|
||||||
|
| Import | Copy run JSON from another project |
|
||||||
|
| View | Display cohort metrics with health indicators |
|
||||||
|
| Analyze | AI diagnosis of weak metrics |
|
||||||
|
| Propose | AI improvement proposals with validation |
|
||||||
|
| Apply | Interactive diff review + file patching |
|
||||||
|
| Fetch community submissions | List/parse/import open community-feedback GitHub issues from jparkerweb/plan2code, close on success |
|
||||||
|
| Delete metrics data | Delete selected runs, all runs + aggregated data, or everything including proposals |
|
||||||
|
|
||||||
|
Community submissions arrive as GitHub issues labeled `community-feedback` on `jparkerweb/plan2code`, created by the finalize prompt's post-Step-6 submission flow; the "Fetch community submissions" option requires an authenticated `gh` CLI to list/close them.
|
||||||
|
|
||||||
|
## Key Source Files
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `types.ts` | All interfaces (`RunMetrics`, `UserFeedback`, `CohortMetrics`, etc.) + `METRIC_TARGETS` |
|
||||||
|
| `collector.ts` | Reads project artifacts → run JSON (parses plan drafts, overview.md, loop logs) |
|
||||||
|
| `aggregator.ts` | Merges runs by prompt generation (SHA cohort) → `aggregated.json` |
|
||||||
|
| `community.ts` | Lists/parses/closes `community-feedback`-labeled GitHub issues via `gh` CLI |
|
||||||
|
| `analyzer.ts` | AI diagnosis via `prompts/analyze.md` template |
|
||||||
|
| `improver.ts` | AI proposals via `prompts/improve.md` + validation (char count, old_text match) |
|
||||||
|
| `applier.ts` | Interactive diff review + file patching |
|
||||||
|
| `cli.ts` | Menu-driven interactive CLI (100% prompts, no flags) |
|
||||||
|
| `invoke-llm.ts` | Unified LLM interface (Claude Code, GitHub Copilot CLI, or Devin CLI) |
|
||||||
|
| `*.test.ts` | vitest suites for aggregator, community, improver (`npm test` in `plan2code-metrics/`) |
|
||||||
|
|
||||||
|
## User Feedback
|
||||||
|
|
||||||
|
The collector parses an optional `## User Feedback` table from `overview.md`:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## User Feedback
|
||||||
|
| Field | Value |
|
||||||
|
|-------|-------|
|
||||||
|
| Rating | 8 |
|
||||||
|
| Reason | Smooth workflow |
|
||||||
|
| Went Well | Planning was thorough |
|
||||||
|
| Went Poorly | Some tasks unclear |
|
||||||
|
```
|
||||||
|
|
||||||
|
Feedback is collected during finalize (Step 5) or retroactively via the CLI. Pipe characters in values are escaped as `\|`. The aggregator computes `avg_user_rating` and `feedback_count` per cohort.
|
||||||
|
|
||||||
|
## Supported AI Agents
|
||||||
|
|
||||||
|
- **Claude Code** (recommended): `claude --print --dangerously-skip-permissions`, prompt written to a temp file and piped to stdin (execa `inputFile`)
|
||||||
|
- **GitHub Copilot CLI**: `copilot --allow-all-tools -s`, prompt on stdin (default model `claude-sonnet-4`)
|
||||||
|
- **Devin CLI**: `devin` CLI with `--print --prompt-file <file> --permission-mode dangerous`
|
||||||
|
|
||||||
|
## Metric Targets
|
||||||
|
|
||||||
|
| Metric | Target | Direction |
|
||||||
|
|--------|--------|-----------|
|
||||||
|
| `avg_confidence` | ≥ 90 | higher is better |
|
||||||
|
| `avg_clarification_rounds` | ≤ 2.0 | lower is better |
|
||||||
|
| `avg_verification_gaps_found` | ≤ 2.0 | lower is better |
|
||||||
|
| `avg_parallel_groups` | ≥ 0.5 | higher is better |
|
||||||
|
| `avg_verification_items_added` | ≤ 1.5 | lower is better |
|
||||||
|
| `avg_task_completion_rate` | ≥ 0.95 | higher is better |
|
||||||
|
| `avg_blocker_count` | ≤ 1.5 | lower is better |
|
||||||
|
| `avg_verification_failures_found` | ≤ 1.0 | lower is better |
|
||||||
|
| `archival_success_rate` | ≥ 0.99 | higher is better |
|
||||||
|
| `avg_user_rating` | ≥ 7.0 | higher is better |
|
||||||
|
|
||||||
|
On start the CLI asks for the plan2code repo path (default: saved `plan2codeRepoPath` in `~/.plan2code-metrics.json`, else auto-detected up to 5 parent dirs) and the project path (default: cwd). Data is stored in `<project>/.plan2code-metrics/` (runs/, aggregated.json, proposals/).
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
---
|
||||||
|
name: plan2code-changelog
|
||||||
|
description: "Validate and fix the CHANGELOG.md version number before opening a PR. Reads main branch to determine the current latest version, classifies changes on the current branch, and proposes the correct next semver. Use this skill when the user mentions changelog, version number, preparing a PR, release version, semver check, or says 'check the changelog', 'what version should this be', 'prepare for PR', or 'fix the version'. Also use proactively when you notice a CHANGELOG entry that may have an incorrect version number."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Plan2Code Changelog Validator
|
||||||
|
|
||||||
|
Ensure the CHANGELOG.md entry for the current branch has the correct semver version before a PR is opened. This skill exists because parallel branches independently pick version numbers that collide or leap-frog when merged — this validates against main's actual state right before the PR.
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
### Step 1 — Gather state
|
||||||
|
|
||||||
|
Run these commands to understand the current situation:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Current latest version on main
|
||||||
|
git show main:CHANGELOG.md | head -20
|
||||||
|
|
||||||
|
# 2. Current branch name (for ticket ID extraction)
|
||||||
|
git branch --show-current
|
||||||
|
|
||||||
|
# 3. What this branch changed (commit subjects)
|
||||||
|
git log main...HEAD --oneline
|
||||||
|
|
||||||
|
# 4. Files changed on this branch
|
||||||
|
git diff main...HEAD --name-only
|
||||||
|
```
|
||||||
|
|
||||||
|
Extract from main's CHANGELOG:
|
||||||
|
- The **latest version number** (first `## vX.Y.Z` line)
|
||||||
|
|
||||||
|
Note: on Windows, PowerShell's console encoding mangles the emoji in the `###` headings to `?`. Read `CHANGELOG.md` with the file-read or grep tool rather than `Get-Content` / `Select-String` when you need to see them.
|
||||||
|
|
||||||
|
Extract from the branch:
|
||||||
|
- The **list of changed files** to classify the change type
|
||||||
|
- The **commit messages** for changelog entry content
|
||||||
|
|
||||||
|
### Step 2 — Classify the change
|
||||||
|
|
||||||
|
Determine the change type by examining what was modified on this branch:
|
||||||
|
|
||||||
|
| Signal | Classification | Version Bump | Heading |
|
||||||
|
|--------|---------------|--------------|---------|
|
||||||
|
| An install target removed, or an existing workflow's contract broken | Breaking change | **Major** (X.0.0) | `### 💥 Breaking` |
|
||||||
|
| New workflow prompt (`.md` file under `src/`) | New workflow | **Minor** (x.Y.0) | `### ✨ Added` |
|
||||||
|
| New capability added to an existing prompt, or a new `.claude/skills/` skill | New capability | **Patch** (x.y.Z) | `### ✨ Added` |
|
||||||
|
| Behavioral changes to existing prompt(s), installer, or docs | Behavior change | **Patch** (x.y.Z) | `### 🔧 Changed` |
|
||||||
|
| Bug fix to existing prompt(s) or tooling | Bug fix | **Patch** (x.y.Z) | `### 🐛 Fixed` |
|
||||||
|
| A prompt, target, or file deleted | Removal | **Patch** (x.y.Z) | `### 🗑️ Removed` |
|
||||||
|
| README / `.readme/` / docs-site only | Documentation | **Patch** (x.y.Z) | `### 📚 Documentation` |
|
||||||
|
| Mix of the above | Use the **highest** bump (major > minor > patch) | Combine headings |
|
||||||
|
|
||||||
|
Use only the headings in this table — the CHANGELOG has historical one-off variants (`🎁 Added`, `📦 Updated`, `📝 Documentation`, `🏎️ Improved`, `🧪 Testing`) that should not be introduced in new entries.
|
||||||
|
|
||||||
|
### Step 3 — Compute the correct version
|
||||||
|
|
||||||
|
Starting from main's latest version:
|
||||||
|
- **Major bump:** increment the first number, reset the rest (e.g., `1.16.1` → `2.0.0`)
|
||||||
|
- **Minor bump:** increment the middle number, reset patch to 0 (e.g., `2.0.0` → `2.1.0`)
|
||||||
|
- **Patch bump:** increment the last number (e.g., `2.1.0` → `2.1.1`)
|
||||||
|
|
||||||
|
### Step 4 — Check the current branch's CHANGELOG
|
||||||
|
|
||||||
|
Read the current `CHANGELOG.md` on the branch. Look for:
|
||||||
|
|
||||||
|
0. **You are on `main` with no diff** — there is no branch to validate. Instead, compare the top CHANGELOG version against `git log` since the commit that released it: if commits have landed on `main` without a CHANGELOG entry, treat those commits as the change set and continue from Step 2. Say so explicitly rather than reporting "nothing to do."
|
||||||
|
|
||||||
|
1. **No entry exists yet for this branch's work** — the branch hasn't added a version entry above main's latest. Proceed to Step 5 to draft one.
|
||||||
|
|
||||||
|
2. **An entry exists but the version is wrong** — the branch has a version entry, but it doesn't match the computed correct version (common when branches were rebased or other PRs merged first). Report the discrepancy:
|
||||||
|
|
||||||
|
```
|
||||||
|
Version check for branch: {branch-name}
|
||||||
|
|
||||||
|
Main is at: {main-version}
|
||||||
|
Branch claims: {branch-version}
|
||||||
|
Correct version: {computed-version} ({classification})
|
||||||
|
|
||||||
|
The version needs to be updated: {branch-version} → {computed-version}
|
||||||
|
```
|
||||||
|
|
||||||
|
Ask: "Update the version to {computed-version}? (yes / no)"
|
||||||
|
|
||||||
|
3. **An entry exists and the version is correct** — report success:
|
||||||
|
|
||||||
|
```
|
||||||
|
Version check for branch: {branch-name}
|
||||||
|
|
||||||
|
Main is at: {main-version}
|
||||||
|
Branch version: {branch-version} ({classification})
|
||||||
|
|
||||||
|
Version is correct. CHANGELOG is ready for PR.
|
||||||
|
```
|
||||||
|
|
||||||
|
Stop here unless the user asks for content changes.
|
||||||
|
|
||||||
|
### Step 5 — Draft or fix the CHANGELOG entry
|
||||||
|
|
||||||
|
**If no entry exists**, draft a new one based on the commits and changed files. Match this repo's house format exactly — a bare `## vX.Y.Z` heading with **no date**, emoji `###` headings from the Step 2 table, and a blank line between bullets:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## {computed-version-with-v-prefix}
|
||||||
|
|
||||||
|
### ✨ Added
|
||||||
|
|
||||||
|
- **{prompt-or-area}** — {what changed, and why it matters to someone installing it}
|
||||||
|
|
||||||
|
### 🔧 Changed
|
||||||
|
|
||||||
|
- **{prompt-or-area}** — {what changed}
|
||||||
|
```
|
||||||
|
|
||||||
|
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.
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
Present the draft and ask for approval before writing.
|
||||||
|
|
||||||
|
**If the version is wrong**, update only the version number — preserve the existing content unless the user asks for content changes too.
|
||||||
|
|
||||||
|
After any changes, show the final CHANGELOG entry for confirmation.
|
||||||
|
|
||||||
|
### Step 6 — Sync `package.json` and `version.json` versions
|
||||||
|
|
||||||
|
After writing or updating the CHANGELOG entry, update the `version` field in `package.json` at the repo root to match the computed version:
|
||||||
|
|
||||||
|
1. Read `package.json` and `version.json` then check the current `version` value.
|
||||||
|
2. If it already matches the computed version, skip — no change needed.
|
||||||
|
3. If it differs, update the `"version"` field in both files to the computed version (e.g., `"version": "2.1.1"`).
|
||||||
|
4. Set `releaseDate` in `version.json` to today's date in `YYYY-MM-DD`. This is the only place a date is recorded — the CHANGELOG headings carry no date.
|
||||||
|
5. Include `package.json` and `version.json` in the same commit as the CHANGELOG changes.
|
||||||
|
|
||||||
|
This keeps `package.json`, `version.json`, and `CHANGELOG.md` in lockstep so `npm pkg get version` always reflects the latest release.
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
|
||||||
|
- Never create a version entry without checking main first — the whole point is to derive the version from main's current state
|
||||||
|
- Always present changes before writing — the user should see and approve the CHANGELOG entry
|
||||||
|
- Match the existing file's format — `## vX.Y.Z` with no date, emoji `###` headings. Do not introduce Keep a Changelog's `## [x.y.z] - date` style
|
||||||
|
- Write for someone reading the release notes, not for someone reading the diff — say what the change lets them do
|
||||||
|
- If multiple change types exist (Added + Changed), use multiple headings under the same version
|
||||||
|
- `version.json`'s `releaseDate` is today's date, i.e. when the release is being prepared, not when the work started
|
||||||
|
- If the branch has no meaningful changes vs main (e.g., only non-shipping files changed), say so and ask if a CHANGELOG entry is actually needed
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
---
|
||||||
|
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).
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
---
|
||||||
|
name: plan2code-publish
|
||||||
|
description: "Publish a GitHub Release for jparkerweb/plan2code whenever CHANGELOG.md's top version is ahead of the latest published release on GitHub — after verifying CHANGELOG.md, version.json, and package.json all agree on the version. Use this skill when the user says 'publish a release', 'create a GitHub release', 'cut a release', 'tag a release', 'tag and release', 'is the changelog published', or otherwise mentions publishing/releasing/tagging this repo."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Plan2Code Release Publisher
|
||||||
|
|
||||||
|
Publish a GitHub Release for `jparkerweb/plan2code` whenever `CHANGELOG.md`'s top version is ahead of the latest published release on GitHub. This turns the merged CHANGELOG entry on `main` into an actual GitHub Release (which also creates the `vX.Y.Z` git tag).
|
||||||
|
|
||||||
|
**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 (`uninstallFiles()` in `install.js`) and every re-install's pre-copy cleanup in `install()` both delete every entry matching `/^plan2code-/` under `~/.claude/skills/`, so a copy placed there would be silently removed.
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
### Step 1 — Preflight: clean working tree
|
||||||
|
|
||||||
|
Run `git status --porcelain`. If the output is non-empty, stop immediately — do not switch branches or take any other action. Tell the user:
|
||||||
|
|
||||||
|
> Working tree has uncommitted changes. Commit or stash them, then re-run this skill.
|
||||||
|
|
||||||
|
### Step 2 — Switch to main and pull
|
||||||
|
|
||||||
|
If the working tree is clean, switch to `main` and pull latest. Run these as two separate, non-chained commands (never `&&`/`;`-chain `git`/`gh` commands — Windows PowerShell 5.1 rejects `&&`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout main
|
||||||
|
git pull origin main
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 3 — Read the three version sources
|
||||||
|
|
||||||
|
Read all three files at the repo root and extract each version:
|
||||||
|
|
||||||
|
- `CHANGELOG.md` — parse the first `## vX.Y.Z` heading. Strip the leading `v` → `$CHANGELOG_VERSION`. Note: plan2code CHANGELOG headings are `## vX.Y.Z` (v-prefixed, **no** date and **no** brackets) — different from a `## [x.y.z] - YYYY-MM-DD` format.
|
||||||
|
- `version.json` — the `version` field → `$VERSION_JSON`. Also read its `releaseDate` field → `$RELEASE_DATE` (informational only — shown at the confirm step, never part of the sync gate; use `(none)` if absent).
|
||||||
|
- `package.json` (root) → the `version` field → `$PACKAGE_JSON`.
|
||||||
|
|
||||||
|
Also capture from `CHANGELOG.md` the **section body** for the top version: everything from the `## vX.Y.Z` heading line itself (heading **included**) up to — but not including — the next `## v` heading, or end-of-file if there is none. Call this `$SECTION`. Keep the `## vX.Y.Z` heading in `$SECTION`; plan2code release bodies include it.
|
||||||
|
|
||||||
|
### Step 4 — Version-sync preflight (STOP on mismatch)
|
||||||
|
|
||||||
|
All three versions must be identical. This enforces the repo's documented invariant (`.agents-docs/AGENTS-code-style.md` → "Version sync"): `CHANGELOG.md`, `version.json`, and `package.json` must always show the same version number.
|
||||||
|
|
||||||
|
If `$CHANGELOG_VERSION`, `$VERSION_JSON`, and `$PACKAGE_JSON` are **not** all equal, **stop** — do not read the release, do not publish. Report exactly which files disagree:
|
||||||
|
|
||||||
|
> ⚠️ Version files are out of sync — refusing to publish. The repo requires `CHANGELOG.md`, `version.json`, and `package.json` to match.
|
||||||
|
>
|
||||||
|
> - **CHANGELOG.md:** $CHANGELOG_VERSION
|
||||||
|
> - **version.json:** $VERSION_JSON
|
||||||
|
> - **package.json:** $PACKAGE_JSON
|
||||||
|
>
|
||||||
|
> Fix the mismatch first, then re-run this skill. To realign: pick the intended version (normally the highest / newest CHANGELOG entry) and update the other two files to match — see the "Version sync" gotcha in `.agents-docs/AGENTS-code-style.md`.
|
||||||
|
|
||||||
|
This skill never modifies these files — it only reads and compares them.
|
||||||
|
|
||||||
|
### Step 5 — Determine the highest published release
|
||||||
|
|
||||||
|
List every published (non-draft) release and take the numerically-highest semver tag. Do **not** rely on `gh release view` / GitHub's "Latest" flag: that flag returns whatever release is *marked* latest — normally the newest semver, but a maintainer can manually pin it to an older release, which would make the Step 6 ahead-comparison misfire.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gh release list --repo jparkerweb/plan2code --limit 100 --json tagName,isDraft -q '.[] | select(.isDraft==false) | .tagName'
|
||||||
|
```
|
||||||
|
|
||||||
|
Strip any leading `v` from each returned tag, compare them as numeric `(major, minor, patch)` tuples (the same rule as Step 6), and take the maximum → `$RELEASE_VERSION`. If the command returns no tags or exits non-zero for **any** reason (no releases yet, transient error, etc.), set `$RELEASE_VERSION = "0.0.0"` — no error-text matching is needed.
|
||||||
|
|
||||||
|
### Step 6 — Compare versions
|
||||||
|
|
||||||
|
Compare `$CHANGELOG_VERSION` vs `$RELEASE_VERSION` as a numeric `(major, minor, patch)` tuple. Never do a plain string/lexicographic compare — e.g. `"1.9.0" > "1.10.0"` is true as strings but wrong numerically.
|
||||||
|
|
||||||
|
### Step 7 — Not ahead: no-op
|
||||||
|
|
||||||
|
If `$CHANGELOG_VERSION` ≤ `$RELEASE_VERSION`, print a simple status message showing both versions and stop:
|
||||||
|
|
||||||
|
> CHANGELOG top version ($CHANGELOG_VERSION) is not ahead of the latest published release ($RELEASE_VERSION). Nothing to publish.
|
||||||
|
|
||||||
|
No error is raised and no release is created.
|
||||||
|
|
||||||
|
### Step 8 — Ahead: compute and confirm
|
||||||
|
|
||||||
|
If `$CHANGELOG_VERSION` > `$RELEASE_VERSION`, compute:
|
||||||
|
|
||||||
|
- `tag = "v$CHANGELOG_VERSION"`
|
||||||
|
- `title = "v$CHANGELOG_VERSION"` (plan2code keeps the `v` prefix in release titles)
|
||||||
|
- `notes` = the header line `# What's New 🎉`, then one blank line, then `$SECTION` verbatim (`$SECTION` already starts with the `## vX.Y.Z` heading). Build this as a real multi-line string with **actual newlines** — the `\n\n` shorthand shown elsewhere means "a blank line," never the literal two-character sequence `\` + `n`. Getting this wrong would run the header and the first CHANGELOG heading together with a stray `\n\n` in the published body.
|
||||||
|
|
||||||
|
Present all three to the user and wait for an explicit answer before any write. Offer the optional decorative title suffix — a plain `vX.Y.Z` title is the default, but a release may append one (e.g. `v1.14.0 - 🔍 Review workflow`):
|
||||||
|
|
||||||
|
> 🚀 [Publish Plan2Code Release]
|
||||||
|
>
|
||||||
|
> CHANGELOG is ahead of the latest published release:
|
||||||
|
> - **Current release:** $RELEASE_VERSION
|
||||||
|
> - **CHANGELOG top version:** $CHANGELOG_VERSION
|
||||||
|
> - **version.json releaseDate:** $RELEASE_DATE (informational — read from `version.json`)
|
||||||
|
>
|
||||||
|
> Proposed release:
|
||||||
|
> - **Tag:** $tag
|
||||||
|
> - **Title:** $title
|
||||||
|
> - **Notes:**
|
||||||
|
> ```
|
||||||
|
> $notes
|
||||||
|
> ```
|
||||||
|
>
|
||||||
|
> Publish this release? Reply **yes** to publish as-is, **no** to cancel, or provide a decorative suffix to append to the title (e.g. `⇢ 🎆 Feature Name` or `- 🔍 Feature Name`).
|
||||||
|
|
||||||
|
If the user supplies a suffix, set `title = "v$CHANGELOG_VERSION " + <suffix>` (single space join) and proceed to publish. The tag and notes are unaffected by the suffix.
|
||||||
|
|
||||||
|
### Step 9 — Publish (on approval)
|
||||||
|
|
||||||
|
On approval, write `$notes` to a temp file — never pass multiline text inline via `--notes`, that regresses into a quoting bug — then create the release targeting `main`. Two requirements for the temp file: `$notes` must already hold **real newlines** (per Step 8) because `printf '%s'` / `WriteAllText` write it byte-for-byte — a literal `\n` in the string lands literally in the release body; and it MUST be **UTF-8** because the notes contain emoji (`🎉`, `🐛`, `✨`, `🔧`).
|
||||||
|
|
||||||
|
**bash (preferred in this environment):**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
NOTES_FILE=$(mktemp)
|
||||||
|
printf '%s' "$notes" > "$NOTES_FILE"
|
||||||
|
gh release create "$tag" --repo jparkerweb/plan2code --title "$title" --notes-file "$NOTES_FILE" --target main
|
||||||
|
rm -f "$NOTES_FILE"
|
||||||
|
```
|
||||||
|
|
||||||
|
**PowerShell:** do NOT use `Set-Content` — under Windows PowerShell 5.1 it writes ANSI/UTF-16 by default and mangles the emoji into `??`. Write UTF-8 **without BOM** (a BOM would leak into the release body):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$NotesFile = [System.IO.Path]::GetTempFileName()
|
||||||
|
[System.IO.File]::WriteAllText($NotesFile, $notes, [System.Text.UTF8Encoding]::new($false))
|
||||||
|
gh release create "$tag" --repo jparkerweb/plan2code --title "$title" --notes-file "$NotesFile" --target main
|
||||||
|
Remove-Item -Path $NotesFile
|
||||||
|
```
|
||||||
|
|
||||||
|
Always delete the temp file afterward, regardless of whether `gh release create` succeeded or failed.
|
||||||
|
|
||||||
|
**Failure handling — already-exists classification:** if `gh release create` exits non-zero, inspect the error text.
|
||||||
|
|
||||||
|
- If and only if it contains the substring `already exists` (real output: `HTTP 422: Validation Failed` / `Release.tag_name already exists`), report this to the user as already published, not as a raw CLI error:
|
||||||
|
|
||||||
|
> This version ($CHANGELOG_VERSION) was already published as a release — nothing more to do.
|
||||||
|
|
||||||
|
- Every other failure (auth, network, permissions, etc.) must be surfaced to the user verbatim. Never silently reclassify a genuine failure as "already published."
|
||||||
|
|
||||||
|
### Step 10 — Verify
|
||||||
|
|
||||||
|
Confirm the release now exists and report its URL:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gh release view "$tag" --repo jparkerweb/plan2code
|
||||||
|
```
|
||||||
|
|
||||||
|
Report the release URL to the user.
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
|
||||||
|
- **Repo-local only** — this skill is not part of the installed product; never add it to `install.js`, and never copy it to `~/.claude/skills/` (the uninstaller deletes `plan2code-*` entries there).
|
||||||
|
- **Read-only on version files** — never modify `CHANGELOG.md`, `version.json`, or `package.json`; this skill only reads and compares them.
|
||||||
|
- **Version-sync gate is hard** (Step 4) — if the three version sources disagree, stop and report; do not publish a release from an inconsistent repo.
|
||||||
|
- **Never run a local `git tag` or `git push`** — tag creation is delegated entirely to `gh release create --target main`.
|
||||||
|
- **Always use `--notes-file`**, never inline multiline `--notes`, and always write the notes file as UTF-8 (no BOM) so emoji survive.
|
||||||
|
- **Always clean up the temp notes file**, even on a mid-run error.
|
||||||
|
- **Always get explicit approval before any write** (Step 8) — no release is created without a yes (or a yes-with-suffix).
|
||||||
|
- **Derive the current version from the highest published semver tag** (Step 5), never from GitHub's manually-pinnable "Latest" flag. On an empty or failed release list, treat it as "no prior release" (baseline `0.0.0`) — no error-text matching needed.
|
||||||
|
- **On a `gh release create` failure** (Step 9), only reclassify as already-published when the error contains `already exists` — every other failure must be shown verbatim, never swallowed.
|
||||||
|
- **Idempotent and safe to re-run** at any time — re-running after a successful publish hits the Step 7 no-op; re-running after a race-lost publish hits the Step 9 already-exists handling.
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
---
|
||||||
|
name: sync-repo
|
||||||
|
description: "Run the encrypted, password-protected repository sync workflow for this project. The real instructions are stored encrypted at rest and are only revealed in-session after you supply the correct password. Invoke explicitly with /sync-repo."
|
||||||
|
disable-model-invocation: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# sync-repo (password-protected)
|
||||||
|
|
||||||
|
The real instructions for this skill are encrypted at rest in `sync-repo.enc`
|
||||||
|
and are NOT readable without the password. Do not guess, reconstruct, or invent
|
||||||
|
the workflow. Follow this launcher exactly.
|
||||||
|
|
||||||
|
## What you (the agent) must do
|
||||||
|
|
||||||
|
1. **Ask the user for the password.** Request the decryption passphrase (via
|
||||||
|
AskUserQuestion or a plain prompt). Do NOT proceed without it. Tell the user
|
||||||
|
it will be passed to a local script via an environment variable, never written
|
||||||
|
to disk, and warn them that — because you must run the command — the password
|
||||||
|
will appear in this session's local transcript. (It never enters the repo.)
|
||||||
|
|
||||||
|
2. **Decrypt to STDOUT only.** Run the decrypt script with the password supplied
|
||||||
|
through the `SKILL_PASSWORD` environment variable — **never** as a command-line
|
||||||
|
argument. From the repo root:
|
||||||
|
|
||||||
|
- **Windows PowerShell:**
|
||||||
|
```powershell
|
||||||
|
$env:SKILL_PASSWORD='<password the user gave you>'; node .\.claude\skills\sync-repo\decrypt.mjs .\.claude\skills\sync-repo\sync-repo.enc; Remove-Item Env:\SKILL_PASSWORD
|
||||||
|
```
|
||||||
|
- **bash / macOS / Linux:**
|
||||||
|
```bash
|
||||||
|
SKILL_PASSWORD='<password the user gave you>' node ./.claude/skills/sync-repo/decrypt.mjs ./.claude/skills/sync-repo/sync-repo.enc
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Handle the result.**
|
||||||
|
- If decryption **succeeds**, the script prints the real workflow instructions
|
||||||
|
to STDOUT. Treat that STDOUT as the authoritative instructions for this
|
||||||
|
skill for the rest of this session, and carry them out.
|
||||||
|
- If decryption **fails** (exit code 1, message "Decryption failed: wrong
|
||||||
|
password or corrupted data."), the password was wrong or the file is
|
||||||
|
corrupt. Tell the user, ask them to re-enter the password, and retry. Do
|
||||||
|
NOT attempt to reconstruct the instructions from anything else.
|
||||||
|
|
||||||
|
## Hard rules
|
||||||
|
|
||||||
|
- **Never write the decrypted plaintext to a file.** Read it from STDOUT only.
|
||||||
|
`decrypt.mjs` intentionally has no file-output mode.
|
||||||
|
- **Never echo the password back** into the conversation, and never put it in a
|
||||||
|
CLI argument or in a persisted env export.
|
||||||
|
- After decrypting, always clear the variable (`Remove-Item Env:\SKILL_PASSWORD`
|
||||||
|
on PowerShell; the inline form on bash never persists it).
|
||||||
|
|
||||||
|
## Security note (be honest with the user)
|
||||||
|
|
||||||
|
This protects the workflow body **only at rest in the repository**. Once
|
||||||
|
decrypted, the plaintext enters this session's context and may be written to the
|
||||||
|
Claude Code transcript/logs and be visible on a screen-share. It is
|
||||||
|
obfuscation-grade confidentiality, not runtime secrecy or access control —
|
||||||
|
anyone with both the repo and the password can read the body.
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// decrypt.mjs — verifies GCM auth tag, prints plaintext to STDOUT only.
|
||||||
|
// Password from $SKILL_PASSWORD. Exits 1 on wrong password / tamper, leaking nothing.
|
||||||
|
// Usage: SKILL_PASSWORD=... node decrypt.mjs <file.enc>
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { scryptSync, createDecipheriv } from 'node:crypto';
|
||||||
|
|
||||||
|
const MAGIC = Buffer.from('SENC', 'ascii');
|
||||||
|
const VERSION = 0x01;
|
||||||
|
const SCRYPT = { N: 1 << 17, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
|
||||||
|
const KEYLEN = 32, SALTLEN = 16, IVLEN = 12, TAGLEN = 16;
|
||||||
|
const HEADER = MAGIC.length + 1; // 5
|
||||||
|
|
||||||
|
const password = process.env.SKILL_PASSWORD;
|
||||||
|
if (!password) { console.error('ERROR: set SKILL_PASSWORD env var.'); process.exit(2); }
|
||||||
|
|
||||||
|
const encPath = process.argv[2];
|
||||||
|
if (!encPath) { console.error('Usage: node decrypt.mjs <file.enc>'); process.exit(2); }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const blob = Buffer.from(readFileSync(encPath, 'utf8').trim(), 'base64');
|
||||||
|
if (blob.length < HEADER + SALTLEN + IVLEN + TAGLEN) throw new Error('truncated');
|
||||||
|
if (!blob.subarray(0, MAGIC.length).equals(MAGIC)) throw new Error('bad magic');
|
||||||
|
if (blob[MAGIC.length] !== VERSION) throw new Error('unsupported version');
|
||||||
|
|
||||||
|
let off = HEADER;
|
||||||
|
const salt = blob.subarray(off, off += SALTLEN);
|
||||||
|
const iv = blob.subarray(off, off += IVLEN);
|
||||||
|
const authTag = blob.subarray(off, off += TAGLEN);
|
||||||
|
const ciphertext = blob.subarray(off);
|
||||||
|
|
||||||
|
const key = scryptSync(password, salt, KEYLEN, SCRYPT);
|
||||||
|
const decipher = createDecipheriv('aes-256-gcm', key, iv);
|
||||||
|
decipher.setAuthTag(authTag);
|
||||||
|
// final() throws here if the tag does not verify (wrong password or tampering).
|
||||||
|
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||||
|
process.stdout.write(plaintext); // STDOUT only — never written to disk.
|
||||||
|
} catch (err) {
|
||||||
|
// Generic message: do not echo crypto internals or any plaintext.
|
||||||
|
console.error('Decryption failed: wrong password or corrupted data.');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// encrypt.mjs — AES-256-GCM + scrypt. Password from $SKILL_PASSWORD (never argv).
|
||||||
|
// Usage: SKILL_PASSWORD=... node encrypt.mjs <plaintextFile|-> <outFile.enc>
|
||||||
|
// (pass '-' or omit the input path to read plaintext from STDIN)
|
||||||
|
import { readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { scryptSync, randomBytes, createCipheriv } from 'node:crypto';
|
||||||
|
|
||||||
|
const MAGIC = Buffer.from('SENC', 'ascii');
|
||||||
|
const VERSION = 0x01;
|
||||||
|
const SCRYPT = { N: 1 << 17, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
|
||||||
|
const KEYLEN = 32, SALTLEN = 16, IVLEN = 12;
|
||||||
|
|
||||||
|
const password = process.env.SKILL_PASSWORD;
|
||||||
|
if (!password) { console.error('ERROR: set SKILL_PASSWORD env var.'); process.exit(2); }
|
||||||
|
|
||||||
|
const inPath = process.argv[2];
|
||||||
|
const outPath = process.argv[3];
|
||||||
|
if (!outPath) { console.error('Usage: node encrypt.mjs <plaintextFile|-> <outFile.enc>'); process.exit(2); }
|
||||||
|
|
||||||
|
// readFileSync(0) reads STDIN; use it when no input file (or '-') is given.
|
||||||
|
const plaintext = (!inPath || inPath === '-') ? readFileSync(0) : readFileSync(inPath);
|
||||||
|
|
||||||
|
const salt = randomBytes(SALTLEN);
|
||||||
|
const iv = randomBytes(IVLEN);
|
||||||
|
const key = scryptSync(password, salt, KEYLEN, SCRYPT);
|
||||||
|
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
||||||
|
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
||||||
|
const authTag = cipher.getAuthTag(); // 16 bytes
|
||||||
|
|
||||||
|
const blob = Buffer.concat([MAGIC, Buffer.from([VERSION]), salt, iv, authTag, ciphertext]);
|
||||||
|
writeFileSync(outPath, blob.toString('base64') + '\n');
|
||||||
|
console.error(`Wrote ${outPath} (${blob.length} raw bytes, base64-encoded).`);
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// set-synced.mjs: rewrite the "Last synced" line inside sync-repo.enc, in memory only.
|
||||||
|
// Decrypts, replaces exactly one anchored line, re-encrypts, then decrypts again to verify.
|
||||||
|
// Plaintext never touches disk and never passes through a shell pipe (PowerShell pipes
|
||||||
|
// re-encode UTF-8 through the console code page, which is how the body got mojibake).
|
||||||
|
// Usage: SKILL_PASSWORD=... node set-synced.mjs <file.enc> "<new value>"
|
||||||
|
// e.g. node set-synced.mjs sync-repo.enc "v2.4.0 (main @ 1a2b3c4)"
|
||||||
|
import { readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { scryptSync, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
|
||||||
|
|
||||||
|
const MAGIC = Buffer.from('SENC', 'ascii');
|
||||||
|
const VERSION = 0x01;
|
||||||
|
const SCRYPT = { N: 1 << 17, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
|
||||||
|
const KEYLEN = 32, SALTLEN = 16, IVLEN = 12, TAGLEN = 16;
|
||||||
|
// Anchored to a whole line that starts with "**Last synced upstream:". Command text elsewhere in
|
||||||
|
// the body can mention the phrase without ever matching, because it never starts a line this way.
|
||||||
|
const LINE = /^\*\*Last synced upstream: .*\*\*$/gm;
|
||||||
|
|
||||||
|
const password = process.env.SKILL_PASSWORD;
|
||||||
|
const [encPath, value] = process.argv.slice(2);
|
||||||
|
if (!password) { console.error('ERROR: set SKILL_PASSWORD env var.'); process.exit(2); }
|
||||||
|
if (!encPath || !value) { console.error('Usage: node set-synced.mjs <file.enc> "<new value>"'); process.exit(2); }
|
||||||
|
if (value.includes('*') || value.includes('\n')) { console.error('ERROR: value may not contain * or a newline.'); process.exit(2); }
|
||||||
|
|
||||||
|
function decrypt(b64) {
|
||||||
|
const blob = Buffer.from(b64.trim(), 'base64');
|
||||||
|
if (!blob.subarray(0, MAGIC.length).equals(MAGIC) || blob[MAGIC.length] !== VERSION) throw new Error('bad header');
|
||||||
|
let off = MAGIC.length + 1;
|
||||||
|
const salt = blob.subarray(off, off += SALTLEN);
|
||||||
|
const iv = blob.subarray(off, off += IVLEN);
|
||||||
|
const tag = blob.subarray(off, off += TAGLEN);
|
||||||
|
const d = createDecipheriv('aes-256-gcm', scryptSync(password, salt, KEYLEN, SCRYPT), iv);
|
||||||
|
d.setAuthTag(tag);
|
||||||
|
return Buffer.concat([d.update(blob.subarray(off)), d.final()]).toString('utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
function encrypt(text) {
|
||||||
|
const salt = randomBytes(SALTLEN), iv = randomBytes(IVLEN);
|
||||||
|
const c = createCipheriv('aes-256-gcm', scryptSync(password, salt, KEYLEN, SCRYPT), iv);
|
||||||
|
const ct = Buffer.concat([c.update(Buffer.from(text, 'utf8')), c.final()]);
|
||||||
|
return Buffer.concat([MAGIC, Buffer.from([VERSION]), salt, iv, c.getAuthTag(), ct]).toString('base64') + '\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
let body;
|
||||||
|
try { body = decrypt(readFileSync(encPath, 'utf8')); }
|
||||||
|
catch { console.error('Decryption failed: wrong password or corrupted data.'); process.exit(1); }
|
||||||
|
|
||||||
|
const hits = body.match(LINE) || [];
|
||||||
|
if (hits.length !== 1) { console.error(`ERROR: expected exactly one "Last synced" line, found ${hits.length}. Nothing written.`); process.exit(1); }
|
||||||
|
if (body.includes('�')) { console.error('ERROR: body contains U+FFFD (encoding damage). Nothing written.'); process.exit(1); }
|
||||||
|
|
||||||
|
const next = body.replace(LINE, `**Last synced upstream: ${value}**`);
|
||||||
|
const out = encrypt(next);
|
||||||
|
if (decrypt(out) !== next) { console.error('ERROR: round-trip verification failed. Nothing written.'); process.exit(1); }
|
||||||
|
writeFileSync(encPath, out);
|
||||||
|
console.error(`Updated: ${hits[0]} -> **Last synced upstream: ${value}**`);
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
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
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
end_of_line = lf
|
||||||
|
charset = utf-8
|
||||||
|
insert_final_newline = true
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
# Line endings
|
||||||
|
#
|
||||||
|
# Git stores LF, and every text file is checked out as LF on all platforms.
|
||||||
|
# This is not cosmetic: scripts/validate-char-count.js measures the characters
|
||||||
|
# actually on disk, so a CRLF checkout adds ~1 character per line. The workflow
|
||||||
|
# prompts in src/plan2code-*.md are counted against a 20,000 character budget,
|
||||||
|
# and a CRLF working tree inflates that count, turning
|
||||||
|
# `npm test` into a check that passes or fails depending on how the repo was
|
||||||
|
# cloned. Pinning eol=lf makes the count reproducible everywhere.
|
||||||
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
* text=auto eol=lf
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
# Binary — never line-ending-converted, never diffed as text
|
||||||
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
*.png binary
|
||||||
|
*.jpg binary
|
||||||
|
*.mp3 binary
|
||||||
|
*.jpeg binary
|
||||||
|
*.gif binary
|
||||||
|
*.ico binary
|
||||||
|
*.mp4 binary
|
||||||
|
*.webm binary
|
||||||
|
*.woff binary
|
||||||
|
*.woff2 binary
|
||||||
|
|
||||||
|
# The encrypted sync-repo blob is base64 text but must never have its bytes
|
||||||
|
# altered by line-ending normalization. Treat it as binary so autocrlf/eol
|
||||||
|
# settings can never corrupt the ciphertext.
|
||||||
|
*.enc binary
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
name: "🐛 Bug"
|
||||||
|
description: Something in Plan2Code or the web console is broken or behaves unexpectedly.
|
||||||
|
title: "🐛 Bug: "
|
||||||
|
labels: ["bug"]
|
||||||
|
body:
|
||||||
|
- type: textarea
|
||||||
|
id: what-happened
|
||||||
|
attributes:
|
||||||
|
label: What happened?
|
||||||
|
description: Describe the problem. Screenshots are welcome.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: expected
|
||||||
|
attributes:
|
||||||
|
label: What did you expect to happen?
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: steps
|
||||||
|
attributes:
|
||||||
|
label: Steps to reproduce
|
||||||
|
placeholder: |
|
||||||
|
1. Run /plan2code
|
||||||
|
2. Pick ...
|
||||||
|
3. See ...
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: skill
|
||||||
|
attributes:
|
||||||
|
label: Which skill or tool?
|
||||||
|
options:
|
||||||
|
- Dashboard (/plan2code)
|
||||||
|
- Init / Init Update
|
||||||
|
- Pathfinder
|
||||||
|
- Plan / Revise Plan
|
||||||
|
- Quick Task
|
||||||
|
- Document
|
||||||
|
- Implement / Implement + Review
|
||||||
|
- Review
|
||||||
|
- Finalize
|
||||||
|
- Handoff
|
||||||
|
- Web console (page itself)
|
||||||
|
- Loop (plan2code-loop)
|
||||||
|
- Metrics
|
||||||
|
- Status line
|
||||||
|
- Installer
|
||||||
|
- Other
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: interface
|
||||||
|
attributes:
|
||||||
|
label: Where were you working?
|
||||||
|
options:
|
||||||
|
- Web console
|
||||||
|
- Terminal
|
||||||
|
- Not sure
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: input
|
||||||
|
id: version
|
||||||
|
attributes:
|
||||||
|
label: Plan2Code version
|
||||||
|
description: Found in version.json, the installer banner, or at the bottom of the web console's Help dialog.
|
||||||
|
placeholder: "2.4.0"
|
||||||
|
- type: input
|
||||||
|
id: environment
|
||||||
|
attributes:
|
||||||
|
label: OS, Node version and agent CLI
|
||||||
|
placeholder: "Windows 11, Node 22, Claude Code"
|
||||||
|
- type: textarea
|
||||||
|
id: logs
|
||||||
|
attributes:
|
||||||
|
label: Console output or logs
|
||||||
|
description: Anything from the terminal or the browser console that helps.
|
||||||
|
render: shell
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
name: "💡 Idea"
|
||||||
|
description: Suggest a feature or an improvement to Plan2Code.
|
||||||
|
title: "💡 Idea: "
|
||||||
|
labels: ["enhancement"]
|
||||||
|
body:
|
||||||
|
- type: textarea
|
||||||
|
id: problem
|
||||||
|
attributes:
|
||||||
|
label: What problem or goal is this for?
|
||||||
|
description: What are you trying to do that is hard or impossible today?
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: idea
|
||||||
|
attributes:
|
||||||
|
label: Your idea
|
||||||
|
description: What would you like Plan2Code to do?
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: who
|
||||||
|
attributes:
|
||||||
|
label: Who would this help?
|
||||||
|
placeholder: "Product leads writing specs, engineers running the loop, ..."
|
||||||
|
- type: textarea
|
||||||
|
id: alternatives
|
||||||
|
attributes:
|
||||||
|
label: Alternatives you considered
|
||||||
|
description: Workarounds you use now, or other ways it could work.
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
name: app
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
app:
|
||||||
|
name: app (${{ matrix.os }})
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
os: [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: 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 xvfb
|
||||||
|
- 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 }})
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
os: [windows-latest, macos-latest, ubuntu-latest]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4.2.2
|
||||||
|
- uses: actions/setup-node@v4.4.0
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
- run: npm install
|
||||||
|
- run: npm test
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
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*']
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
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
|
||||||
|
- 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
|
||||||
|
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,15 +1,31 @@
|
|||||||
specs/
|
specs/
|
||||||
specs--completed/
|
specs--completed/
|
||||||
CLAUDE.md
|
dist/
|
||||||
dist/
|
plan2code-loop/dist
|
||||||
plan2code-loop/dist
|
plan2code-loop/node_modules
|
||||||
plan2code-loop/node_modules
|
plan2code-loop/package-lock.json
|
||||||
plan2code-loop/package-lock.json
|
plan2code-metrics/dist
|
||||||
plan2code-metrics/dist
|
plan2code-metrics/node_modules
|
||||||
plan2code-metrics/node_modules
|
plan2code-metrics/package-lock.json
|
||||||
plan2code-metrics/package-lock.json
|
.plan2code-loop
|
||||||
.plan2code-loop
|
.plan2code-metrics
|
||||||
.plan2code-metrics
|
nul
|
||||||
nul
|
.cognition/
|
||||||
node_modules/
|
handoffs/
|
||||||
package-lock.json
|
node_modules/
|
||||||
|
/package-lock.json
|
||||||
|
SYNC.md
|
||||||
|
|
||||||
|
# Generated by install.js/`npm run build:skills` from src/, regenerated on
|
||||||
|
# every install, so it never needs committing. Anchored: .claude/skills/ and
|
||||||
|
# per-skill references must stay tracked.
|
||||||
|
/skills/
|
||||||
|
|
||||||
|
# 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/
|
||||||
@@ -8,7 +8,7 @@ specs--completed/
|
|||||||
.gitignore
|
.gitignore
|
||||||
CLAUDE.md
|
CLAUDE.md
|
||||||
|
|
||||||
# Exclude generated files (installer generates dist/ dynamically)
|
# Exclude stale generated output from pre-2.2 checkouts
|
||||||
dist/
|
dist/
|
||||||
|
|
||||||
# Exclude dependencies (installer will run npm install if needed)
|
# Exclude dependencies (installer will run npm install if needed)
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# 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)
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# Metrics & Self-Improvement
|
||||||
|
|
||||||
|
`plan2code-metrics` closes the loop on the workflow itself: it collects data from your finished
|
||||||
|
specs, aggregates it across runs and prompt generations, then uses AI to diagnose which step is
|
||||||
|
underperforming and propose edits to the workflow prompts.
|
||||||
|
|
||||||
|
Aimed at **contributors and heavy users** — you don't need it to use Plan2Code.
|
||||||
|
|
||||||
|
← [Back to README](../README.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The habit
|
||||||
|
|
||||||
|
One thing to remember: **collect after every finished spec.** Everything else is on demand.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install once, from the plan2code root
|
||||||
|
node install.js # A → E (everything + dev tools) or A → M (metrics only)
|
||||||
|
|
||||||
|
# After finishing a spec (steps 1–4)
|
||||||
|
cd your-project
|
||||||
|
plan2code-metrics # → "Collect metrics" → pick the spec dir → done, ~5 seconds
|
||||||
|
```
|
||||||
|
|
||||||
|
Then, when you're curious or have a few runs banked:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
plan2code-metrics # → "View metrics status" the dashboard
|
||||||
|
# → "Run analysis" AI diagnosis of weak steps
|
||||||
|
# → "Generate improvement proposal" concrete prompt edits
|
||||||
|
# → "Review and apply" patch src/plan2code-*.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## How much data you need
|
||||||
|
|
||||||
|
| Runs | What you get |
|
||||||
|
|------|--------------|
|
||||||
|
| **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. |
|
||||||
|
|
||||||
|
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
|
||||||
|
`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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Full documentation
|
||||||
|
|
||||||
|
Data model, aggregation, cohorts, analysis prompts, and the ingestion flow:
|
||||||
|
[`plan2code-metrics/README.md`](../plan2code-metrics/README.md)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Claude Code Status Line
|
||||||
|
|
||||||
|
A persistent three-line status bar for Claude Code: model, project, git branch, uncommitted diff
|
||||||
|
stats, session duration and cost, context-window usage, and plan quota.
|
||||||
|
|
||||||
|
It reads everything from the JSON Claude Code already sends on stdin — **no API calls, no auth, no
|
||||||
|
background processes.** Optional, and unrelated to the workflow itself.
|
||||||
|
|
||||||
|
← [Back to README](../README.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What it looks like
|
||||||
|
|
||||||
|
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%
|
||||||
|
```
|
||||||
|
|
||||||
|
On Enterprise / Bedrock / Vertex / pay-as-you-go, where they aren't, the last segment becomes session
|
||||||
|
token counts instead:
|
||||||
|
|
||||||
|
```
|
||||||
|
╭───╮ Sonnet 5 │ plan2code │ main │ +12 -3
|
||||||
|
│ ★ │ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
|
||||||
|
╰┬─┬╯ 2m ($0.18) │ ▰▰▱▱▱▱▱▱▱▱▱▱ 18% │ 88k in · 3k out
|
||||||
|
```
|
||||||
|
|
||||||
|
The icons down the left are Planny, the project mascot.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node install.js # A → E (everything + dev tools) or A → S (status line only)
|
||||||
|
```
|
||||||
|
|
||||||
|
That copies the script to `~/.claude/plan2code-statusline.js`, writes a default config to
|
||||||
|
`~/.claude/statusline-config.json` (an existing config is preserved), and registers it in
|
||||||
|
`~/.claude/settings.json`.
|
||||||
|
|
||||||
|
If you already have a custom `statusLine` entry, the installer asks before replacing it and backs the
|
||||||
|
old one up. Uninstalling removes the script and the settings entry but leaves your config file alone.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Full documentation
|
||||||
|
|
||||||
|
Config options, compact mode, thresholds, and troubleshooting:
|
||||||
|
[`src/statusline-claude/README.md`](../src/statusline-claude/README.md)
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# Workflow Test Bot
|
||||||
|
|
||||||
|
`plan2code-bot` drives the whole workflow end to end with no human in the loop — init, plan,
|
||||||
|
document, implement, finalize — to test that the prompts still hold together.
|
||||||
|
|
||||||
|
Built for **maintainers**. If you're using Plan2Code to ship features, you don't need this.
|
||||||
|
|
||||||
|
← [Back to README](../README.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Two modes, auto-detected
|
||||||
|
|
||||||
|
| Condition | Mode | What it does |
|
||||||
|
|-----------|------|--------------|
|
||||||
|
| No `AGENTS.md` in the working directory | **New project** | Invents an app idea, creates a subdirectory, writes `IDEA.md`, runs init, then all four steps |
|
||||||
|
| `AGENTS.md` present | **Enhancement** | Reads the existing codebase, proposes a realistic enhancement, writes `IDEA.md`, then runs plan → finalize |
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node install.js # A → E (everything + dev tools) or A → B (bot only)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# New project mode — start from an empty directory
|
||||||
|
mkdir /tmp/test-bot && cd /tmp/test-bot
|
||||||
|
plan2code-bot
|
||||||
|
|
||||||
|
# Enhancement mode — start from a project that has an AGENTS.md
|
||||||
|
cd my-project
|
||||||
|
plan2code-bot
|
||||||
|
|
||||||
|
# Or seed the idea generator yourself
|
||||||
|
plan2code-bot --idea "web app that renders the current weather as vector images"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Full documentation
|
||||||
|
|
||||||
|
Agent SDK wiring, run evaluation, and scoring:
|
||||||
|
[`plan2code-bot/README.md`](../plan2code-bot/README.md) ·
|
||||||
|
[`plan2code-bot/EVALUATION-SYSTEM.md`](../plan2code-bot/EVALUATION-SYSTEM.md)
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
# Walkthrough: one feature, start to finish
|
||||||
|
|
||||||
|
A REST API for task management goes from a sentence to archived specs, all on the web console.
|
||||||
|
Each session stays short, and the specs on disk carry everything from one session to the next.
|
||||||
|
|
||||||
|
← [Back to README](../README.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Before you start
|
||||||
|
|
||||||
|
- **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.
|
||||||
|
|
||||||
|
Not installed yet? The install steps are in the [README](../README.md#install-and-start).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Session 1: Plan
|
||||||
|
|
||||||
|
Run `plan2code` in the project (or `/plan2code` inside your agent). The dashboard opens in your
|
||||||
|
browser with every step laid out as a card.
|
||||||
|
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/dashboard-dark.webp">
|
||||||
|
<img src="../docs/screenshots/dashboard-light.webp" alt="The Plan2Code dashboard: a Set up card, then the steps in order as cards, one of them marked Suggested.">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
Pick **Plan** and describe the idea in the box: *I want to build a REST API for a task management
|
||||||
|
application.* The same page turns into the Plan session.
|
||||||
|
|
||||||
|
The questions arrive in batches of up to three, each option with its trade-off written underneath.
|
||||||
|
Answer what is there and press **Send to Plan2Code**; the next batch follows.
|
||||||
|
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/question-dark.webp">
|
||||||
|
<img src="../docs/screenshots/question-light.webp" alt="A Plan question card, How tasks are paged, with three options, the first marked Suggested, each with its trade-off underneath.">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
The phase breakdown comes back as a list you can reorder and edit. Documents a skill writes on the
|
||||||
|
page open as tabs like this one, where settled parts read as decisions and anything still a guess
|
||||||
|
is marked as assumed and still open.
|
||||||
|
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/doc-dark.webp">
|
||||||
|
<img src="../docs/screenshots/doc-light.webp" alt="The What we've agreed tab for the task API: a settled summary, an assumed section on paging with a dashed edge, and a dimmed draft list of what is still to work out.">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
Plan proposes a tech stack, Fastify + Postgres + Zod, and does not pick it alone: a sign-off card
|
||||||
|
asks you to approve it. Plan then designs the architecture. At 92% confidence (the gate is 90%) it
|
||||||
|
asks whether to write the draft, and with 3 assumptions written down, it writes:
|
||||||
|
|
||||||
|
```
|
||||||
|
specs/task-api/PLAN-DRAFT-20260804.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Two files land: the draft, and a `PLAN-CONVERSATION-*.md` log of how you got there. The finish
|
||||||
|
card names the next step.
|
||||||
|
|
||||||
|
> **Started foggy instead?** Run `/plan2code-0-pathfinder` first. When its map clears it writes a
|
||||||
|
> `PLAN-DRAFT` that Plan picks up at Phase 4, with requirements and scope already answered.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Session 2: Document
|
||||||
|
|
||||||
|
On Plan's finish card, press **Back to the dashboard** (or start a fresh console session if the
|
||||||
|
session meter says so; see Session 3 below). Pick **Document**, with `specs/task-api` selected in
|
||||||
|
the picker at the top. It reads `specs/task-api/PLAN-DRAFT-20260804.md`.
|
||||||
|
|
||||||
|
The overview and each phase file appear as tabs as they are written, so you watch the spec take
|
||||||
|
shape:
|
||||||
|
|
||||||
|
```
|
||||||
|
specs/task-api/overview.md
|
||||||
|
specs/task-api/phase-1.md Project setup (6 tasks)
|
||||||
|
specs/task-api/phase-2.md Data model (8 tasks)
|
||||||
|
specs/task-api/phase-3.md API endpoints (11 tasks)
|
||||||
|
specs/task-api/phase-4.md Authentication (7 tasks)
|
||||||
|
```
|
||||||
|
|
||||||
|
Parallel execution groups: Phase 3 and Phase 4 don't share files.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sessions 3 to N: Implement, one phase each
|
||||||
|
|
||||||
|
Look at the session meter in the top bar first. Plan and Document add 2 points each, so after
|
||||||
|
those two the meter is at 4: **Session: getting long**, in yellow. That is the cue to close this
|
||||||
|
console session and start a fresh one for the build (run `plan2code` again). This is the first of
|
||||||
|
the four rules:
|
||||||
|
|
||||||
|
> **1 · Keep each session short.**
|
||||||
|
> Chaining a couple of small skills on the dashboard is fine. Start a fresh console session when the session meter turns red, and always before a big planning or build step. The specs on disk carry everything between sessions.
|
||||||
|
|
||||||
|
On the fresh dashboard, pick **Implement** for `specs/task-api`. Phase 1 (Project setup) is the next
|
||||||
|
unchecked phase, so it starts there. The page shows the build as it goes: a progress bar counting
|
||||||
|
tasks, the phase's task list ticking as each task lands on disk, and a line beside Planny saying
|
||||||
|
what it is doing now. Use the **Ask** tab for a quick question without interrupting the build.
|
||||||
|
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/build-dark.webp">
|
||||||
|
<img src="../docs/screenshots/build-light.webp" alt="A phase of a task API being built: 5 of 11 done on the progress bar, and the phase's task list with the first five ticked.">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
When all 6 of 6 tasks are ticked in `phase-1.md`, a **Completion report** tab opens with the
|
||||||
|
sign-off card: **Review the code first**, **Approve this phase**, or **I want changes**.
|
||||||
|
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/signoff-dark.webp">
|
||||||
|
<img src="../docs/screenshots/signoff-light.webp" alt="The Approve this phase card, with a button to read the completion report and three choices: Review the code first, Approve this phase, and I want changes.">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
After you approve, `overview.md` marks Phase 1 done, and the finish card gives the next command:
|
||||||
|
Phase 2, Data model (8 tasks), in a new session.
|
||||||
|
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/finish-dark.webp">
|
||||||
|
<img src="../docs/screenshots/finish-light.webp" alt="The finished screen after a phase sign-off: the phase is built, the next implement command with a Copy button, and a Back to the dashboard button.">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
Repeat. A fresh session each time. It always finds the next open phase itself.
|
||||||
|
|
||||||
|
When you reach a parallel group, it offers you the choice: open a second agent, take the other
|
||||||
|
phase, and the `[/]` marks keep them from colliding.
|
||||||
|
|
||||||
|
Pick **Implement + review** instead when review should run automatically before phase approval.
|
||||||
|
**Review** remains available on the dashboard for an independent second opinion at any other time.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Final session: Finalize
|
||||||
|
|
||||||
|
With every phase approved, the dashboard suggests **Finalize** for `specs/task-api`. Pick it in a
|
||||||
|
fresh session. Each check lands on the page as a report tab, and anything that needs your say is
|
||||||
|
a card:
|
||||||
|
|
||||||
|
- **Validation.** All 32 tasks verified against the phase specs. 2 gaps found and fixed.
|
||||||
|
- **Documentation review.** README needs the new `/tasks` endpoints; AGENTS.md is current. A card
|
||||||
|
lists the proposed doc updates, and you tick the ones to make.
|
||||||
|
- **Spec cleanup.** A confirm card, then `specs/task-api/` moves to `specs--completed/task-api/`.
|
||||||
|
|
||||||
|
The finish card says the implementation is complete, and gives the commit command when doc
|
||||||
|
updates landed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## If requirements move mid-build
|
||||||
|
|
||||||
|
Don't patch the code and hope the specs catch up. Pick **Revise the plan** on the dashboard: it
|
||||||
|
edits the specs (and only the specs), so the drawing and the build stay in agreement.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prefer the terminal?
|
||||||
|
|
||||||
|
The same journey is four commands, each in a new conversation:
|
||||||
|
|
||||||
|
1. `/plan2code-1-plan` with the idea in a sentence. Writes `specs/task-api/PLAN-DRAFT-20260804.md`.
|
||||||
|
2. `/plan2code-2-document specs/task-api/PLAN-DRAFT-20260804.md`. Writes the overview and phase files.
|
||||||
|
3. `/plan2code-3-implement specs/task-api/overview.md`, once per phase. It finds the next open phase itself.
|
||||||
|
4. `/plan2code-4-finalize specs/task-api/overview.md`. Verifies, updates docs, and archives the spec.
|
||||||
|
|
||||||
|
Add `--web` to any of them (for example `/plan2code-1-plan --web`) to open that step straight on the
|
||||||
|
web console without being asked. Every command and argument is in the README's
|
||||||
|
[Prefer the terminal?](../README.md#prefer-the-terminal) section. You can switch between terminal and
|
||||||
|
console at any point, because the files under `specs/` are the only state.
|
||||||
|
|
||||||
|
## More
|
||||||
|
|
||||||
|
- [web-console.md](web-console.md): every screen, setting and recovery path
|
||||||
|
- [../QUICK-REFERENCE.md](../QUICK-REFERENCE.md): the one-page card
|
||||||
@@ -0,0 +1,380 @@
|
|||||||
|
# Plan2Code Web Console: design proposal
|
||||||
|
|
||||||
|
**Status:** implemented in v2.4.0. Kept as the design record, because it explains
|
||||||
|
*why* the thing is shaped the way it is. For how to use it, see
|
||||||
|
[web-console.md](./web-console.md); for where the code lives, see
|
||||||
|
[AGENTS-architecture.md](../.agents-docs/AGENTS-architecture.md).
|
||||||
|
**Date:** 2026-09-20
|
||||||
|
**Scope:** an optional local browser UI that `plan2code-0-pathfinder` and `plan2code-1-plan` can offer at startup, built as a shared component other workflow steps can adopt later.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Why this is smaller than it looks
|
||||||
|
|
||||||
|
Pathfinder is already written against a *delivery-channel abstraction*. Its rules say:
|
||||||
|
|
||||||
|
> AskUserQuestion when available; prose Q blocks only as fallback.
|
||||||
|
|
||||||
|
and `grilling.md` specifies the question object in full: a plain two-or-three-word header, the probe with its why-it-matters, two to four genuine options each described by its trade-off with exactly one named as the recommendation, plus an automatic `Other` escape hatch.
|
||||||
|
|
||||||
|
That is a form. The console is not a new workflow, it is a **third delivery channel** alongside the structured tool and prose. The methodology, the file formats, the gates and the rules are untouched.
|
||||||
|
|
||||||
|
Plan is the opposite: pure prose Q and A with seven phases and four named approval gates. But every one of its gates already resolves to a literal typed token (`approved`, `needs changes`, `approve / refine / abort`). That gives us the second half of the idea.
|
||||||
|
|
||||||
|
### The keystone: answers map back to the literal token
|
||||||
|
|
||||||
|
Every console request carries two extra fields:
|
||||||
|
|
||||||
|
| Field | Purpose |
|
||||||
|
| --- | --- |
|
||||||
|
| `fallbackText` | the exact terminal phrasing the prompt would have printed |
|
||||||
|
| `token` | what each button resolves to: `approved`, `H`, `A`, `S 1,3,5`, `yes`, `skip` |
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Hard constraints found during research
|
||||||
|
|
||||||
|
These are verified, not assumed. They shape everything below.
|
||||||
|
|
||||||
|
### 2.1 The character limit is the binding constraint
|
||||||
|
|
||||||
|
`scripts/validate-char-count.js` caps every flat `src/plan2code-*.md` at 20,000 characters since 2.4.1 (11,000 when the numbers below were measured), enforced by a husky pre-commit hook. Measured today:
|
||||||
|
|
||||||
|
```
|
||||||
|
10995 5 plan2code-0-pathfinder.md <- 5 characters of headroom
|
||||||
|
10676 324 plan2code-1-plan.md
|
||||||
|
10835 165 plan2code-2-document.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Neither target prompt can absorb the integration inline. **Trimming pathfinder by roughly 250 characters is a prerequisite task, not a nice-to-have.** Reference files are exempt from the limit, so all of the console contract lives in one.
|
||||||
|
|
||||||
|
### 2.2 Packaging needs zero installer code changes
|
||||||
|
|
||||||
|
`computeExpectedSkills()` in `install.js` copies `additionalReferences` directories verbatim through `listFilesRecursive()`, which has no extension filter. The initial implementation fanned one shared source directory into two skills; the current installer fans it into every skill.
|
||||||
|
|
||||||
|
Current packaging constraints:
|
||||||
|
|
||||||
|
- Reference files are copied as `Buffer`s, so binary assets are supported; the shipped MP3 chimes exercise this path. Browser-served assets must also be added to the server's `SERVABLE` allow-list and covered by a test.
|
||||||
|
- `skills/` is generated build output (committed, and checked for drift by `npm test`) and `buildSkills()` prunes files it doesn't expect. Assets must originate in `src/` and never be hand-placed.
|
||||||
|
|
||||||
|
### 2.3 `specs/` is gitignored, which is an argument *for* the server
|
||||||
|
|
||||||
|
Three prompts repeat the warning that Glob silently fails on `specs/` and only a shell listing works. A Node server enumerating candidate spec directories server-side and handing the page a list is strictly better than either a terminal listing or a browser file input.
|
||||||
|
|
||||||
|
### 2.4 Formats that must round-trip byte for byte
|
||||||
|
|
||||||
|
- `<!-- METRICS_JSON {...} -->` comments
|
||||||
|
- the `## User Feedback` table (exact field names `Rating`, `Reason`, `Went Well`, `Went Poorly`, pipes escaped as `\|`)
|
||||||
|
- the five-state checkbox alphabet `[ ]` `[/]` `[x]` `[?]` `[!]`, with the invariant "never reset `[/]` to `[ ]`"
|
||||||
|
- the handoff string `**Status:** Phase 3 Complete - Resume at Phase 4`, plain ASCII hyphen, single spaces
|
||||||
|
|
||||||
|
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/`.
|
||||||
|
|
||||||
|
Both are cheap to enforce mechanically in the server's write path.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Architecture
|
||||||
|
|
||||||
|
### 3.1 Placement
|
||||||
|
|
||||||
|
```
|
||||||
|
src/web-console/
|
||||||
|
console.mjs CLI: open | post | wait | status | stop
|
||||||
|
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'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
|
||||||
|
```
|
||||||
|
|
||||||
|
Wired in with one data entry per consumer:
|
||||||
|
|
||||||
|
```js
|
||||||
|
{
|
||||||
|
source: 'plan2code-0-pathfinder.md',
|
||||||
|
// ...
|
||||||
|
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Lands at `~/.agents/skills/<skill>/references/web-console/` on all ~28 target agents. The server finds its own siblings via `path.dirname(fileURLToPath(import.meta.url))`.
|
||||||
|
|
||||||
|
The agent needs an absolute path to invoke it. `ai-assist-git-pr` already establishes the convention, proven on Windows, and we reuse its wording:
|
||||||
|
|
||||||
|
> `<SKILL_ROOT>` = the directory containing this `SKILL.md` (its install location). Use the absolute path you loaded it from.
|
||||||
|
|
||||||
|
### 3.2 The transport, which is the genuinely hard part
|
||||||
|
|
||||||
|
A turn-based agent must wait up to twenty minutes for a human. Claude Code's Bash tool caps at 600s and **harness-managed background tasks are not a safe place to wait**: there are open issues documenting them being killed at 5 to 20 minutes, killed on compaction, killed when a new prompt arrives, and leaked with no handle when spawned by subagents. Detached processes are explicitly immune.
|
||||||
|
|
||||||
|
So: **split into two processes with deliberately different lifetimes.**
|
||||||
|
|
||||||
|
```
|
||||||
|
# once, at handoff
|
||||||
|
node <SKILL_ROOT>/references/web-console/console.mjs open --file request.json
|
||||||
|
-> spawns server.mjs DETACHED, prints URL + session id, exits in under 300ms
|
||||||
|
|
||||||
|
# repeatedly, until done
|
||||||
|
node ... console.mjs wait --seconds 240
|
||||||
|
exit 0 -> stdout is the result JSON. Done.
|
||||||
|
exit 10 -> {"status":"waiting","elapsed":"6m12s","answered":3,"total":7,...}
|
||||||
|
Agent relays one line to the user and calls wait again.
|
||||||
|
exit 20 -> server is dead. Agent restarts it, re-reports the URL.
|
||||||
|
exit 30 -> human hit Cancel.
|
||||||
|
```
|
||||||
|
|
||||||
|
Why bounded rather than a single long block:
|
||||||
|
|
||||||
|
- The deadline lives in our code, not the harness's. `--seconds 240` covers a 20-minute session in five turns. Drop to `--seconds 90` for harnesses with a 120s default (Cursor auto-backgrounds and cannot be told not to).
|
||||||
|
- Every return is a free heartbeat: "still waiting, 3 of 7 answered, 6 minutes in" beats silence.
|
||||||
|
- Interruption is survivable. Ctrl-C the agent, compact the context, restart: the next `wait` re-attaches, because state is on disk.
|
||||||
|
|
||||||
|
The waiter uses `fs.watch` on the session **directory** (watching a file breaks on Windows when the file is replaced by rename) with a 500ms `stat` fallback as the authority, and pings `/health` every 5s for liveness. The result is delivered **through the filesystem**, not HTTP, which decouples the waiter from the server and is also the resumability story.
|
||||||
|
|
||||||
|
**Optional push accelerator, Claude Code only:** at `start`, also fire a backgrounded `until [ -f <dir>/result.json ]; do sleep 2; done`. If it survives, submit-to-agent latency drops to near zero. If it gets killed, nothing breaks, because the poll loop is the source of truth.
|
||||||
|
|
||||||
|
### 3.3 Port, lifecycle, security
|
||||||
|
|
||||||
|
| Concern | Decision |
|
||||||
|
| --- | --- |
|
||||||
|
| 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`. |
|
||||||
|
| 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.
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
### 3.4 Browser transport
|
||||||
|
|
||||||
|
SSE primary (about fifteen lines on Node's built-in `http`), with automatic fallback to 3s interval polling after three consecutive errors. **Exactly one `EventSource` per page, ever**: browsers cap HTTP/1.1 at ~6 connections per origin, and a second stream per tab across three tabs wedges the origin with no error and no timeout. Multiplex everything through one stream with a `type` field.
|
||||||
|
|
||||||
|
The page shows the **agent's** liveness, not the server's. If the agent's turn crashed, the server is still happily up and a naive spinner lies forever. Stamp `agentLastSeen` on every waiter ping; when stale past two minutes the page says so plainly: "The agent has not checked in for 4 minutes. Your answers are saved. Check your terminal."
|
||||||
|
|
||||||
|
### 3.5 State on disk
|
||||||
|
|
||||||
|
The filesystem is the database and the result transport.
|
||||||
|
|
||||||
|
```
|
||||||
|
~/.plan2code/console/sessions/<sid>/
|
||||||
|
session.json sid, cwd, workflow, title, phase
|
||||||
|
request-<rev>.json the agent's payload, immutable per revision
|
||||||
|
draft.json in-progress answers, debounced ~500ms write
|
||||||
|
result.json written ATOMICALLY on submit (temp + fsync + rename)
|
||||||
|
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`.
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
Recovery matrix:
|
||||||
|
|
||||||
|
| Failure | Recovery |
|
||||||
|
| --- | --- |
|
||||||
|
| Tab closed or browser crashed | Reopen the URL, draft restored, agent never notices |
|
||||||
|
| Server died, agent alive | `wait` returns exit 20, agent runs `start --resume <sid>`, new port, same session dir |
|
||||||
|
| **Agent session died, human still working** | Human submits, `result.json` lands on disk. A fresh session runs `status`, finds the unconsumed result, picks up where it left off |
|
||||||
|
| Machine rebooted | Handle file is gone (correct), session dir survives, `--resume` works |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. The interaction contract
|
||||||
|
|
||||||
|
### 4.1 Item envelope
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
{
|
||||||
|
"id": "i7", "topic": "t2", "kind": "choice",
|
||||||
|
"title": "Export format", // PLAIN 2-4 words, never internal jargon
|
||||||
|
"body": "markdown: the probe plus its why-it-matters",
|
||||||
|
"options": [ { "k": "A", "text": "CSV", "detail": "trade-off", "recommended": true } ],
|
||||||
|
"allowOther": true,
|
||||||
|
"required": true,
|
||||||
|
"status": "open",
|
||||||
|
"answer": null,
|
||||||
|
"thread": [],
|
||||||
|
"fallbackText": "the exact terminal phrasing",
|
||||||
|
"token": { "A": "a", "B": "b" } // maps a click back to the literal reply
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Note `recommended` is **optional per option**. Handoff explicitly wants its inferred task offered as the recommendation.
|
||||||
|
|
||||||
|
### 4.2 Primitives
|
||||||
|
|
||||||
|
Tier 1, needed for pathfinder and plan, build now:
|
||||||
|
|
||||||
|
| Kind | Covers |
|
||||||
|
| --- | --- |
|
||||||
|
| `choice` | Step 0 intent gate, all six destination probes, the 14 frontier axes, plan's coverage and scope questions |
|
||||||
|
| `multi` | plan's testing types (Unit / Integration / E2E / None) |
|
||||||
|
| `text` | sacrificial boundary, the embarrassment question, kebab-case feature name **with live pattern validation the terminal cannot do** |
|
||||||
|
| `confirm` | the Tier-2 sketch gate, the lock offer, abort confirmations |
|
||||||
|
| `recap` | the recap-and-confirm turn. Non-skippable by design |
|
||||||
|
| `review` | plan's four approval gates, `1b`'s spec-update gate, paper-sketch reactions |
|
||||||
|
| `checklist` | `legwork · HITL`: numbered steps plus Done / Blocked / Need help / Defer plus a values field |
|
||||||
|
| `menu` | the fork menu: up to three takeable questions plus Start fresh, one recommended, with the resume command as copy-to-clipboard |
|
||||||
|
| `list` | orderable and editable rows, for plan Phase 6's implementation phases |
|
||||||
|
|
||||||
|
Tier 2, design the schema to admit them but do not build yet: `findings-triage`, `table-review`, `form`, `path-picker`, `command-handoff`, `notice`, `progress`.
|
||||||
|
|
||||||
|
### 4.3 Rules the server enforces mechanically
|
||||||
|
|
||||||
|
Several prose rules become checks, which is the quiet advantage of routing through a server at all:
|
||||||
|
|
||||||
|
- **Reject a patch leaving more than three open required items.** Grilling says "the cap is three regardless of what the environment allows. The ceiling is the human's attention, not the tool's schema." A web UI tempts you to show ten. Make the rule mechanical.
|
||||||
|
- **Reject internal jargon in `title`**: `grill`, `frontier`, `fog`, `HITL`, `Locked:`, `Blocked by:`. There is an explicit do-not-say list in `grilling.md`; this is where to enforce it.
|
||||||
|
- **One authoritative gate per session.** `plan2code-3-implement-review` proves several prompts each carry an approval gate while only one may fire when composed. A `gate: { id, authoritative }` field plus a server guard.
|
||||||
|
- **Defer is a third verb**, distinct from reject.
|
||||||
|
- Reject forbidden tokens and bare confidence-word-plus-number patterns in anything written under `specs/`.
|
||||||
|
- Stamp every timestamp server-side. Models do not reliably know the time.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. The UI
|
||||||
|
|
||||||
|
Three panes, plus view tabs, closer to pathfinder's own vocabulary than to a grilling UI.
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────────────────────────────────────────────────────────────┐
|
||||||
|
│ 🧭 audit-export · Pathfinder · Working 4 of 9 cleared ▓▓▓▓░░░░░ │
|
||||||
|
│ ● Waiting on you · 3 questions [Questions] [Map] [Draft] │
|
||||||
|
├───────────────┬──────────────────────────────┬───────────────────────┤
|
||||||
|
│ THE MAP │ What you end up with │ DISCUSSION │
|
||||||
|
│ │ │ │
|
||||||
|
│ ✓ Destination │ Why this matters: ... │ thread on this item │
|
||||||
|
│ ✓ Codebase │ │ │
|
||||||
|
│ ● Export fmt │ ○ A CSV, ... │ │
|
||||||
|
│ ○ Size cap │ ◉ B Parquet RECOMMENDED │ │
|
||||||
|
│ ⊘ Retention │ ○ C Both, ... │ │
|
||||||
|
│ │ ○ Something else ______ │ │
|
||||||
|
│ NOT YET CLEAR │ │ │
|
||||||
|
│ · fog item │ Not sure, skip for now │ │
|
||||||
|
├───────────────┴──────────────────────────────┴───────────────────────┤
|
||||||
|
│ 2 staged · Export format → B · +1 comment ⌘↩ [Send to Agent] │
|
||||||
|
└──────────────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 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 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.
|
||||||
|
- `withInputs()` focus preservation, raw-string diffing before re-render, and the `prefers-reduced-motion` handling that keeps progress indicators legible rather than freezing them.
|
||||||
|
|
||||||
|
### What to change
|
||||||
|
|
||||||
|
- **Topics, not rounds.** Grill groups the nav by round, which is a temporal artifact: "questions the agent happened to ask on turn 4". Its own sample data has one round containing three unrelated subjects. Product people cannot use that. Group by topic, stable and nameable.
|
||||||
|
- **Show real progress.** Grill has no "N of M" counter at all. Pathfinder's trail footer already computes `4/9 cleared` and a plain-English confidence line. Put both in the header. In a 45-minute session with a PM, "how much longer is this" is the first question asked.
|
||||||
|
- **Recommendations become optional.** Grill always leads with one, which is right when the agent has an opinion and you are pushing on it. In discovery the agent frequently should not have an opinion, and pre-filling one anchors a PM into rubber-stamping. Neutral mode: no `rec`, or reframed as "what similar products do".
|
||||||
|
- **Real, accessible form controls.** Grill's options are `<li>` with `onclick`, so they are unreachable by keyboard and invisible to screen readers. Non-negotiable to fix if non-technical stakeholders are in scope.
|
||||||
|
- **Markdown actually renders.** Grill escapes everything and sets `white-space: pre-line`; there is no markdown at all. A plan document cannot be shown that way.
|
||||||
|
- **Rename everything.** "Grill", "durable", "Defer", "Reopen", "Why A." is a vocabulary for interrogating an engineer who already has a plan.
|
||||||
|
- **Do not dim rejected options to 45%.** In discovery the rejected options are often the most valuable thing in the room, and an engineer joining late needs to see why B lost.
|
||||||
|
|
||||||
|
### Two things the console unlocks that the terminal cannot
|
||||||
|
|
||||||
|
- **Tier-2 UI sketches.** `resolve.md` already sanctions building 3 to 5 structurally different UI variants switched by "a URL search param plus a small floating bar". The console can host them in a sandboxed iframe with a proper variant switcher. This is already in the methodology and currently awkward.
|
||||||
|
- **Anchored reactions.** `resolve.md` insists every sketch probe "names its row or element". With `anchors: { "row5": "b3" }`, clicking the probe highlights the row. That is the inline-commenting capability, scoped to something the methodology already demands.
|
||||||
|
|
||||||
|
### Room-screen polish (v2.4.0)
|
||||||
|
|
||||||
|
Built for a mixed product and engineering room reading one screen together.
|
||||||
|
|
||||||
|
- **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.
|
||||||
|
- **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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. The startup question
|
||||||
|
|
||||||
|
Both prompts open with one ask. Pathfinder already uses `AskUserQuestion`, so this costs almost nothing:
|
||||||
|
|
||||||
|
> Run this session in the **web console** (a local page in your browser, better for walking through decisions with someone) or **here in the terminal**?
|
||||||
|
|
||||||
|
Recommended default is an open decision (see §8). Because the markdown files stay the source of truth, the user can switch either way mid-session at no cost, and the prompt should say so.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Work plan
|
||||||
|
|
||||||
|
| # | Task | Notes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 0 | **Trim `plan2code-0-pathfinder.md` by ~250 characters** | Hard prerequisite. 5 characters of headroom today. Candidates: the `grilling.md` fallback blockquote, the Rules list. |
|
||||||
|
| 1 | `src/web-console/` skeleton: `console.mjs` start/wait/status/stop, detached spawn, handle file, reap sweep | The transport is the risky part, build and prove it first |
|
||||||
|
| 2 | `server.mjs`: the six security controls, SSE, atomic result write with Windows `EPERM` retry | |
|
||||||
|
| 3 | `index.html` + `app.js` + `app.css` + vendored `marked` lexer, token-to-DOM renderer | |
|
||||||
|
| 4 | Tier 1 primitives, staging, drafts, Send | |
|
||||||
|
| 5 | `console.md`: the agent contract | The only file the prompts point at |
|
||||||
|
| 6 | `SOURCE_PROMPTS` entries + `npm run build:skills` + commit `skills/` | Zero installer code changes |
|
||||||
|
| 7 | Pathfinder integration: startup ask, channel rule, `Read` line | ~250 chars, funded by task 0 |
|
||||||
|
| 8 | Plan integration | 324 chars headroom, fits, trim ~150 for margin |
|
||||||
|
| 9 | CHANGELOG + `version.json` + `package.json` in lockstep | `plan2code-publish` refuses to release on mismatch |
|
||||||
|
|
||||||
|
### Three things most likely to bite during implementation
|
||||||
|
|
||||||
|
1. **Forgetting `windowsHide: true` on the detached spawn.** It defaults to `false`, and `detached` on Windows forces a console window that "once enabled, cannot be disabled". Every handoff flashes a black box at the user.
|
||||||
|
2. **`fs.rename` `EPERM` from antivirus and search indexers on Windows.** Intermittent, unreproducible on demand, looks exactly like a logic bug. Retry three times with backoff from day one.
|
||||||
|
3. **Relying on `SIGTERM` for cleanup on Windows.** It does not arrive. Build the idle deadline first, not last, and comment why.
|
||||||
|
|
||||||
|
### Non-obvious portability notes
|
||||||
|
|
||||||
|
- grill-with-ui's heredoc idiom (`patch <<'EOF'`) is **not portable to PowerShell**, which is the default shell for Claude Code on Windows. Use a `--file <path>` form as the primary documented interface.
|
||||||
|
- `nohup ... &` is bash-only. Backgrounding happens inside `console.mjs start`, never in the shell command the agent writes.
|
||||||
|
- Always emit `node "<abs>/console.mjs"` quoted. Install paths contain spaces.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Open decisions
|
||||||
|
|
||||||
|
1. **Default channel.** Terminal (lower ceremony for an engineer working solo) or console (better for the cross-functional sessions that motivated this)? Recommendation: console marked as recommended in the ask, terminal as the low-ceremony alternative.
|
||||||
|
2. **Vendoring `marked`.** It is MIT and dependency-free, but it is the first vendored third-party code in the repo, against a house style of "Node built-ins only". The alternative, a hand-rolled parser, is materially worse on both correctness and security. Recommendation: vendor it, pin the version, record the SHA-256.
|
||||||
|
3. **Single-driver or multi-user.** Everything above assumes one browser, one driver, no identity or attribution. A facilitated workshop with one person at the keyboard works fine. Two people answering independently is a different product and reaches into the state model. Recommendation: single-driver for v1, say so explicitly.
|
||||||
|
4. **Third consumer.** After pathfinder and plan, `/plan2code-review` is the strongest case: two of its rules exist only because output goes to a terminal ("for 15+ findings, present top 10", "output tables as direct markdown, NOT inside code blocks") and a browser deletes both. Its `S 1,3,5` fix selection is literally a checkbox list compressed into a CLI token, and one findings UI serves both `/plan2code-review` and `/plan2code-3-implement-review`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Honest assessment of size
|
||||||
|
|
||||||
|
This is not a weekend. Rough shape: `console.mjs` plus `server.mjs` around 700 to 900 lines, the client around 900 to 1,200, the contract file 300 to 400 lines of prose, plus the prompt trims and build wiring. The transport and lifecycle work (tasks 1 and 2) is where the risk concentrates, and it is worth proving end to end on one primitive before building the other eight.
|
||||||
|
|
||||||
|
A smaller first cut that still tests the whole idea: pathfinder only, `choice` and `text` and `recap` only, no artifact pane. That exercises the transport, the token mapping, the fallback path and the three-probe cap, which are the parts most likely to be wrong.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Credits
|
||||||
|
|
||||||
|
The architecture owes a large debt to `grill-with-ui`, whose file-ownership model, staged-then-send interaction, commitment tiers and assumed-region idea are all borrowed here. The implementation is independent.
|
||||||
@@ -0,0 +1,971 @@
|
|||||||
|
# The Web Console
|
||||||
|
|
||||||
|
## New here? A two-minute tour
|
||||||
|
|
||||||
|
**Launch it.** After installing, run `plan2code` in your project folder. It starts Claude Code or
|
||||||
|
Devin on the dashboard, and the page opens in your browser. In any other agent, run `/plan2code`
|
||||||
|
inside it, or add `--web` to a skill (`/plan2code-1-plan --web plan a lunch voting app`).
|
||||||
|
|
||||||
|
**What you see.**
|
||||||
|
|
||||||
|
- **The dashboard** has a card for every skill. The one it suggests next is flagged. Pick a card and
|
||||||
|
that skill starts on the same page.
|
||||||
|
- **Questions** come laid out with the trade-offs next to each option and a progress bar on top.
|
||||||
|
Nothing is sent until you press **Send**, and half-typed answers survive a closed tab.
|
||||||
|
- **Tabs** show the document taking shape, the build progress and, always last, **Ask**, where you can
|
||||||
|
put a quick question to the running agent.
|
||||||
|
- **Sign-off** asks for your approval at the end of a phase. You can run the code review first from
|
||||||
|
the same card, or press **Show me it working** to have the agent start the app and show you
|
||||||
|
screenshots of the change right on the page.
|
||||||
|
|
||||||
|
**Where next.** [walkthrough.md](walkthrough.md) follows one feature from the first idea to the
|
||||||
|
last phase. The rest of this file is the reference: every card, button and rule. Prefer the terminal?
|
||||||
|
Run the same commands without `--web` and answer there; the files under `specs/` are identical.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
The web console is the main way to use Plan2Code: a local page in your browser
|
||||||
|
where you pick a step, answer its questions, watch the documents and the build
|
||||||
|
take shape, and approve the work. Every skill runs on it, and `/plan2code` is
|
||||||
|
the front door: it opens a dashboard of all of them, and whichever you pick
|
||||||
|
starts right there on the same page.
|
||||||
|
|
||||||
|
It exists because the hardest part of adopting Plan2Code is not the engineering.
|
||||||
|
It is getting the person who actually knows what the product should do into the
|
||||||
|
room. Pathfinder and Planning are the two steps where that person matters most,
|
||||||
|
and they were the two steps that looked like a wall of terminal text.
|
||||||
|
|
||||||
|
## Quick start
|
||||||
|
|
||||||
|
1. Install Plan2Code (see [Install and start](../README.md#install-and-start) in the README).
|
||||||
|
2. Run `plan2code` in your project, or `/plan2code` inside your agent. The dashboard opens in your
|
||||||
|
browser.
|
||||||
|
3. Pick a card. The same page becomes that step's session.
|
||||||
|
4. Answer on the page and press **Send to Plan2Code**.
|
||||||
|
|
||||||
|
Starting a step by its own command instead? Add `--web` (for example `/plan2code-1-plan --web`) and
|
||||||
|
it opens on the page without asking.
|
||||||
|
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/dashboard-dark.webp">
|
||||||
|
<img src="../docs/screenshots/dashboard-light.webp" alt="The Plan2Code dashboard: a Set up card, then the steps in order as cards, one of them marked Suggested.">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
Scroll down for the utilities. Outside a git repository the **Git** card says so and still offers to start one:
|
||||||
|
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/dashboard-utilities-dark.webp">
|
||||||
|
<img src="../docs/screenshots/dashboard-utilities-light.webp" alt="The utility cards: Quick task, Review, Handoff and Git, which notes that the folder is not a git repository yet and offers to start one.">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What you get
|
||||||
|
|
||||||
|
- **Every question laid out**, with the trade-offs written next to each option
|
||||||
|
instead of scrolling past in your history.
|
||||||
|
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/question-dark.webp">
|
||||||
|
<img src="../docs/screenshots/question-light.webp" alt="A Plan question card, How tasks are paged, with three options, the first marked Suggested, each with its trade-off underneath.">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
- **A progress bar.** "4 of 9 settled" answers the first thing anybody asks.
|
||||||
|
- **Previous and Next under each card**, walking the questions still waiting, so
|
||||||
|
the list on the left is somewhere to jump from rather than the only way round.
|
||||||
|
- **An example you can accept.** Where a question comes with one, an *Autofill
|
||||||
|
suggestion* button puts it in the box as a real answer for you to edit. It
|
||||||
|
disappears as soon as you have typed anything of your own.
|
||||||
|
- **Answers you have settled read as answers**, not as a form you might still be
|
||||||
|
able to change: what you chose, stated in words, with everything else locked.
|
||||||
|
- **A question you have sent is held** until Plan2Code answers it, showing
|
||||||
|
what you sent. The rest of the page carries on working, so you can read ahead
|
||||||
|
or answer the next question while you wait.
|
||||||
|
- **The document taking shape**, in a tab, with the parts that are still guesses
|
||||||
|
clearly marked as guesses.
|
||||||
|
- **A brief, on demand** (Pathfinder). Press *Write a brief*, choose how far back,
|
||||||
|
and what comes back is a plain-English report of what has been decided, what is
|
||||||
|
still open and what happens next, in its own tab with Print and Save buttons.
|
||||||
|
It is the thing you take to a meeting.
|
||||||
|
- **Nothing is sent until you press Send.** Everything before that is local and
|
||||||
|
reversible, so nobody has to worry about committing to something by accident.
|
||||||
|
- **Nothing gets lost.** Close the tab, reload, restart your machine: your
|
||||||
|
half-typed answers are still there. Once you press Send, what you sent is
|
||||||
|
held until Plan2Code actually collects it, so it cannot be written over.
|
||||||
|
- **It tells you when the other half stops listening.** The terminal and this
|
||||||
|
page are two programs that fail separately, and a page that sat there saying
|
||||||
|
"one moment" forever was the worst way to find that out. Now it says so, and
|
||||||
|
says what to do: answering anyway still works, because what you send is held
|
||||||
|
on disk until something comes for it.
|
||||||
|
- **Starters picked for your role.** Tell *User Preferences* what you do
|
||||||
|
(engineer, product lead, architect, designer, QA, engineering manager) and
|
||||||
|
the starter templates on an idea card and the starter questions on the Ask
|
||||||
|
tab put the most useful ones first. It changes the order, never the
|
||||||
|
questions a skill asks (see *Your role* below).
|
||||||
|
- **Light or dark, and a highlight color you pick.** The gear button at the
|
||||||
|
top right opens *User Preferences*: your role first, then these. It follows
|
||||||
|
your system by default; set it to one or the other if
|
||||||
|
you would rather it stayed put. Remembered on your machine, so it carries
|
||||||
|
over to every session.
|
||||||
|
- **A card as wide as you want it.** The same panel has a *Card width*
|
||||||
|
setting — **Narrow** (720px), **Comfortable** (880px, the default) or
|
||||||
|
**Wide** (1080px) — that widens the question card, the Previous / Next pager
|
||||||
|
and the document tabs together. The dashboard keeps its own layout, and on a
|
||||||
|
small window the column simply fits the window. Remembered with the colors,
|
||||||
|
so it follows you into every session.
|
||||||
|
- **Text that uses the card.** A question's text runs the full width of the
|
||||||
|
card rather than stopping in a narrow column, and the answer box you are
|
||||||
|
typing in grows to fill the card's free height: the box of a text question,
|
||||||
|
the *Something else* box once you pick it, or the note under a verdict,
|
||||||
|
yes/no or recap once it shows. Other boxes stay small. Drag the handle to
|
||||||
|
make it taller; it never shrinks below the space it was given, and on a short
|
||||||
|
window the card scrolls instead of squeezing the box under 160px.
|
||||||
|
- **Send tells you it is ready.** While there is something to send, the Send
|
||||||
|
button pulses gently; it goes still when there is nothing to send.
|
||||||
|
- **Each tab remembers where you were.** Scroll halfway down a document,
|
||||||
|
jump to the questions, come back: you are where you left off. The same goes
|
||||||
|
for a long question card. It lasts as long as the tab is open.
|
||||||
|
- **The spec's overview, one click away.** When the session is working on a
|
||||||
|
spec that has an `overview.md`, an **Overview** tab shows it — read-only,
|
||||||
|
and read fresh from disk each time you open the tab, so an edit shows up
|
||||||
|
straight away. No file, no tab. On the dashboard it follows the spec picked
|
||||||
|
at the top, and disappears for *start from scratch*.
|
||||||
|
- **Where you are, at the bottom.** The footer names the folder the session
|
||||||
|
was launched from and its git branch (`plan2code · feature/…`), muted in
|
||||||
|
the middle. Click it to open the Workspace dialog (see *Your workspace*).
|
||||||
|
Outside a git repo it shows only the folder.
|
||||||
|
- **A chime when it's your turn.** The page plays a sound when new questions
|
||||||
|
arrive, when a new tab (a document, the overview) joins the strip, and when
|
||||||
|
the session opens or closes, so you can look away without missing your cue.
|
||||||
|
Starting a skill from the dashboard plays its own sound too. The same panel
|
||||||
|
has a *Play sounds* switch for all of them, and a box per moment (Planny
|
||||||
|
snoring, Planny waking up, starting a skill, session opens, skill is ready,
|
||||||
|
session ends, new questions, a reply on Ask, a new tab), so you can keep only
|
||||||
|
the ones you want. Ticking a box plays its sound; everything is remembered
|
||||||
|
like the colors.
|
||||||
|
- **Files in your notes.** Show instead of describe: attach a screenshot, a
|
||||||
|
photo or a document to any note or quick question (see *Attachments in notes
|
||||||
|
and questions* below).
|
||||||
|
- **A notebook of your own.** One per project folder, in named tabs, for
|
||||||
|
jottings and screenshots that are yours, not the agent's (see *Your notebook*
|
||||||
|
below).
|
||||||
|
- **A nudge when it might be waiting on you.** Your agent may stop in the
|
||||||
|
terminal to ask permission for something, and the page cannot see that. So
|
||||||
|
the dashboard and every starting screen carry a one-line tip about hands-off
|
||||||
|
modes (`auto` mode in Claude Code, `smart` mode in Devin) that can cut down
|
||||||
|
on those stops, though they may still need your attention, and when the agent
|
||||||
|
has been working and silent for about 30 seconds, Planny's line asks
|
||||||
|
*"Still working, or waiting on an approval in your terminal?"* — well before
|
||||||
|
the two-minute *"Still working on it"* line.
|
||||||
|
- **The tab icon says whose turn it is.** A bar along the bottom of Planny's
|
||||||
|
favicon follows the line beside him: dashed amber while Plan2Code is
|
||||||
|
working or picking up your answers, solid green when it is your move, solid
|
||||||
|
red when it has gone quiet or the connection is lost (busy is dashed so the
|
||||||
|
states differ by pattern, not only color). A finished session goes back to
|
||||||
|
the plain icon, so a console left in a background tab can be checked at a
|
||||||
|
glance.
|
||||||
|
- **Help.** The **?** at the top right opens a Help dialog with 18 topics,
|
||||||
|
one per tab down the left (across the top on a narrow window), opening on
|
||||||
|
the one for where you are. It is part of the page itself, so it still reads
|
||||||
|
fully when the page has lost its program.
|
||||||
|
- Works offline, on your own machine only. No account, no install, no network.
|
||||||
|
|
||||||
|
An Implement phase ends on a sign-off card: read the completion report, then
|
||||||
|
review the code first, approve the phase, or ask for changes. Implement +
|
||||||
|
review has already reviewed the code, so its card has no review button.
|
||||||
|
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/signoff-dark.webp">
|
||||||
|
<img src="../docs/screenshots/signoff-light.webp" alt="The Approve this phase card, with a button to read the completion report and three choices: Review the code first, Approve this phase, and I want changes.">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
The **Ask** tab is a chat beside the cards, for a quick question at any point.
|
||||||
|
When a question is really a new task, the answer ends with a ready-to-paste
|
||||||
|
prompt in a block with a Copy button, to take into a new conversation.
|
||||||
|
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/ask-dark.webp">
|
||||||
|
<img src="../docs/screenshots/ask-light.webp" alt="The Ask tab: the question Where are tasks paged? and Plan2Code's answer naming the file.">
|
||||||
|
</picture>
|
||||||
|
|
||||||
|
## Using it
|
||||||
|
|
||||||
|
The easy way in is the dashboard:
|
||||||
|
|
||||||
|
```
|
||||||
|
/plan2code
|
||||||
|
```
|
||||||
|
|
||||||
|
A page opens with every skill laid out as cards — the setup pair, the pipeline
|
||||||
|
in order, and the utilities alongside — with a note about what it made of your
|
||||||
|
project (no AGENTS.md yet, a spec waiting on Phase 2) and a *Suggested* flag on
|
||||||
|
the card it would pick. **Git** is among the utilities, always available: it opens
|
||||||
|
the git board, three tabs — Changes, Branches and Sync — that open on the
|
||||||
|
likely next step (Help's *The git board* topic walks through it), and asks
|
||||||
|
before every push, publish and delete. In a folder that is not a git
|
||||||
|
repository its card says *Not a git repository yet: it offers to start one*,
|
||||||
|
and clicking it still works. **Codebase X-ray** is always available too: it
|
||||||
|
explains how and why an area works, or ranks its rough spots into
|
||||||
|
`specs/<name>/ARCHITECTURE-BRIEF-<date>.md`, and never changes code.
|
||||||
|
**Diagnose a bug** sits beside it, also always
|
||||||
|
available: it finds a bug's cause and writes it up as
|
||||||
|
`specs/<bug-name>/DIAGNOSIS-<date>.md` without fixing it. Pick such a spec in
|
||||||
|
the picker and it reads *Bug diagnosed*: Quick Task (suggested) and Plan light
|
||||||
|
up, while Document, Implement, Implement + Review and Finalize stay greyed. Once
|
||||||
|
Quick Task has fixed it, the folder reads *Bug fixed*: Quick Task offers to
|
||||||
|
archive it to `specs--completed/`, and until then the picker never opens on it
|
||||||
|
and hides it while *Hide unavailable workflows* is on. Its chip has a visible
|
||||||
|
**Delete** button in place of the hover ✕ other specs carry, and one confirm
|
||||||
|
removes the folder (any other spec also asks you to type its name). Click a card and Planny
|
||||||
|
flies while it gets ready;
|
||||||
|
a few seconds later the same page is that skill's console, already running. No
|
||||||
|
command names to remember.
|
||||||
|
|
||||||
|
Handoffs this checkout has not picked up yet follow the specs in the picker as
|
||||||
|
dashed **Handoff** chips, each with its title and age. Select one and the skill
|
||||||
|
cards give way to a preview: when it was written, its spec, the skill it came
|
||||||
|
from and its Next task. **Pick it up here** carries on in that skill and spec
|
||||||
|
in this same session (Quick Task takes over, and says so, when the skill or
|
||||||
|
spec is gone), and the chip is gone from the next dashboard. **Read it all**
|
||||||
|
opens the whole document, **Copy for a new conversation** copies a one-line
|
||||||
|
prompt that points a fresh conversation at the file, and **Delete** removes it
|
||||||
|
for good after one confirm. Handoffs from *Stop with a handoff* (below) and
|
||||||
|
from the Handoff skill land in the same place, `~/.plan2code/handoffs/`.
|
||||||
|
|
||||||
|
A freshly opened dashboard starts with Planny asleep in the middle of the page.
|
||||||
|
Click to wake him: he snores once while he gets a gentle shake side to side,
|
||||||
|
then about five seconds of him powering on to a boot-up sound (arms lifting
|
||||||
|
off his sides, his star opening, a hop and a cheer) before he glides into his spot at
|
||||||
|
the top and the menu rises in. (Browsers stay silent until your first click,
|
||||||
|
so the snoring usually starts with it; with *Sounds* off, the same wake-up
|
||||||
|
plays without audio.)
|
||||||
|
It plays only on a fresh `/plan2code`: not on a reload, not when you come
|
||||||
|
back with **Back to the dashboard**, and not after a launch. To skip it — from
|
||||||
|
the asleep screen or mid-animation — press the muted **Skip** button at the
|
||||||
|
bottom right or hit Escape; either goes straight to the dashboard, silent.
|
||||||
|
With reduced motion switched on in your system settings you get the awake
|
||||||
|
dashboard at once.
|
||||||
|
|
||||||
|
Or start any step directly by its command (the full list is in the README's
|
||||||
|
[Prefer the terminal?](../README.md#prefer-the-terminal) section).
|
||||||
|
|
||||||
|
The first thing it asks is how you would like to work:
|
||||||
|
|
||||||
|
> **How would you like to work through this?**
|
||||||
|
>
|
||||||
|
> - **In your browser** (suggested)
|
||||||
|
> - **Here in the terminal**
|
||||||
|
|
||||||
|
Pick the browser and a page opens at a `127.0.0.1` address, straight away:
|
||||||
|
opening the page is the first thing the skill does, before it reads your
|
||||||
|
project, so for the first few seconds you see a starting screen naming the step
|
||||||
|
("Starting Pathfinder") while it gets its bearings — for the core steps, with
|
||||||
|
Planny acting that step out. The questions replace it the
|
||||||
|
moment they are ready. Answer what is there, press **Send to Plan2Code**, and
|
||||||
|
it carries on. You can switch back to the
|
||||||
|
terminal at any point by saying so: the files under `specs/` are the same either
|
||||||
|
way, and neither side owns them.
|
||||||
|
|
||||||
|
While the page is open, the agent's messages in the terminal end with a
|
||||||
|
pointer back to it — `→ Look at the web console: http://127.0.0.1:…` — and
|
||||||
|
while it is waiting on you it says so in those words: *Waiting on your answer
|
||||||
|
in the web console*. Glance at the terminal, and it always tells you where to
|
||||||
|
look.
|
||||||
|
|
||||||
|
Know you want the page already? Pass `--web` with the command —
|
||||||
|
`/plan2code-1-plan --web plan a lunch voting app` — and it opens the console
|
||||||
|
without asking. The flag is dropped before the rest of the argument is read, so
|
||||||
|
it never becomes part of the request.
|
||||||
|
|
||||||
|
Sharing the link with a colleague on another machine will not work, and that is
|
||||||
|
deliberate. It is bound to your own machine only. To work through a session
|
||||||
|
together, share your screen.
|
||||||
|
|
||||||
|
For the same reason, the web console is only offered when the agent is running
|
||||||
|
on your own machine. An agent working in a cloud VM, a container or over SSH
|
||||||
|
stays in the terminal: a `127.0.0.1` link from somewhere else is a link you
|
||||||
|
cannot open.
|
||||||
|
|
||||||
|
### Your role
|
||||||
|
|
||||||
|
The first control in *User Preferences* (the gear button) is **Role**:
|
||||||
|
Engineer, Product lead / PM, Architect / tech lead, Designer (UX), QA / test
|
||||||
|
engineer, Engineering manager, or **Not set / none of these**, the default.
|
||||||
|
It only reorders things: the starter templates on an idea card and the starter
|
||||||
|
questions on the Ask tab. It never changes what a skill asks or does. It is
|
||||||
|
kept in `looks.json` with your colors, so it follows you into every session,
|
||||||
|
and **Back to default** sets it back to *Not set*.
|
||||||
|
|
||||||
|
Until you have chosen, the dashboard shows a one-line banner at the top —
|
||||||
|
*Pick your role to get starter templates ordered for you.* — with **Set up
|
||||||
|
preferences** and **Not now**. Choosing any role, *Not set* included, or
|
||||||
|
pressing *Not now* puts it away for good.
|
||||||
|
|
||||||
|
### Starter templates
|
||||||
|
|
||||||
|
The first "What's the idea?" box in Pathfinder, Plan and Quick Task has a row
|
||||||
|
of starter templates above it: **Blank** first, then outlines to fill in (an
|
||||||
|
engineering spec, product requirements, a design decision, a bug
|
||||||
|
investigation, a refactor, a data migration, and so on), in the order your
|
||||||
|
role puts them. With a role chosen, the first one carries a *For your role*
|
||||||
|
pill. Pick one and the box fills with editable Markdown, one `## heading` per
|
||||||
|
answer with the answer on the lines under it, and the first `[blank]` is
|
||||||
|
selected so you can type straight over it. Brackets mark only the parts you
|
||||||
|
fill in; everything else is a default you can keep or edit. If you have
|
||||||
|
already typed something, a strip asks **Replace** or **Keep mine** first.
|
||||||
|
Only what is in the box is sent, exactly as if you had typed it.
|
||||||
|
|
||||||
|
The templates live in the page (`public/starters.js`), not in the prompts. A
|
||||||
|
skill only marks its fresh-idea card with `"templates": "idea"`, and `post`
|
||||||
|
refuses that flag on anything but a `text` card. A resumed map or plan asks
|
||||||
|
no idea question, so it shows no templates, and the terminal never has them.
|
||||||
|
|
||||||
|
### Leave for later (Pathfinder)
|
||||||
|
|
||||||
|
Pathfinder's scope question is **Leave for later** — *"Which of these features
|
||||||
|
are we leaving out this time?"* It is a tick-any list of 3–5 features someone
|
||||||
|
might expect, each ending with what leaving it out means ("Scheduled exports
|
||||||
|
(Leaving this out = someone runs each export by hand)"), with a recommended
|
||||||
|
set to tick in one go. The features you tick become the first lines of the
|
||||||
|
map's *Out of scope*. Every option names a feature, never a rule to keep, so a
|
||||||
|
tick always means "not this time".
|
||||||
|
|
||||||
|
### Skipping a question
|
||||||
|
|
||||||
|
**Skip this one**, on an optional question, now moves you straight on: the card
|
||||||
|
reads *Skipped* for a beat (about a quarter of a second) and the next open
|
||||||
|
question comes up. On the last one, focus goes to **Send to Plan2Code**
|
||||||
|
instead. A click or a key press in that beat cancels the move. **Do not skip**
|
||||||
|
on a skipped card brings it back.
|
||||||
|
|
||||||
|
### Your workspace
|
||||||
|
|
||||||
|
The folder label in the middle of the footer — `shop · main`, or
|
||||||
|
`shop + 2 folders · main` once you have added some (shorter on a narrow
|
||||||
|
window) — opens the **Workspace** dialog: the folders the agent uses as
|
||||||
|
context for this console session.
|
||||||
|
|
||||||
|
- **The folder you started in** is always first. It can be renamed and given a
|
||||||
|
description, but not removed.
|
||||||
|
- **Add a folder** by pasting a path (`../shared-ui` counts from the folder
|
||||||
|
you started in; `~` is your home folder) or with **Browse…**, which opens
|
||||||
|
your system's own folder picker. Browse… is hidden when the page looks like
|
||||||
|
it is being reached from another machine (SSH, a dev container, a
|
||||||
|
Codespace). A path that is not a folder, one already in the list, and a name
|
||||||
|
already taken are each refused with a message (a taken name comes with a
|
||||||
|
**Use @name-2** button); a folder inside another one in the list is
|
||||||
|
accepted, with a note.
|
||||||
|
- **Every folder has an `@name`** (lowercase letters, numbers and hyphens) and
|
||||||
|
an optional one-line *What is it?*. Type `@` in the Ask box, a note or a
|
||||||
|
typed answer and a list of names pops up; the agent reads `@shared-ui` as
|
||||||
|
that folder.
|
||||||
|
- **What the agent does with them.** It is told the list when its session
|
||||||
|
opens and each change once after that. Added folders are read-only
|
||||||
|
reference: it reads them, reads each one's `AGENTS.md` (or `CLAUDE.md`)
|
||||||
|
before first using it, and changes one only if you ask. Your harness may
|
||||||
|
ask permission the first time it reads outside the project.
|
||||||
|
- **Marks.** *This folder no longer exists* when it is gone from disk; *The
|
||||||
|
agent can't read this yet* when the agent reported a failed read (in Claude
|
||||||
|
Code with a copyable `/add-dir <path>` to run); *Inside another folder in
|
||||||
|
the list* for a nested one.
|
||||||
|
|
||||||
|
The workspace carries across skills you start from the dashboard and back, and
|
||||||
|
it is remembered for next time:
|
||||||
|
|
||||||
|
- **Saved on every change**, in `~/.plan2code/console/workspaces.json` (beside
|
||||||
|
`looks.json`, never in the project, since the paths are your machine's),
|
||||||
|
keyed by the folder you started in.
|
||||||
|
- **One list per spec.** *Start from scratch* on the dashboard shows the
|
||||||
|
project's list. Picking a spec loads its own; the first time, it starts as a
|
||||||
|
copy of the project's, and after that the two are separate. A spec created
|
||||||
|
mid-run (Pathfinder, Plan) takes the list in force with it. The line under
|
||||||
|
the dialog's title says whose list it is.
|
||||||
|
- **Forgotten on archive.** Finalize's Spec Cleanup step says it will forget
|
||||||
|
the spec's list and runs `console.mjs forget --spec specs/<name>` after the
|
||||||
|
move.
|
||||||
|
|
||||||
|
### Subagents
|
||||||
|
|
||||||
|
On a build (Implement, Implement + review, Quick task), a review and
|
||||||
|
Pathfinder, the agent can hand independent pieces of work to helpers
|
||||||
|
(subagents) while it keeps the conversation with you.
|
||||||
|
|
||||||
|
- **The button.** An icon in the top bar, after Stop session (and Write a
|
||||||
|
brief on Pathfinder): one larger node linked to three smaller ones, lit in
|
||||||
|
your highlight color while helpers are on. It shows only on those skills,
|
||||||
|
and only when the skill's copy of the console can pass the setting on.
|
||||||
|
- **The dialog.** A click opens it; the button never switches anything by
|
||||||
|
itself. **Use helpers** or **Work alone**, the instruction the agent follows
|
||||||
|
(**Reset to default** puts the shipped one back), and how many helpers may
|
||||||
|
run at once (1 to 20; your agent's own limit still applies). Under Helpers,
|
||||||
|
**Helper strength** sets how strong a model and how much effort helpers get:
|
||||||
|
**Balanced** (the default), **Thrifty** (one step lighter; reviews never
|
||||||
|
below standard), **Best** (strongest and high effort, except lookups) or
|
||||||
|
**Match my session** (nothing set on helpers). **Save** sends
|
||||||
|
it; the agent hears of it at its next check-in, as a setting, not as
|
||||||
|
something you typed.
|
||||||
|
- **Saved per project and per skill**, on until switched off, in
|
||||||
|
`~/.plan2code/console/subagents.json`. The next session of the same skill
|
||||||
|
in the same folder starts the same way.
|
||||||
|
- **The Subagents tab.** With the first helper the agent reports, a tab
|
||||||
|
appears before Ask: one row per helper with what it was asked and whether it
|
||||||
|
is running, done or failed, plus a one-line result at the end. Rows change at
|
||||||
|
the agent's check-ins, not live. *Working alone* means your agent has no way
|
||||||
|
to start helpers here. Each row may carry one quiet line such as "Standard,
|
||||||
|
medium effort" ("Session model" when the helper runs on yours). The rules
|
||||||
|
live in `helper-strength.md` and apply in terminal sessions too. The tab
|
||||||
|
clears when you go back to the dashboard.
|
||||||
|
- **Pathfinder's research** always uses helpers, whatever the switch says, and
|
||||||
|
they show in the tab too.
|
||||||
|
|
||||||
|
### Your notebook
|
||||||
|
|
||||||
|
The **Notebook** icon in the top bar, on the dashboard, every skill and the
|
||||||
|
finished screen, opens a large dialog with a scratch pad for the folder you are
|
||||||
|
working in.
|
||||||
|
|
||||||
|
- **Tabs.** A row of named tabs sits across the top, each with its own text and
|
||||||
|
its own pictures. **+ New tab** asks for a name first (1 to 40 characters, no
|
||||||
|
two the same in any case, up to 20 tabs), in a small dialog. There is no
|
||||||
|
toolbar under the row: a double-click (or **F2**) on a tab renames it, the **x**
|
||||||
|
beside its name deletes it (the **Delete** key does too), and tabs are moved
|
||||||
|
only by dragging them. The tab you left open is the one you come back to.
|
||||||
|
Delete opens a dialog that asks twice and takes the tab's text and pictures
|
||||||
|
with it; with no tab left, the dialog asks you to make one. A notebook from before tabs opens
|
||||||
|
as one tab called **Notes**.
|
||||||
|
- **Markdown, styled as you type.** The editor shows Markdown in place:
|
||||||
|
headings grow, bullets draw, bold, code, quotes and links take their look, and
|
||||||
|
the marks come back on the line you are on. The text itself stays plain
|
||||||
|
Markdown (saved as the tab's `note.md`, up to 1 MB).
|
||||||
|
- **Pictures beside it.** Paste a screenshot, drop files on the dialog or press
|
||||||
|
**Add image**: each becomes a thumbnail in a strip under the text (up to 200
|
||||||
|
per tab). Click one for a full-screen preview (arrow keys step through, Esc
|
||||||
|
closes); its **X** asks before it deletes.
|
||||||
|
- **It saves itself**, about a second after you stop typing, when you close the
|
||||||
|
dialog and before you switch tabs. If a tab's text cannot be saved, switching
|
||||||
|
is refused ("Not saved yet, so staying on this tab") rather than losing it.
|
||||||
|
If the connection drops, your text stays in the page and is retried, and the
|
||||||
|
browser tab warns before you close it with something unsaved.
|
||||||
|
- **One per folder, kept between sessions.** Every session started in the same
|
||||||
|
folder (each git worktree counts as its own) opens the same notebook, in
|
||||||
|
`~/.plan2code/notepads/<folder-name>-<12 hex>/`: `meta.json` (which folder it
|
||||||
|
belongs to), `tabs.json` (the tabs, their order and the last one open) and one
|
||||||
|
folder per tab, `tabs/<id>/`, holding its `note.md` and `images/`. Two pages
|
||||||
|
open on one folder share it, and the last save wins.
|
||||||
|
- **Private.** It never goes into your project, your session or anything the
|
||||||
|
agent reads, so the agent never sees it. It stays on this machine.
|
||||||
|
- **Removed only when you say.** No automatic cleanup touches it. Once the
|
||||||
|
newest file in a notebook is 30 days old or more, *User Preferences →
|
||||||
|
Cleanup* offers it as one item named after its folder's full path
|
||||||
|
(*Notebook for /home/sam/code/shop*),
|
||||||
|
and deleting it removes the whole notebook, every tab's text and pictures.
|
||||||
|
|
||||||
|
### Session meter
|
||||||
|
|
||||||
|
A small ring pill in the top bar — **Session: fresh** (green), **Session:
|
||||||
|
getting long** (yellow), **Session: time for a fresh start** (red) — counts the
|
||||||
|
work this console session has done. Click it for the count, a list of each
|
||||||
|
step that added points and what it added (for example *Quick task started +1*),
|
||||||
|
and a **What is this?** link to Help.
|
||||||
|
|
||||||
|
Each skill run adds points (`WEIGHTS` in `public/meter.js`): Plan, Document,
|
||||||
|
Review, Init and Init update 2; Revise plan, Quick task and Finalize 1; a
|
||||||
|
Pathfinder map 2 and each question its research subagents settle 1; a built phase by its size,
|
||||||
|
one point per 3 tasks it completed (rounded up), plus 1 for Implement + Review
|
||||||
|
(a flat 2, or 3, if the agent did not report a task count); Handoff and the dashboard 0.
|
||||||
|
A build counts while it runs: each task the progress bar ticks off adds to the
|
||||||
|
build's row (*Implement + Review: 9 tasks built so far*), Implement + Review's
|
||||||
|
review stage adds its 1 as it starts, and the approved phase takes the row over
|
||||||
|
with its final score, so the meter never waits for the sign-off to catch up.
|
||||||
|
On top of that, every 2 questions you answer on the page add 1 point to the
|
||||||
|
skill run you answered them in (`ANSWERS_PER_POINT`), so a long Pathfinder or a
|
||||||
|
Plan with many clarifying questions weighs more than a short one. A review run on the
|
||||||
|
page after a quick task or a phase sign-off counts as a Review too. Green is
|
||||||
|
under 5, yellow from 5, red from 10, and the ring is full at 15. At red the dashboard
|
||||||
|
also shows a banner: starting a **new console session** keeps the agent sharp
|
||||||
|
(resuming this one carries the count along). It is a rule of thumb, not a
|
||||||
|
reading of the agent's real context, and it never blocks anything.
|
||||||
|
|
||||||
|
### While something is being built
|
||||||
|
|
||||||
|
Implementation, Implement + Review and a Quick Task spend most of their time
|
||||||
|
building rather than asking, so the page shows the build instead:
|
||||||
|
|
||||||
|
- **What it is doing right now**, beside Planny ("Task 5 of 9: the rate
|
||||||
|
limiter"), and the progress bar counting tasks done. Tasks are counted
|
||||||
|
within the phase, to match the bar — the phase is already named in the
|
||||||
|
headline — so you never see "Task 4.2 of 6"; the page rewrites that form if
|
||||||
|
an agent still sends it.
|
||||||
|
- **The phase's task list** in its own tab, ticking as each task lands on
|
||||||
|
disk, and **the phase file itself** (`phase-3.md`) rendered in the next —
|
||||||
|
the prerequisites and task specs, not just the checklist.
|
||||||
|
- **Any question the build needs answered** (which phase, a spec conflict,
|
||||||
|
failing tests) appears as an ordinary question, and the sign-off is a
|
||||||
|
**Completion report** tab with an *Approve this phase* card.
|
||||||
|
- A long task is not mistaken for a stall. The build says how long it may go
|
||||||
|
quiet, and the page only calls it stuck after that.
|
||||||
|
|
||||||
|
### Review before you approve
|
||||||
|
|
||||||
|
The *Approve this phase* card carries a **Review the code first** button beside
|
||||||
|
the approval. Press it and the same session runs a focused code review of
|
||||||
|
exactly the files the phase changed, before you are asked to approve anything.
|
||||||
|
The findings come back as a tab, and a *Which to fix* card lists every one with
|
||||||
|
its severity: tick the ones to fix (or use the *Critical and warnings* / *All
|
||||||
|
of them* quick picks), press Send, and it fixes and re-checks them before the
|
||||||
|
approval card comes back.
|
||||||
|
|
||||||
|
A quick task has no approval step, so its offer sits on the finished screen
|
||||||
|
instead: a large **Review it now** button above the next step, with **No
|
||||||
|
thanks, I am done** beside it. If the session has already closed, the button
|
||||||
|
turns into the `/plan2code-review` command to run in the terminal.
|
||||||
|
|
||||||
|
Implement + Review shows neither: it reviews every phase before sign-off
|
||||||
|
already.
|
||||||
|
|
||||||
|
### When a session ends
|
||||||
|
|
||||||
|
A finished session says so, and ends in one of three shapes:
|
||||||
|
|
||||||
|
- **A next step.** What happened, and the exact command to run next (with a
|
||||||
|
Copy button) — the next phase, Finalize, a commit.
|
||||||
|
- **All done.** Nothing is left to run, so there is no command to copy:
|
||||||
|
*"All done, nothing left to run."* Init, Init update and Handoff end this
|
||||||
|
way, and so do Review and Finalize when nothing landed that needs committing.
|
||||||
|
- **Paused.** You pressed *Stop session*. The card names what was saved and
|
||||||
|
gives the command that picks it up later. Nothing else is offered.
|
||||||
|
|
||||||
|
*Stop session* offers two ways to stop (on the dashboard, where nothing has
|
||||||
|
started, it is a plain Stop). **Stop with a handoff**, the suggested one,
|
||||||
|
saves your place as usual and also has the agent write a handoff: where the
|
||||||
|
work stands and the next task, kept in `~/.plan2code/handoffs/` rather than in
|
||||||
|
your project. The paused card names the file, and the dashboard offers it as a
|
||||||
|
chip until it is picked up. **Just stop and save** saves your place and gives
|
||||||
|
the resume command, nothing more; where the step has nothing saved yet it reads
|
||||||
|
*Stop anyway*, under a warning about what is lost.
|
||||||
|
|
||||||
|
When the next step is another Plan2Code skill, the screen also has a
|
||||||
|
**Continue here** button beside it: one press starts that skill in the same
|
||||||
|
conversation, as a dashboard card would. It disappears once the session meter is
|
||||||
|
red, when a fresh conversation is the better choice. A finished Quick Task or
|
||||||
|
Finalize that ends on a commit can also offer **Update CHANGELOG first**, beside
|
||||||
|
**Commit it now**: it opens Changelog right there, and Changelog's yes to
|
||||||
|
*Commit this now?* carries on to Git.
|
||||||
|
|
||||||
|
The first two also carry a **Back to the dashboard** button (beside the next
|
||||||
|
step, or as the main button under "All done"). Press it and the same page turns
|
||||||
|
back into the skill menu, in the same conversation, so the next skill starts
|
||||||
|
right there. The agent keeps listening for it for about ten minutes after the
|
||||||
|
session ends; after that, or once the session has closed, the button turns into
|
||||||
|
the `/plan2code` command instead. That command is on both of these screens
|
||||||
|
anyway, for starting the dashboard in a fresh conversation — the better choice
|
||||||
|
after a long skill, since a fresh conversation starts with a clean context.
|
||||||
|
|
||||||
|
You don't have to finish first. On every skill but the dashboard itself, a
|
||||||
|
small **triangle** pointing left, in your highlight color, sits beside *Stop
|
||||||
|
session*. Press it, confirm, and the agent saves your place exactly as a stop
|
||||||
|
would, with any answers you have ready going along. Then the page turns into
|
||||||
|
the dashboard instead of showing a finish card. Pick the same skill again to
|
||||||
|
carry on, or pick another one. Like Stop, it only works on your turn, and where
|
||||||
|
nothing is saved yet (early in a plan) the confirm says what would be lost.
|
||||||
|
|
||||||
|
### Attachments in notes and questions
|
||||||
|
|
||||||
|
Any note, any quick question on the Ask tab, and the fresh-idea box on
|
||||||
|
Pathfinder, Plan and Quick Task can carry files (on a card they travel with your
|
||||||
|
answer as a note attachment), three ways:
|
||||||
|
|
||||||
|
- the **+ Attach file** button beside the box (pick one or more files),
|
||||||
|
- **paste** a screenshot or a copied file straight into the box,
|
||||||
|
- **drag and drop** files onto the notes panel or the Ask composer.
|
||||||
|
|
||||||
|
Two kinds are allowed:
|
||||||
|
|
||||||
|
- **Images.** Each is shrunk and re-encoded in your browser (JPEG, 2000 px on
|
||||||
|
the long edge at most, phone-photo rotation kept) and shows as a thumbnail.
|
||||||
|
- **Documents**: text, code and PDF (`.md`, `.txt`, `.json`, `.yaml`, `.csv`,
|
||||||
|
`.log`, `.js`, `.ts`, `.py`, `.sql`, `.pdf` and the like), up to 10 MB each.
|
||||||
|
They upload exactly as they are and show as a chip with the file type, name
|
||||||
|
and size. The server checks the contents match the type (a PDF header, or
|
||||||
|
UTF-8 text with no NUL bytes), and a document is never opened from the page.
|
||||||
|
|
||||||
|
Up to 5 attachments per note and 5 per question, images and documents counted
|
||||||
|
together. Anything else (`.docx`, a file over 10 MB, a dotfile such as `.env`)
|
||||||
|
picked or dropped is refused with a message naming the file; a paste only
|
||||||
|
picks up the files it can attach, and leaves any text to paste as usual. Each
|
||||||
|
file uploads straight away while you carry on typing, and sits in a tray with a
|
||||||
|
remove button; removing one deletes its file. A failed upload offers retry or
|
||||||
|
remove and holds back only that note, so the rest of your answers still send.
|
||||||
|
|
||||||
|
The files are stored with the session, in
|
||||||
|
`~/.plan2code/console/sessions/<id>/uploads/`, never in your project, under a
|
||||||
|
random name the server picks. When you send, each note is followed by one line
|
||||||
|
per attachment:
|
||||||
|
|
||||||
|
```
|
||||||
|
Note on Header row: Please keep the header row.
|
||||||
|
Image: /home/sam/.plan2code/console/sessions/<id>/uploads/<uuid>.jpg (header.png)
|
||||||
|
File: /home/sam/.plan2code/console/sessions/<id>/uploads/<uuid>.pdf (api-spec.pdf)
|
||||||
|
```
|
||||||
|
|
||||||
|
and the agent opens those paths with its own file reader. Uploads from sessions
|
||||||
|
untouched for 30 days are swept away the next time a session opens.
|
||||||
|
|
||||||
|
**Keeping the ones a spec cites.** When the agent is about to write a file
|
||||||
|
under `specs/<idea>/` that links to one of your note attachments (a plan, the
|
||||||
|
overview, a phase file, a Pathfinder question or the map), it first copies the
|
||||||
|
attachment into `specs/<idea>/attachments/` with `console.mjs keep` and links
|
||||||
|
the copy, so the spec still shows it after the session is swept. The copy is
|
||||||
|
named `<slug of your file name>-<8 characters of the upload id>.<ext>`, so
|
||||||
|
keeping the same upload twice reuses it. Attachments nothing cites stay in the
|
||||||
|
session, and quick-question attachments are never kept. `keep` is run by the
|
||||||
|
agent, in its own shell; the server itself still never writes into your
|
||||||
|
project.
|
||||||
|
|
||||||
|
### Ask a quick question
|
||||||
|
|
||||||
|
The **Ask** tab, always the last tab, on the dashboard and in every skill,
|
||||||
|
opens a **Quick question** chat. Ask anything about the project's files, or
|
||||||
|
anything at all, without waiting for a card. The agent running the skill
|
||||||
|
answers at its next check-in (in a build, after the task it is on), and the
|
||||||
|
workflow carries on meanwhile. Asking never holds up a card send, and a card
|
||||||
|
send never holds up a question.
|
||||||
|
|
||||||
|
- **Context only when you add it.** A question starts with no context, so it
|
||||||
|
reads as a general question. **+ Add context**, beside *+ Attach file*,
|
||||||
|
lists the last 3 places you visited (question cards, document sections, a
|
||||||
|
spec picked on the dashboard) plus *This spec*; pick one and an *About: …*
|
||||||
|
chip sits above the box. × removes it, and it clears after the question is
|
||||||
|
sent.
|
||||||
|
- **Starter questions.** An empty conversation offers a few questions to start
|
||||||
|
from, chosen for the skill you are in and ordered by your role; the ones
|
||||||
|
that need context appear once you have added some. Clicking one fills the
|
||||||
|
box without sending it.
|
||||||
|
- **Pictures.** The same as notes: the button, paste, or drag and drop, up to 5
|
||||||
|
per question.
|
||||||
|
- **Ten questions per conversation.** The `N of 10` counter is always in view.
|
||||||
|
After the tenth is answered, **New conversation** starts a clean one. So does
|
||||||
|
switching skills through the dashboard.
|
||||||
|
- **Edits need your approval.** Ask for a change to a file and the agent
|
||||||
|
replies with a summary and the list of files it would touch, with
|
||||||
|
**Approve** and **Decline**. Nothing changes until you approve. Afterwards
|
||||||
|
it lists what changed, with line counts, and nothing is committed unless you
|
||||||
|
spell out a commit in your message. It never edits the running skill's own
|
||||||
|
files under `specs/`, and a chat message never answers a card or moves the workflow on: that is what the cards are for.
|
||||||
|
- **When you cannot send.** Two different lines explain it: "That's 10
|
||||||
|
questions in this conversation" means start a new one, and "No agent is
|
||||||
|
connected right now" means the session has finished or the agent has gone
|
||||||
|
quiet, so resume it to ask. Either way the conversation above stays
|
||||||
|
readable.
|
||||||
|
|
||||||
|
A reply that lands while you are on another tab puts a dot on **Ask** and
|
||||||
|
chimes once (if sounds are on).
|
||||||
|
|
||||||
|
### When an update is out
|
||||||
|
|
||||||
|
When a newer Plan2Code release is out, the dashboard shows an **UPDATE
|
||||||
|
AVAILABLE** banner at the top. Click it for the details: the version you
|
||||||
|
have, the new one (linked to its Releases page) and the command that updates
|
||||||
|
you, `plan2code update`, with a Copy button. It updates everything that was
|
||||||
|
installed (the skills, the `plan2code` command and any extras you added), with
|
||||||
|
no menu, and never uninstalls anything. If the `plan2code` command is not
|
||||||
|
installed, the dialog also shows the install command,
|
||||||
|
`npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git`, to run
|
||||||
|
instead. **×** hides the banner for this session; the next dashboard shows it
|
||||||
|
again until you update.
|
||||||
|
|
||||||
|
The `plan2code` command tells you too: before it starts your agent it prints
|
||||||
|
one line, `Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`.
|
||||||
|
It reads the same saved check, so it never waits on the network; when that
|
||||||
|
check is missing or old, it refreshes it in the background for next time.
|
||||||
|
|
||||||
|
The check uses your own git login to read the repo's release tags, once an
|
||||||
|
hour at most. If git cannot reach the repo (no git, no access, offline), you
|
||||||
|
simply see no banner, and nothing waits on it. The version in Help always
|
||||||
|
links to the Releases page.
|
||||||
|
|
||||||
|
### Keyboard
|
||||||
|
|
||||||
|
| Key | Does |
|
||||||
|
| --- | --- |
|
||||||
|
| `Ctrl` + `Enter` (`⌘` + `Enter` on a Mac) | Send |
|
||||||
|
| `Tab` / `Space` | Move between options and pick one |
|
||||||
|
| In the Ask box: `Enter` / `Ctrl` + `Enter` (`⌘` + `Enter`) | `Enter` is a new line; `Ctrl` + `Enter` sends the quick question, never the cards |
|
||||||
|
| `Esc` | Closes whichever dialog is open; on the dashboard, backs out of a pick |
|
||||||
|
| In Help: arrow keys, `Home`, `End` | Move between topics (the arrows wrap). `Ctrl` + `Enter` does nothing inside Help |
|
||||||
|
|
||||||
|
Every control is a real button, radio or checkbox, so screen readers and
|
||||||
|
keyboard-only navigation work.
|
||||||
|
|
||||||
|
## Models in User Preferences
|
||||||
|
|
||||||
|
The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude, Devin and Codex tabs) lets you add a model that came out before Plan2Code was updated; additions are kept in `~/.plan2code/models.json`, and **Reset to default** removes them. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused. Maintainers refresh the curated list with the repo-local `/plan2code-model-update` skill, which shows a diff and changes only what they approve.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| What happened | What to do |
|
||||||
|
| --- | --- |
|
||||||
|
| You closed the tab | Open the link again. Everything is where you left it. After about two minutes with no tab open the link stops working: ask the agent to resume the session for a new one. |
|
||||||
|
| The link stopped working | Tell the agent. It restarts the session and gives you a new link. |
|
||||||
|
| Your agent session died while you were mid-answer | Press Send anyway. Your answers are written to disk and are never discarded, including when the session is restarted. The next session picks them up. |
|
||||||
|
| The page says Plan2Code is not running | It has not checked in for a few minutes. Look at the terminal: it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type `continue` in the terminal and it picks your answers up. Answering here still works, and what you send is held for it. |
|
||||||
|
| You are not sure anything is connected | The **?** at the top right opens Help. Its *What this page is* tab says what keeps the page alive and whether both halves are talking at that moment, and *When something looks stuck* covers what to check. |
|
||||||
|
| You would rather use the terminal after all | Say so. Nothing is lost. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## How it works
|
||||||
|
|
||||||
|
Nothing is installed. The skills ship a small zero-dependency Node server
|
||||||
|
(`references/web-console/`), and the workflow step starts it when you say yes.
|
||||||
|
|
||||||
|
```
|
||||||
|
agent server (detached) your browser
|
||||||
|
| | |
|
||||||
|
|-- open (binds the port, starts ->| |
|
||||||
|
| the server AND the browser) ---|---------------------------->|
|
||||||
|
|<-- http://127.0.0.1:PORT/s/TOK/ |<---- the page, first state -|
|
||||||
|
| | already inside it |
|
||||||
|
|-- post the first questions ----->|---- pushed to the page ---->|
|
||||||
|
|-- wait --seconds 240 ----------->| |
|
||||||
|
| (returns every 4 minutes with | |
|
||||||
|
| progress, then waits again) |<---- you press Send --------|
|
||||||
|
|<-- your answers -----------------| |
|
||||||
|
```
|
||||||
|
|
||||||
|
The server runs detached rather than as a background task of the agent, because
|
||||||
|
agent background tasks get killed at various timeouts, and that would take your
|
||||||
|
half-finished answers with them.
|
||||||
|
|
||||||
|
**It is built to show you something fast.** A browser takes most of a second to
|
||||||
|
turn up after it is asked, so `open` binds the page's port itself and sends the
|
||||||
|
browser there before the server has even finished starting; the server takes
|
||||||
|
the port over a moment later, and the browser's request waits for it rather
|
||||||
|
than being refused. The page arrives with the session already inside it, so it
|
||||||
|
draws the real screen without asking for anything first, in your own theme and
|
||||||
|
colors from the first frame. On a Windows laptop the page is in front of you in
|
||||||
|
roughly the time the browser itself takes to open.
|
||||||
|
|
||||||
|
**It stays up while the page is open.** The page pings it every few seconds, so
|
||||||
|
the idle clock never runs down while you are there. Close the tab and it shuts
|
||||||
|
itself down about two minutes later; it stops after four hours regardless, and
|
||||||
|
the agent stops it outright when the session ends.
|
||||||
|
|
||||||
|
That also means **the server routinely outlives the agent**. It is the agent, not
|
||||||
|
the server, that reads your answers, and the two fail separately. The page tells
|
||||||
|
the two apart: the **?** button at the top right opens Help, whose *What this
|
||||||
|
page is* tab says which halves are talking right now (and *When something
|
||||||
|
looks stuck* covers what to check), and Planny stops looking busy once
|
||||||
|
nothing is listening rather than spinning at you indefinitely.
|
||||||
|
|
||||||
|
**State lives in three places**, and none of them is your repository (the one
|
||||||
|
exception being the note attachments the agent keeps for a spec, above):
|
||||||
|
|
||||||
|
| Where | What | Survives |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `~/.plan2code/console/sessions/<id>/` | the questions, your draft, your answers | 30 days after the session was last touched |
|
||||||
|
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
|
||||||
|
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
|
||||||
|
| `~/.plan2code/handoffs/<id>.md`, `<id>.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not |
|
||||||
|
| `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notebook for one folder: `meta.json`, `tabs.json` and, per tab, `tabs/<id>/note.md` and `tabs/<id>/images/` (`notepads.mjs` is their one owner; the agent never reads them) | until you delete it through Cleanup, which offers it once its newest file is 30 days old |
|
||||||
|
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
|
||||||
|
| `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always |
|
||||||
|
| `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session |
|
||||||
|
| your system temp directory | the port, process id and session token | until reboot |
|
||||||
|
|
||||||
|
Each of the workspace and meter files has exactly one writer: the server owns
|
||||||
|
`workspace.json` (the page changes it only through the `/workspace` routes
|
||||||
|
under Security), and `console.mjs` owns `ledger.ndjson` and
|
||||||
|
`workspace-cursor.json`. The meter's count is never stored; it is folded from
|
||||||
|
the ledger every time (`public/meter.js`), so a repeated `post` never counts
|
||||||
|
twice. The logic lives in small pure modules the tests import directly —
|
||||||
|
`public/workspace.js` (names, the footer label, the change lines the agent
|
||||||
|
reads), `public/meter.js` and `public/mentions.js` (the `@name` popover) — and
|
||||||
|
**Browse…** runs the per-OS picker in `picker.mjs`, copied from the
|
||||||
|
`plan2code` launcher and kept in step with it by a test.
|
||||||
|
|
||||||
|
**Old sessions clean themselves up.** Each time a session opens, whole session
|
||||||
|
folders nobody has touched for 30 days are deleted — questions, drafts,
|
||||||
|
answers, uploads and all, paused or not — along with stray scratch files
|
||||||
|
(`.json` / `.mjs`) left at the top of `~/.plan2code/console/` for as long, and
|
||||||
|
handoffs in `~/.plan2code/handoffs/` untouched for as long, both files each.
|
||||||
|
Your `looks.json` and the `console-dir` pointer are never touched, and neither
|
||||||
|
is the session being opened. Nothing of value goes with them: the page is
|
||||||
|
never the record, `specs/` in your project is.
|
||||||
|
|
||||||
|
**Or clean up on demand.** *User Preferences → Cleanup* → **Find files to
|
||||||
|
clean up** lists, with sizes, everything in `~/.plan2code/` that is not
|
||||||
|
needed: sessions untouched for 30 days (never the one you are in), anything at
|
||||||
|
the top of `~/.plan2code/console/` other than `sessions/`, `looks.json`,
|
||||||
|
`workspaces.json`, `subagents.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` other than
|
||||||
|
`console/`, `bin/`, `launcher.json`, `install.json` (what you installed, which
|
||||||
|
`plan2code update` reads), `models.json`, `handoffs/` (old handoffs go by
|
||||||
|
age, above) and `notepads/`. Each notebook whose newest file is 30 days old or
|
||||||
|
more is listed as one item, *Notebook for* its folder, and goes whole; no
|
||||||
|
automatic sweep ever removes one. It also lists each
|
||||||
|
folder in the project's `specs--completed/` whose newest file is more than 30
|
||||||
|
days old: archived specs Finalize moved there. Deleting one is permanent:
|
||||||
|
`specs--completed/` is usually gitignored, so git can't restore it. A stray is listed once
|
||||||
|
it has sat untouched for an hour, so a lock or temp file another session is
|
||||||
|
writing right now is never caught. **Delete these** removes
|
||||||
|
that list and nothing else. A console running from another home
|
||||||
|
(`PLAN2CODE_CONSOLE_HOME`) only ever looks inside that home.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
It is a local dev server that reads files in your project (never writing to it)
|
||||||
|
and keeps its own state in your home folder, so it is built to be boring about
|
||||||
|
this:
|
||||||
|
|
||||||
|
- Bound to `127.0.0.1` only, never `0.0.0.0`. Not reachable from your network.
|
||||||
|
- A `Host` header allow-list, which is what stops a website you happen to be
|
||||||
|
visiting from talking to it through a DNS rebinding trick.
|
||||||
|
- A 128-bit token in the link, swapped for an `HttpOnly; SameSite=Strict` cookie
|
||||||
|
on first load so it leaves your address bar, your history and any screenshot.
|
||||||
|
- A strict Content Security Policy with no inline script allowed.
|
||||||
|
- Markdown written by the agent is turned into page elements directly and never
|
||||||
|
into an HTML string, so a document that quotes a hostile README cannot run
|
||||||
|
anything. It shows up as text, which is what it is.
|
||||||
|
- Uploads are named by the server (`<uuid>.jpg`, or `<uuid>.<ext>` with the
|
||||||
|
extension taken from the allow-list, via `crypto.randomUUID()`), never by the
|
||||||
|
file name you sent, and live only under the session's own `uploads/`. The
|
||||||
|
server checks the bytes: a JPEG header for images (4 MB cap), and for
|
||||||
|
documents a `%PDF-` header or strict UTF-8 with no NUL byte (10 MB cap).
|
||||||
|
Documents are served back only under a fixed type (`application/pdf`, or
|
||||||
|
`text/plain` for text and code) with `nosniff` (and `sandbox` on text), so
|
||||||
|
the Sent box can link them. A send may only point at
|
||||||
|
uploads inside that session's `uploads/`, images in `images` and documents
|
||||||
|
in `files`.
|
||||||
|
|
||||||
|
### Routes
|
||||||
|
|
||||||
|
The upload routes, the send, the overview and handoff reads, the workspace and the notebook. Like every page route, they are on `127.0.0.1`
|
||||||
|
behind the session cookie, and the ones that write also check the request's
|
||||||
|
origin.
|
||||||
|
|
||||||
|
| Route | Does |
|
||||||
|
| --- | --- |
|
||||||
|
| `POST /upload` | Raw bytes, original name in `x-p2c-name`. `Content-Type: image/jpeg`: writes `uploads/<uuid>.jpg` and answers `{ ok, id, kind: "image", path, url, name, size }`; not a JPEG → 415, over 4 MB → 413. `Content-Type: application/octet-stream`: a document, its extension from the name's allow-listed extension; writes `uploads/<uuid>.<ext>` and answers `{ ok, id, kind: "file", path, name, size }` with no `url`; not an allowed extension or contents that do not match → 415 `type`, over 10 MB → 413. Any other content type → 415. |
|
||||||
|
| `GET /uploads/<id>.<ext>` | Serves an upload: an image as `image/jpeg` (the thumbnail after a reload), a document as `application/pdf` or `text/plain; charset=utf-8` with `nosniff` and, on text, `Content-Security-Policy: sandbox`. Only `<uuid>.<allowed ext>` names under `uploads/`; anything else is 404. |
|
||||||
|
| `DELETE /uploads/<id>.<ext>` | Deletes an image or document removed before sending. 204, or 404 if it is not there. |
|
||||||
|
| `POST /submit` | The Send. A note may carry `images` and `files`, each `[{ path, name }]`: at most 5 together, images in `images` and documents in `files`, every path inside this session's `uploads/`, otherwise 400. |
|
||||||
|
| `POST /chat` | A Quick question `{ text, about?, images?, files?, conversation }`, or `{ reset: true, conversation }` for New conversation. Appended to the session's `chat.ndjson`. 400 `too-long` (over 4,000 characters), `image`, `file` or `bad`; 409 `offline`, `stale` or `limit` (10 per conversation). Never refused because a card send is still uncollected. |
|
||||||
|
| `POST /chat/decision` | Approve or Decline on an edit the agent proposed: `{ re, decision, text?, conversation }`. Once per proposal; does not count toward the 10. |
|
||||||
|
| `GET /overview?spec=specs/<name>` | The Overview tab's read of `<spec>/overview.md`, as `text/markdown` with `cache-control: no-store`. On the dashboard `spec` must be one of the scanned specs; elsewhere the session's own spec is used. The file's real path must stay inside the project, so `../`, absolute paths and symlinks pointing out all get 404. |
|
||||||
|
| `GET /handoff?id=<id>` | *Read it all*: the handoff's `.md` from `~/.plan2code/handoffs/`, as `text/markdown` with `cache-control: no-store`. A dashboard only, and only an id its own scan listed: a used, unknown or malformed id is 404. |
|
||||||
|
| `GET /workspace` | The Workspace dialog's list: folders, `missing`, `remote` and the agent's folder `issues`. `?check=1` re-checks every folder on disk first. |
|
||||||
|
| `POST /workspace/add` | `{ path, name?, description? }`. The path is resolved against the folder the session started in (`~` expanded) and must be a folder: 400 `not-a-folder`, `duplicate` (with its `name`; compared case-insensitively on Windows and macOS), `bad-name`, or `name-taken` with a `suggest`. Answers the new entry, `nested: true` when it sits inside another folder in the list. |
|
||||||
|
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
|
||||||
|
| `POST /workspace/remove` | `{ id }`. 400 `original` for the folder the session started in, 404 `unknown`. |
|
||||||
|
| `POST /workspace/browse` | Opens the system folder picker and answers `{ path }` or `{ cancelled: true }`; never adds anything itself. 409 `busy` while one is open, 404 `no-picker` when the session looks remote or no picker exists. |
|
||||||
|
| `GET /notepad[?tab=<id>]` | The notepad for the folder this session runs in: `{ tabs: [{ id, name }], last, tab: { id, text, savedAt, images: [{ id, url, thumb }] } | null }`, with the tab's `text`, `savedAt` and `images` repeated at the top. Without `tab` it answers the last one used; 404 `no-such-tab` for an id it does not have. A notepad in the first shape answers one virtual tab, Notes. Reading never creates or moves a file. |
|
||||||
|
| `POST /notepad/text?tab=<id>` | `{ text }`. Saves that tab's `note.md` and answers `{ ok, savedAt }`; 400 `bad`, 404 `no-such-tab`, 413 `too-long` (over 1 MB). |
|
||||||
|
| `POST /notepad/image?tab=<id>` | Raw `image/jpeg` (the page re-encodes every picture first). Writes the tab's `images/<uuid>.jpg` and answers `{ ok, id, url }`; 415 `not-jpeg`, 413 `too-large` (over 4 MB), 409 `too-many` (200 pictures in the tab). |
|
||||||
|
| `POST /notepad/thumb?id=<uuid>&tab=<id>` | Raw `image/jpeg`: that picture's thumbnail. 404 `not-found` or `no-such-tab`, 415 `not-jpeg`, 413 `too-large`. |
|
||||||
|
| `POST /notepad/image/delete?tab=<id>` | `{ id }`. Deletes a picture and its thumbnail; 404 `not-found` or `no-such-tab`. |
|
||||||
|
| `POST /notepad/tab` | `{ name }`. Makes a tab, which becomes the last one used, and answers `{ ok, id, name }`; 400 `bad-name`, 409 `duplicate-name` (any case) or `too-many-tabs` (20). |
|
||||||
|
| `POST /notepad/tab/rename` | `{ id, name }`. Answers `{ ok, id, name }`; 400 `bad-name`, 404 `no-such-tab`, 409 `duplicate-name`. |
|
||||||
|
| `POST /notepad/tab/delete` | `{ id }`. Removes the tab from the index, then its folder (text and pictures); 404 `no-such-tab`. |
|
||||||
|
| `POST /notepad/tab/order` | `{ order: [id] }`, every current id exactly once; 400 `bad` otherwise. |
|
||||||
|
| `POST /notepad/tab/last` | `{ id }`. Remembers the open tab; 404 `no-such-tab`. |
|
||||||
|
| `GET /notepad/images/<tab>/<uuid>.jpg`, `<uuid>.thumb.jpg` | Serves a picture or its thumbnail as `image/jpeg`, only by a tab id and a UUID name, a regular file (never a link) whose real path stays inside `~/.plan2code/notepads/`; anything else is 404. |
|
||||||
|
| `POST /subagents` | `{ on, instruction, max }` (`instruction: null` for the shipped default). Saves the switch for this project and skill and answers `{ ok, setting }`; 400 `not-offered` on a skill without the switch, `bad`, `too-long` (over 2,000 characters) or `max` (outside 1 to 20). |
|
||||||
|
|
||||||
|
## For maintainers
|
||||||
|
|
||||||
|
| | |
|
||||||
|
| --- | --- |
|
||||||
|
| Source | `src/web-console/` (one row per file in the files table of `.agents-docs/AGENTS-architecture.md`; a test keeps it complete) |
|
||||||
|
| Ships as | `skills/<every skill>/references/web-console/` |
|
||||||
|
| Wiring | one `additionalReferences` entry per skill in `install.js`; the dashboard's menu lives in `public/skills.js` (each entry's `card`; `SKILL_CATALOG` in `public/answers.js` is a lookup on it) |
|
||||||
|
| Agent contract | `src/web-console/console.md` (read once), its topic files (`console-*.md`), `notes/<workflow>.md`, and `building.md` / `building-review.md` for the builds; `console.mjs help <topic>` prints any of them |
|
||||||
|
| Tests | `node --test scripts/test-web-console-*.mjs` (split by area, shared setup in `scripts/web-console-test-helpers.mjs`), also run by `npm test` |
|
||||||
|
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs a local Chrome or Edge for the paint columns, driven through `playwright-core` from `npm install`; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
|
||||||
|
| Screenshots | `node scripts/capture-screenshots.mjs` (needs a local Chrome or Edge, driven through `playwright-core` from `npm install`; `PLAN2CODE_TEST_BROWSER=chrome|msedge` forces one) |
|
||||||
|
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only, and CodeMirror 6 (MIT) for the notebook's editor as one bundled file, `public/vendor/codemirror.esm.js`, made by the dev-only `node scripts/vendor-codemirror.mjs` from a pinned lock (about 500 KB, loaded only when the Notebook is first opened); the page's policy blocks the `<style>` element CodeMirror writes, so the editor lives in a shadow root where it adopts its rules as a constructed stylesheet (steps in the architecture doc's Notebook point) |
|
||||||
|
|
||||||
|
Edit `src/` only. `skills/` is a committed build artifact: regenerate it with
|
||||||
|
`npm run build:skills` and commit it with the source change, since `npm test`
|
||||||
|
(via `--verify-skills`) fails when it drifts from `src/`.
|
||||||
|
|
||||||
|
### Driving it by hand
|
||||||
|
|
||||||
|
You do not need an agent to poke at the console. Point `PLAN2CODE_CONSOLE_HOME`
|
||||||
|
somewhere disposable first, so you never touch a real session:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export PLAN2CODE_CONSOLE_HOME=/tmp/p2c-play # Windows: $env:PLAN2CODE_CONSOLE_HOME
|
||||||
|
|
||||||
|
cat > /tmp/payload.json <<'JSON'
|
||||||
|
{ "workflow": "pathfinder", "title": "Playing about",
|
||||||
|
"items": [ { "id": "q1", "kind": "choice", "title": "Export format",
|
||||||
|
"body": "Pick one.",
|
||||||
|
"options": [ { "k": "A", "text": "CSV", "recommended": true },
|
||||||
|
{ "k": "B", "text": "Excel" } ],
|
||||||
|
"token": { "A": "a", "B": "b" } } ],
|
||||||
|
"agent": { "status": "waiting" } }
|
||||||
|
JSON
|
||||||
|
|
||||||
|
node src/web-console/console.mjs open --file /tmp/payload.json # prints the URL, opens the browser
|
||||||
|
node src/web-console/console.mjs wait --session <sid> --seconds 60
|
||||||
|
node src/web-console/console.mjs stop --all
|
||||||
|
```
|
||||||
|
|
||||||
|
`node src/web-console/console.mjs help` prints the same command summary an
|
||||||
|
agent gets when it finds the binary before the docs.
|
||||||
|
|
||||||
|
`wait` exits `0` with the answers, `10` if nobody has finished yet, `20` if the
|
||||||
|
server died, `30` on Cancel. Pick `--seconds` to sit under whatever your harness
|
||||||
|
allows a single command: it is a poller, so killing it costs nothing, and a
|
||||||
|
collected result is printed before it is marked collected, which means an
|
||||||
|
interrupted handover can only repeat itself, never lose an answer. `status`
|
||||||
|
lists sessions and flags any whose answers were submitted but never collected.
|
||||||
|
|
||||||
|
When something misbehaves, the session directory is the whole story:
|
||||||
|
`state.json` (what the agent published), `draft.json` (what the person has typed
|
||||||
|
but not sent), `result.json` (what they sent), `events.ndjson` (an append-only
|
||||||
|
log you can `cat`), and `server.log`.
|
||||||
|
|
||||||
|
Set `--idle-ms 60000` on `open` if you want the server to shut itself down
|
||||||
|
quickly while experimenting.
|
||||||
|
|
||||||
|
Two environment variables help when the start is what you are looking at:
|
||||||
|
|
||||||
|
| Variable | Does |
|
||||||
|
| --- | --- |
|
||||||
|
| `PLAN2CODE_CONSOLE_TRACE=1` | `open` prints a timeline of its steps to stderr (roots found, server spawned, port bound, browser sent, state written, server listening). |
|
||||||
|
| `PLAN2CODE_BROWSER` | The command that opens the link instead of the system default, run through the shell with the link appended, e.g. `PLAN2CODE_BROWSER='firefox --new-tab'`. |
|
||||||
|
|
||||||
|
Every `console.mjs open` also writes its own directory to
|
||||||
|
`$PLAN2CODE_CONSOLE_HOME/console-dir` (or `~/.plan2code/console/console-dir`
|
||||||
|
when the override is unset): it is how an agent finds the console on a later
|
||||||
|
session without searching the skill install dirs.
|
||||||
|
|
||||||
|
The vendored file is `src/web-console/public/vendor/marked.esm.js`,
|
||||||
|
sha256 `7a7d9a521ac9384e0c3a075120a7c486cbd0c3c32cc5601bbb79a23e97403690`.
|
||||||
|
Only `marked.lexer()` is used; the rendering is ours, in `public/render.js`, and
|
||||||
|
builds DOM nodes rather than HTML so nothing needs sanitising.
|
||||||
|
|
||||||
|
### Refreshing the screenshots
|
||||||
|
|
||||||
|
The docs and the landing page show the console through the images in
|
||||||
|
`docs/screenshots/`, one light and one dark WebP per screen. Rerun the capture
|
||||||
|
after any change a person would see on the page: a new layout, a renamed
|
||||||
|
button, a different colour.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node scripts/capture-screenshots.mjs # every screen
|
||||||
|
node scripts/capture-screenshots.mjs --only dashboard # one screen
|
||||||
|
```
|
||||||
|
|
||||||
|
Each screen is staged with no agent, from the payloads in
|
||||||
|
`scripts/screenshots/` (its README names the file behind each screen), in a
|
||||||
|
throwaway sample project and console home that the script removes when it is
|
||||||
|
done. It prints each file's size and warns over 300 KB.
|
||||||
|
|
||||||
|
Open every image before you commit it: the right screen, both themes, nothing
|
||||||
|
cut off, and no username, home path or real project name anywhere on it.
|
||||||
@@ -1,298 +1,110 @@
|
|||||||
# AGENTS.md
|
# AGENTS.md
|
||||||
|
|
||||||
This file provides guidance to AI coding agents like Claude Code (claude.ai/code), Cursor AI, Codex, Gemini CLI, GitHub Copilot, and other AI coding assistants when working with code in this repository.
|
This file provides guidance to AI coding agents working with code in this repository.
|
||||||
|
|
||||||
## Project Overview
|
## Project Overview
|
||||||
|
|
||||||
Plan2Code is a structured 4-step workflow methodology for AI-assisted software development. It provides prompt templates that can be installed globally or per-project for various AI coding tools (Claude Code, Cursor, Copilot, Continue, Windsurf, Codeium).
|
Plan2Code is a structured 4-step workflow methodology for AI-assisted software development. It provides prompt templates that can be installed globally or per-project for various AI coding tools (Claude Code, Cursor, Copilot, Continue, Windsurf, Codeium, Devin, Zed).
|
||||||
|
|
||||||
**Version:** Check `version.json` for current version
|
**Version:** Check `version.json` for current version
|
||||||
**Author:** Justin Parker
|
**Author:** Justin Parker
|
||||||
**License:** MIT
|
**License:** MIT
|
||||||
|
|
||||||
## Architecture
|
Plan2Code is started from the project the person works in (`cd` into it, then run `plan2code`), not from this repository; every newcomer doc says so, next to the Node.js 18+ requirement.
|
||||||
|
|
||||||
```
|
## How to Use This File
|
||||||
plan2code/
|
|
||||||
├── src/ # Source workflow prompts (8 markdown files)
|
This file is an index — each section below contains a brief summary and a link to a detail file in `.agents-docs/`. Read only the sections relevant to your current task. Full details (commands, tables, file lists) are in the linked files. The sections "Project Overview", "How to Use This File", "Mascot", and "Keeping this file current" / "Failure log" are fully inline here and are never split into `.agents-docs/`.
|
||||||
├── plan2code-loop/ # Autonomous loop CLI tool (Node.js/TypeScript)
|
|
||||||
│ ├── src/ # TypeScript source
|
## Architecture
|
||||||
│ └── dist/ # Built output (tsup)
|
|
||||||
├── plan2code-metrics/ # Recursive self-improvement toolchain
|
High-level directory structure, key files, workflow prompt inventory, and file naming conventions.
|
||||||
│ ├── src/ # TypeScript source
|
|
||||||
│ │ └── prompts/ # Internal AI prompt templates (no char limit)
|
Details: [Architecture](./.agents-docs/AGENTS-architecture.md)
|
||||||
│ └── dist/ # Built output (tsup)
|
|
||||||
├── scripts/ # Development scripts
|
## Plan2Code Loop
|
||||||
│ └── validate-char-count.js # Pre-commit character count validator
|
|
||||||
├── dist/ # Generated distribution files (auto-generated)
|
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.
|
||||||
│ ├── global-commands/ # For global installation (~/.claude/, etc.)
|
|
||||||
│ └── local-commands/ # For per-project installation (.claude/, etc.)
|
Details: [Plan2Code Loop](./.agents-docs/AGENTS-plan2code-loop.md)
|
||||||
├── .husky/ # Git hooks (husky)
|
|
||||||
│ └── pre-commit # Runs character count validation
|
## Plan2Code Metrics
|
||||||
├── docs/ # Documentation and assets
|
|
||||||
├── specs/ # Feature specs (if any in-progress)
|
Recursive self-improvement toolchain (`plan2code-metrics/`) for collecting run metrics, aggregating by prompt generation, diagnosing weak steps, and proposing prompt edits.
|
||||||
├── install.js # Interactive installer (Node.js)
|
|
||||||
├── package.json # Root package (husky only, private: true)
|
Details: [Plan2Code Metrics](./.agents-docs/AGENTS-plan2code-metrics.md)
|
||||||
├── version.json # Version metadata
|
|
||||||
└── README.md # User documentation
|
## Plan2Code Status Line (Claude CLI)
|
||||||
```
|
|
||||||
|
Optional CLI status bar (`src/statusline-claude/`) for Claude Code. Displays model (+ effort), project/worktree, branch, git diff stats, duration + session cost, context usage, and usage stats (rate limits or token counts). Reads data directly from Claude Code's stdin JSON (plus timeout-bounded git calls): no API calls, no auth, no background processes.
|
||||||
## Key Files
|
|
||||||
|
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line section)
|
||||||
| File | Purpose |
|
|
||||||
|------|---------|
|
## Web Console
|
||||||
| `install.js` | Main installer - generates and installs workflow files to AI tool directories |
|
|
||||||
| `src/plan2code-*.md` | Source workflow prompts (the "source of truth") |
|
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`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-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 (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 five 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; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||||
| `scripts/validate-char-count.js` | Pre-commit validator ensuring all source prompts ≤ 11,000 chars |
|
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
||||||
| `version.json` | Version metadata (name, version, description) |
|
|
||||||
| `QUICK-REFERENCE.md` | User quick-reference card |
|
## Skill Scripts
|
||||||
|
|
||||||
## Workflow Prompts (in `src/`)
|
Deterministic workflow steps run as Node scripts shipped in each skill's `scripts/` (shared ones in `src/skill-scripts/`, a skill's own in `src/<skill>-scripts/`, listed per skill in `SOURCE_PROMPTS` → `scripts`). Prose keeps the judgment. JSON on stdout, documented exit codes, tests run against the built `skills/` tree.
|
||||||
|
|
||||||
| File | Step | Purpose |
|
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Skill Scripts section)
|
||||||
|------|------|---------|
|
|
||||||
| `plan2code---init.md` | Init | Generate AGENTS.md for projects |
|
## Development Commands
|
||||||
| `plan2code---init-update.md` | Update | Update AGENTS.md with learnings |
|
|
||||||
| `plan2code---quick-task.md` | 0 | Lightweight planning for small tasks |
|
Build commands, installer menu options, non-interactive skill-build verification, skills CLI delegation, skill format, and how to edit workflow prompts.
|
||||||
| `plan2code-1--plan.md` | 1 | Requirements analysis & architecture |
|
|
||||||
| `plan2code-1b--revise-plan.md` | 1b | Mid-implementation revisions |
|
Details: [Development Commands](./.agents-docs/AGENTS-development-commands.md)
|
||||||
| `plan2code-2--document.md` | 2 | Create implementation specs |
|
|
||||||
| `plan2code-3--implement.md` | 3 | Execute implementation (phase by phase) |
|
## Code Style & Gotchas
|
||||||
| `plan2code-4--finalize.md` | 4 | Validate, summarize, feedback, archive (7 steps) |
|
|
||||||
|
Language/toolchain conventions for `install.js` vs TypeScript packages, and pitfalls to avoid (version sync, `.gitignore` pre-flight, character limits, User Feedback table format).
|
||||||
## Plan2Code Loop (`plan2code-loop/`)
|
|
||||||
|
Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
|
||||||
A separate Node.js CLI tool that autonomously implements specs by looping through tasks.
|
|
||||||
|
## Mascot
|
||||||
### Loop Architecture
|
|
||||||
|
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 loop uses an **LLM-driven discovery** approach:
|
|
||||||
- Node app just orchestrates iterations and parses completion markers
|
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 `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||||
- The LLM reads spec files (`overview.md`, `phase-X.md`) to discover tasks
|
|
||||||
- The LLM finds unchecked checkboxes, implements ONE task per iteration, marks it complete
|
```
|
||||||
- No regex parsing of markdown in Node - the AI handles all task discovery
|
╭───╮
|
||||||
|
│ ★ │╱
|
||||||
### Loop Commands
|
╱│ ◡ │
|
||||||
|
╰┬─┬╯
|
||||||
```bash
|
```
|
||||||
# Build the loop CLI
|
|
||||||
cd plan2code-loop && npm run build
|
## Keeping this file current
|
||||||
|
|
||||||
# Run the loop (after linking) - fully interactive
|
The `Failure log` section below is a recording of mistakes made by previous AI Agents while working with this code base.
|
||||||
plan2code-loop
|
|
||||||
```
|
When you make a mistake, get corrected, or discover something about this codebase that wasn't written down:
|
||||||
|
|
||||||
The CLI auto-detects specs in `./specs/`, prompts for selection if multiple found, and handles session continuation interactively. Session state is stored per-spec in `specs/<feature>/.plan2code-loop/`.
|
1. Add one line to the `Failure log` below, in the imperative, describing the correct behaviour.
|
||||||
|
2. Keep it specific to this repo. General advice belongs nowhere.
|
||||||
### Loop Modes
|
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.
|
||||||
The CLI asks users to choose a loop mode:
|
5. A skill rule broken twice becomes a script check (a `scripts/` test or a skill-script check), not more prose.
|
||||||
- **One task per loop** (default) - Each agent invocation implements exactly one task. The Node controller handles git commits.
|
6. Before adding a line, look for one on the same topic: sharpen or extend that one rather than adding a near-duplicate.
|
||||||
- **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.
|
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.
|
||||||
|
|
||||||
### Completion Markers
|
## Failure log
|
||||||
|
|
||||||
The LLM must output one of these formats:
|
- Do not audit `CHANGELOG.md` headings through PowerShell — the emoji come back as `?`. See the gotcha for the correct approach.
|
||||||
- `TASK_COMPLETE: 1.1 - Task description` - Task done successfully
|
- 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.
|
||||||
- `TASK_BLOCKED: 1.1 - Reason` - Cannot complete task
|
- 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`).
|
||||||
- `PHASE_COMPLETE` - Current phase finished (phase mode only)
|
- 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.
|
||||||
- `LOOP_COMPLETE` - All phases finished
|
- 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.
|
||||||
## Plan2Code Metrics (`plan2code-metrics/`)
|
- 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).
|
||||||
A recursive self-improvement toolchain for plan2code contributors. Collects run metrics, aggregates by prompt generation, diagnoses weak steps via AI, and proposes surgical prompt edits.
|
- 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`).
|
||||||
|
- Register a new skill in `install.js` `SOURCE_PROMPTS` before running its `scripts/test-script-<name>.mjs`: importing `scripts/skill-script-helpers.mjs` rebuilds `skills/` and prunes any skill folder `install.js` does not list, so the script under test vanishes.
|
||||||
### Metrics Data Flow
|
- 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 `npm test` fails only timing-bound suites (the chat stress test, the page-cards redraw test "a redraw keeps the place of...", then a cascade in the session suite starting at "no submitted frame within 5s") while the machine is busy, rerun those files alone, and the `node --test` list with `--test-concurrency=4`, before suspecting the change: they failed that way on untouched code under load during the web console file split, and the redraw test did again in three phases of web-console-health. In web-console-notepad, four more failed only in full runs and passed alone: the Workspace page's @-mention test, the dashboard page's handoff chip test, the session suite's document route (`connect ETIMEDOUT`) and the notepad page's 200 KB typing test (why its budget there is 200 ms, not the 92 ms it takes alone). In helper-strength, the page-cards test "a card cut by the window fades at its bottom edge..." did the same.
|
||||||
```
|
- 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 behaviour 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.
|
||||||
Collect → Aggregate → Analyze → Improve → Apply
|
- Post a helper as `done` or `failed` in the same turn its completion notice arrives: its row stays `running` on the Subagents tab until a post says otherwise (a build once reached its sign-off with one row spinning). A `finish` is now refused while any helper is `running`.
|
||||||
```
|
- 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 → 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.
|
||||||
1. **Collector** reads project artifacts (`specs/<feature>/`) → writes `RunMetrics` JSON per run
|
|
||||||
2. **Aggregator** groups runs by prompt SHA fingerprint (cohorts) → `aggregated.json`
|
|
||||||
3. **Analyzer** invokes AI with aggregated metrics + prompt contents → diagnosis markdown
|
|
||||||
4. **Improver** invokes AI with diagnosis → validated `PromptEdit[]` proposals (char limit + verbatim checks)
|
|
||||||
5. **Applier** shows interactive diffs → patches `src/plan2code-*.md` files
|
|
||||||
|
|
||||||
### Metrics Commands
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd plan2code-metrics && npm run build # Build the CLI
|
|
||||||
plan2code-metrics # Run (fully interactive, no flags)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Metrics CLI Menu
|
|
||||||
|
|
||||||
| Option | Action |
|
|
||||||
|--------|--------|
|
|
||||||
| Collect | Read spec artifacts → run JSON |
|
|
||||||
| Import | Copy run JSON from another project |
|
|
||||||
| View | Display cohort metrics with health indicators |
|
|
||||||
| Analyze | AI diagnosis of weak metrics |
|
|
||||||
| Propose | AI improvement proposals with validation |
|
|
||||||
| Apply | Interactive diff review + file patching |
|
|
||||||
|
|
||||||
### Key Files
|
|
||||||
|
|
||||||
| File | Purpose |
|
|
||||||
|------|---------|
|
|
||||||
| `types.ts` | All interfaces (`RunMetrics`, `UserFeedback`, `CohortMetrics`, etc.) + `METRIC_TARGETS` |
|
|
||||||
| `collector.ts` | Reads project artifacts → run JSON (parses plan drafts, overview.md, loop logs) |
|
|
||||||
| `aggregator.ts` | Merges runs by prompt generation (SHA cohort) → `aggregated.json` |
|
|
||||||
| `analyzer.ts` | AI diagnosis via `prompts/analyze.md` template |
|
|
||||||
| `improver.ts` | AI proposals via `prompts/improve.md` + validation (char count, old_text match) |
|
|
||||||
| `applier.ts` | Interactive diff review + file patching |
|
|
||||||
| `cli.ts` | Menu-driven interactive CLI (100% prompts, no flags) |
|
|
||||||
| `invoke-llm.ts` | Unified LLM interface (Claude Code or Copilot CLI) |
|
|
||||||
|
|
||||||
### User Feedback
|
|
||||||
|
|
||||||
The collector parses an optional `## User Feedback` table from `overview.md`:
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
## User Feedback
|
|
||||||
| Field | Value |
|
|
||||||
|-------|-------|
|
|
||||||
| Rating | 8 |
|
|
||||||
| Reason | Smooth workflow |
|
|
||||||
| Went Well | Planning was thorough |
|
|
||||||
| Went Poorly | Some tasks unclear |
|
|
||||||
```
|
|
||||||
|
|
||||||
Feedback is collected during finalize (Step 5) or retroactively via the CLI. Pipe characters in values are escaped as `\|`. The aggregator computes `avg_user_rating` and `feedback_count` per cohort.
|
|
||||||
|
|
||||||
### Supported AI Agents
|
|
||||||
|
|
||||||
- **Claude Code** (recommended): `claude` CLI with `--inputFile` for prompt delivery
|
|
||||||
- **GitHub Copilot CLI**: `copilot` CLI with stdin prompt delivery
|
|
||||||
|
|
||||||
### Metric Targets
|
|
||||||
|
|
||||||
| Metric | Target | Direction |
|
|
||||||
|--------|--------|-----------|
|
|
||||||
| `avg_confidence` | ≥ 90 | higher is better |
|
|
||||||
| `avg_task_completion_rate` | ≥ 0.95 | higher is better |
|
|
||||||
| `avg_blocker_count` | ≤ 1.5 | lower is better |
|
|
||||||
| `avg_completion_marker_success_rate` | ≥ 0.95 | higher is better |
|
|
||||||
| `avg_verification_failures_found` | ≤ 1.0 | lower is better |
|
|
||||||
| `archival_success_rate` | ≥ 0.99 | higher is better |
|
|
||||||
| `avg_user_rating` | ≥ 7.0 | higher is better |
|
|
||||||
|
|
||||||
Data stored in `.plan2code-metrics/` (runs/, aggregated.json, proposals/).
|
|
||||||
|
|
||||||
## Development Commands
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Install dev dependencies (sets up husky pre-commit hooks)
|
|
||||||
npm install
|
|
||||||
|
|
||||||
# Run the interactive installer (always interactive — any CLI args are silently ignored)
|
|
||||||
node install.js
|
|
||||||
|
|
||||||
# Plan2Code Loop
|
|
||||||
cd plan2code-loop && npm install # First time setup
|
|
||||||
cd plan2code-loop && npm run build # Build the CLI
|
|
||||||
|
|
||||||
# Plan2Code Metrics
|
|
||||||
cd plan2code-metrics && npm install # First time setup
|
|
||||||
cd plan2code-metrics && npm run build # Build the CLI
|
|
||||||
```
|
|
||||||
|
|
||||||
### Installer Menu Options
|
|
||||||
|
|
||||||
**Main menu:**
|
|
||||||
|
|
||||||
| Option | Action |
|
|
||||||
|--------|--------|
|
|
||||||
| `I` | Install Plan2Code for all platforms + loop CLI |
|
|
||||||
| `U` | Uninstall Plan2Code files + loop CLI (confirmation required) |
|
|
||||||
| `C` | Open CUSTOM sub-menu |
|
|
||||||
| `Q` | Quit |
|
|
||||||
|
|
||||||
**CUSTOM sub-menu (`C`):**
|
|
||||||
|
|
||||||
| Option | Action |
|
|
||||||
|--------|--------|
|
|
||||||
| `L` | Show local (per-project) install instructions |
|
|
||||||
| `O` | Install plan2code-loop CLI only |
|
|
||||||
| `M` | Install plan2code-metrics CLI only |
|
|
||||||
| `Q` | Return to main menu |
|
|
||||||
|
|
||||||
## How the Installer Works
|
|
||||||
|
|
||||||
1. **Reads source prompts** from `src/plan2code-*.md`
|
|
||||||
2. **Generates platform-specific files** with appropriate headers (YAML frontmatter for some platforms)
|
|
||||||
3. **Writes to `dist/`** subdirectories organized by destination type
|
|
||||||
4. **Copies to target directories** (global: `~/.claude/commands/`, etc.)
|
|
||||||
|
|
||||||
### Platform-Specific File Formats
|
|
||||||
|
|
||||||
| Platform | Extension / File | Local Dir | Global Dir | Header |
|
|
||||||
|----------|-----------------|-----------|------------|--------|
|
|
||||||
| Claude Code | `.md` | — | — | None |
|
|
||||||
| Cursor | `.md` | — | — | None |
|
|
||||||
| Copilot CLI | `.md` | — | — | YAML frontmatter |
|
|
||||||
| Continue | `.prompt.md` | — | — | YAML frontmatter |
|
|
||||||
| Windsurf | `.md` | — | — | YAML frontmatter |
|
|
||||||
| VS Code Copilot | `.prompt.md` | — | — | YAML frontmatter |
|
|
||||||
| Codeium | `.md` | — | — | YAML frontmatter |
|
|
||||||
| Claude Code (Skills) | `SKILL.md` in subdir | `.claude/skills/<skill-name>/` | `~/.claude/skills/<skill-name>/` | YAML frontmatter + `disable-model-invocation: true` |
|
|
||||||
| Agent Skills (Amp · Gemini CLI · OpenCode) | `SKILL.md` in subdir | `.agents/skills/<skill-name>/` | `~/.agents/skills/<skill-name>/` | YAML frontmatter (no disable flag) |
|
|
||||||
| Crush | `SKILL.md` in subdir | — (global only) | `~/.config/crush/skills/<skill-name>/` (Unix) / `%LOCALAPPDATA%\crush\skills\<skill-name>\` (Windows) | YAML frontmatter |
|
|
||||||
| Gemini CLI (TOML) | `.toml` | `.gemini/commands/` | `~/.gemini/commands/` | None (TOML fields: `description`, `prompt`) |
|
|
||||||
|
|
||||||
## Naming Convention
|
|
||||||
|
|
||||||
Workflow files follow a strict naming pattern:
|
|
||||||
- **Utilities:** `plan2code---<name>.md` (triple dash)
|
|
||||||
- **Numbered steps:** `plan2code-<N>--<name>.md` (single dash, number, double dash)
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
- `plan2code---init.md` (utility)
|
|
||||||
- `plan2code-1--plan.md` (step 1)
|
|
||||||
- `plan2code-1b--revise-plan.md` (step 1b)
|
|
||||||
|
|
||||||
## Editing Workflow Prompts
|
|
||||||
|
|
||||||
When modifying workflow prompts in `src/`:
|
|
||||||
|
|
||||||
1. Edit the source file in `src/`
|
|
||||||
2. Run `node install.js` to regenerate distribution files
|
|
||||||
3. Test the workflow in your AI tool of choice
|
|
||||||
4. The `dist/` folder is regenerated automatically - don't edit files there directly
|
|
||||||
|
|
||||||
## Code Style
|
|
||||||
|
|
||||||
- **install.js:** CommonJS, Node.js built-ins only (no external deps), ANSI colors via `COLORS` constant, readline-based prompts
|
|
||||||
- **plan2code-loop & plan2code-metrics:** TypeScript + ESM, built with tsup (target ES2022, moduleResolution: bundler)
|
|
||||||
- External deps: `@inquirer/prompts`, `chalk`, `execa`, `ora`
|
|
||||||
- Interactive CLI via `@inquirer/prompts` (select, input, confirm)
|
|
||||||
- **File operations:** Synchronous fs in all packages
|
|
||||||
|
|
||||||
## Gotchas/Pitfalls
|
|
||||||
|
|
||||||
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` to match. The installer displays the version from `version.json` in its header.
|
|
||||||
- **Loop `.gitignore` setup:** `ensureGitignore()` runs at startup in `Controller.run()` as a pre-flight step, not just inside `createTaskCommit()`. This is critical for phase mode where the Node controller doesn't handle commits — without it, `git add -A` would stage spec files.
|
|
||||||
- **Workflow file character limit:** All `src/plan2code-*.md` files must be ≤ 11,000 characters. A husky pre-commit hook enforces this. The 11,000 limit leaves buffer for platform-specific YAML headers (106-142 chars) to stay under Windsurf's 12,000 char limit.
|
|
||||||
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 11,000 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
|
|
||||||
- **User Feedback table format:** The `## User Feedback` markdown table in `overview.md` has a strict format the collector regex depends on. Field names must be exactly `Rating`, `Reason`, `Went Well`, `Went Poorly`. Pipe characters in values must be escaped as `\|`.
|
|
||||||
|
|
||||||
## Git Commit Messages
|
|
||||||
|
|
||||||
- **AI Assisted footer:** All git commit messages must include `AI Assisted` as the final line, separated from the message body by a blank line
|
|
||||||
- **Commit paths:** This is enforced across all commit surfaces:
|
|
||||||
- Loop task mode: `createTaskCommit()` in `plan2code-loop/src/utils/git.ts` appends the footer automatically
|
|
||||||
- Loop phase mode: Prompt template instructs the LLM to add `-m "AI Assisted"` as the final flag
|
|
||||||
- Implement mode: User-facing commit suggestions in `src/plan2code-3--implement.md` include the footer
|
|
||||||
- **Init workflow:** `src/plan2code---init.md` generates AGENTS.md files with a Git Commit Messages section that includes this convention by default
|
|
||||||
|
|
||||||
## Mascot
|
|
||||||
|
|
||||||
The project has a mascot called "Planny" - an ASCII art robot that appears in installer output and workflow prompts. Mascot variants are defined in `MASCOT` constant in `install.js` and appear in workflow markdown files.
|
|
||||||
|
|
||||||
```
|
|
||||||
╭───╮
|
|
||||||
│ ● │
|
|
||||||
│ ◡ │
|
|
||||||
╰───╯
|
|
||||||
```
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
**CRITICAL — MANDATORY FIRST STEP: You MUST read [AGENTS.md](./AGENTS.md) before responding to ANY user message, including simple questions. Do NOT skip this step regardless of how trivial the request appears. No exceptions.**
|
||||||
|
|
||||||
|
See AGENTS.md for complete project documentation including:
|
||||||
|
- Development commands and setup
|
||||||
|
- Architecture overview
|
||||||
|
- Workflow prompt reference
|
||||||
|
- Plan2Code Loop CLI details
|
||||||
|
- Code style and gotchas
|
||||||
|
- Keeping this file current / Failure log
|
||||||
|
- Section details in .agents-docs/
|
||||||
|
|
||||||
|
This file exists for Claude Code auto-loading. All AI coding agents should reference AGENTS.md.
|
||||||
@@ -1,23 +1,66 @@
|
|||||||
# Plam2Code Quick Reference
|
# Plan2Code Quick Reference
|
||||||
|
|
||||||
|
## Before you start
|
||||||
|
|
||||||
|
- **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.
|
||||||
|
|
||||||
|
## Launch
|
||||||
|
|
||||||
|
The web console is the main way in: a local page where questions, documents, build progress and sign-offs live.
|
||||||
|
|
||||||
|
| How | Command | What happens |
|
||||||
|
| ------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------- |
|
||||||
|
| 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 | `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 everything that was installed, with no menu; 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/`, never shown to the agent).
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
| Step | Command | Input | Output |
|
Every command below is what a dashboard card runs. Typed on its own, each one asks "web console or terminal?" first.
|
||||||
| ------ | ------------------------------- | --------------- | ----------------------------------- |
|
|
||||||
| Init | /plan2code---init | None | AGENTS.md file |
|
| Step | Command | Input | Output |
|
||||||
| Update | /plan2code---init-update | AGENTS.md | Updated AGENTS.md |
|
| ---------- | ----------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------- |
|
||||||
| 0 | /plan2code---quick-task | Requirements | Conversational plan |
|
| — | /plan2code | None | Web console dashboard — a menu of every skill below, launched on the page |
|
||||||
| 1 | /plan2code-1--plan | Requirements | PLAN-CONVERSATION-<date>.md + PLAN-DRAFT-<date>.md |
|
| Init | /plan2code-init | None | AGENTS.md file |
|
||||||
| 1b | /plan2code-1b--revise-plan | Specs + changes | Updated specs |
|
| Update | /plan2code-init-update | AGENTS.md | Updated AGENTS.md |
|
||||||
| 2 | /plan2code-2--document | PLAN-DRAFT.md | overview.md + Phase files |
|
| 0 | /plan2code-0-pathfinder | A foggy idea | pathfinder/map.md *or* GitHub Issues + PLAN-DRAFT-<date>.md |
|
||||||
| 3 | /plan2code-3--implement | overview.md | Implemented code |
|
| quick | /plan2code-quick-task | Requirements | A short plan, then the change built (standalone, not a pipeline step) |
|
||||||
| 4 | /plan2code-4--finalize | overview.md | Archived specs |
|
| review | /plan2code-review | Scope guidance | Review findings + fixes |
|
||||||
|
| 1 | /plan2code-1-plan | Requirements | PLAN-CONVERSATION-<date>.md + PLAN-DRAFT-<date>.md |
|
||||||
|
| 1b | /plan2code-1b-revise-plan | Specs + changes | Updated specs |
|
||||||
|
| 2 | /plan2code-2-document | PLAN-DRAFT.md | overview.md + Phase files |
|
||||||
|
| 3 | /plan2code-3-implement | overview.md | Implemented code |
|
||||||
|
| 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 |
|
||||||
|
| changelog | /plan2code-changelog | Your branch | `CHANGELOG.md` entries and the `package.json` version, from the default branch's latest version |
|
||||||
|
| 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.
|
||||||
|
|
||||||
## File Structure
|
## File Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
specs/
|
specs/
|
||||||
└── <feature-name>/
|
└── <feature-name>/
|
||||||
|
├── pathfinder/ # From Step 0 (optional, if charted locally)
|
||||||
|
│ ├── map.md # the map: destination, decisions, fog
|
||||||
|
│ ├── questions/NN-<slug>.md # one decision question per file
|
||||||
|
│ └── briefs/brief-<date>.md # on-demand plain-English decision briefs
|
||||||
|
│ # (GitHub Issues backend: map issue + sub-issues instead)
|
||||||
├── PLAN-DRAFT-<date>.md # From Step 1 (verified plan)
|
├── PLAN-DRAFT-<date>.md # From Step 1 (verified plan)
|
||||||
├── PLAN-CONVERSATION-<date>.md # From Step 1 (conversation log)
|
├── PLAN-CONVERSATION-<date>.md # From Step 1 (conversation log)
|
||||||
├── overview.md # From Step 2
|
├── overview.md # From Step 2
|
||||||
@@ -31,9 +74,9 @@ Note: `<date>` uses YYYYMMDD format (e.g., `20250204`)
|
|||||||
|
|
||||||
## Key Rules
|
## Key Rules
|
||||||
|
|
||||||
- Start NEW conversation for each step (and each implementation phase)
|
- Keep sessions short: fresh console session when the meter turns red, and before a big plan or build step
|
||||||
- ONE phase per conversation (but parallel phases can run in separate instances)
|
- ONE phase per conversation (but parallel phases can run in separate instances)
|
||||||
- Reply "approved" to complete phases
|
- Approve phases on the sign-off card (or reply "approved" in the terminal)
|
||||||
- 90% confidence required before planning completes
|
- 90% confidence required before planning completes
|
||||||
- Never look in `specs--completed/` (it's archived specs)
|
- Never look in `specs--completed/` (it's archived specs)
|
||||||
|
|
||||||
@@ -44,67 +87,57 @@ Note: `<date>` uses YYYYMMDD format (e.g., `20250204`)
|
|||||||
| `[ ]` | Pending | Not started |
|
| `[ ]` | Pending | Not started |
|
||||||
| `[/]` | In Progress | Agent working (or paused) |
|
| `[/]` | In Progress | Agent working (or paused) |
|
||||||
| `[x]` | Complete | Approved |
|
| `[x]` | Complete | Approved |
|
||||||
|
| `[!]` | Blocked | Couldn't be done; the line says why and what you need to do |
|
||||||
|
| `[?]` | Assumed | Couldn't be verified, assumed complete; check it |
|
||||||
|
|
||||||
## Parallel Execution
|
## Parallel Execution
|
||||||
|
|
||||||
When phases have no file conflicts or dependencies, they can run simultaneously:
|
When phases have no file conflicts or dependencies, they can run simultaneously:
|
||||||
|
|
||||||
1. Documentation Mode auto-detects parallel-eligible phases
|
1. Documentation Mode auto-detects parallel-eligible phases
|
||||||
2. Implementation Mode shows selection UI with status for each phase
|
2. Implementation Mode asks which phase to take (a card on the web console), with the status of each
|
||||||
3. Run multiple `/plan2code-3--implement` instances on different phases
|
3. Run multiple `/plan2code-3-implement` instances on different phases
|
||||||
4. `[/]` status shows which phases are actively being worked on
|
4. `[/]` status shows which phases are actively being worked on
|
||||||
|
|
||||||
## Quick Troubleshooting
|
## Quick Troubleshooting
|
||||||
|
|
||||||
| Issue | Solution |
|
| Issue | Solution |
|
||||||
| ---------------------- | ------------------------------------------------- |
|
| ---------------------- | ------------------------------------------------ |
|
||||||
| Lost context mid-phase | Attach spec files, say "resume from Task X.Y" |
|
| Lost context mid-phase | Attach spec files, say "resume from Task X.Y" |
|
||||||
| Wrong phase started | Say "abort", start correct phase |
|
| Wrong phase started | Say "abort", start correct phase |
|
||||||
| Need to change plan | Use `/plan2code-1b--revise-plan` |
|
| Need to change plan | Use `/plan2code-1b-revise-plan` |
|
||||||
| Multiple spec folders | Specify which: "Continue with specs/user-auth/" |
|
| Multiple spec folders | Specify which: "Continue with specs/user-auth/" |
|
||||||
| Need AGENTS.md file | Use `/plan2code---init` to generate one |
|
| Need AGENTS.md file | Use `/plan2code-init` to generate one |
|
||||||
| Update AGENTS.md | Use `/plan2code---init-update` after sessions |
|
| Update AGENTS.md | Use `/plan2code-init-update` after sessions |
|
||||||
| Run phases in parallel | Check Parallel Execution Groups in overview.md |
|
| Run phases in parallel | Check Parallel Execution Groups in overview.md |
|
||||||
|
|
||||||
## Workflow Decision
|
## Workflow Decision
|
||||||
|
|
||||||
```
|
```
|
||||||
New to a project?
|
New to a project?
|
||||||
└── /plan2code---init → Generate AGENTS.md for project-specific guidance
|
└── /plan2code-init → Generate AGENTS.md for project-specific guidance
|
||||||
|
|
||||||
Learned something during a session?
|
Learned something during a session?
|
||||||
└── /plan2code---init-update → Add learnings to AGENTS.md
|
└── /plan2code-init-update → Add learnings to AGENTS.md
|
||||||
|
|
||||||
|
Too foggy to plan? (big idea, don't yet know what the questions are)
|
||||||
|
└── /plan2code-0-pathfinder → chart it, clear one decision at a time
|
||||||
|
├── continue-or-stop menu between decisions; fresh session recommended after ~3
|
||||||
|
└── then → /plan2code-1-plan (resumes at Phase 4)
|
||||||
|
|
||||||
Is it a quick, small task?
|
Is it a quick, small task?
|
||||||
├── Yes → /plan2code---quick-task (standalone)
|
├── Yes → /plan2code-quick-task (standalone)
|
||||||
└── No → /plan2code-1--plan (full workflow)
|
└── No → /plan2code-1-plan (full workflow)
|
||||||
├── /plan2code-2--document
|
├── /plan2code-2-document
|
||||||
├── /plan2code-3--implement (repeat per phase)
|
├── /plan2code-3-implement (repeat per phase)
|
||||||
|
│ ├── OR: /plan2code-3-implement-review (review gate before approval)
|
||||||
│ └── OR: plan2code-loop (autonomous alternative)
|
│ └── OR: plan2code-loop (autonomous alternative)
|
||||||
└── /plan2code-4--finalize
|
└── /plan2code-4-finalize
|
||||||
|
|
||||||
Need to revise mid-implementation?
|
Need to revise mid-implementation?
|
||||||
└── /plan2code-1b--revise-plan
|
└── /plan2code-1b-revise-plan
|
||||||
```
|
```
|
||||||
|
|
||||||
## Autonomous Loop (Alternative)
|
## Autonomous Loop (Alternative)
|
||||||
|
|
||||||
The `plan2code-loop` CLI is an **alternative** to Step 3, not a replacement.
|
`plan2code-loop` is a hands-off alternative to Step 3. See [.readme/autonomous-loop.md](.readme/autonomous-loop.md).
|
||||||
|
|
||||||
| Approach | Use When |
|
|
||||||
|----------|----------|
|
|
||||||
| `/plan2code-3--implement` | You want interactive control per phase |
|
|
||||||
| `plan2code-loop` | You want hands-off autonomous execution |
|
|
||||||
|
|
||||||
```bash
|
|
||||||
plan2code-loop # Fully interactive - auto-detects specs, prompts for options
|
|
||||||
```
|
|
||||||
|
|
||||||
### Loop Modes
|
|
||||||
|
|
||||||
| Mode | Description |
|
|
||||||
|------|-------------|
|
|
||||||
| **One task per loop** (default) | One task per agent invocation. Node handles git commits. |
|
|
||||||
| **One phase per loop** | All tasks in a phase per invocation. LLM handles git commits. Best for smart models with larger context. |
|
|
||||||
|
|
||||||
Session state stored per-spec in `specs/<feature>/.plan2code-loop/`
|
|
||||||
@@ -1,516 +1,454 @@
|
|||||||
# Plan2Code: AI-Assisted Software Development Workflow
|
|
||||||
|
# Plan2Code
|
||||||
A structured 4-step workflow for developing features and projects with AI assistance. This methodology emphasizes thorough planning before implementation, ensuring well-documented, maintainable code.
|
|
||||||
|
**A spec-driven workflow for AI coding agents.**
|
||||||
<img src="docs/desk.jpg" alt="Plan2Code Workflow" height="275">
|
|
||||||
|
<img src="docs/banner.jpg" alt="banner" data="object-fit:contain;" style="max-width:1024px;">
|
||||||
## Overview
|
|
||||||
|
You work through Plan2Code on a page in your browser. The dashboard lists every step as a card, and
|
||||||
```
|
each step's questions, progress and sign-offs arrive on that same page while your agent does the
|
||||||
🤔 📝 ⚡ 🧹
|
work. What you decide still lands in your repo as plain files: an approved plan becomes phase
|
||||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
documents, and the agent builds to them one phase at a time, so the next session, the next agent and
|
||||||
│ Step 1 │ │ Step 2 │ │ Step 3 │ │ Step 4 │
|
the next engineer all start from the same specs.
|
||||||
│ PLAN │ --> │ DOCUMENT │ --> │ IMPLEMENT │ --> │ FINALIZE │
|
|
||||||
└─────────────────┘ └─────────────────┘ └─────────────────┘ └─────────────────┘
|
One command opens it, every step is a card, and the terminal is always there if you prefer it.
|
||||||
New Chat New Chat New Chat (per phase) New Chat
|
|
||||||
```
|
Version 3.0.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||||
|
|
||||||
| Command | When to Use |
|
---
|
||||||
|----------------------------------|----------------------------------------------------------|
|
|
||||||
| `/plan2code---init` | Generate AGENTS.md file for new/existing projects |
|
## See it
|
||||||
| `/plan2code---init-update` | Update AGENTS.md with new learnings from coding sessions |
|
|
||||||
| `/plan2code---quick-task` | Small, quick tasks that don't need full workflow |
|
<picture>
|
||||||
| `/plan2code-1--plan` | Starting a new feature (full planning) |
|
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/dashboard-dark.webp">
|
||||||
| `/plan2code-1b--revise-plan` | Requirements change mid-implementation |
|
<img src="docs/screenshots/dashboard-light.webp" alt="The Plan2Code dashboard for a project mid-build: a Set up card, then the steps in order, with the Implement card marked Suggested and reading Phase 3 of 4 is next.">
|
||||||
| `/plan2code-2--document` | After planning, create implementation specs |
|
</picture>
|
||||||
| `/plan2code-3--implement` | Execute implementation (one phase per conversation) |
|
|
||||||
| `/plan2code-4--finalize` | All phases complete, ready to archive |
|
The dashboard, in a project halfway through a build. It suggests the next step for the spec you pick.
|
||||||
|
|
||||||
**Key Rules:**
|
---
|
||||||
- Start NEW conversation for each step (and each implementation phase)
|
|
||||||
- ONE phase per conversation
|
## Install and start
|
||||||
- Reply "approved" to complete phases
|
|
||||||
- 90% confidence required before planning completes
|
### Before you start
|
||||||
|
|
||||||
See [QUICK-REFERENCE.md](QUICK-REFERENCE.md) for full reference card.
|
- **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.
|
||||||
## Installation
|
|
||||||
|
Installation needs network access and runs through the [skills CLI](https://skills.sh). To update, run `plan2code update` (or re-run the install command).
|
||||||
Plan2Code includes an interactive installer that generates and installs workflow files for all major AI coding assistants.
|
|
||||||
|
```bash
|
||||||
<img src="docs/install-script.jpg" width="600">
|
npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git
|
||||||
|
```
|
||||||
### Prerequisites
|
|
||||||
|
This fetches the installer to a temp directory, builds the workflow as Agent Skills, delegates
|
||||||
The install script requires **Node.js** (v14 or later). If you don't have Node.js installed:
|
installation to `skills add`, and cleans up after itself. The installed skills work independently
|
||||||
|
from then on.
|
||||||
1. Download from [nodejs.org](https://nodejs.org/) (recommended)
|
|
||||||
2. Or use a package manager:
|
**Back at your prompt with no output at all?** The installer always opens the menu below, so nothing
|
||||||
- **macOS:** `brew install node`
|
means npm could not reach the repository and hid the reason. Run
|
||||||
- **Windows:** `winget install OpenJS.NodeJS` or `choco install nodejs`
|
`git ls-remote https://github.com/jparkerweb/plan2code.git` to see it: usually the network, a proxy
|
||||||
- **Linux:** `sudo apt install nodejs` (Debian/Ubuntu) or `sudo dnf install nodejs` (Fedora)
|
or the VPN.
|
||||||
|
|
||||||
### Supported Platforms
|
The installer opens this menu (cloning and running `node install.js`, below, opens the same one):
|
||||||
|
|
||||||
- Claude Code
|
```
|
||||||
- Cursor
|
╔═════════════════════════════════════════════════════════╗
|
||||||
- Windsurf
|
║ INSTALL PLAN2CODE ║
|
||||||
- Continue
|
╠═════════════════════════════════════════════════════════╣
|
||||||
- Codeium (IntelliJ)
|
║ I. INSTALL Install skills + the plan2code command ║
|
||||||
- GitHub Copilot CLI
|
║ U. UNINSTALL Remove everything Plan2Code installed ║
|
||||||
- VS Code GitHub Copilot
|
║ A. ADVANCED Project install, dev tools, and more ║
|
||||||
- Gemini CLI
|
║ Q. QUIT Exit ║
|
||||||
- Crush
|
╚═════════════════════════════════════════════════════════╝
|
||||||
- Amp
|
```
|
||||||
- OpenCode
|
|
||||||
|
### Start
|
||||||
### Install via npx (Recommended — No Clone Required)
|
|
||||||
|
1. `cd` into your project, then run `plan2code`. It starts Claude Code, Devin or Codex on the dashboard,
|
||||||
Run the interactive installer directly using `npx` with your preferred GitHub authentication method:
|
and the dashboard opens in your browser.
|
||||||
|
2. In a project without an `AGENTS.md`, pick **Set up this project** first: Plan and Quick task
|
||||||
**If you use SSH keys:**
|
need it.
|
||||||
```bash
|
3. Pick a card.
|
||||||
npx git+ssh://git@github.com/jparkerweb/plan2code.git
|
|
||||||
```
|
Already inside your agent? Type `/plan2code` instead (`$plan2code` in Codex).
|
||||||
|
|
||||||
**If you use HTTPS authentication:**
|
<details>
|
||||||
```bash
|
<summary>About the plan2code command</summary>
|
||||||
npx git+https://github.com/jparkerweb/plan2code.git
|
|
||||||
```
|
Install (`I`) adds `plan2code` as a global command (Advanced `A` → `D` adds just the command). Run it from any project and the Plan2Code
|
||||||
|
dashboard opens right there, in **Claude Code**, **Devin** or **Codex**. With more than one installed it asks which and
|
||||||
This downloads the installer to a temporary location, runs it, installs the workflow files to your machine, and cleans up automatically. The installed workflows remain on your system and work independently. To update or reinstall, simply run the command again.
|
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
|
||||||
### Standard Installation (Clone Method)
|
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
|
||||||
#### No Clone Required
|
`claude /plan2code` yourself if you want prompts. The installer then offers a desktop shortcut (answer `y`),
|
||||||
|
which opens a folder picker first. Uninstalling (`U`) removes both.
|
||||||
Run the interactive installer directly using `npx` with your preferred GitHub authentication method:
|
</details>
|
||||||
|
|
||||||
**If you use SSH keys:**
|
<details>
|
||||||
```bash
|
<summary>About the desktop app</summary>
|
||||||
npx git+ssh://git@github.com/jparkerweb/plan2code.git
|
|
||||||
```
|
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
|
||||||
**If you use HTTPS authentication:**
|
dashboard, opens inside it. A launch card asks which agent, model and effort to start on, with
|
||||||
```bash
|
permission checks off as its own tick (on by default, matching the terminal flow; untick it to keep
|
||||||
npx git+https://github.com/jparkerweb/plan2code.git
|
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
|
||||||
This downloads the installer to a temporary location, runs it, installs the workflow files to your machine, and cleans up automatically. The installed workflows remain on your system and work independently. To update or reinstall, simply run the command again.
|
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
|
||||||
#### Standard Installation (Clone Method)
|
command and the app together, and the bar offers the same **Update skills** when the app and the
|
||||||
|
installed skills disagree.
|
||||||
```bash
|
|
||||||
# Clone the repository
|
The first release is unsigned, so macOS (**Open Anyway** in System Settings, Privacy & Security) or
|
||||||
git clone https://github.com/jparkerweb/plan2code.git
|
Windows (**More info**, then **Run anyway**) may ask you to allow it once. The app starts the agent
|
||||||
cd plan2code
|
with its normal approval prompts unless you tick the launch card's permission-checks-off option (the
|
||||||
|
plain `plan2code` command above, without the app, still starts with checks off by default). Details:
|
||||||
# Run the interactive installer
|
[docs/desktop-app.md](docs/desktop-app.md).
|
||||||
node install.js
|
</details>
|
||||||
|
|
||||||
# OPTIONAL: Install dev dependencies (ONLY if you plan to modify/contribute to Plan2Code)
|
**Supported tools:** every agent supported by the skills CLI, including Claude Code · Cursor ·
|
||||||
npm install
|
GitHub Copilot · Windsurf · Codex · Continue · Codeium · Zed · Amp · OpenCode · Devin · Crush · Pi ·
|
||||||
```
|
Gemini CLI · Cline · Roo · Kilo · Goose · Trae · Qwen Code.
|
||||||
|
|
||||||
The installer displays an interactive menu:
|
The installer keeps one canonical copy of each skill under `~/.agents/skills/` and links it into
|
||||||
|
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
|
||||||
║ INSTALL PLAN2CODE ║
|
would also find maintainer-only skills under `.claude/skills/`. The installer targets `skills/`
|
||||||
╠════════════════════════════════════════════════════════════════╣
|
explicitly.
|
||||||
║ I. INSTALL Install Plan2Code for all platforms ║
|
|
||||||
║ U. UNINSTALL Remove Plan2Code files ║
|
<details>
|
||||||
║ C. CUSTOM Advanced options ║
|
<summary>Prefer to clone?</summary>
|
||||||
║ Q. QUIT Exit ║
|
|
||||||
╚════════════════════════════════════════════════════════════════╝
|
```bash
|
||||||
|
git clone https://github.com/jparkerweb/plan2code.git
|
||||||
SELECT OPTION (I, U, C, Q) [I]:
|
cd plan2code
|
||||||
```
|
node install.js
|
||||||
|
|
||||||
---
|
# Only if you plan to modify or contribute to Plan2Code itself
|
||||||
|
npm install && npx husky
|
||||||
## Important: Start Fresh Conversations
|
```
|
||||||
|
</details>
|
||||||
**Start a new conversation/chat session before each step.** This includes:
|
|
||||||
|
---
|
||||||
- Step 1: New conversation
|
|
||||||
- Step 2: New conversation
|
## A session on the page
|
||||||
- Step 3: New conversation **for each phase** (Phase 1, Phase 2, etc.)
|
|
||||||
- Step 4: New conversation
|
**Answer the questions.** They arrive a few at a time, each option with its trade-off written beside
|
||||||
|
it, and a progress bar says how far along you are.
|
||||||
Fresh conversations prevent context pollution and ensure the AI focuses on the current task with the relevant specifications.
|
|
||||||
|
<picture>
|
||||||
---
|
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/question-dark.webp">
|
||||||
|
<img src="docs/screenshots/question-light.webp" alt="A Plan question card, How tasks are paged, with three options, the first marked Suggested, each with its trade-off underneath.">
|
||||||
## The Workflow Steps
|
</picture>
|
||||||
|
|
||||||
### Step 1: Planning Mode 🤔
|
**Watch the build.** Tasks tick off as they land, and the line beside Planny says what is being
|
||||||
|
worked on right now.
|
||||||
**Purpose:** Thoroughly analyze requirements and design the solution architecture before writing any code.
|
|
||||||
|
<picture>
|
||||||
**AI Role:** Senior software architect and technical product manager
|
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/build-dark.webp">
|
||||||
|
<img src="docs/screenshots/build-light.webp" alt="A phase of a task API being built: 5 of 11 done on the progress bar, and the phase's task list with the first five ticked.">
|
||||||
**Phases (completed one at a time):**
|
</picture>
|
||||||
|
|
||||||
1. **Requirements Analysis** - Extract functional/non-functional requirements, identify ambiguities
|
**Sign off.** Read the completion report, then approve the phase or ask for changes. In Implement,
|
||||||
2. **System Context Examination** - Review existing codebase, identify integration points
|
you can also have the code reviewed first; Implement + review has already done it.
|
||||||
3. **Tech Stack** - Recommend and confirm all technologies (requires user sign-off)
|
|
||||||
4. **Architecture Design** - Propose patterns, define components, design interfaces/schemas
|
<picture>
|
||||||
5. **Technical Specification** - Break down implementation phases, identify risks
|
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/signoff-dark.webp">
|
||||||
6. **Transition Decision** - Finalize plan when confidence reaches 90%+
|
<img src="docs/screenshots/signoff-light.webp" alt="The Approve this phase card, with a button to read the completion report and three choices: Review the code first, Approve this phase, and I want changes.">
|
||||||
|
</picture>
|
||||||
**Output:** `specs/<feature-name>/PLAN-DRAFT-<date>.md` and `specs/<feature-name>/PLAN-CONVERSATION-<date>.md` (date format: YYYYMMDD)
|
|
||||||
|
**Ask a quick question any time.** The Ask tab is a chat beside the cards, answered at the agent's
|
||||||
**Key Behaviors:**
|
next check-in, and it never holds up your answers.
|
||||||
|
|
||||||
- AI stops after each phase for clarification
|
<picture>
|
||||||
- Must reach 90% confidence before finalizing
|
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/ask-dark.webp">
|
||||||
- All assumptions are documented
|
<img src="docs/screenshots/ask-light.webp" alt="The Ask tab: the question Where are tasks paged? and Plan2Code's answer naming the file.">
|
||||||
- User must approve tech stack decisions
|
</picture>
|
||||||
|
|
||||||
---
|
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
|
||||||
### Step 2: Documentation Mode 📝
|
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 never sees. The session meter in the top bar turns from green
|
||||||
**Purpose:** Transform the planning output into structured, actionable implementation documents.
|
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
|
||||||
**Required Context:** Attach or reference the `specs/<feature-name>/PLAN-DRAFT-<date>.md` from Step 1 (or provide the planning conversation).
|
step in the same session.
|
||||||
|
|
||||||
**Output Structure:**
|
---
|
||||||
|
|
||||||
```
|
## The workflow
|
||||||
specs/
|
|
||||||
└── <feature-name>/
|
```
|
||||||
├── overview.md # High-level overview with phase checkboxes and parallel groups
|
┌╴╴╴╴╴╴╴╴╴╴╴╴┐
|
||||||
├── Phase 1.md # Detailed tasks for Phase 1
|
╎0 PATHFINDER╎ optional · for an idea too big or unclear to plan
|
||||||
├── Phase 2.md # Detailed tasks for Phase 2
|
└╴╴╴╴╴╴┬╴╴╴╴╴┘
|
||||||
└── Phase N.md # ...additional phases
|
▼
|
||||||
```
|
┌────────────┐ ┌────────────┐ ┌────────────┐ ┌╴╴╴╴╴╴╴╴╴╴╴╴┐ ┌────────────┐
|
||||||
|
│ 1 PLAN │─>│ 2 DOCUMENT │─>│3 IMPLEMENT │─>╎ REVIEW ╎─>│ 4 FINALIZE │
|
||||||
The `overview.md` includes a "Parallel Execution Groups" section that identifies which phases can be run simultaneously in separate agent instances.
|
│decide what │ │ draw it as │ │build to the│ ╎ optional ╎ │verify, sum,│
|
||||||
|
│ to build │ │phase specs │ │ drawing │ ╎ any time ╎ │ archive │
|
||||||
**Document Format:**
|
└────────────┘ └────────────┘ └────────────┘ └╴╴╴╴╴╴╴╴╴╴╴╴┘ └────────────┘
|
||||||
|
short sessions: fresh when the meter turns red, and before a big step
|
||||||
- Each phase file contains detailed one-story-point tasks
|
├◀─────────────── one feature, start to archive ──────────────────▶┤
|
||||||
- All tasks have checkboxes `[ ]` for progress tracking
|
```
|
||||||
- Each phase is self-contained (developer needs no prior context)
|
|
||||||
- Unit/E2E testing excluded unless explicitly requested
|
Each box is a card on the dashboard. Chaining a couple of small steps in one session is fine, but
|
||||||
|
start a fresh session before a big plan or build step: planning context leaking into implementation
|
||||||
---
|
is where most agent drift starts.
|
||||||
|
|
||||||
### Step 3: Implementation Mode ⚡
|
The dashboard's cards, and when each one lights up for the spec you pick:
|
||||||
|
|
||||||
**Purpose:** Execute the implementation following the documented specifications.
|
| Card | What it is for | Lights up when |
|
||||||
|
|------|----------------|----------------|
|
||||||
**AI Role:** Senior software engineer
|
| 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 |
|
||||||
**Required Context:** Provide the path to `specs/<feature-name>/overview.md`. The command will auto-detect the next uncompleted phase and read the corresponding `Phase X.md` file automatically.
|
| 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, a drafted plan or a bug diagnosis |
|
||||||
**Workflow:**
|
| 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 |
|
||||||
1. Identify the next uncompleted phase (unchecked in `overview.md`)
|
| 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 |
|
||||||
2. Check for parallel execution options (if phases can run simultaneously)
|
| 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 |
|
||||||
3. Implement ALL tasks in that phase exactly as specified
|
| Finalize | Checks the work, writes the summary, files the specs away and suggests the commit message. | Every task in the spec is done |
|
||||||
4. Update `Phase X.md` checkboxes as tasks complete `[x]`
|
| 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) |
|
||||||
5. Update `overview.md` phase checkbox when phase completes
|
| Review | A second opinion on the changes. Problems ranked, and you pick what gets fixed. | Always |
|
||||||
6. Perform code review to ensure nothing was missed
|
| 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 |
|
||||||
7. Add completion summary to the phase document
|
| 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 |
|
||||||
**Parallel Execution:** If the next phase is part of a parallel-eligible group, you'll be prompted to choose which phase to implement. This allows running multiple agent instances simultaneously on different phases that don't conflict with each other.
|
| Changelog | Checks the CHANGELOG version against the main branch and suggests entries for what is new. | Always |
|
||||||
|
| Git | Branches, pull, push and commits on one board, asking before anything leaves your machine. | Always (offers to start a repository outside one) |
|
||||||
**Key Rules:**
|
|
||||||
|
---
|
||||||
- **Start a new conversation for EACH phase**
|
|
||||||
- Work on ONE phase per conversation (unless told otherwise)
|
## The four rules that do most of the work
|
||||||
- Follow specifications EXACTLY as documented
|
|
||||||
- Keep checkboxes updated (enables progress tracking across sessions)
|
**1 · Keep each session short.**
|
||||||
- Do NOT run tests unless specified in phase tasks
|
Chaining a couple of small skills on the dashboard is fine. Start a fresh console session when the session meter turns red, and always before a big planning or build step. The specs on disk carry everything between sessions.
|
||||||
|
|
||||||
---
|
**2 · No code until the plan hits 90% confidence.**
|
||||||
|
Step 1 will not finalize below the threshold. Under it, the agent keeps asking and keeps reading your
|
||||||
### Step 4: Finalization Mode 🧹
|
code — and writes every assumption down where you can argue with it.
|
||||||
|
|
||||||
**Purpose:** Validate implementation, create summaries, and archive documentation.
|
**3 · Checkboxes are the state, not the chat.**
|
||||||
|
Progress lives in the spec files. Any agent, any session, resumes cold from them.
|
||||||
**Required Context:** Attach or reference the `specs/<feature-name>/` directory contents.
|
|
||||||
|
**4 · Approve a phase to close it.**
|
||||||
**Steps:**
|
On the sign-off card, or by replying `approved` in the terminal. Nothing advances on a guess about
|
||||||
|
what you meant.
|
||||||
1. **Validation** - Verify all tasks implemented correctly, check for issues
|
|
||||||
2. **Summary** - Document what was built and list all modified/created files
|
---
|
||||||
3. **Documentation Review** - Identify any needed README/CHANGELOG updates
|
|
||||||
4. **Spec Cleanup** - Move completed specs to `specs--completed/<implementation-name>/`
|
## What lands in your repo
|
||||||
5. **Final Confirmation** - Confirm completion
|
|
||||||
|
Each feature gets a folder under `specs/` (the plan, the overview and one file per phase), and Step 4
|
||||||
---
|
moves it to `specs--completed/`. The layout and progress marks are on the
|
||||||
|
[quick reference](QUICK-REFERENCE.md#file-structure).
|
||||||
## How to Use
|
|
||||||
|
Add `specs/` to your project's `.gitignore` (`plan2code-loop` adds it for you): it's your working
|
||||||
After running `node install.js`, use the slash commands directly in your AI tool:
|
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
|
||||||
/plan2code-1--plan # Start planning a new feature
|
keep the two out of each other's way.
|
||||||
/plan2code-2--document # Create implementation docs from plan
|
|
||||||
/plan2code-3--implement # Begin/continue implementation
|
---
|
||||||
/plan2code-4--finalize # Wrap up after all phases complete
|
|
||||||
```
|
## The six steps in detail
|
||||||
|
|
||||||
---
|
Each step is its own run, and the specs on disk are the only thing carried from one to the next.
|
||||||
|
Chain a small one onto the last, or start a fresh session for a big one (rule 1).
|
||||||
## Complete Workflow Example
|
|
||||||
|
### 0 · Pathfinder 🧭 (optional)
|
||||||
### Starting a New Project
|
|
||||||
|
On the page: one question at a time with the options and their trade-offs, the map growing in its own
|
||||||
**Session 1 - Planning (New Chat):**
|
tab, and a **Write a brief** button for a printable summary.
|
||||||
|
|
||||||
```
|
Some ideas are too big and unclear to plan: you can feel the shape of the work but you can't write
|
||||||
User: [Paste or invoke Step 1 prompt]
|
it as requirements, so planning would just invent the answers. Pathfinder finds the *way* to the
|
||||||
I want to build a REST API for a task management application.
|
destination; Step 1 then walks it.
|
||||||
|
|
||||||
AI: 🤔 [REQUIREMENTS ANALYSIS]
|
1. **Name the destination** — one or two lines fixing what this effort is finding its way to. Settled
|
||||||
... asks clarifying questions, works through phases ...
|
first, because it fixes scope. It also asks where the map should live: **local files** under
|
||||||
|
gitignored `specs/` (private, solo — the default), or **GitHub Issues** (a map issue with one
|
||||||
AI: 🤔 [TRANSITION DECISION]
|
sub-issue per decision, native blocking, so your team can see and work the frontier in the tracker).
|
||||||
Confidence: 92%. Creating specs/task-api/PLAN-DRAFT-20250204.md...
|
2. **Chart the map** — a breadth-first grilling surfaces the open decisions. Anything you can phrase
|
||||||
```
|
*sharply* becomes a question file; anything you can only sense stays listed as fog.
|
||||||
|
3. **Clear the questions one at a time** — resolving one burns off the fog behind it, graduating
|
||||||
**Session 2 - Documentation (New Chat):**
|
whatever just became sharp into new questions. After each decision it offers a menu: take the next
|
||||||
|
question here, or start fresh — recommended after about three, to keep the agent sharp.
|
||||||
```
|
Ask for a **brief** at any point and you get a dated, plain-English summary of what has been
|
||||||
User: [Paste or invoke Step 2 prompt]
|
decided, what is still open, and what is next — meeting minutes, with no jargon in them.
|
||||||
[Attach: specs/task-api/PLAN-DRAFT-20250204.md]
|
4. **Hand off** — when nothing is left to decide, it writes a `PLAN-DRAFT` that
|
||||||
|
`/plan2code-1-plan` resumes from at Phase 4, with requirements, context, and scope already
|
||||||
AI: 📝 [DOCUMENTATION]
|
answered.
|
||||||
Creating specs/task-api/overview.md...
|
|
||||||
Creating specs/task-api/Phase 1.md...
|
**Question types:** `grill` (a decision only you can make — the default) · `research` (a fact gates
|
||||||
Creating specs/task-api/Phase 2.md...
|
it; background agents resolve these, several in parallel) · `sketch` (you need something concrete to
|
||||||
...
|
react to) · `legwork` (manual work that has to happen before a decision is possible).
|
||||||
```
|
|
||||||
|
It never answers its own questions, and it **plans, it never builds.** When the urge to just build it
|
||||||
**Session 3 - Implementation Phase 1 (New Chat):**
|
arrives, the map is done. Skip Step 0 entirely when you already know what you're building.
|
||||||
|
|
||||||
```
|
**Out:** `specs/<feature>/pathfinder/map.md` + `questions/` (or a `pathfinder:map` issue and its
|
||||||
User: [Paste or invoke Step 3 prompt]
|
sub-issues) → `PLAN-DRAFT-<date>.md`. The draft is always a local file — that is what Step 1 reads.
|
||||||
[Provide: specs/task-api/overview.md]
|
|
||||||
|
### 1 · Plan 🤔
|
||||||
AI: ⚡ [PHASE 1: Project Setup]
|
|
||||||
(Auto-detected Phase 1 as next uncompleted phase)
|
On the page: questions in batches of up to three, the phase breakdown as a list you can reorder and
|
||||||
Implementing tasks...
|
edit, and a sign-off at each stage.
|
||||||
✓ Phase 1 complete. Updated checkboxes in Phase 1.md and overview.md.
|
|
||||||
```
|
The agent works as a senior architect through seven phases, stopping for you after each: requirements
|
||||||
|
analysis · system context (reading your actual codebase) · scope assessment (a large project saves and
|
||||||
**Session 4 - Implementation Phase 2 (New Chat):**
|
resumes in a fresh session) · tech stack (needs your explicit sign-off) · architecture design ·
|
||||||
|
technical specification · transition decision.
|
||||||
```
|
|
||||||
User: [Paste or invoke Step 3 prompt]
|
It won't finalize below **90% confidence**, and every assumption it makes is written into the draft.
|
||||||
[Provide: specs/task-api/overview.md]
|
|
||||||
|
**In:** a description of the feature. **Out:** `PLAN-DRAFT-<date>.md` + `PLAN-CONVERSATION-<date>.md`
|
||||||
AI: ⚡ [PHASE 2: Database Models]
|
|
||||||
(Auto-detected Phase 2 as next uncompleted phase)
|
### 2 · Document 📝
|
||||||
Implementing tasks...
|
|
||||||
✓ Phase 2 complete. Updated checkboxes in Phase 2.md and overview.md.
|
On the page: a question only where the plan leaves something open, each phase file appearing as its
|
||||||
```
|
own tab as it is written, and one sign-off at the end.
|
||||||
|
|
||||||
**Sessions 5-N - Continue Implementation (New Chat for each phase):**
|
The plan becomes the drawing. One `overview.md` with the phase checklist, plus one file per phase of
|
||||||
|
one-story-point tasks. Each phase is **self-contained** — an agent opening `phase-3.md` cold needs
|
||||||
```
|
nothing else to build it. Unit and E2E tests are excluded unless you ask for them.
|
||||||
... repeat for each remaining phase ...
|
|
||||||
```
|
The overview also identifies the **parallel execution groups**: phases with no shared files or
|
||||||
|
dependencies, safe to run in separate agents at once.
|
||||||
**Final Session - Finalization (New Chat):**
|
|
||||||
|
**In:** the `PLAN-DRAFT`. **Out:** `overview.md` + `phase-1…N.md`
|
||||||
```
|
|
||||||
User: [Paste or invoke Step 4 prompt]
|
### 3 · Implement ⚡
|
||||||
[Provide: specs/task-api/overview.md]
|
|
||||||
|
On the page: a progress bar and the phase's task list ticking over as tasks land, then the completion
|
||||||
AI: 🧹 [VALIDATION]
|
report and a sign-off card where you approve, ask for changes, or have the code reviewed first.
|
||||||
Verifying implementation...
|
|
||||||
|
Point it at `overview.md` and it does the rest: finds the next unchecked phase, implements every task
|
||||||
AI: 🧹 [SPEC CLEANUP]
|
exactly as specified, ticks tasks off as they land, then reviews its own work against the spec and
|
||||||
Moving to specs--completed/task-api/
|
writes a completion summary.
|
||||||
|
|
||||||
Implementation complete!
|
One phase per conversation. It won't run tests unless the phase says to.
|
||||||
```
|
|
||||||
|
**In:** `specs/<feature>/overview.md`. **Out:** working code, and updated checkboxes.
|
||||||
---
|
|
||||||
|
Want a second pair of eyes before you sign off? `/plan2code-3-implement-review` builds the phase the
|
||||||
## Progress Tracking
|
same way, runs a focused review and the fixes you pick, and only then asks for approval.
|
||||||
|
|
||||||
The checkbox system enables seamless progress tracking across multiple sessions:
|
### Review 🔬 — optional, any time
|
||||||
|
|
||||||
**Phase Status (overview.md):**
|
On the page: a few questions on scope, the findings as a report you can read in full, and a list
|
||||||
|
where you tick what gets fixed.
|
||||||
| Checkbox | Status | Meaning |
|
|
||||||
|----------|--------|---------|
|
An independent second opinion, not a rubber stamp. It figures out its own scope (conversation
|
||||||
| `[ ]` | Pending | Not yet started |
|
context, your instruction, or the git diff as a fallback), analyses across 11 dimensions, and ranks
|
||||||
| `[/]` | In Progress | Agent actively working (or paused/aborted) |
|
findings Critical / Warning / Suggestion. Every finding cites a file and a line, or it gets dropped —
|
||||||
| `[x]` | Complete | Finished and approved |
|
and the review pass is read-only. It fixes things only if you ask, and verifies each fix afterwards.
|
||||||
|
|
||||||
```markdown
|
Spec-aware when `specs/` exists, and works fine without it. Most useful right after a planning or
|
||||||
## Phases
|
implementation step, but there's no wrong time to run it.
|
||||||
|
|
||||||
- [x] Phase 1: Project Setup
|
### 4 · Finalize 🧹
|
||||||
- [x] Phase 2: Database Models
|
|
||||||
- [/] Phase 3: API Endpoints <- In progress (agent working)
|
On the page: the task audit and the summary as reports, a list of the doc updates to approve, and a
|
||||||
- [ ] Phase 4: Authentication <- Next available
|
confirmation before anything is archived.
|
||||||
```
|
|
||||||
|
Validates every task against its phase spec, writes the summary and the list of files touched, flags
|
||||||
**Task Status (phase-X.md):**
|
the docs that drifted (`README`, `CHANGELOG`, `AGENTS.md`), then archives the whole spec folder —
|
||||||
|
`pathfinder/` included — to `specs--completed/`. That folder is the record of *why* the code looks
|
||||||
```markdown
|
like this.
|
||||||
## Tasks
|
|
||||||
|
**In:** `specs/<feature>/overview.md`. **Out:** archived specs.
|
||||||
- [x] Create routes file
|
|
||||||
- [x] Implement GET /tasks
|
---
|
||||||
- [ ] Implement POST /tasks <- Current task
|
|
||||||
- [ ] Implement PUT /tasks/:id
|
## Prefer the terminal?
|
||||||
- [ ] Implement DELETE /tasks/:id
|
|
||||||
```
|
Every skill also runs right in the terminal. Each one asks at the start whether you want the web
|
||||||
|
console or the terminal; add `--web` to skip the question and go straight to the web console:
|
||||||
The `[/]` status enables parallel execution - multiple agents can work on different phases simultaneously, and you can see which phases are actively being worked on.
|
`/plan2code-1-plan --web plan a REST API for tasks`.
|
||||||
|
|
||||||
---
|
| Command | Use it when |
|
||||||
|
|---------|-------------|
|
||||||
## Best Practices
|
| `/plan2code` | Open the dashboard in the web console: every skill below as a card, launched on the page |
|
||||||
|
| `/plan2code-0-pathfinder` | The idea is too big and unclear to plan. Charts it as decisions, clears them one at a time, hands a hot plan draft to Step 1 |
|
||||||
1. **Start fresh conversations** - New chat for each step and each implementation phase
|
| `/plan2code-1-plan` | Starting a feature. Full requirements → architecture pass |
|
||||||
2. **Always attach specs** - The AI needs the spec files to understand the current state
|
| `/plan2code-2-document` | Planning is done. Turn the plan into phase specs |
|
||||||
3. **Don't skip planning** - The upfront investment prevents costly rework later
|
| `/plan2code-3-implement` | Build the next phase (one per conversation) |
|
||||||
4. **Confirm tech stack** - Ensure AI gets explicit approval before architecture design
|
| `/plan2code-3-implement-review` | Build the next phase and review it before you approve it (instead of `/plan2code-3-implement`) |
|
||||||
5. **One phase at a time** - Keeps conversations focused and manageable
|
| `/plan2code-review` | Independent second opinion on local changes, then optional fixes |
|
||||||
6. **Update checkboxes immediately** - Maintains accurate progress state
|
| `/plan2code-4-finalize` | All phases done. Validate, summarize, archive |
|
||||||
7. **Review phase output** - Verify each phase before moving to the next
|
| `/plan2code-init` | Generate this repo's `AGENTS.md` so every agent starts informed |
|
||||||
8. **Keep spec files** - The completed folder serves as project documentation
|
| `/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, saved in `~/.plan2code/handoffs/` and listed on the dashboard to pick up |
|
||||||
## What to Attach at Each Step
|
| `/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 |
|
||||||
| Step | Required Input |
|
| `/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 |
|
||||||
| Step 1 (Plan) | None (describe your feature/project) |
|
|
||||||
| Step 2 (Document) | `specs/<feature>/PLAN-DRAFT-<date>.md` or planning conversation |
|
---
|
||||||
| Step 3 (Implement) | `specs/<feature>/overview.md` (auto-detects phase) |
|
|
||||||
| Step 4 (Finalize) | `specs/<feature>/overview.md` |
|
## Troubleshooting
|
||||||
|
|
||||||
---
|
**The skills aren't recognised.** 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
|
||||||
## Autonomous Loop (Alternative to Step 3)
|
gitignored.
|
||||||
|
|
||||||
For hands-off implementation, Plan2Code includes an optional autonomous loop CLI that iterates through your spec tasks automatically.
|
**Your tool doesn't read Agent Skills.** Since v2.2.0, Plan2Code ships only as skills. If your tool
|
||||||
|
has no skill support, paste the relevant `src/plan2code-*.md` manually or point it at the installed
|
||||||
> **Note:** The loop is an **alternative** to `/plan2code-3--implement`, not a replacement. Use the manual Step 3 workflow when you want direct control over each phase, or use the loop when you prefer autonomous execution.
|
copy under `~/.agents/skills/`.
|
||||||
|
|
||||||
### When to Use Each
|
**The agent starts coding during planning.** The prompts forbid it, but models drift. Say: "Stay in
|
||||||
|
planning mode. Do not write code yet."
|
||||||
| Approach | Best For |
|
|
||||||
|----------|----------|
|
**The agent doesn't know what to implement.** Give it the path to `overview.md` — it reads the phase
|
||||||
| `/plan2code-3--implement` | Interactive control, reviewing each phase, complex logic requiring human judgment |
|
file itself from there.
|
||||||
| `plan2code-loop` | Straightforward implementations, batch processing, overnight runs |
|
|
||||||
|
**You lost track between sessions.** `overview.md` has the phase status; the phase files have the
|
||||||
### Installing the Loop
|
task status. That's the whole state.
|
||||||
|
|
||||||
```bash
|
**The agent isn't following the spec.** Point at the specific phase document and tell it to re-read
|
||||||
# From the plan2code root directory:
|
the requirements.
|
||||||
|
|
||||||
# Option 1: Install everything (recommended)
|
**Too many or too few phases.** Fix it in Step 2 — a phase should be a logical grouping of work, not
|
||||||
node install.js # Select I at the menu
|
a fixed size.
|
||||||
|
|
||||||
# Option 2: Install loop only
|
**The agent runs on another machine, or over SSH.** The page is served on `127.0.0.1` of the machine
|
||||||
node install.js # Select C, then O at the menu
|
the agent runs on, so your browser can only reach it there. A forwarded port often works; otherwise
|
||||||
```
|
work in the terminal, which loses nothing.
|
||||||
|
|
||||||
### Using the Loop
|
**Web console problems** (lost contact, a closed tab, a dead link): see
|
||||||
|
[.readme/web-console.md](.readme/web-console.md#troubleshooting).
|
||||||
```bash
|
|
||||||
# Run the loop - fully interactive
|
---
|
||||||
plan2code-loop
|
|
||||||
```
|
## Customizing
|
||||||
|
|
||||||
The CLI will:
|
The prompts are yours to edit. Common changes: add testing requirements in Step 2, move the 90%
|
||||||
1. Auto-detect specs in `./specs/` directory
|
confidence threshold in Step 1, restructure the `specs/` layout, or add review gates to Step 3.
|
||||||
2. Let you select a spec if multiple are found
|
Source files live in `src/`; run `npm run build:skills`, then re-run `node install.js` to push your
|
||||||
3. Prompt to continue if an existing session is found
|
edits out through the skills CLI.
|
||||||
4. Ask for JIRA ticket ID, agent selection, loop mode, and max iterations
|
|
||||||
|
---
|
||||||
### Loop Modes
|
|
||||||
|
## Dive deeper
|
||||||
| Mode | Behavior | Git Commits | Best For |
|
|
||||||
|------|----------|-------------|----------|
|
Core reference:
|
||||||
| **One task per loop** (default) | Each agent call implements one task | Node controller commits after each task | Smaller models, cautious execution |
|
|
||||||
| **One phase per loop** | Each agent call implements all tasks in a phase | LLM commits after each task (with JIRA ID) | Smart models with larger context windows, related tasks |
|
- **[.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 in the top bar
|
||||||
|
- **[QUICK-REFERENCE.md](QUICK-REFERENCE.md)** — the one-page card: commands, inputs, outputs, decision tree
|
||||||
Session state is stored per-spec in `specs/<feature>/.plan2code-loop/`, keeping each feature's progress isolated.
|
- **[.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
|
||||||
The loop will:
|
- **[CHANGELOG.md](CHANGELOG.md)** — what changed, and why
|
||||||
1. Read your `overview.md` and phase files
|
|
||||||
2. Find the first unchecked task (or phase, in phase mode)
|
Optional tooling — none of it is required to use the workflow:
|
||||||
3. Implement it and mark the checkbox complete
|
|
||||||
4. Repeat until all tasks are done or max iterations reached
|
- **[.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
|
||||||
See [plan2code-loop/](plan2code-loop/) for full documentation.
|
- **[.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
|
||||||
---
|
|
||||||
|
|
||||||
## File Structure After Complete Implementation
|
|
||||||
|
|
||||||
```
|
|
||||||
your-project/
|
|
||||||
├── specs/
|
|
||||||
│ └── another-feature/ # In-progress feature
|
|
||||||
│ ├── overview.md
|
|
||||||
│ └── Phase 1.md
|
|
||||||
├── specs--completed/
|
|
||||||
│ └── feature-name/
|
|
||||||
│ ├── overview.md # Archived with completion summary
|
|
||||||
│ ├── Phase 1.md # All checkboxes marked [x]
|
|
||||||
│ ├── Phase 2.md
|
|
||||||
│ └── ...
|
|
||||||
├── your project files...
|
|
||||||
└── README.md
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Customization
|
|
||||||
|
|
||||||
Feel free to modify these prompts to fit your workflow:
|
|
||||||
|
|
||||||
- **Add testing phases** - Uncomment/add testing requirements in Step 2
|
|
||||||
- **Adjust confidence threshold** - Change the 90% threshold in Step 1
|
|
||||||
- **Modify output structure** - Customize the specs folder organization
|
|
||||||
- **Add code review steps** - Enhance Step 3 with additional review gates
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Troubleshooting
|
|
||||||
|
|
||||||
**Slash commands/workflows not recognized:**
|
|
||||||
|
|
||||||
- Ensure you ran `node install.js` and selected the appropriate platform
|
|
||||||
- Restart your AI tool after installation
|
|
||||||
- For per-project installation, ensure the directory isn't in `.gitignore`
|
|
||||||
|
|
||||||
**AI jumps ahead to implementation during planning:**
|
|
||||||
|
|
||||||
- The prompts explicitly forbid this, but if it happens, remind the AI: "Stay in planning mode. Do not write code yet."
|
|
||||||
|
|
||||||
**AI doesn't know what to implement:**
|
|
||||||
|
|
||||||
- Make sure you provided the path to `overview.md`
|
|
||||||
- The AI will auto-detect the next phase and read the corresponding `Phase X.md` file
|
|
||||||
|
|
||||||
**Lost progress between sessions:**
|
|
||||||
|
|
||||||
- Check `overview.md` for phase status
|
|
||||||
- Review individual phase files for task completion status
|
|
||||||
|
|
||||||
**AI not following spec exactly:**
|
|
||||||
|
|
||||||
- Reference the specific phase document and ask it to re-read the requirements
|
|
||||||
|
|
||||||
**Too many/few phases:**
|
|
||||||
|
|
||||||
- Adjust during Step 2 (Documentation) - phases should represent logical groupings of work
|
|
||||||
|
After Width: | Height: | Size: 3.1 KiB |
|
After Width: | Height: | Size: 71 KiB |
|
Before Width: | Height: | Size: 185 KiB |
@@ -0,0 +1,140 @@
|
|||||||
|
# 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 (Claude, Devin or Codex), model and effort (Claude and Codex
|
||||||
|
only) to start on. Permission checks off is its own tick, on by default (see below; New Session
|
||||||
|
keeps whatever you picked); a CLI the app cannot find is named, with how to install it, instead of
|
||||||
|
just being greyed out. The card is skipped when the launcher already passed an agent to start.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## 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: 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: 24 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 884 B |
@@ -0,0 +1,7 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="Plan2Code">
|
||||||
|
<rect x="6" y="2.6" width="20" height="25.4" rx="4.4" fill="#eef3fa" stroke="#3b332c" stroke-width="2.2" />
|
||||||
|
<rect x="9.6" y="27.6" width="4.8" height="2.6" rx="1.3" fill="#3b332c" />
|
||||||
|
<rect x="17.6" y="27.6" width="4.8" height="2.6" rx="1.3" fill="#3b332c" />
|
||||||
|
<path d="M16 8.8 L17.41 12.26 L21.14 12.53 L18.28 14.94 L19.17 18.57 L16 16.6 L12.83 18.57 L13.72 14.94 L10.86 12.53 L14.59 12.26 Z" fill="#2455a4" />
|
||||||
|
<path d="M12.2 20.6 Q16 24.2 19.8 20.6" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 636 B |
|
Before Width: | Height: | Size: 147 KiB |
|
Before Width: | Height: | Size: 95 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 107 KiB |
|
After Width: | Height: | Size: 110 KiB |
|
After Width: | Height: | Size: 114 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 109 KiB |
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 122 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 103 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 |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 104 KiB |
@@ -1,14 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "plan2code",
|
"name": "plan2code",
|
||||||
"version": "1.8.1",
|
"version": "3.0.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"bin": {
|
"bin": {
|
||||||
"plan2code": "./install.js"
|
"plan2code-install": "./install.js"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepare": "husky"
|
"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 --test-concurrency=8 scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-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-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-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-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"husky": "^9.0.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,34 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
## 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
|
||||||
|
cargo test --workspace
|
||||||
|
```
|
||||||
|
|
||||||
|
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,115 @@
|
|||||||
|
# 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 test --workspace` passes 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, model, 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 **Expand** it back; its size from
|
||||||
|
before collapsing is remembered
|
||||||
|
- [ ] Docked right, collapsed: the **Expand** 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; cancelling 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
|
||||||
|
|
||||||
|
## 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,9 @@
|
|||||||
|
[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"
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
//! 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>`
|
||||||
|
//! <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),
|
||||||
|
Echo(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
Command::Echo(line.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
say("FAKE-AGENT ready");
|
||||||
|
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::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 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,30 @@
|
|||||||
|
[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"
|
||||||
|
|
||||||
|
[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).
|
||||||
|
winapi = { version = "0.3.9", features = ["handleapi", "jobapi2", "minwindef", "ntdef", "winnt"] }
|
||||||
@@ -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",
|
||||||
|
"windows": ["main"],
|
||||||
|
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "core:window:allow-set-title"]
|
||||||
|
}
|
||||||
|
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,409 @@
|
|||||||
|
//! 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>;
|
||||||
|
|
||||||
|
/// 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 the brief.
|
||||||
|
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>>,
|
||||||
|
/// 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),
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 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((StartChoice { kind, model, effort, mode }, brief));
|
||||||
|
match self.shared.spawn(&mut inner) {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 emit(&self, inner: &Inner) {
|
||||||
|
(self.sink)(AgentEvent::State(self.snapshot(inner)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the agent in `inner.last_start` and watch for it to end.
|
||||||
|
fn spawn(self: &Arc<Self>, inner: &mut Inner) -> Result<(), String> {
|
||||||
|
let (choice, brief) = inner.last_start.clone().ok_or("no agent has been started")?;
|
||||||
|
let prompt = brief.unwrap_or_else(|| choice.kind.default_prompt().to_string());
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
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());
|
||||||
|
match self.spawn(inner) {
|
||||||
|
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,393 @@
|
|||||||
|
//! 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,461 @@
|
|||||||
|
//! 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,460 @@
|
|||||||
|
//! 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,
|
||||||
|
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> {
|
||||||
|
let console_dir = find_console_dir()?;
|
||||||
|
let session = Self::open_session(&console_dir, &project_dir, &embed_origin, None)?;
|
||||||
|
Ok(ConsoleSupervisor { console_dir, project_dir, embed_origin, 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, session, stopped: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_session(
|
||||||
|
console_dir: &Path,
|
||||||
|
project_dir: &Path,
|
||||||
|
embed_origin: &str,
|
||||||
|
resume: Option<&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", "dashboard", "--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", "--session", &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) = (&self.console_dir, &self.project_dir, &self.embed_origin);
|
||||||
|
self.session = resume_or_fresh(&sid, on_disk, |resume| {
|
||||||
|
Self::open_session(console_dir, project_dir, embed_origin, resume)
|
||||||
|
})?;
|
||||||
|
self.stopped = false;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `console.mjs stop --session <sid>`: the console's own orderly shutdown.
|
||||||
|
pub fn stop(&mut self) -> Result<(), String> {
|
||||||
|
if self.stopped {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let output = node_command(&self.console_dir)
|
||||||
|
.args(["stop", "--session", &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().map_or(true, |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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[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,224 @@
|
|||||||
|
//! 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,15 @@
|
|||||||
|
//! The parts of the app that tests reach directly.
|
||||||
|
|
||||||
|
pub mod agent_manager;
|
||||||
|
pub mod agents;
|
||||||
|
pub mod announce;
|
||||||
|
pub mod brief;
|
||||||
|
pub mod console_supervisor;
|
||||||
|
pub mod handoff;
|
||||||
|
pub mod node_check;
|
||||||
|
pub mod project;
|
||||||
|
pub mod pty_host;
|
||||||
|
pub mod restart_brief;
|
||||||
|
pub mod session_reader;
|
||||||
|
pub mod settings;
|
||||||
|
pub mod versions;
|
||||||
@@ -0,0 +1,822 @@
|
|||||||
|
// Hide the extra console window on Windows release builds.
|
||||||
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
|
||||||
|
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, BeforeFresh, Sink};
|
||||||
|
use plan2code_app_lib::agents::{self, Agent, AgentKind, PermissionMode};
|
||||||
|
use plan2code_app_lib::console_supervisor::{app_origin, origin_of, session_on_disk, ConsoleSupervisor};
|
||||||
|
use plan2code_app_lib::node_check;
|
||||||
|
use plan2code_app_lib::project::{self, ProjectDir};
|
||||||
|
use plan2code_app_lib::restart_brief;
|
||||||
|
use plan2code_app_lib::settings;
|
||||||
|
use plan2code_app_lib::versions;
|
||||||
|
use tauri::ipc::{Channel, InvokeResponseBody};
|
||||||
|
use tauri::{Emitter, Manager, State};
|
||||||
|
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
|
||||||
|
|
||||||
|
type PageChannel = Arc<Mutex<Option<Channel<InvokeResponseBody>>>>;
|
||||||
|
|
||||||
|
// The project the app is working on, the console it supervises for it and the
|
||||||
|
// agent it runs there.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct AppState {
|
||||||
|
project: Mutex<Option<ProjectDir>>,
|
||||||
|
// The agent and model the launcher chose, from its arguments.
|
||||||
|
launch: project::LaunchChoice,
|
||||||
|
console: Arc<Mutex<Option<ConsoleSupervisor>>>,
|
||||||
|
agent: Mutex<Option<Arc<AgentManager>>>,
|
||||||
|
// Where the agent's output and state changes go: the page's latest channel.
|
||||||
|
page: PageChannel,
|
||||||
|
// This window's endpoint for pages the agent's `console.mjs open` wants shown here.
|
||||||
|
announce: Arc<Mutex<Option<AnnounceServer>>>,
|
||||||
|
// The Node version `main()` found before opening the window (Task 1.7 exits
|
||||||
|
// cleanly on anything else, so this is always a passing version once the
|
||||||
|
// window exists), and which binary that was, with `resolved_path`'s PATH
|
||||||
|
// (Task 9.9): the first-run checklist's Node row names both.
|
||||||
|
node_version: Option<String>,
|
||||||
|
node_binary: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// The operating system and, on Windows, the build number xterm needs for ConPTY.
|
||||||
|
#[tauri::command]
|
||||||
|
fn platform_info() -> serde_json::Value {
|
||||||
|
let build = if cfg!(windows) { windows_build() } else { None };
|
||||||
|
serde_json::json!({ "os": std::env::consts::OS, "windowsBuild": build })
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the launch card offers per agent: whether its CLI is on PATH (else how
|
||||||
|
// to install it), and whether it takes its own reasoning effort.
|
||||||
|
#[tauri::command]
|
||||||
|
fn agent_availability() -> serde_json::Value {
|
||||||
|
// Built-ins first, then the custom agents, read afresh on every call so
|
||||||
|
// "Check again" sees a change to agents.json.
|
||||||
|
let mut entries: Vec<_> = AgentKind::ALL
|
||||||
|
.iter()
|
||||||
|
.map(|&kind| {
|
||||||
|
let at = agents::installed_at(kind);
|
||||||
|
serde_json::json!({
|
||||||
|
"id": kind.id(),
|
||||||
|
"label": kind.label(),
|
||||||
|
"installed": at.is_some(),
|
||||||
|
// Which binary was used (Task 9.9), when one was found.
|
||||||
|
"path": at.map(|p| p.to_string_lossy().into_owned()),
|
||||||
|
"installHint": kind.install_hint(),
|
||||||
|
"installUrl": kind.install_url(),
|
||||||
|
"hasEffort": kind.has_effort(),
|
||||||
|
"custom": false,
|
||||||
|
"models": null,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
for custom in agents::custom_agents() {
|
||||||
|
let at = Agent::Custom(custom.clone()).installed_at();
|
||||||
|
entries.push(serde_json::json!({
|
||||||
|
"id": custom.id,
|
||||||
|
"label": custom.name,
|
||||||
|
"installed": at.is_some(),
|
||||||
|
"path": at.map(|p| p.to_string_lossy().into_owned()),
|
||||||
|
"installHint": null,
|
||||||
|
"installUrl": null,
|
||||||
|
"hasEffort": false,
|
||||||
|
"custom": true,
|
||||||
|
"models": custom.models,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
serde_json::json!(entries)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Opens a built-in agent install page in the default browser. Any other id
|
||||||
|
// is an error: the page never names the link itself.
|
||||||
|
#[tauri::command]
|
||||||
|
fn open_install_page(id: String) -> Result<(), String> {
|
||||||
|
let url = agents::install_page_url(&id)?;
|
||||||
|
// The same switches as the console open-link.mjs.
|
||||||
|
if std::env::var_os("NO_BROWSER").is_some_and(|v| !v.is_empty())
|
||||||
|
|| std::env::var_os("PLAN2CODE_NO_BROWSER").is_some_and(|v| !v.is_empty())
|
||||||
|
{
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let mut command = if cfg!(windows) {
|
||||||
|
let mut c = std::process::Command::new("rundll32.exe");
|
||||||
|
c.args(["url.dll,FileProtocolHandler", url]);
|
||||||
|
c
|
||||||
|
} else if cfg!(target_os = "macos") {
|
||||||
|
let mut c = std::process::Command::new("open");
|
||||||
|
c.arg(url);
|
||||||
|
c
|
||||||
|
} else {
|
||||||
|
let browser = std::env::var("BROWSER").ok().filter(|b| !b.is_empty()).unwrap_or_else(|| "xdg-open".to_string());
|
||||||
|
let mut c = std::process::Command::new(browser);
|
||||||
|
c.arg(url);
|
||||||
|
c
|
||||||
|
};
|
||||||
|
command.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||||
|
}
|
||||||
|
command.spawn().map(|_| ()).map_err(|e| format!("could not open {url}: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// `cmd /c ver` prints e.g. `Microsoft Windows [Version 10.0.26300.1234]`.
|
||||||
|
fn windows_build() -> Option<u32> {
|
||||||
|
let out = std::process::Command::new("cmd").args(["/c", "ver"]).output().ok()?;
|
||||||
|
let text = String::from_utf8_lossy(&out.stdout);
|
||||||
|
let version = text.split("Version ").nth(1)?;
|
||||||
|
version.split('.').nth(2)?.trim().parse().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sends the agent's output as raw bytes and its state changes as JSON, on the
|
||||||
|
// page's latest channel. Nothing is sent while no page has registered one.
|
||||||
|
fn page_sink(page: PageChannel) -> Sink {
|
||||||
|
Arc::new(move |event| {
|
||||||
|
let Ok(guard) = page.lock() else { return };
|
||||||
|
let Some(channel) = guard.as_ref() else { return };
|
||||||
|
let body = match event {
|
||||||
|
AgentEvent::Output(bytes) => InvokeResponseBody::Raw(bytes),
|
||||||
|
AgentEvent::State(snapshot) => match serde_json::to_string(&snapshot) {
|
||||||
|
Ok(json) => InvokeResponseBody::Json(json),
|
||||||
|
Err(_) => return,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let _ = channel.send(body);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// The manager for the current project, made on first use. A manager for a
|
||||||
|
// different folder replaces an idle one.
|
||||||
|
fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
|
||||||
|
let dir = {
|
||||||
|
let project = state.project.lock().map_err(|e| e.to_string())?;
|
||||||
|
project.as_ref().map(|p| p.dir.clone()).ok_or("no project folder chosen")?
|
||||||
|
};
|
||||||
|
let mut guard = state.agent.lock().map_err(|e| e.to_string())?;
|
||||||
|
if let Some(agent) = guard.as_ref() {
|
||||||
|
// Only the same folder's manager is reused: an active agent for a
|
||||||
|
// folder the project has since moved away from must not be handed
|
||||||
|
// back as if it belonged to the new one.
|
||||||
|
if agent.folder() == &dir {
|
||||||
|
return Ok(Arc::clone(agent));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let sink = page_sink(Arc::clone(&state.page));
|
||||||
|
let agent = Arc::new(AgentManager::new(dir, sink));
|
||||||
|
agent.set_before_fresh(before_fresh_hook(state));
|
||||||
|
*guard = Some(Arc::clone(&agent));
|
||||||
|
Ok(agent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// What New Session does before the fresh agent starts. It leaves the brief for
|
||||||
|
// the dashboard, from the console session running now, then forgets that
|
||||||
|
// session, so the fresh agent's `open` starts one of its own: a session that
|
||||||
|
// joined the old one would carry its meter along, still red after the very
|
||||||
|
// press the red meter asks for. The old console is left to shut itself down
|
||||||
|
// once the frame moves on to the new page.
|
||||||
|
fn before_fresh_hook(state: &AppState) -> BeforeFresh {
|
||||||
|
let console = Arc::clone(&state.console);
|
||||||
|
let announce = Arc::clone(&state.announce);
|
||||||
|
Arc::new(move || {
|
||||||
|
let sid = console.lock().ok().and_then(|guard| guard.as_ref().map(|sup| sup.session().sid.clone()));
|
||||||
|
let note = sid.and_then(|sid| restart_brief::note_for_restart(&sid));
|
||||||
|
if let Ok(guard) = announce.lock() {
|
||||||
|
if let Some(server) = guard.as_ref() {
|
||||||
|
server.forget_current();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
note
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_agent(state: &AppState) -> Option<Arc<AgentManager>> {
|
||||||
|
state.agent.lock().ok().and_then(|guard| guard.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
// The origin the app page has, which the console must allow as its frame
|
||||||
|
// parent. In a release build that is a constant, but `tauri dev` serves the
|
||||||
|
// page from a loopback dev server, so the window is asked for its real URL.
|
||||||
|
/// A page the agent's `open` announced: the supervisor follows it, or adopts
|
||||||
|
/// it when the agent started the console (the app owns its stop from there).
|
||||||
|
/// Says whether the window should show it. A session outside this app's
|
||||||
|
/// console store is refused: `cargo test` run by the agent inside the app
|
||||||
|
/// once announced a test's throwaway console, the window followed it, and
|
||||||
|
/// when the test shut it down the reconnect opened an empty dashboard, so the
|
||||||
|
/// build's own page was never seen again.
|
||||||
|
fn take_announced(state: &AppState, notice: &PageNotice, origin: String, on_disk: impl Fn(&str) -> bool) -> bool {
|
||||||
|
if !on_disk(¬ice.sid) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if let Ok(mut guard) = state.console.lock() {
|
||||||
|
match guard.as_mut() {
|
||||||
|
Some(sup) => sup.follow(¬ice.url, ¬ice.sid),
|
||||||
|
None => {
|
||||||
|
let dir = state.project.lock().ok().and_then(|p| p.as_ref().map(|p| p.dir.clone()));
|
||||||
|
if let Some(dir) = dir {
|
||||||
|
if let Ok(sup) = ConsoleSupervisor::adopt(dir, origin, ¬ice.url, ¬ice.sid) {
|
||||||
|
*guard = Some(sup);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_origin(app: &tauri::AppHandle) -> String {
|
||||||
|
app.get_webview_window("main")
|
||||||
|
.and_then(|window| window.url().ok())
|
||||||
|
.and_then(|url| origin_of(url.as_str()))
|
||||||
|
.unwrap_or_else(|| app_origin().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gives the agent the in-app signal: this window's announce endpoint and the
|
||||||
|
// origin its console must allow. The agent's own `open` then shows its pages
|
||||||
|
// here (it asks the window which session is current). Without an endpoint the
|
||||||
|
// agent gets nothing and opens pages the plain way.
|
||||||
|
fn sync_agent_env(app: &tauri::AppHandle) {
|
||||||
|
let state = app.state::<AppState>();
|
||||||
|
let Some(agent) = current_agent(&state) else { return };
|
||||||
|
let env = match state.announce.lock().ok() {
|
||||||
|
Some(guard) => guard
|
||||||
|
.as_ref()
|
||||||
|
.map(|server| server.agent_env(&window_origin(app), &app.package_info().version.to_string()))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
None => Vec::new(),
|
||||||
|
};
|
||||||
|
agent.set_env(env);
|
||||||
|
}
|
||||||
|
|
||||||
|
// `on_output` is deliberately not a parameter here: `agent_reattach` already
|
||||||
|
// registered `state.page` when the page mounted (`main()` on the frontend
|
||||||
|
// calls it before this), and that registration must stay the only one. Every
|
||||||
|
// Channel argument Tauri deserializes for an invoke is a fresh wrapper around
|
||||||
|
// the same frontend id; dropping one (as happened here when it replaced the
|
||||||
|
// reattach registration) sends the frontend an "end" message that
|
||||||
|
// unregisters that id for good, breaking all future sends through it.
|
||||||
|
#[tauri::command]
|
||||||
|
fn agent_start(
|
||||||
|
app: tauri::AppHandle,
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
kind: String,
|
||||||
|
model: Option<String>,
|
||||||
|
effort: Option<String>,
|
||||||
|
mode: String,
|
||||||
|
cols: u16,
|
||||||
|
rows: u16,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let kind = agents::find_agent(&kind).ok_or_else(|| format!("unknown agent: {kind}"))?;
|
||||||
|
let mode = PermissionMode::from_id(&mode).ok_or_else(|| format!("unknown permission mode: {mode}"))?;
|
||||||
|
let agent = agent_for_project(&state)?;
|
||||||
|
agent.resize(cols, rows)?;
|
||||||
|
sync_agent_env(&app);
|
||||||
|
agent.start(kind.clone(), model, effort, mode, None)?;
|
||||||
|
// A settings file that cannot be written must not stop the agent.
|
||||||
|
if let Some(file) = settings::settings_file() {
|
||||||
|
let _ = settings::save_last_agent(&file, kind.id());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn agent_input(state: State<'_, AppState>, data: String) -> Result<(), String> {
|
||||||
|
match current_agent(&state) {
|
||||||
|
Some(agent) => agent.input(data.as_bytes()),
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn agent_resize(state: State<'_, AppState>, cols: u16, rows: u16) -> Result<(), String> {
|
||||||
|
match current_agent(&state) {
|
||||||
|
Some(agent) => agent.resize(cols, rows),
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn agent_restart(state: State<'_, AppState>) -> Result<(), String> {
|
||||||
|
current_agent(&state).ok_or("no agent has been started")?.restart()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn idle_snapshot_json() -> serde_json::Value {
|
||||||
|
serde_json::json!({ "state": "idle", "kind": null, "mode": null, "generation": 0 })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page that just mounted (a reload, or this window's first paint while an
|
||||||
|
/// agent survived it) registers its output channel here instead of through
|
||||||
|
/// `agent_start`, which would try to start a second agent. Replays the
|
||||||
|
/// current generation's recent output on it at once, so the terminal does
|
||||||
|
/// not come up blank.
|
||||||
|
#[tauri::command]
|
||||||
|
fn agent_reattach(state: State<'_, AppState>, on_output: Channel<InvokeResponseBody>) -> Result<serde_json::Value, String> {
|
||||||
|
let agent = current_agent(&state);
|
||||||
|
*state.page.lock().map_err(|e| e.to_string())? = Some(on_output.clone());
|
||||||
|
if let Some(agent) = &agent {
|
||||||
|
let replay = agent.replay();
|
||||||
|
if !replay.is_empty() {
|
||||||
|
let _ = on_output.send(InvokeResponseBody::Raw(replay));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(match &agent {
|
||||||
|
Some(agent) => serde_json::to_value(agent.snapshot()).unwrap_or_default(),
|
||||||
|
None => idle_snapshot_json(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Asks before quitting while an agent runs; "no" keeps the app open.
|
||||||
|
fn confirm_quit(app: &tauri::AppHandle) {
|
||||||
|
let app = app.clone();
|
||||||
|
app.dialog()
|
||||||
|
.message("An agent is still running. Quit and stop it?")
|
||||||
|
.title("Quit Plan2Code")
|
||||||
|
.kind(MessageDialogKind::Warning)
|
||||||
|
.buttons(MessageDialogButtons::YesNo)
|
||||||
|
.show({
|
||||||
|
let app = app.clone();
|
||||||
|
move |quit| {
|
||||||
|
if quit {
|
||||||
|
quit_app(&app);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn agent_is_active(app: &tauri::AppHandle) -> bool {
|
||||||
|
current_agent(&app.state::<AppState>()).is_some_and(|agent| agent.is_active())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stops the agent, then the console, then exits.
|
||||||
|
fn quit_app(app: &tauri::AppHandle) {
|
||||||
|
let state = app.state::<AppState>();
|
||||||
|
if let Some(agent) = current_agent(&state) {
|
||||||
|
agent.stop();
|
||||||
|
}
|
||||||
|
if let Ok(mut guard) = state.console.lock() {
|
||||||
|
if let Some(mut console) = guard.take() {
|
||||||
|
let _ = console.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
app.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the page draws its bar from: the folder (or that none is chosen yet)
|
||||||
|
/// and the agent the picker starts on.
|
||||||
|
#[tauri::command]
|
||||||
|
fn app_state(state: State<'_, AppState>) -> serde_json::Value {
|
||||||
|
let project = state.project.lock().ok().and_then(|p| p.clone());
|
||||||
|
let settings_file = settings::settings_file();
|
||||||
|
// The agent picked in the launcher starts the bar's picker, ahead of the app's own last one.
|
||||||
|
// An id that no longer resolves (a removed custom agent) is skipped.
|
||||||
|
let known = |id: &String| agents::find_agent(id).is_some();
|
||||||
|
let last_agent = state
|
||||||
|
.launch
|
||||||
|
.agent
|
||||||
|
.clone()
|
||||||
|
.filter(known)
|
||||||
|
.or_else(|| settings_file.as_ref().and_then(|file| settings::load_last_agent(file)).filter(known))
|
||||||
|
.or_else(|| project::remembered_agent().filter(known));
|
||||||
|
let term_panel = settings_file.as_ref().map_or(
|
||||||
|
settings::TermPanelSettings {
|
||||||
|
dock: settings::DEFAULT_TERM_DOCK.to_string(),
|
||||||
|
fraction: settings::DEFAULT_TERM_FRACTION,
|
||||||
|
collapsed: false,
|
||||||
|
},
|
||||||
|
|file| settings::load_term_panel(file),
|
||||||
|
);
|
||||||
|
let first_run_done = settings_file.as_ref().is_some_and(|file| settings::load_first_run_done(file));
|
||||||
|
serde_json::json!({
|
||||||
|
"projectDir": project.as_ref().map(|p| p.dir.to_string_lossy().into_owned()),
|
||||||
|
"projectDirSource": project.as_ref().map(|p| p.source),
|
||||||
|
"lastAgent": last_agent,
|
||||||
|
"launchModel": state.launch.model,
|
||||||
|
// Task 1.7 already exits before the window opens on a missing or too-old
|
||||||
|
// Node, so this is always a pass; the checklist's Node row just names it.
|
||||||
|
"nodeVersion": state.node_version,
|
||||||
|
"nodeBinary": state.node_binary,
|
||||||
|
"skillsVersion": versions::installed_skills_version(),
|
||||||
|
"firstRunDone": first_run_done,
|
||||||
|
// The launcher always passes `--project` alongside `--agent`, so an
|
||||||
|
// explicit `--agent` means skip straight to starting it, no checklist
|
||||||
|
// or launch card shown.
|
||||||
|
"autoStart": state.launch.agent,
|
||||||
|
"termPanel": term_panel,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The terminal pane's toolbar remembers its shape here: dock side, size and
|
||||||
|
/// whether it was left collapsed. A settings file that cannot be written is
|
||||||
|
/// reported to the caller; the pane itself keeps working either way.
|
||||||
|
#[tauri::command]
|
||||||
|
fn save_term_panel(dock: String, fraction: f64, collapsed: bool) -> Result<(), String> {
|
||||||
|
let file = settings::settings_file().ok_or("no home folder found")?;
|
||||||
|
settings::save_term_panel(&file, &dock, fraction, collapsed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first-run checklist passed once: later launches go straight to the
|
||||||
|
/// launch card (Task 9.4).
|
||||||
|
#[tauri::command]
|
||||||
|
fn save_first_run_done() -> Result<(), String> {
|
||||||
|
let file = settings::settings_file().ok_or("no home folder found")?;
|
||||||
|
settings::save_first_run_done(&file)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The app's version (`tauri.conf.json`'s, which Tauri puts in the package info) beside the
|
||||||
|
/// installed skills' version. The bar shows its Update line when they differ (FR-14).
|
||||||
|
#[tauri::command]
|
||||||
|
fn version_status(app: tauri::AppHandle) -> versions::VersionStatus {
|
||||||
|
versions::status(&app.package_info().version.to_string(), versions::installed_skills_version())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What `update_skills` resolves with: the installer's last line, and the version status
|
||||||
|
/// re-read afterwards, so the bar can say plainly whether the mismatch is actually gone.
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct UpdateOutcome {
|
||||||
|
message: String,
|
||||||
|
status: versions::VersionStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run the existing installer's update, pinned to this app's own release tag. Only the bar's
|
||||||
|
/// button asks for it: never silently. `progress` carries each line of the installer's own
|
||||||
|
/// output live, for the bar to show while it runs.
|
||||||
|
#[tauri::command]
|
||||||
|
async fn update_skills(app: tauri::AppHandle, progress: Channel<String>) -> Result<UpdateOutcome, String> {
|
||||||
|
let version = app.package_info().version.to_string();
|
||||||
|
let message = tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
versions::run_update(&version, |line| {
|
||||||
|
let _ = progress.send(line.to_string());
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())??;
|
||||||
|
let status = versions::status(&app.package_info().version.to_string(), versions::installed_skills_version());
|
||||||
|
Ok(UpdateOutcome { message, status })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The OS folder picker, shown when no folder is known; a choice becomes the
|
||||||
|
/// launcher's remembered folder.
|
||||||
|
#[tauri::command]
|
||||||
|
fn pick_project_folder(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<Option<String>, String> {
|
||||||
|
let picked = app
|
||||||
|
.dialog()
|
||||||
|
.file()
|
||||||
|
.blocking_pick_folder()
|
||||||
|
.and_then(|p| p.as_path().map(|dir| dir.to_path_buf()));
|
||||||
|
let Some(dir) = picked else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let choice = project::remember_folder(&dir)?;
|
||||||
|
let text = choice.dir.to_string_lossy().into_owned();
|
||||||
|
*state.project.lock().map_err(|e| e.to_string())? = Some(choice);
|
||||||
|
Ok(Some(text))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stops the old project's agent and console and clears both from state, so
|
||||||
|
/// neither `agent_for_project` nor `console_start` can hand either back once
|
||||||
|
/// the project has moved on (Task 9.5). `state.page` is deliberately left
|
||||||
|
/// alone: it is the page's own output channel, not the project's, and it must
|
||||||
|
/// stay the single live registration for `agentChannel`'s id for the page's
|
||||||
|
/// whole lifetime. Dropping it here (even briefly, to `None`) sends the
|
||||||
|
/// frontend an "end" message that unregisters that id for good — no later
|
||||||
|
/// command can ever re-register the same frontend `Channel` object after
|
||||||
|
/// that, whatever it passes, so a project switch would silently and
|
||||||
|
/// permanently cut the new agent's output off from the page.
|
||||||
|
fn teardown_project(state: &AppState) -> Result<(), String> {
|
||||||
|
if let Some(agent) = current_agent(state) {
|
||||||
|
agent.stop();
|
||||||
|
}
|
||||||
|
*state.agent.lock().map_err(|e| e.to_string())? = None;
|
||||||
|
if let Ok(mut guard) = state.console.lock() {
|
||||||
|
if let Some(mut sup) = guard.take() {
|
||||||
|
let _ = sup.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Switch to a different project folder, picked fresh: a clean teardown of
|
||||||
|
/// the old one (its agent stopped, its console stopped) before the new
|
||||||
|
/// folder is remembered, so `agent_for_project` and `console_start` start
|
||||||
|
/// fresh for it rather than reusing anything from the one just left. Picking
|
||||||
|
/// nothing (cancelled) leaves the current project untouched. One project per
|
||||||
|
/// window stays; this replaces it, it does not add a second.
|
||||||
|
#[tauri::command]
|
||||||
|
fn change_project(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<Option<String>, String> {
|
||||||
|
let picked = app
|
||||||
|
.dialog()
|
||||||
|
.file()
|
||||||
|
.blocking_pick_folder()
|
||||||
|
.and_then(|p| p.as_path().map(|dir| dir.to_path_buf()));
|
||||||
|
let Some(dir) = picked else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
|
||||||
|
teardown_project(&state)?;
|
||||||
|
|
||||||
|
let choice = project::remember_folder(&dir)?;
|
||||||
|
let text = choice.dir.to_string_lossy().into_owned();
|
||||||
|
*state.project.lock().map_err(|e| e.to_string())? = Some(choice);
|
||||||
|
Ok(Some(text))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The console the agent opened, alive and as it is now, or restarted on the
|
||||||
|
/// same session when it died. The app never starts a dashboard of its own:
|
||||||
|
/// the agent does, by running the skill, and announces it. Nothing to show yet
|
||||||
|
/// is an error the page words for the person.
|
||||||
|
#[tauri::command]
|
||||||
|
fn console_start(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
|
||||||
|
console_start_impl(&state)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn console_start_impl(state: &AppState) -> Result<serde_json::Value, String> {
|
||||||
|
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||||
|
let sup = guard.as_mut().ok_or("The agent has not opened the dashboard yet.")?;
|
||||||
|
if !sup.health() {
|
||||||
|
sup.restart_if_dead()?;
|
||||||
|
}
|
||||||
|
serde_json::to_value(sup.session()).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bar's poll: none (never started or stopped on purpose), running, or
|
||||||
|
/// dead (started but not answering).
|
||||||
|
#[tauri::command]
|
||||||
|
fn console_status(state: State<'_, AppState>) -> serde_json::Value {
|
||||||
|
let Ok(guard) = state.console.lock() else {
|
||||||
|
return serde_json::json!({ "state": "none", "url": null });
|
||||||
|
};
|
||||||
|
match guard.as_ref() {
|
||||||
|
Some(sup) if sup.stopped() => serde_json::json!({ "state": "none", "url": null }),
|
||||||
|
Some(sup) if sup.health() => serde_json::json!({ "state": "running", "url": sup.session().url }),
|
||||||
|
Some(sup) => serde_json::json!({ "state": "dead", "url": sup.session().url }),
|
||||||
|
None => serde_json::json!({ "state": "none", "url": null }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
|
||||||
|
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||||
|
if let Some(mut sup) = guard.take() {
|
||||||
|
sup.stop()?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// Without Node 18+ the console and skills cannot run: say so and stop (FR-13).
|
||||||
|
let status = node_check::check_node();
|
||||||
|
let node_problem = node_check::problem_message(&status);
|
||||||
|
let node_version = match &status {
|
||||||
|
node_check::NodeStatus::Ok(version) => Some(version.clone()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let node_binary = node_version.as_ref().and_then(|_| node_check::node_binary_path());
|
||||||
|
|
||||||
|
let args = std::env::args().collect::<Vec<_>>();
|
||||||
|
tauri::Builder::default()
|
||||||
|
.plugin(tauri_plugin_dialog::init())
|
||||||
|
.manage(AppState {
|
||||||
|
project: Mutex::new(project::resolve(&args)),
|
||||||
|
launch: project::launch_choice(&args),
|
||||||
|
node_version,
|
||||||
|
node_binary,
|
||||||
|
..AppState::default()
|
||||||
|
})
|
||||||
|
.invoke_handler(tauri::generate_handler![
|
||||||
|
platform_info,
|
||||||
|
agent_availability,
|
||||||
|
open_install_page,
|
||||||
|
agent_start,
|
||||||
|
agent_input,
|
||||||
|
agent_resize,
|
||||||
|
agent_restart,
|
||||||
|
agent_reattach,
|
||||||
|
app_state,
|
||||||
|
save_term_panel,
|
||||||
|
save_first_run_done,
|
||||||
|
version_status,
|
||||||
|
update_skills,
|
||||||
|
pick_project_folder,
|
||||||
|
change_project,
|
||||||
|
console_start,
|
||||||
|
console_status,
|
||||||
|
console_stop
|
||||||
|
])
|
||||||
|
.on_window_event(|window, event| {
|
||||||
|
// Closing with an agent running asks first; "no" keeps the window open.
|
||||||
|
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
|
||||||
|
let app = window.app_handle().clone();
|
||||||
|
if agent_is_active(&app) {
|
||||||
|
api.prevent_close();
|
||||||
|
confirm_quit(&app);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.setup(move |app| {
|
||||||
|
// Pages the agent's `open` announces: the supervisor and the agent's
|
||||||
|
// environment follow the console, and the page frame shows it.
|
||||||
|
let handle = app.handle().clone();
|
||||||
|
let server = AnnounceServer::start(Arc::new(move |notice| {
|
||||||
|
let state = handle.state::<AppState>();
|
||||||
|
let taken = take_announced(&state, ¬ice, window_origin(&handle), session_on_disk);
|
||||||
|
if taken {
|
||||||
|
let _ = handle.emit("console-page", ¬ice);
|
||||||
|
} else {
|
||||||
|
eprintln!("plan2code: ignored a page outside the console store: {}", notice.sid);
|
||||||
|
}
|
||||||
|
taken
|
||||||
|
}));
|
||||||
|
match server {
|
||||||
|
Ok(server) => {
|
||||||
|
if let Ok(mut slot) = app.state::<AppState>().announce.lock() {
|
||||||
|
*slot = Some(server);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Without it the agent opens pages the plain way; nothing else breaks.
|
||||||
|
Err(error) => eprintln!("plan2code: no announce endpoint: {error}"),
|
||||||
|
}
|
||||||
|
if let Some(message) = &node_problem {
|
||||||
|
app.dialog()
|
||||||
|
.message(message)
|
||||||
|
.title("Plan2Code needs Node.js")
|
||||||
|
.kind(MessageDialogKind::Error)
|
||||||
|
.blocking_show();
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.build(tauri::generate_context!())
|
||||||
|
.expect("error while building the Plan2Code app")
|
||||||
|
.run(|app, event| {
|
||||||
|
// Cmd+Q and the app menu's Quit on macOS end the app without closing the
|
||||||
|
// window first. An exit asked for in code (`code` is set) is `quit_app`'s own.
|
||||||
|
if let tauri::RunEvent::ExitRequested { api, code: None, .. } = event {
|
||||||
|
if agent_is_active(app) {
|
||||||
|
api.prevent_exit();
|
||||||
|
confirm_quit(app);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
fn state_for(dir: &str) -> AppState {
|
||||||
|
AppState {
|
||||||
|
project: Mutex::new(Some(ProjectDir { dir: PathBuf::from(dir), source: project::ProjectSource::Picked })),
|
||||||
|
..AppState::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn notice(sid: &str) -> PageNotice {
|
||||||
|
PageNotice { url: "http://127.0.0.1:5555/s/t/".into(), sid: sid.into(), workflow: "dashboard".into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A supervisor following the build's console, adopted with the repo's own
|
||||||
|
/// console source so it never depends on an installed one.
|
||||||
|
fn following_the_build() -> ConsoleSupervisor {
|
||||||
|
std::env::set_var("PLAN2CODE_CONSOLE_DIR", PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"));
|
||||||
|
ConsoleSupervisor::adopt(PathBuf::from("."), app_origin().to_string(), "http://127.0.0.1:4444/s/b/", "build")
|
||||||
|
.expect("adopt with the repo's console")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sid_followed(state: &AppState) -> String {
|
||||||
|
state.console.lock().unwrap().as_ref().unwrap().session().sid.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adopted, never started here: skip Drop's `stop`.
|
||||||
|
fn let_go(state: &AppState) {
|
||||||
|
std::mem::forget(state.console.lock().unwrap().take());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_page_from_outside_the_console_store_never_takes_the_window() {
|
||||||
|
// A test's throwaway console, opened by `cargo test` inside the app with
|
||||||
|
// the agent's in-app variables: following it swapped a build's page for
|
||||||
|
// the test's, then for an empty dashboard once the test shut it down.
|
||||||
|
let state = state_for("project-a");
|
||||||
|
assert!(!take_announced(&state, ¬ice("test-console"), app_origin().to_string(), |_| false));
|
||||||
|
assert!(state.console.lock().unwrap().is_none(), "nothing adopted");
|
||||||
|
|
||||||
|
// Already following the build's own console: it stays on that one.
|
||||||
|
*state.console.lock().unwrap() = Some(following_the_build());
|
||||||
|
assert!(!take_announced(&state, ¬ice("test-console"), app_origin().to_string(), |_| false));
|
||||||
|
assert_eq!(sid_followed(&state), "build");
|
||||||
|
let_go(&state);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_page_from_the_console_store_is_followed() {
|
||||||
|
let state = state_for("project-a");
|
||||||
|
*state.console.lock().unwrap() = Some(following_the_build());
|
||||||
|
assert!(take_announced(&state, ¬ice("next"), app_origin().to_string(), |_| true));
|
||||||
|
assert_eq!(sid_followed(&state), "next");
|
||||||
|
let_go(&state);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Covers the folder-matching rule itself (Task 9.5's fix); a genuinely
|
||||||
|
// *active* agent for the old folder needs a real spawned process to
|
||||||
|
// prove against, which only the `tests/agent_manager.rs` harness (the
|
||||||
|
// fake agent) can build — out of reach for an inline test here. The
|
||||||
|
// by-hand "Change project" check (RELEASE-CHECKLIST.md) covers that case.
|
||||||
|
#[test]
|
||||||
|
fn a_different_folder_never_gets_the_old_manager_back() {
|
||||||
|
let state = state_for("project-a");
|
||||||
|
let first = agent_for_project(&state).expect("a manager for project-a");
|
||||||
|
assert_eq!(first.folder(), &PathBuf::from("project-a"));
|
||||||
|
|
||||||
|
// The project moved on; the slot still holds project-a's manager
|
||||||
|
// until a fresh call replaces it.
|
||||||
|
*state.project.lock().unwrap() = Some(ProjectDir { dir: PathBuf::from("project-b"), source: project::ProjectSource::Picked });
|
||||||
|
let second = agent_for_project(&state).expect("a manager for project-b");
|
||||||
|
assert_eq!(second.folder(), &PathBuf::from("project-b"));
|
||||||
|
assert!(!Arc::ptr_eq(&first, &second), "project-a's manager must never stand in for project-b's");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn new_session_forgets_the_windows_session_so_the_fresh_agent_starts_its_own() {
|
||||||
|
let state = state_for("project-a");
|
||||||
|
let server = AnnounceServer::start(Arc::new(|_| true)).unwrap();
|
||||||
|
let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap();
|
||||||
|
*state.announce.lock().unwrap() = Some(server);
|
||||||
|
let body = r#"{"url":"http://127.0.0.1:5000/s/abc/","sid":"s1","workflow":"plan"}"#;
|
||||||
|
let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||||
|
let token = state.announce.lock().unwrap().as_ref().unwrap().token().to_string();
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
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();
|
||||||
|
assert!(answer.starts_with("HTTP/1.1 204"), "the page was announced: {answer}");
|
||||||
|
assert_eq!(state.announce.lock().unwrap().as_ref().unwrap().current().map(|n| n.sid), Some("s1".to_string()));
|
||||||
|
|
||||||
|
// No console supervised here, so no brief to write: only the forgetting.
|
||||||
|
assert_eq!(before_fresh_hook(&state)(), None);
|
||||||
|
assert_eq!(state.announce.lock().unwrap().as_ref().unwrap().current(), None, "the fresh agent's open must not join s1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_same_folder_reuses_the_same_manager() {
|
||||||
|
let state = state_for("project-a");
|
||||||
|
let first = agent_for_project(&state).unwrap();
|
||||||
|
let second = agent_for_project(&state).unwrap();
|
||||||
|
assert!(Arc::ptr_eq(&first, &second), "the same folder should not make a second manager");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn have_node() -> bool {
|
||||||
|
std::process::Command::new("node").arg("--version").output().map(|o| o.status.success()).unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A real console, the same way `tests/console_supervisor.rs` sets one
|
||||||
|
/// up: `PLAN2CODE_CONSOLE_DIR` points at the repo's own console source,
|
||||||
|
/// `PLAN2CODE_CONSOLE_HOME` keeps its session files out of the real one.
|
||||||
|
fn real_console() -> Option<plan2code_app_lib::console_supervisor::ConsoleSupervisor> {
|
||||||
|
if !have_node() {
|
||||||
|
eprintln!("skipping: node is not on PATH");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let console_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console");
|
||||||
|
if !console_dir.join("console.mjs").is_file() {
|
||||||
|
eprintln!("skipping: console source missing at {}", console_dir.display());
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let pid = std::process::id();
|
||||||
|
let project = std::env::temp_dir().join(format!("p2c-main-test-project-{pid}"));
|
||||||
|
std::fs::create_dir_all(&project).unwrap();
|
||||||
|
std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console_dir);
|
||||||
|
std::env::set_var("PLAN2CODE_CONSOLE_HOME", std::env::temp_dir().join(format!("p2c-main-test-home-{pid}")));
|
||||||
|
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(
|
||||||
|
plan2code_app_lib::console_supervisor::ConsoleSupervisor::start(
|
||||||
|
project,
|
||||||
|
plan2code_app_lib::console_supervisor::app_origin().to_string(),
|
||||||
|
)
|
||||||
|
.expect("start a real console for the test"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn teardown_clears_the_console_so_console_start_refuses_not_reconnects() {
|
||||||
|
let Some(sup) = real_console() else { return };
|
||||||
|
let state = state_for("project-a");
|
||||||
|
*state.console.lock().unwrap() = Some(sup);
|
||||||
|
assert!(console_start_impl(&state).is_ok(), "console_start should work before the project changes");
|
||||||
|
|
||||||
|
teardown_project(&state).unwrap();
|
||||||
|
|
||||||
|
let err = console_start_impl(&state).expect_err("console_start must refuse, not reconnect to the old session");
|
||||||
|
assert!(err.contains("has not opened the dashboard"), "unexpected message: {err:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
//! 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::OnceLock;
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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. Resolved
|
||||||
|
/// once per launch: none of these change while the app runs.
|
||||||
|
pub fn resolved_path() -> &'static str {
|
||||||
|
static PATH: OnceLock<String> = OnceLock::new();
|
||||||
|
PATH.get_or_init(|| {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
if !inherited.is_empty() {
|
||||||
|
parts.push(inherited);
|
||||||
|
}
|
||||||
|
parts.join(if cfg!(windows) { ";" } else { ":" })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
//! 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)?;
|
||||||
|
std::fs::write(file, json).map_err(err)?;
|
||||||
|
Ok(ProjectDir { dir: dir.to_path_buf(), source: ProjectSource::Picked })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::agents::AgentKind;
|
||||||
|
|
||||||
|
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(AgentKind::Codex.id().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(AgentKind::Claude.id().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(AgentKind::Devin.id().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,280 @@
|
|||||||
|
//! 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 colour.
|
||||||
|
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,216 @@
|
|||||||
|
//! 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,217 @@
|
|||||||
|
//! 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,200 @@
|
|||||||
|
//! 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";
|
||||||
|
|
||||||
|
/// 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
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())?;
|
||||||
|
std::fs::write(file, json).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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 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,273 @@
|
|||||||
|
//! 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).
|
||||||
|
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(10), |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(10), |_| {}),
|
||||||
|
);
|
||||||
|
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(10), |_| {})
|
||||||
|
});
|
||||||
|
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(10), |_| {})
|
||||||
|
});
|
||||||
|
assert!(result.unwrap_err().contains("is missing"));
|
||||||
|
}
|
||||||
|
}
|
||||||