Compare commits

...
12 Commits
Author SHA1 Message Date
jparkerweb 6114914dd6 Merge pull request #10 from jparkerweb/git-things
Git things
2026-10-08 18:16:47 -07:00
jparkerweb 4932ad4162 Record the getting-started overhaul in the changelog and agent docs
AI Assisted
2026-10-08 17:37:10 -07:00
jparkerweb a3b117dafc Explain stuck sessions in Help and add a Before you close this panel to finished screens
AI Assisted
2026-10-08 17:21:34 -07:00
jparkerweb 3469a74cc1 Add a Before you start block to the newcomer docs and a test to keep them in step
AI Assisted
2026-10-08 17:02:40 -07:00
jparkerweb b639c8945d Add Codex to the plan2code command and explain what to do without an agent
AI Assisted
2026-10-08 16:54:18 -07:00
jparkerweb 9cd39f6ce8 Simplify the installer menu and add getting-started steps after install
AI Assisted
2026-10-08 16:45:56 -07:00
jparkerweb d4cfd32c9a Point the sync instructions at the rewritten commit hashes
AI Assisted
2026-10-08 09:28:42 -07:00
jparkerweb 8215b7a9c5 Move upstream names out of plain text and into the encrypted sync instructions
AI Assisted
2026-10-08 09:27:29 -07:00
jparkerweb 3dfd44ba88 Show pending files on the Git commit card, add Commit it now, and default Subagents to on
AI Assisted
2026-10-08 08:52:52 -07:00
jparkerweb 3414a19ce6 Add the changelog skill and dashboard card to v2.6.0
AI Assisted
2026-10-08 07:22:26 -07:00
jparkerweb 50a78a6917 Add the git-commit skill and dashboard card, and the No changes button, as v2.6.0
AI Assisted
2026-10-07 23:18:40 -07:00
jparkerweb 1877ca1fa7 Stop tracking skills/ build output, rebuilt by the installer instead
AI Assisted
2026-10-07 23:13:04 -07:00
592 changed files with 2651 additions and 377727 deletions

No files matched your search

+18 -11
View File
@@ -5,7 +5,7 @@
```
plan2code/
├── src/ # Source workflow prompts (13 markdown files)
├── 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
@@ -50,10 +50,10 @@ plan2code/
│ ├── check-skill-table.mjs # src/plan2code.md "What each skill reads and writes" table vs each skill's prompt and references
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
│ ├── test-web-console.mjs, test-launcher.mjs # node --test suites
│ ├── test-web-console.mjs, test-launcher.mjs, test-getting-started.mjs # node --test suites (the last keeps the newcomer docs in step)
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, skill-script-helpers.mjs # Skill script suites and fixtures
│ └── validate-char-count.js # Pre-commit character count validator
├── skills/ # Committed build artifact — one Agent Skill per src/ prompt
├── 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)
@@ -80,12 +80,12 @@ plan2code/
|------|---------|
| `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 committed for installation and drift verification |
| `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 or Devin (installed by `I` and `A`; also via Custom → D) |
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`) |
## Workflow Prompts (in `src/`)
@@ -104,6 +104,8 @@ plan2code/
| `plan2code-review.md` | review | Post-implementation comprehensive review |
| `plan2code-4-finalize.md` | 4 | Validate, summarize, feedback, archive (steps 1–7, +optional 6.5) |
| `plan2code-handoff.md` | handoff | Compact the conversation into a self-contained handoff document for a fresh session |
| `plan2code-changelog.md` | changelog | Check the CHANGELOG version against the default branch, suggest editable entries for new work, keep `package.json` aligned, offer Git commit |
| `plan2code-git-commit.md` | git-commit | Commit with a clear message, suggested splits, a branch offer on the default branch, and an optional push |
## Naming Convention
@@ -141,13 +143,15 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
| Script | Skills | Does |
|---|---|---|
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/lib.mjs`, so the dashboard and the skills share one spec classifier |
| `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update | The `<subject>` / ticket / `AI Assisted` command from the branch name |
| `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update | The `<subject>` / `AI Assisted` commit command (two `-m` flags), with optional `git add` |
| `review-scope.mjs` | review, implement(-review), quick-task | Review Mode's git fallback: files, lines, doc share, base branch |
| `agents-md.mjs` | init, init-update | AGENTS.md structure, budget, orphans, broken links, always-inline sections |
| `agent-files.mjs` | init, init-update | Detect and replace other agents' config files with AGENTS.md pointers |
| `pathfinder.mjs` (own) | 0-pathfinder | `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate`, `lint`, `brief-data` |
| `feedback-payload.mjs` (own) | 4-finalize | STEP 6.5's payload (real sha256 prompt hashes) and the gh / browser / print submission tiers |
| `handoff-path.mjs` (own) | handoff | Timestamped path, OS temp dir, git ignore check |
| `changelog-state.mjs` (own) | changelog | `state`, `bump`, `set-package-version`: the default branch's version, whether the branch's entry can be extended (not released, not on another branch), the file's heading style, the gap since the entry was last touched; only `set-package-version` writes, and only the version field |
| `git-state.mjs` (own) | git-commit | `state`, `branch-check`, `init-check`: the repo snapshot, branch-name check and git init safety check, read-only |
**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.
@@ -204,6 +208,7 @@ Key design points:
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `models.json`). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). When it is `false` the Git commit card stays clickable and shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `lib.mjs`: one `git status --porcelain -z` (3 second timeout, `null` when git cannot say) counting modified, staged, deleted and untracked paths. At `0` the card greys out with `GIT_CLEAN_REASON`; above it the detail line is `pendingNote(n)` ("3 files to commit"); `null` leaves it clickable. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git-commit` in the same session. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `app.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `app.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
- **No git process.** `repoRoots()` in `lib.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
@@ -240,9 +245,10 @@ Key design points:
- **`validate()` in `lib.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 17 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `app.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
- **Stuck sessions are explained twice, in Help and on the status line.** `stuck` ("When something looks stuck") is the second tab in `HELP_TABS`; its panel opens with a `help-callout` ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (`openHelpOn("stuck")`) inside the existing `role="status"` element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from `renderCloseGuide()` in `renderHandoff()` (Safe to close, Start fresh, Carry on). Tests in `scripts/test-web-console.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
- **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 --verify-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then `node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs`. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then `node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-getting-started.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs scripts/test-script-git-commit.mjs scripts/test-script-changelog.mjs`. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
**Adding a file under `public/` needs three edits, not one:** the file itself, the `SERVABLE` allow-list in `server.mjs`, and (for a module the page imports) a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a new module missing from it 404s and the page dies at import with no useful error (a test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint.
@@ -268,18 +274,19 @@ src/statusline-claude/
**Adaptive plan-usage display:** the formatter auto-selects between `5h/7d` rate-limit percentages (Pro/Max/Teams — when `rate_limits` present in stdin) and `Nk in · Nk out` session-token counts (Bedrock/Vertex/PAYG — when `rate_limits` absent). Segment is hidden when neither shape is available.
**Installer integration** lives in `install.js` under the `STATUS LINE INSTALLATION` section (`installStatusLine`, `uninstallStatusLine`). Included in `A` (Install All + dev tools); also available individually via Custom → `S`.
**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 two CLIs (the `CLIS` table in the launcher):
Typing `plan2code` in any directory opens the dashboard skill against the current project, **in that directory**, in one of 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 both 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, `claude` or `devin` also work); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with neither it exits 127 naming both. `--cli claude` / `--cli devin` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=`, it asks `Which model should <CLI> use?` from the curated `src/launcher/models.json` (copied to `~/.plan2code/bin/models.json`, overwritten by every install) merged with the user's additions in `~/.plan2code/models.json` (edited in the console's User Preferences → Models). Enter keeps the model the CLI last used; a pick appends `--model <id>`. Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin` commands and a temp home.
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it exits 127 and prints `SKILL_STEPS`: how to install an agent, `cd` into the project, and type `/plan2code` (`$plan2code` in Codex). An uninstalled `--cli` pick prints the same steps after its error. `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=`, it asks `Which model should <CLI> use?` from the curated `src/launcher/models.json` (copied to `~/.plan2code/bin/models.json`, overwritten by every install) merged with the user's additions in `~/.plan2code/models.json` (edited in the console's User Preferences → Models). Enter keeps the model the CLI last used; a pick appends `--model <id>`. Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin` commands and a temp home.
**Design constraints:**
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
@@ -299,4 +306,4 @@ On a terminal it first prints a Planny banner (`renderBanner()`). With both on `
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 both `I` and `A` get it), `U` removes it, and Custom → `D` installs it alone.
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
+1 -1
View File
@@ -22,7 +22,7 @@
- **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 a committed build artifact:** edit `src/`, run `npm run build:skills`, and commit the regenerated skills in the same change. `npm test` runs `install.js --verify-skills` and fails on missing, unexpected, or stale files. Never edit `skills/` by hand.
- **`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.
+10 -10
View File
@@ -14,8 +14,8 @@ node install.js
# Regenerate skills/ from src/ (non-interactive)
npm run build:skills
# Full check (about 70s): char limits, skills/ drift, browser-module parse check,
# dashboard skill-table check, web console + launcher node:test suites
# 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
@@ -29,7 +29,7 @@ node scripts/bench-web-console.mjs [--runs 7] [--workflow dashboard]
# before committing: right screen, both themes, no username or home path in frame.
npm i --no-save puppeteer-core # once; never added to package.json
node scripts/capture-screenshots.mjs # every screen
node scripts/capture-screenshots.mjs --only dashboard # one screen
node scripts/capture-screenshots.mjs --only dashboard # one screen (dashboard-utilities scrolls to the utility cards)
# Plan2Code Loop
cd plan2code-loop && npm install # First time setup
@@ -64,13 +64,12 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
| Option | Action |
|--------|--------|
| `I` | Install the Plan2Code skills globally via the `skills` CLI, plus the global `plan2code` command (opens the dashboard in Claude Code or Devin) — no dev tools |
| `A` | Everything in `I` plus every dev tool: `plan2code-loop`, `plan2code-bot`, `plan2code-metrics`, and the Claude Code status line |
| `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) |
| `C` | Open CUSTOM sub-menu |
| `A` | Open the ADVANCED sub-menu |
| `Q` | Quit |
**CUSTOM sub-menu (`C`):**
**ADVANCED sub-menu (`A`):**
| Option | Action |
|--------|--------|
@@ -80,6 +79,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
| `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
@@ -89,7 +89,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
| Flag | Action |
|------|--------|
| `--build-skills` | Regenerate `skills/` from `src/`, pruning stale skills and reference files |
| `--verify-skills` | Compare committed `skills/` with `src/`; exits 1 on drift and is run by `npm test` |
| `--verify-skills` | Diff local `skills/` against `src/`; exits 1 on drift. Diagnostic only, the installer rebuilds anyway |
## How the Installer Works
@@ -97,7 +97,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
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). Custom → `L` runs the same flow without `-g` and without the launcher.
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.
@@ -128,7 +128,7 @@ See the `skills/` build-artifact gotcha in [Code Style & Gotchas](./AGENTS-code-
1. Edit the source file under `src/`.
2. Run `npm run build:skills`.
3. Test the workflow in an AI tool.
4. Commit regenerated `skills/` beside the source change; `npm test` fails on drift.
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 -1
View File
@@ -1 +1 @@
U0VOQwGXVSGXI36GSw72BYVsi/4ONgA24308DH4YD+cAxK7y8sA5FELtBHEOS9Afj/6nBCRvL156GKEdmKfri1gtkU2XYz/x1lJBa15+a3TWTqeQrPUKLxSW0Ah0UGuPPQVxwoIBXMz9ADPlbG+qpsw/behYXr491MJC8qqRNqrQA/I0bAkLvxer4AZPz/SGohCbpQy3EmmwYOUshDm8QLEp+VjkUZfJmbjWSPXsNRhyKuMzAEHQI3OiWA/MR/qqkOzjhGHb98erQhu3Ebz3fbeR9qSDyezBoBOJN8dRb7K5HFh8IRVFhKsX5CltpO1zEcisJUN0kcI7cz6GCYDt1v+L2KVfJNFVbfveB7vZvDVUTdQ2Gu87M1GFr4bQqUjRp9TM5VpPRuUkv3IDrIcXgdc1I9lQgHki74tVmt1QBtzyOznRd4BN+8dekrE/PRlH99gPTrvCk2WRZkrddlXsBlj+qUYHOwdmldf+b2HAcFjmYu6j/585evlOvbJgMkg+Mhhbr0q7TJcSDGfF8tCRLURMA+p1bvhbZ28fRm74KKTStT85JND+4AUQQXtFxi2r98pY+1fkA8i7Gz8lNR6s0SqaJPOV0NPue0SMqeD37G7LUvmoBz7f6BhmX7O3XcTC+2ewcH4FmZH8qCSeNDGhuyMZJZxjSWyAjrCGPjBVE4IYCnLcaA8A4ZIjbAldtMNAGgfUEMNbwZpuX0ox9LzkZuOHyPICg7IIwXkP1V7HZcejYiAdmqyY8RxNdqtC4QhAjBE5GCcixqY+UwiG3tA0n4a0+Z33u9O+7wHIQ2/C22mjzwbqWoX7R8zqIcUoiY9UB69NFOb23FQTTb3nhm/KwvVlj7jE0B0Bjm+rha+KcetU6GmY3bWvfMmdSF8l2XWdlYVvSlIgHCZ9Pv/ftrBZbdf552tVOOqZgv0HOhBH+gb2DxOlFRRyfOg7BpQzUr3B1CAV2o9aZ3Q7nb02r2658HE51eIftyYfWxpmRLRlrcSkiUXhTEwFSYptH29qIhu2jgzPZ75yUXmWCNa20mddUOjwd+SOroprx7fpkiEta27UC1jBg4IabC3U4sgwd3xy3JUYd9S819bqUhjUlRqGTT89hzPdCFWOP+Ym4R6VZAcAzXgoWhFP2EANONmTRoijJs5UFYfeaazXTjJNDoDU18u1T9a9WWSY5nu5KMrON1Xwpy/uOQZ/YwyTN9PJ3mQRLr4Ohb0ZVUH/BKoNk1iuX9ex5qJlhE+PaFkOdsE1fDL1xncAdsP/Byy2MipW+J/0Bsg8Cxuudi+rL1N/ZoI2lef/zAzx20Op/fYeAL8xebbT3kNCnBC5Re4ui5ccm/n9k6RF4UO+/asNd3fPVtTVkXtETAn3yHcDdZXx37vgnEeCrPRtNUaFkVvrayuEeM2wohkKn7qriEcOrhW/bIu2BW8SKYKmNqS6oMmT4xCFLjTYcYZgzcreWlJ0PjpHYXY0SdJG5iQdPCTYyL1iAitCRnAIYKPH8gMitwcCHeibMvtfso7dncZzcoH1zxkitorzGzpTM/HUbrl+vCuG0NRSyuwlD0r0tSwnBjziK03G5zoKJ6XW4kwcZkMuucDh/W1jKyZdf30NaxlEckscWbnOcpq7pbdrOYejcWxtJaB/7tJXc0mO/LAqrRrCL3k7xoGcmVtTEZJqfwEKxPfJb3k9GWZl2UL87MbZNfTR/aVEYQKbM68/KkdmjSPlF80rJYKLP4WPGobWKEy+AwUMrHFhCQSEV+1AjU8EaWjWbO2TBytbTDC8yHXvFTUJItBpB9rAXZFT4iUCaDVarY3GuOxIiTXVWS6N6hWxz4ev/cxQep1klOhnOtS19bVQAFnmNBKGB8zi8cHxvRo+GHGed8X/k1EF9lDbtFDRIL6Z7HkPzu7qdGgCPfM5eziYafyQKps62jFYzA47+MiHvk68ngqCKihondqeHNOTr+p+QIpn8Al9W1zMETlthjpACxWyFgmVjuHsXscpsu7tOOIM87/HYqXiaybI+GmsOhsa7zTor9UGV0mrRaZvIhd5fpeTWze6pJe66KU7Yji/2swSLBn9oLjHk+x+8qCKoZybD0hVUJKftR7YUEpfZmMeeI07gCArXp48ND0D2+o/Ju2oxabsO9X5UXmhU7vkd3QwB5GwbvDV0OfMIgSvQ0BDntPmVnXFPhPqh6lr41FX0tQ5FTLtjph70QqAv6f7MCV90zS/XMH2vduOgyyuEHxeXVxeAN6QA64cns2yo+p+Xc+8oX2F6B6OUsxMMTwRpR2RHNImx0WRy/yLT342RsgCZpZgQcgglkaSIBbvFMMmaME3t+n8M3LgX7bM/7beod26A4KxZW2y/mffBnfcycoSEvvygcPqy04Dbk8j0XUOUN84VzW5MDfkR1OQmR1Ql3dwSH4d4yLljzg4WDVIC9icDAUGvTvZfK6yjTXD/4gp1IWS9J0W7P/Aeiab1b+pmJxXHi3WO9aUCDyrCkbxyPMOLSiydMFmux9JMeyMXOVQBjJYiT3hn4/U3HTWXwWYEIozauHY6/CqJmVogSGaWWLcJJBd5BANfE9DqJgDqUqoz5tC+Ger0pX1EU91OF0NE+QPWmXxdk/Ah8p2c0A0+4hKOL6xFa7wG6Sq8bJipcuqo5DnxtXhqhi00YQo3fyDG/gCOvgJjEoGaE2NI3+5krNzOqFkpT2vR2goiM2cERxi9z/uTURdqWt/H1yJup/RJUpKvr06YvgzPgm+SGLCf4IOi+VGOdOPbXjLcjmkBZ+to/7+ODKx72XYubVxToCjIf7KaIZkWWQOXwkoIa3ceFoZXaMKT/hIKy4/SXAcDcQqKwHVVl0zXaoVLXsH0qpMHOkb6iVpGGdNsVYebmaz7yWJwUIJu+vVzEs2gPrIZXD2f4c/+5t5UWDb9tybDw1XombuH2TUnmXA6v6bNzDCUU2rPfnoz3GozOOPkCLtI0Yog8MLefPMYbRGi9gKSMqdl+Uc4MMtZd89YNXvTKG1EE6t3pXio6YUoRDwPhibEvvOSszqhdm8NYitOdmRK7NRoBgEdzCJJZ9N/YoItPLXrsiGqRTx6x7x6f2IbBkK202nbRD7EM5yud8NBOm55QFmgK4X/msLNbBzAuBtQawUyOFu5fZREs0/ar7ALGM8c8gzwFp5v4sUypVVk44zTDMcR2/UjcvbAQBl3aqJkFwdATGi2zOrDJ1eeLYIh1p7p+lZB6VhKzJFxCq5s/qcptUBt/rc6jRk42BDqb8opMNJOCZdbLTX5wC8y55JZZpNX5jnesXMnXrCxVnbXe7JrsG8Ea/qneUBCejI9/qzMwS3MYB/usANyOHr2A2ctF8GXVCvE5v1wasr1om/WlFx7gjbAqQORiBNunJih1PFREuyZJUE2XB6foUJupGnbfn1cLGKJuIX32aIPI+Oy89mWcr9+RoaxVuZfL7ztGcB2a1XaCPeU+xR+t41+ArIEkW0X0dTiYV8JINmAyWzNBIHZLABtjOfs/9M1qmlOX7xjuTJZgQdHMz8vuxHtbt2pYrskMoQ4gKzhJ7uoCjChgZx4qG/JQ1iNlDYYsyX66wQiC6CcITx4xmJTX5K9/78uks/WO2H0r8/g+i126U3qy7SITEpvERkgOSfhHxP43aL2443uK67EZ9DH52mEtl4RLU5ulLzMvo1qpHbU5YVaIJYSjscIiyvPwu5onjaFp+JR5VJa7Gb9Pv7MLVR+NUBtK6DDuwxE82HTVAX6qiiOAcpLnvfbgsAXzFvrXNu+KroRxd4JYOZT9NNtiVprLPdV+g9y17iD061IcRMADggiQZY9NbO1TRCrm13JJy7xtC7K5FfBy8jA1x+Y4M7ht/lj2b4toepkfn1WyFVa4z34Zy9JOGomU5eR4cdW13KXGoufaWKp/jxD8DzTlQlb+9/rLfgIzzChvdbvZq6Kh2bHe1psgiojLbu0WXZzWke5LTA3mAt+/slGZyHGBBpxUaeFC6LGCRX548dkJHK1erjF86sfgbw22MCdQiIqR61TxFYdyQjVIvvR2qbxijhHVruwvUd7MyDeH6dA6wqaxqlUa6sNty+0RNFll9SKWsfyzeQWTu9kuD+vTE8USxPfRtWY0eEk1U4lG42XIVaOtEuC1h3RaCJuBX+B82oJL9TLirqc+zTNKU8dZACRhdtoB1y4S5U2qWfz1+wKVlWs1ru0NJiXNrn+ctyqVCAqkk1rUujtAEzYVlHCDviF99xOwF44e/OxhaaLaMO/ZagDm5EXqgdH3nkSRywQc3e6ot4WKCcyQ3+M2PVCDIVw+DvcUlTAAIsvrIfqL1C4KmrjPNVxny+UlA+39bYnIKAoN1yhiEXqV+o1BZVMtDvH2ESx5/sCjoO+cVZMUyiopOP3xYJrJeGvRLjfTV5VXBHdQ/ewzAdxxNcjCOm9iCA8RIBs4Sv5SAcBFVOcKi/YyCgH7sTVueKp3wFF3bf1Y3mKZ0z13iiqAa9N+hssNScEPtWcf1sLCj1sE5h/MBmc5b5NsoQA1nrUbj3rYQ1og9jOCOK+W1QGaRFthylTSYMdw6AEAjz+rWC2BogvfVazc8+O4ekUivkkhXoDqdb+q852KPOXI6b17/b45BK88VUO8WCGmVvtJOPiXaasLik7VOYZZr8E+HfxhCk6JddLXDrV+9Us8vT5f7n6M0RDeGAmL/8CoQy7vhMMgRuC18x8g0LRBdE3KsuGusIdX+FuvThIUQJav9W3cOovCjXnI6PtXQIs6+0WVlCBnh+neMg9OcX1lTHg81pBfKJJaNtmuUeMTz0eQ+drV8BdqDUosShP0ie0082aEcKG6yAQKmfcrEvdnqSvMJxJISYKqN8JvclavMAO22Lg9NugprLEWOjoD7gsgQg89EZihdHNbABEvJJ3HMY8xdyQXUE4iXxe4JvHLdSXIfhV0e3eVTTEXrJEn47LtDE0M90Ne/OhGEAfG44Md2J8esgEfqsmgJdoJ8CADZq3jxRmrBRzmTao1vqrnTtloPWPbvLine truncated
U0VOQwHlDc6GXsacM1cljlQP8y5A2pfARxFGNkmxiK3VxP1nQ9BIp3Z9PZAvB/qlVfrIGc7bCpdtmhsc42H0uveWo+th315m1M0PZWI9GzUWFTL5kShCH6ffFbL3oZpZwdz8l/+oncjsGShQMy0tUp+46YIPBJZGbF6SLG8/O5MC9IcsJfIob7WQUDca0IuSbxPkqC5WqN9PiZNM5P0tXayc3ARK+tUmpO3ywLT+0AJi0m1HWxNMNr3jCqCbwfMzpv5AMZR8jwkJHnCfUZ2DlfmTptnRFx7BjbPIDE8O3nlzOzQj2IFF5CNkPFM+uHvWcd/vUYgqCeBzG51Hi+urt6gW9Q/geoDR8AfioqNeVjakuH3pSjE4kBFsvyO7RSO8wXlwgc/nZHW5BIzHKWVUB12THRtIA0kOmnf/Tk5Da20dRENuCP35KZvBXu1KKn/BQ4hJ/dCB1K4FqKOnqHKE8+CoYCTvlursoAC0rphfufcwXvuAysmtPZGgrOTM7x3z825I8HY6K2Y1dh6h0kxwZ9UDbMzrSH/3WP/jMywD76Ep2qMFMdXKRsypxvIkwJCsptq0NilJN9hALdGwq5G5nRvBCP+nxy6brdCknbKxb8XHkcS8fDAUSifBD4/K9EbDDkXrykKFnA1Vh82LC9tU8o6Uwi99EzpZeWkoZCLHMqJlXPu+FEKvBQYiVa4pDQ/XHSu6lUvUFbdQlRL0vHjNfOq5hjF1kqHj4B+cCiD/FNMqAu9N57+UQNgjI2KzvdlOUAySqp22Bg9sTWa4Nj1ObWRqEx2WH+d4BLkd8N3RgA8OAlOPfF1BCUrDQAnhFoWZmyiPkfm8nCx1eHGFBB/Q4uLloBvhwv2EAoPy2U2pCqO723/C/NJNc4BFK0iuvBaoCNYm1P8mDpzX/fYRQq7kMLlQ+/5urLNfDclPJaJ0bCEHYfcssnrcpt+xshHfNhrLnQ6Ns/ULS8queCAJeNaxe7fOZ+WE1AiSWdXeXFdjnQbFgl0A91zntdfsB0wVW1X4q5sGzQo1NUOYHWi53M+ROBszKXpp4GHSML1OpJQixydcRpQIfNPg2j96RfFOXrJZWc05QSEnjckj3b6sIJLNATEKLY9314CunAG70y/GryqOoLtQmLwXTBRgTx/et7/ItKsvUaK3Z3cEFLflEU5Ny9iHA7Yuxs0rmdn6NjV+IXA9eEf+Uc+2eSHmVCaUgJuhDtnyaO6RpqCJkbs5wf7c/udW2G5QfWZCTLHG80p/7BsA3q2VvEvbQnC+LLPgnyJJpDKL+q/x8KdZ1x/iY4P1J3B5nehEztoMHi8dgUsL3NkItdnJMKf5VQsyW1vnv4kZo7qZ+6+Z/IuqZZNy0aT3N1hJZWDPboFRmcGpTE8ShwblGnrTdnIZlhyk0m951creqltUp13bPWSFOj1zt/yDmW1yBUkkOmpnbJzmzxd9G4kpzHsV6NvGE4JsFVAQnGHgMI6zxMwKM7He+As/+FlwJgdmAPeIZ+PtciZMv+ySi9/xSXMwpJHSXFo2NkkWj8QJke5l9BsDGj66ZTjkW5R1RmYNhVAPTrP32a02kPj2JYgDOAIAGcz0q1Somb4LqVNAp6/Y6DFY3iniC3bV6vZagVLcgQFngHRgZ3HzILWcytJZwhVoMpE18DXpTBuubqytM/bnVFRZ6GxLJtcRCt24RnMRYipuR19kq+ncxEN7Xl7LkPdpsfFPelS9srxAWbivtD32SjCxsIKte+vns2lU6J12UoXP86LVDtTZCRkh/bmCDs4ecks02NVu2htm47UjPMVx1KDqTGPlPGZA+Vuj/eaWdoqvpEJzeOCgcrhUehDqQCpm0ZfCPJ924eGdfZGQZaaO4CZ6H4asHTTabWpu1cuLqVQkO030VAHJaDNE8fqxiPN3rsXmRjxTTSuc/N2i5OyGdqJdXbItMdmaWOU7p5XkmkUDVhhKiHBBcGsUekx0TSMmNkkbLJBy0DK2wkMP9utLDAxAzT5v0uTKKbPPpMYqGbhveN9+HClsD3cHGZ1xT3ag8Xg3s04zwoOhmXNvoDOOtcDaqbJacrMBhj8Hj6PUKGd2JlaU8M6GuBRXHzbmfPlDL7eQLhvRuwDAlVTfePRFs/L7i45xQ40t2z+Mxu1h+eQRuw3ePVscNX7xe7h+l+6MddyT7XuR2hiP4CapOJQ8uYgjdIUDDTAblNhIh99KvM4mevwzcZ+K6J/Kc3MFCeJzOIGYL0xCSKKnrvdihkYiw02U9okgkfz2eVwtmGHWl4iu/ymPc89d/4kmwflIIL3aYNCIyO7UaZHyRHLg8MrCZOZk4p/cY9CecHQStTZ2pnii7CeXzrckFa0JFwU6DKI192FbthJ3/F/9DZFWb10CIYVxzjWM7EwQtCzP9BAZQ2v89CxMh82arb6BgOnTWr55vH7UJFeKDQYSc/MT/VNnzhWCJZaLiJcB7RXwL2HFI6K/d7a5frcEEBGWhVACJjjqnFGBBlrOT1QMLeJX1Ru1sXqVsEYte8hg5/WzKs2LFmJcp/FqapQmpXa5vSKzgqD14GLij/LHA/2tTnS3Idb42A3rMDvm6ekrv/3gv/KFg+udrZv5cWLgX9QNktHBEUJNEQWVR1R7xAvdIo5SPrQxj7mu+wRsu8JXm8wXvTZFw9wJADOPUPrim6fU5JbGKhOVlIgePXisGYuh6doIl7ZKfdvwaFzOT2Fp+8KHmlmK6FPEGNEG9QaltbjIwg/XXmzjjTUfrSmgOeWay7e+MABTPnc2OUk+moSYKO1fhEgynVtd9xeeX7w+Rpcy6QL9Ut6Mz77/vLkZD0QviJReItBKajsIoKtrOGgHJ/R/z/XcdMsdbEwFweb3bp43B83jFKb0GeuWxhzzjtqIBeXnJvL8kGv3dXmDNM6BWi/JBs9r0Cyx1KCHSPDc3UIhk1FAOkKiu4a043D064M+IC+JqMcQT62eUw+uZ/dPh8x6rJIWSCRldOondtJDvKfsVYU/7gC73i31RD2SRZCj67JB8wFpXkOS+EjDFtkNvN8c2BJ0W8bMXE1UwKrPktOV6O/XpY6tsj+BqzaeU6DMPP7WVlrQ5NjLCUerxwTKXCcUqH00b8pkkvRZoBTz/nuhdBTsQWE9YZ2L/UTX38Y+eTNPOdBeBHkyTc/GHbvDOM5xsw8/Y4Mx4+NSDdrdWd0EL3uc9W16QmQKTzozRYJbSmat2xQNbGlOJRCUoX1FZoQXFJQfFNLjg3VzlhzFusAkxEICXS/6nOESDTH3xIw44vkegypd3xiizZ9RrhdEYiaU+0zfJp6p91v5czqUqRfnyKbLS9bv8/nHUq5HGz/AfumZKS2yXjHxSxYD/zbKc1Z88BsMvFXhOFD4GnN2Y5W0RP02XBwWDxP5BdWTfXB6dkgVw4HFDFnbmgeZWfc0AgRzZTuua5gCjGc0kmDYayJrojW7mGMTJYQJzwLCrKp2pDr5A6n8bNPCbCdp2RK6I8sgTyJjrX+2TbkMlulE/Vne1yKOdtdzkMeQ7jcO3rEK77pRymnmRtBxcp4DUEhkSHyfedXwr/9UewQPZ8eXWJOQPzJng3IrvY+L1diu0NBYu4qYCtNscNfkju52+wnluL2I8kOUWVPuDfRtF3tloaohl0nEnnXjyMuC+53+2F4MKNJRsE2eiPTVV1lfRuBgFfIcEI8q+E+GN3vXZ2lr3ouVt5bI5y1xZW8Sjt7zmPmSiyKkU3NZsL65b1PA718YO8i9+YBemw8VYfGfDn3JEc3f1P5WFYl0POYWWnCwlPe13J4ErZ8k3PBIuPGAqaE6W1d5yIkrLUnthDIOREghCve5L0HfguZZt+TUuHoq7iYLeJpYDYhGawnINJfUiZJH1MzYPixy+GZKyVBqZdr/dxPpdt/BVOsZ6WDNifkRrHaN18QrOJ4zFUAvFJDYq/1jYkLVflaoyxDlviOwAX/geIMRRTeDyZM9ucc0FG5h8qyeqoJQErMqaQT9BfvrvBI3JuRQiH5XuXRbz+uQMJljvhqs/lRhkeTWtMu9BdkEqlnyJskehE9qBzfLIw6lHYrtGs0NAPwN1m2Es+c502RAUp5nlIinJUR5/f7q2p7jgqVWuj1ifD7N2XoWFdMqM2+kb7suSYlY+gUPYK/Uz7T2as77U9OVzqS+udjWgdy3v/gfZOhuXhs0zrP/hBxswvSrpyhTq61bAAH7xOQGO3+IMxW4G4OgrfArNDMCflsFAgpktwmjkyTfM1YrZSEC9/65b1WE5lUi7r1Vx2PF0gogexigbz//Dp5MlfTsQkjRlLVv0rb6tnLXriCW9rdt2c491XRTMPR+348A9ckMYBbgRebXsfxVNrHK1ehgFT3C/vDbp4fXKGTNMITfvneJEN+RvfJFJW2JCNeAGwdqmpZJ5by+xlMP5a1K6eZNxnyqEhad/hfkvWMmBZo7dbuiDksFZm9iyaXJARGUsu+laEJClYyjEfhP9YvVdAs/5sL0NPCAw9OfqgUB+ZpFOFvtRun8E4Vmu4k4EZHgdW3bIrOmtUxFkkpOVQN+5EqmeiiB39dpOb8pn7KhhDLgnG8CTwA0Q9+WI3QtLA7BouOO49Y45K/7RrmKy1dgknDkv2Pe+7axcyI87UnY6XlpEaWrebS8YPlCpiAF8ZASKV93VDIx83RmhMe8SP6iiF2jYvXR6N7na6B9LW9/waV8U/1O8thqf45UgJ2LprQjjGYyXJ51VeFn0iRPEkyIygzdW02hq3COIWW2CAPIqxmtT3SuG7tqFb6Oa/QN2XS1d4ilSuEU7jIxkrvTVjQGtptVXFPxVylBLYVc6rsM+5gPHvQRpeg4t7OwbAJBPWvwa9dPIB01GdK0ppG6rTtNWvdtdzME1PSExjw035fI0OIC2AnMKqIufE0AkYYFO48ugN0Lg5SKSllypChiI2m80+wFDhe+X3AfX8t4pldQhdW84sV0mfWllfwqYhGU4LWOuIMYiK2Clx+9F2s8VwjSwRs7102mxu8f0vQoIq5A+7/Line truncated
+5
View File
@@ -16,6 +16,11 @@ 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/
+1 -1
View File
@@ -25,7 +25,7 @@ hand, or the reverse — the checkboxes are the only handoff.
```bash
# From the plan2code root directory
node install.js # A (everything + dev tools) — or C → O (loop only)
node install.js # A → E (everything + dev tools) or A → O (loop only)
```
## Run
+1 -1
View File
@@ -16,7 +16,7 @@ One thing to remember: **collect after every finished spec.** Everything else is
```bash
# Install once, from the plan2code root
node install.js # A (everything + dev tools) — or C → M (metrics only)
node install.js # A → E (everything + dev tools) or A → M (metrics only)
# After finishing a spec (steps 1–4)
cd your-project
+1 -1
View File
@@ -36,7 +36,7 @@ The icons down the left are Planny, the project mascot.
## Install
```bash
node install.js # A (everything + dev tools) — or C → S (status line only)
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
+1 -1
View File
@@ -19,7 +19,7 @@ Built for **maintainers**. If you're using Plan2Code to ship features, you don't
## Install
```bash
node install.js # A (everything + dev tools) — or C → B (bot only)
node install.js # A → E (everything + dev tools) or A → B (bot only)
```
## Run
+11
View File
@@ -7,6 +7,17 @@ Each session stays short, and the specs on disk carry everything from one sessio
---
## 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
+11 -2
View File
@@ -50,6 +50,13 @@ it opens on the page without asking.
<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 commit** 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 commit, which notes that the folder is not a git repository yet and offers to start one.">
</picture>
---
## What you get
@@ -186,7 +193,9 @@ The easy way in is the dashboard:
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. Click one and Planny flies while it gets ready; a few
the card it would pick. **Git commit** is among the utilities, always available; 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. Click one 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.
@@ -358,7 +367,7 @@ Pathfinder, the agent can hand independent pieces of work to helpers
run at once (1 to 20; your agent's own limit still applies). **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**, off by default, in
- **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
+4
View File
@@ -10,6 +10,8 @@ Plan2Code is a structured 4-step workflow methodology for AI-assisted software d
**Author:** Justin Parker
**License:** MIT
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
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/`.
@@ -93,3 +95,5 @@ When you make a mistake, get corrected, or discover something about this codebas
- After a sync merge, run `npm test` before trusting a "clean" file: when upstream and plan2code fixed the same bug, `git merge-file` keeps both copies without a conflict (a sync once left `let pattern` declared twice in `app.js`, caught only by `parse-check`).
- When extracting upstream files in Git Bash, run `git show <ref>:<path>` with `MSYS_NO_PATHCONV=1` and `C:/` style paths (never `/c/`): path conversion rewrites `origin/main:.readme/x.md` into `origin\main;.readme\x.md`, the show fails, and the merge silently runs against an empty "theirs". Check every extracted file is non-empty before merging.
- After a sync, grep the result for the upstream owner slug and company name in any case (the `/sync-repo` body lists them): the rebrand map only rewrites URLs, so a bare owner slug once slipped through into `feedback-payload.mjs` (and its test) until it was fixed by hand to `jparkerweb/plan2code`. No upstream name may appear in plain text anywhere in this repo.
- Keep plan2code's ticket-free `commit-msg.mjs` (`<subject>`, `AI Assisted`) in every `/sync-repo`: upstream's ticket-from-branch rule was ported by mistake once and removed in v2.6.0.
- When a new first-run dialog is added to the web console, set its seen flag in `scripts/capture-screenshots.mjs`'s `looks.json` too: the Welcome dialog once covered the regenerated dashboard screenshots until `welcomeSeen: true` was added.
+25
View File
@@ -2,6 +2,31 @@
All notable changes to Plan2Code will be documented in this file.
## v2.6.0
### ✨ Added
- **web-console**: the breakdown question's "Anything else about this breakdown?" field has a **No changes** button. One click fills the box with "no changes", so you no longer type it. The old "(type 'no changes' if none)" hint is gone from the label.
- **git-commit**: a new `/plan2code-git-commit` skill and dashboard card. It reads what changed, drafts the commit message for your approval, offers a new branch first on the default branch, suggests splitting work that is really two jobs, and asks before every commit and push (never a force-push). Outside a git repository it offers to start one.
- **changelog**: a new `/plan2code-changelog` skill and dashboard card, just left of Git commit. It reads the default branch's latest version, classifies the branch's work and picks the version. When the branch already owns a version that is not released and not on another branch, it adds to that entry instead of starting a new one. It compares the branch with the newest entry, suggests the entries that are missing for you to edit, keeps `package.json` aligned, and offers to run Git commit next. The facts come from `changelog-state.mjs`, with tests in `scripts/test-script-changelog.mjs`.
- **web-console**: the Git commit card counts the files waiting ("3 files to commit") and greys out on a clean tree, from a bounded `git status` the scan runs when the dashboard opens. If git cannot answer, the card stays clickable.
- **web-console**: the Commit this? question in Git commit has a collapsed **Show the N files** table of every path and its state, so "15 files" can be read before you say yes.
- **web-console**: a finished quick task or phase build gets a **Commit it now** button beside the printed git command. It starts Git commit in the same session, as if you had clicked its dashboard card.
- **web-console**: the dashboard scan reports `isGit`, found from the filesystem without spawning git (linked worktrees count). The Git commit card stays clickable outside a repository and says "Not a git repository yet: it offers to start one". The skill has its own Planny pose and a Help entry.
- **installer**: after an install it prints getting-started steps: how to start Plan2Code from the project you want to work in, and what to do if no agent CLI is installed yet.
- **launcher**: the `plan2code` command can start Codex as well as the other agent CLIs. The Codex launch line follows Codex's documentation and has not been tried by hand.
- **launcher**: when no agent CLI is installed, `plan2code` now explains how to get one and how to run the skill from it, instead of printing one line and exiting.
- **docs**: the README, quick reference, docs site and package READMEs open with a "Before you start" block: Node.js 18+ is needed, start Plan2Code from your project, and the ways in. `scripts/test-getting-started.mjs` keeps them in step.
- **web-console**: Help's "When something looks stuck" tab is now second, opens with a "Check this first" callout about a permission prompt waiting in the terminal, and lists four symptoms with a likely cause and what to do. The quiet and Not running status lines carry a "What to check" button that opens it.
- **web-console**: every finished and paused screen shows a "Before you close this" panel: the tab is safe to close, why to restart the agent or start a new session, and the two ways to carry on.
### 🔧 Changed
- **installer**: the menu is now Install, Uninstall, Advanced and Quit. The former Custom choices live under Advanced.
- **web-console**: Subagents is now on by default for the skills that offer it, until you turn it off for a project and skill. A saved Off is kept.
- **commits**: every commit Plan2Code suggests is now `<subject>`, a blank line, then `AI Assisted`. `commit-msg.mjs` no longer reads a ticket from the branch name and rejects `--ticket`.
- **build**: `skills/` is no longer tracked. It is gitignored build output, rebuilt by the installer and `npm run build:skills`, as upstream does. `npm test` now runs `install.js --build-skills` instead of `--verify-skills`, so it fails on a broken source entry rather than on drift. `--verify-skills` stays as a diagnostic.
## v2.5.1
### ✨ Added
+26 -17
View File
@@ -1,13 +1,20 @@
# 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 or Devin on the dashboard (`--cli claude` / `--cli devin` to choose) |
| Inside any agent | `/plan2code` | Opens the dashboard: a card for every skill, launched on the same page |
| From your project (shell) | `plan2code` | Opens Claude Code, Devin or Codex on the dashboard (`--cli claude` / `devin` / `codex` to choose) |
| Inside any agent | `/plan2code` (`$plan2code` in Codex) | Opens the dashboard: a card for every skill, launched on the same page |
| Install / update | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command; re-run it to update |
| Straight into a skill | `/plan2code-1-plan --web` (any step) | Skips the "web console or terminal?" question and opens the page |
@@ -17,21 +24,23 @@ Pick a skill on the dashboard and the same page becomes that session. Details: [
Every command below is what a dashboard card runs. Typed on its own, each one asks "web console or terminal?" first.
| Step | Command | Input | Output |
| -------- | ------------------------------- | --------------- | --------------------------------------------------------------------------------------- |
| — | /plan2code | None | Web console dashboard — a menu of every skill below, launched on the page |
| Init | /plan2code-init | None | AGENTS.md file |
| Update | /plan2code-init-update | AGENTS.md | Updated AGENTS.md |
| 0 | /plan2code-0-pathfinder | A foggy idea | pathfinder/map.md *or* GitHub Issues + PLAN-DRAFT-<date>.md |
| quick | /plan2code-quick-task | Requirements | A short plan, then the change built (standalone, not a pipeline step) |
| 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/`) |
| Step | Command | Input | Output |
| ---------- | ----------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------- |
| — | /plan2code | None | Web console dashboard — a menu of every skill below, launched on the page |
| Init | /plan2code-init | None | AGENTS.md file |
| Update | /plan2code-init-update | AGENTS.md | Updated AGENTS.md |
| 0 | /plan2code-0-pathfinder | A foggy idea | pathfinder/map.md *or* GitHub Issues + PLAN-DRAFT-<date>.md |
| quick | /plan2code-quick-task | Requirements | A short plan, then the change built (standalone, not a pipeline step) |
| 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/`) |
| changelog | /plan2code-changelog | Your branch | `CHANGELOG.md` entries and the `package.json` version, from the default branch's latest version |
| git-commit | /plan2code-git-commit | Your changes | A commit (`<subject>` / `AI Assisted`): suggested splits, a branch offer on the default branch, optional push |
**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.
+24 -15
View File
@@ -13,7 +13,7 @@ the next engineer all start from the same specs.
One command opens it, every step is a card, and the terminal is always there if you prefer it.
Version 2.5.1 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
Version 2.6.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
---
@@ -30,8 +30,14 @@ The dashboard, in a project halfway through a build. It suggests the next step f
## Install and start
Requires [Node.js](https://nodejs.org/) 18 or later and network access — installation runs through
the [skills CLI](https://skills.sh). To update, re-run the install command.
### 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.
Installation needs network access and runs through the [skills CLI](https://skills.sh). To update, re-run the install command.
```bash
npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git
@@ -47,33 +53,32 @@ The installer opens this menu (cloning and running `node install.js`, below, ope
╔═════════════════════════════════════════════════════════╗
║ INSTALL PLAN2CODE ║
╠═════════════════════════════════════════════════════════╣
║ I. INSTALL Install Plan2Code skills everywhere ║
║ A. ALL Install Plan2Code + dev tools ║
║ U. UNINSTALL Remove Plan2Code skills and dev tools ║
║ C. CUSTOM Advanced options ║
║ I. INSTALL Install skills + the plan2code command ║
║ U. UNINSTALL Remove everything Plan2Code installed ║
║ A. ADVANCED Project install, dev tools, and more ║
║ Q. QUIT Exit ║
╚═════════════════════════════════════════════════════════╝
```
### Start
1. In any project, run `plan2code`. It starts Claude Code or Devin on the dashboard, and the
dashboard opens in your browser.
1. `cd` into your project, then run `plan2code`. It starts Claude Code, Devin or Codex on the dashboard,
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
need it.
3. Pick a card.
Already inside your agent? Type `/plan2code` instead.
Already inside your agent? Type `/plan2code` instead (`$plan2code` in Codex).
<details>
<summary>About the plan2code command</summary>
The installer adds `plan2code` as a global command (Custom `C` → `D` adds just the command). Run it from any project and the Plan2Code
dashboard opens right there, in **Claude Code** or **Devin**. With both installed it asks which and
remembers your pick; `plan2code --cli claude` or `--cli devin` skips the question, and `--model <name>`
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
remembers your pick; `plan2code --cli claude`, `--cli devin` or `--cli codex` skips the question, and `--model <name>`
chooses the model. It works in cmd, PowerShell, Git Bash, macOS and Linux shells, and needs the
Claude Code or Devin CLI on your `PATH`. It starts the agent with permission prompts off
(`--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass` in Devin); run
Claude Code, Devin or Codex CLI on your `PATH`. It starts the agent with permission prompts off
(`--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass` in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex); run
`claude /plan2code` yourself if you want prompts. The installer then offers a desktop shortcut (answer `y`),
which opens a folder picker first. Uninstalling (`U`) removes both.
</details>
@@ -183,6 +188,8 @@ The dashboard's cards, and when each one lights up for the spec you pick:
| Quick task | Too small for the full process? A quick plan, then it just builds it. | Always |
| Review | A second opinion on the changes. Problems ranked, and you pick what gets fixed. | Always |
| Handoff | Pack this conversation into a document a fresh session can pick up cold. | Always |
| Changelog | Checks the CHANGELOG version against the main branch and suggests entries for what is new. | Always |
| Git commit | Commits your changes with a clear message, suggests a split when it is really two jobs, and offers to push. | Always (offers to start a repository outside one) |
---
@@ -349,6 +356,8 @@ console or the terminal; add `--web` to skip the question and go straight to the
| `/plan2code-quick-task` | A small change that doesn't warrant the full sequence |
| `/plan2code-1b-revise-plan` | Requirements moved mid-build. Revise the specs, not the code |
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from |
| `/plan2code-changelog` | Check the CHANGELOG version against the default branch, suggest entries for new work you can edit, keep `package.json` aligned, then offer Git commit |
| `/plan2code-git-commit` | Commit with a clear message, suggested splits, a branch offer on the default branch, and an optional push |
---
+24 -3
View File
@@ -112,6 +112,11 @@ h3 { font-size: 1.45rem; margin: 8px 0; }
.copy .tick { display: none; }
.copy.-done .clip { display: none; }
.copy.-done .tick { display: block; }
.before { margin: 0 auto 20px; max-width: 640px; text-align: left; background: var(--panel); border: 1px solid var(--rule-2); border-radius: var(--radius); padding: 14px 18px; font-size: 15px; }
.before h3 { font-size: 1.05rem; margin: 0 0 8px; }
.before ul { margin: 0; padding-left: 20px; color: var(--ink-2); }
.before li { margin: 4px 0; }
.before strong { color: var(--ink); }
.then { margin: 12px 0 0; color: var(--ink-2); font-size: 15px; }
/* Hero: centered headline, then the dashboard at full width. */
@@ -215,6 +220,14 @@ footer a { color: inherit; }
</svg>
<h1 id="hero-title">Plan and build with your AI agent, on one page.</h1>
<p class="lede">Plan2Code asks the questions, drafts the plan and builds it one phase at a time. You answer and approve in your browser, and the specs land in your repo.</p>
<div class="before" id="before-start">
<h3>Before you start</h3>
<ul>
<li><strong>Node.js 18 or newer.</strong> Check with <code>node --version</code>. No Node? Get it from <a href="https://nodejs.org/">nodejs.org</a> (the LTS download), or run <code>winget install OpenJS.NodeJS.LTS</code> on Windows, <code>brew install node</code> on macOS, or use <code>nvm</code> on Linux. Then open a new terminal.</li>
<li><strong>Start from your project.</strong> Open your terminal in the project you want to work on (<code>cd</code> into it) before you run anything. Plan2Code works on the folder you start it in.</li>
<li><strong>No agent yet?</strong> Install Claude Code, Codex or Devin first.</li>
</ul>
</div>
<div class="cmd">
<pre id="install-cmd"><span aria-hidden="true">$ </span>npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git</pre>
<button class="copy" type="button" aria-label="Copy the install command">
@@ -223,7 +236,7 @@ footer a { color: inherit; }
<span class="label">Copy</span>
</button>
</div>
<p class="then">then run <code>plan2code</code> in any project.</p>
<p class="then">then, from your project, run <code>plan2code</code> (Claude Code, Devin or Codex), or type <code>/plan2code</code> in your agent (<code>$plan2code</code> in Codex).</p>
</div>
</section>
@@ -356,7 +369,15 @@ footer a { color: inherit; }
<section class="s alt close" id="install" aria-labelledby="install-title">
<div class="narrow">
<h2 id="install-title">Install</h2>
<p class="muted">Needs Node.js 18 or later. Run it again any time to update.</p>
<p class="muted">Run it again any time to update.</p>
<div class="before" id="before-start-2">
<h3>Before you start</h3>
<ul>
<li><strong>Node.js 18 or newer.</strong> Check with <code>node --version</code>. No Node? Get it from <a href="https://nodejs.org/">nodejs.org</a> (the LTS download), or run <code>winget install OpenJS.NodeJS.LTS</code> on Windows, <code>brew install node</code> on macOS, or use <code>nvm</code> on Linux. Then open a new terminal.</li>
<li><strong>Start from your project.</strong> Open your terminal in the project you want to work on (<code>cd</code> into it) before you run anything. Plan2Code works on the folder you start it in.</li>
<li><strong>No agent yet?</strong> Install Claude Code, Codex or Devin first.</li>
</ul>
</div>
<div class="cmd">
<pre><span aria-hidden="true">$ </span>npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git</pre>
<button class="copy" type="button" aria-label="Copy the install command">
@@ -365,7 +386,7 @@ footer a { color: inherit; }
<span class="label">Copy</span>
</button>
</div>
<p class="then">then run <code>plan2code</code> in any project.</p>
<p class="then">then, from your project, run <code>plan2code</code> (Claude Code, Devin or Codex), or type <code>/plan2code</code> in your agent (<code>$plan2code</code> in Codex).</p>
</div>
</section>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 KiB

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

After

Width:  |  Height:  |  Size: 100 KiB

+108 -53
View File
@@ -12,7 +12,7 @@
*
* DESCRIPTION:
* Install Plan2Code skills globally or into the current project via skills.sh.
* Builds the committed skills/ artifact from source prompts in src/.
* Builds the (gitignored) skills/ artifact from source prompts in src/.
* Supports non-interactive --build-skills and --verify-skills maintenance hooks.
*/
@@ -103,8 +103,8 @@ const MASCOT = {
],
};
// Generated skills directory: the committed, canonical Agent Skills build of src/.
// `npm run build:skills` regenerates it and `npm test` (`--verify-skills`) fails on drift.
// Generated skills directory: the gitignored Agent Skills build of src/.
// The installer and `npm run build:skills` regenerate it; `--verify-skills` diffs a stale tree.
// `skills add` consumes this directory; nothing else is platform-specific any more.
const SKILLS_DIR_NAME = 'skills';
const SKILLS_DIR = path.join(__dirname, SKILLS_DIR_NAME);
@@ -262,6 +262,26 @@ const SOURCE_PROMPTS = [
isUtility: true,
scripts: ['specs.mjs'],
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-changelog.md',
stepNumber: 'changelog',
name: 'changelog',
displayName: 'Changelog Mode',
description: 'Check the CHANGELOG version against the default branch, suggest entries for new work, keep package.json aligned',
isUtility: true,
scripts: [],
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
},
{
source: 'plan2code-git-commit.md',
stepNumber: 'git-commit',
name: 'git-commit',
displayName: 'Git Commit Mode',
description: 'Commit changes with a clear message, suggest splits, offer a branch and a push',
isUtility: true,
scripts: ['commit-msg.mjs'],
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
}
];
@@ -288,6 +308,8 @@ function generateStepLabel(prompt) {
if (prompt.stepNumber === 'update') return 'Update';
if (prompt.stepNumber === 'review') return 'Review';
if (prompt.stepNumber === 'handoff') return 'Handoff';
if (prompt.stepNumber === 'git-commit') return 'Git Commit';
if (prompt.stepNumber === 'changelog') return 'Changelog';
if (prompt.stepNumber === 'quick') return 'Quick Task';
return `Step ${prompt.stepNumber}`;
}
@@ -728,7 +750,7 @@ function verifySkillsSync() {
if (problems.length > 0) {
console.error(`${SKILLS_DIR_NAME}/ is out of sync with src/:\n`);
for (const problem of problems) console.error(` ${problem}`);
console.error(`\n${problems.length} problem(s). Run 'npm run build:skills' and commit the result.`);
console.error(`\n${problems.length} problem(s). Run 'npm run build:skills' to regenerate it.`);
return false;
}
console.log(`${SKILLS_DIR_NAME}/ matches src/ — ${expected.size} file(s) across ${SOURCE_PROMPTS.length} skill(s) ✓`);
@@ -954,12 +976,11 @@ async function install() {
return 1;
}
// Point at the dashboard first: the `plan2code` command when it installed, the skill otherwise.
const dashboardWhere = launcherFailed ? 'Open the dashboard in your agent:' : 'Open the dashboard from any project:';
const dashboardCommand = launcherFailed ? '/plan2code' : LAUNCHER_COMMAND;
// The steps come first: where to start, the ways in, and what to do without an agent.
printGettingStarted({ commandInstalled: !launcherFailed });
console.log(`${COLORS.GREEN} ╭───╮${COLORS.RESET} ${COLORS.BRIGHT}All done! Happy coding!${COLORS.RESET}`);
console.log(`${COLORS.GREEN} ╲│ ${COLORS.CYAN}★${COLORS.GREEN} │╱${COLORS.RESET} ${COLORS.BRIGHT}${dashboardWhere}${COLORS.RESET}`);
console.log(`${COLORS.GREEN} │ ${COLORS.BRIGHT}◡${COLORS.GREEN} │${COLORS.RESET} ${COLORS.BRIGHT}${COLORS.CYAN}${dashboardCommand}${COLORS.RESET}`);
console.log(`${COLORS.GREEN} ╲│ ${COLORS.CYAN}★${COLORS.GREEN} │╱${COLORS.RESET}`);
console.log(`${COLORS.GREEN} │ ${COLORS.BRIGHT}◡${COLORS.GREEN} │${COLORS.RESET}`);
console.log(`${COLORS.GREEN} ╰┬─┬╯${COLORS.RESET} ${COLORS.DIM}Docs:${COLORS.RESET} ${COLORS.BRIGHT}https://github.com/jparkerweb/plan2code${COLORS.RESET}`);
console.log('');
console.log(`${COLORS.DIM} Update later with:${COLORS.RESET} ${COLORS.CYAN}npx skills update -g${COLORS.RESET}`);
@@ -968,6 +989,42 @@ async function install() {
return launcherFailed ? 1 : 0;
}
/**
* Print what to do after installing: where to start, the ways in, and what to do when no AI
* agent is installed. Used at the end of every install route so they all end the same way.
*/
function printGettingStarted({ commandInstalled }) {
const agents = ['claude', 'devin', 'codex'].filter((name) => isCommandOnPath(name));
const line = (text = '') => console.log(` ${text}`);
console.log(`${COLORS.CYAN}╔═══════════════════════════════════════════════════════════════════════════╗${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}HOW TO USE PLAN2CODE${COLORS.RESET}`, 76) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(`${COLORS.CYAN}╚═══════════════════════════════════════════════════════════════════════════╝${COLORS.RESET}`);
console.log('');
line(`${COLORS.BRIGHT}1. Open a terminal IN the project you want to work on${COLORS.RESET}`);
line(' Plan2Code works on the folder you start it in.');
line(` ${COLORS.CYAN}cd path/to/your-project${COLORS.RESET}`);
console.log('');
line(`${COLORS.BRIGHT}2. Start Plan2Code${COLORS.RESET}`);
if (commandInstalled) {
line(` ${COLORS.CYAN}${LAUNCHER_COMMAND}${COLORS.RESET} opens your AI agent on the Plan2Code dashboard`);
line(` or, inside the agent itself: ${COLORS.CYAN}/plan2code${COLORS.RESET} (Claude Code, Devin) ${COLORS.CYAN}$plan2code${COLORS.RESET} (Codex)`);
} else {
line(` Inside your AI agent, type ${COLORS.CYAN}/plan2code${COLORS.RESET} (Claude Code, Devin) or ${COLORS.CYAN}$plan2code${COLORS.RESET} (Codex)`);
}
console.log('');
line(`${COLORS.BRIGHT}3. Pick a card on the page that opens in your browser${COLORS.RESET}`);
line(' Any AI agent that reads Agent Skills can run Plan2Code the same way.');
console.log('');
if (agents.length === 0) {
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING} NO AI AGENT FOUND ON THIS COMPUTER${COLORS.RESET}`);
line('Plan2Code runs inside an AI coding agent. Install one, open a new terminal, then follow the steps above:');
line(` Claude Code ${COLORS.CYAN}npm i -g @anthropic-ai/claude-code${COLORS.RESET}`);
line(` Codex ${COLORS.CYAN}npm i -g @openai/codex${COLORS.RESET}`);
line(' Devin https://devin.ai');
console.log('');
}
}
// ============================================================================
// UNINSTALLATION
// ============================================================================
@@ -1087,47 +1144,30 @@ function runInteractive() {
console.log(`${COLORS.CYAN}╔═════════════════════════════════════════════════════════╗${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}INSTALL PLAN2CODE${COLORS.RESET}`, 58) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(`${COLORS.CYAN}╠═════════════════════════════════════════════════════════╣${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}I.${COLORS.RESET} ${COLORS.GREEN}INSTALL${COLORS.RESET} Install Plan2Code skills everywhere`, 58) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}A.${COLORS.RESET} ${COLORS.MAGENTA}ALL${COLORS.RESET} Install Plan2Code + dev tools`, 58) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}U.${COLORS.RESET} ${COLORS.RED}UNINSTALL${COLORS.RESET} Remove Plan2Code skills and dev tools`, 58) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}C.${COLORS.RESET} ${COLORS.BLUE}CUSTOM${COLORS.RESET} Advanced options`, 58) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}I.${COLORS.RESET} ${COLORS.GREEN}INSTALL${COLORS.RESET} Install skills + the plan2code command`, 58) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}U.${COLORS.RESET} ${COLORS.RED}UNINSTALL${COLORS.RESET} Remove everything Plan2Code installed`, 58) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}A.${COLORS.RESET} ${COLORS.BLUE}ADVANCED${COLORS.RESET} Project install, dev tools, and more`, 58) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}Q.${COLORS.RESET} ${COLORS.DIM}QUIT${COLORS.RESET} Exit`, 58) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(`${COLORS.CYAN}╚═════════════════════════════════════════════════════════╝${COLORS.RESET}`);
console.log('');
// Input prompt
console.log('');
const answer = await question(`${COLORS.CYAN}${SYMBOLS.SELECT} SELECT OPTION${COLORS.RESET} (I, A, U, C, Q) [I]: `);
const answer = await question(`${COLORS.CYAN}${SYMBOLS.SELECT} SELECT OPTION${COLORS.RESET} (I, U, A, Q) [I]: `);
const input = answer.trim().toUpperCase() || 'I';
// I path — skills only. The loop remains optional via A or Custom → O.
// I path: skills and the plan2code command. The dev tools stay optional under Advanced.
if (input === 'I') {
rl.close();
process.exit(await install());
}
// A path — Install Everything (skills + loop + bot + metrics + Claude status line)
if (input === 'A') {
rl.close();
const loopResult = installPlan2CodeLoop();
console.log('');
const botResult = installPlan2CodeBot();
console.log('');
const metricsResult = installPlan2CodeMetrics();
console.log('');
const statusLineResult = await installStatusLine();
console.log('');
const installResult = await install();
const exitCode = loopResult !== 0 ? loopResult : botResult !== 0 ? botResult : metricsResult !== 0 ? metricsResult : statusLineResult !== 0 ? statusLineResult : installResult;
process.exit(exitCode);
}
// U path — Uninstall All
if (input === 'U') {
console.log('');
console.log(`${COLORS.RED} ╭───╮${COLORS.RESET}`);
console.log(`${COLORS.RED} ╲│ ${COLORS.YELLOW}★${COLORS.RED} │╱${COLORS.RESET} ${COLORS.YELLOW}!${COLORS.RESET}`);
console.log(`${COLORS.RED} │ ${COLORS.YELLOW}~${COLORS.RED} │${COLORS.RESET} ${COLORS.DIM}Are you sure? This will remove Plan2Code from all platforms.${COLORS.RESET}`);
console.log(`${COLORS.RED} │ ${COLORS.YELLOW}~${COLORS.RED} │${COLORS.RESET} ${COLORS.DIM}Are you sure? This removes everything Plan2Code installed: skills, the plan2code command and any dev tools.${COLORS.RESET}`);
console.log(`${COLORS.RED} ╰┬─┬╯${COLORS.RESET}`);
console.log('');
const confirmAnswer = await question(`${COLORS.RED}${SYMBOLS.SELECT} CONFIRM UNINSTALL${COLORS.RESET} (Y/N) [N]: `);
@@ -1150,11 +1190,11 @@ function runInteractive() {
}
}
// C path — CUSTOM sub-menu
if (input === 'C') {
// A path: ADVANCED sub-menu
if (input === 'A') {
console.log('');
console.log(`${COLORS.CYAN}╔════════════════════════════════════════════════════════════════╗${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}CUSTOM OPTIONS${COLORS.RESET}`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}ADVANCED OPTIONS${COLORS.RESET}`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(`${COLORS.CYAN}╠════════════════════════════════════════════════════════════════╣${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}L.${COLORS.RESET} ${COLORS.BLUE}LOCAL${COLORS.RESET} Install skills into the current project only`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}O.${COLORS.RESET} ${COLORS.GREEN}LOOP CLI${COLORS.RESET} Install plan2code-loop CLI only`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
@@ -1162,53 +1202,70 @@ function runInteractive() {
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}S.${COLORS.RESET} ${COLORS.GREEN}STATUS${COLORS.RESET} Install Claude Code status line`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}B.${COLORS.RESET} ${COLORS.GREEN}BOT${COLORS.RESET} Install plan2code-bot CLI only`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}D.${COLORS.RESET} ${COLORS.GREEN}P2C CMD${COLORS.RESET} Install the plan2code command only`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}E.${COLORS.RESET} ${COLORS.MAGENTA}EVERYTHING${COLORS.RESET} Install Plan2Code + all dev tools`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}║${COLORS.RESET} ${COLORS.BRIGHT}Q.${COLORS.RESET} ${COLORS.DIM}BACK${COLORS.RESET} Return to main menu`, 65) + `${COLORS.CYAN}║${COLORS.RESET}`);
console.log(`${COLORS.CYAN}╚════════════════════════════════════════════════════════════════╝${COLORS.RESET}`);
console.log('');
const customAnswer = await question(`${COLORS.CYAN}${SYMBOLS.SELECT} SELECT OPTION${COLORS.RESET} (L, O, M, S, B, D, Q) [Q]: `);
const customAnswer = await question(`${COLORS.CYAN}${SYMBOLS.SELECT} SELECT OPTION${COLORS.RESET} (L, O, M, S, B, D, E, Q) [Q]: `);
const customInput = customAnswer.trim().toUpperCase() || 'Q';
// C > L — install skills into the current project
// A > E: install everything (skills + loop + bot + metrics + Claude status line)
if (customInput === 'E') {
rl.close();
const loopResult = installPlan2CodeLoop();
console.log('');
const botResult = installPlan2CodeBot();
console.log('');
const metricsResult = installPlan2CodeMetrics();
console.log('');
const statusLineResult = await installStatusLine();
console.log('');
const installResult = await install();
const exitCode = loopResult !== 0 ? loopResult : botResult !== 0 ? botResult : metricsResult !== 0 ? metricsResult : statusLineResult !== 0 ? statusLineResult : installResult;
process.exit(exitCode);
}
// A > L: install skills into the current project
if (customInput === 'L') {
rl.close();
process.exit(installProjectSkills());
}
// C > O — install loop CLI only
// A > O: install loop CLI only
if (customInput === 'O') {
rl.close();
const result = installPlan2CodeLoop();
process.exit(result);
}
// C > M — install metrics CLI only
// A > M: install metrics CLI only
if (customInput === 'M') {
rl.close();
const result = installPlan2CodeMetrics();
process.exit(result);
}
// C > S — install status line
// A > S: install status line
if (customInput === 'S') {
rl.close();
const result = await installStatusLine();
process.exit(result);
}
// C > B — install bot CLI only
// A > B: install bot CLI only
if (customInput === 'B') {
rl.close();
const result = installPlan2CodeBot();
process.exit(result);
}
// C > D — install the global `plan2code` command (opens the dashboard in Claude Code or Devin)
// A > D: install the global `plan2code` command (opens the dashboard in Claude Code, Devin or Codex)
if (customInput === 'D') {
rl.close();
process.exit(await installLauncher());
}
// C > Q — back to main menu
// A > Q: back to main menu
return main();
}
@@ -1220,7 +1277,7 @@ function runInteractive() {
}
// Invalid input — loop back
console.log(`\n${COLORS.RED}${SYMBOLS.ERROR} Invalid option. Please choose I, A, U, C, or Q.${COLORS.RESET}\n`);
console.log(`\n${COLORS.RED}${SYMBOLS.ERROR} Invalid option. Please choose I, U, A, or Q.${COLORS.RESET}\n`);
return main();
}
@@ -2187,7 +2244,7 @@ function uninstallPlan2CodeBot() {
}
// ============================================================================
// PLAN2CODE COMMAND (global `plan2code` → dashboard in Claude Code or Devin)
// PLAN2CODE COMMAND (global `plan2code` → dashboard in Claude Code, Devin or Codex)
// ============================================================================
/**
@@ -2422,7 +2479,7 @@ function installDesktopShortcut(binDir, file) {
P2C_FILE: file,
P2C_SCRIPT: `${shim}.ps1`,
P2C_ARGS: LAUNCHER_PICK_FOLDER_FLAG,
P2C_DESCRIPTION: 'Open the Plan2Code dashboard in Claude Code or Devin',
P2C_DESCRIPTION: 'Open the Plan2Code dashboard in Claude Code, Devin or Codex',
P2C_ICON: icon,
}
);
@@ -2442,7 +2499,7 @@ function installDesktopShortcut(binDir, file) {
`# ${LAUNCHER_MARKER}`,
'Type=Application',
`Name=${SHORTCUT_NAME}`,
'Comment=Open the Plan2Code dashboard in Claude Code or Devin',
'Comment=Open the Plan2Code dashboard in Claude Code, Devin or Codex',
`Exec="${shim}" ${LAUNCHER_PICK_FOLDER_FLAG}`,
...(icon ? [`Icon=${icon}`] : []),
'Terminal=true',
@@ -2537,14 +2594,12 @@ async function installLauncher({ quiet = false } = {}) {
if (!isDirOnPath(binDir)) {
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} ${binDir} is not on your PATH — add it to use ${COLORS.BRIGHT}${LAUNCHER_COMMAND}${COLORS.RESET} from any directory`);
}
if (!isCommandOnPath('claude') && !isCommandOnPath('devin')) {
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} Neither the ${COLORS.BRIGHT}claude${COLORS.RESET} nor the ${COLORS.BRIGHT}devin${COLORS.RESET} CLI is on your PATH — install one before running ${COLORS.BRIGHT}${LAUNCHER_COMMAND}${COLORS.RESET}`);
}
// The shortcut is a convenience on top of the command, so a failure here only warns.
await offerDesktopShortcut(binDir);
console.log(` ${COLORS.DIM}Run '${LAUNCHER_COMMAND}' in any project to open the Plan2Code dashboard in Claude Code or Devin${COLORS.RESET}`);
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} It starts the agent with permission prompts off (${COLORS.CYAN}--permission-mode bypassPermissions${COLORS.RESET} in Claude Code, ${COLORS.CYAN}bypass${COLORS.RESET} in Devin). Run ${COLORS.CYAN}claude /plan2code${COLORS.RESET} yourself if you want prompts.`);
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} The ${LAUNCHER_COMMAND} command starts the agent with permission prompts off (${COLORS.CYAN}--permission-mode bypassPermissions${COLORS.RESET} in Claude Code, ${COLORS.CYAN}bypass${COLORS.RESET} in Devin, ${COLORS.CYAN}--dangerously-bypass-approvals-and-sandbox${COLORS.RESET} in Codex). Run ${COLORS.CYAN}claude /plan2code${COLORS.RESET} yourself if you want prompts.`);
console.log('');
// Inside install() the final summary prints the steps once, after everything else.
if (!quiet) printGettingStarted({ commandInstalled: true });
return 0;
}
@@ -2593,7 +2648,7 @@ function uninstallLauncher() {
// MAIN
// ============================================================================
// Non-interactive build hooks for the committed skills/ artifact.
// Non-interactive build hooks for the generated skills/ artifact.
const argv = process.argv.slice(2);
if (argv.includes('--build-skills')) {
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "plan2code",
"version": "2.5.1",
"version": "2.6.0",
"private": true,
"bin": {
"plan2code-install": "./install.js"
@@ -8,7 +8,7 @@
"scripts": {
"prepare": "husky",
"build:skills": "node install.js --build-skills",
"test": "node scripts/validate-char-count.js && node install.js --verify-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs"
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-getting-started.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs scripts/test-script-git-commit.mjs scripts/test-script-changelog.mjs"
},
"devDependencies": {
"husky": "^9.0.0"
+1 -1
View File
@@ -13,7 +13,7 @@ From the plan2code root:
```bash
node install.js
# Select C > B to install bot only, or I to install everything
# Select A > B to install the bot only, or A > E to install everything
```
Or manually:
+2 -2
View File
@@ -6,8 +6,8 @@ Recursive self-improvement toolchain for plan2code contributors. Collects metric
```bash
# Install (one-time, from the plan2code root)
node install.js # → "A" (Install All + dev tools) includes metrics
# → or "M" (Metrics only) under the CUSTOM sub-menu
node install.js # → "A" then "E" (Everything) includes metrics
# → or "M" (Metrics only) under the ADVANCED sub-menu
# After finishing any project spec (steps 1-4):
cd your-project
+17 -5
View File
@@ -13,7 +13,7 @@
// The shots use the console's Ocean highlight rather than its default orange:
// it is the console's nearest to the Plan2Code blue the site and README use.
//
// Shots: dashboard, question, doc, build, signoff, finish, ask.
// Shots: dashboard, dashboard-utilities, question, doc, build, signoff, finish, ask.
//
// Needs puppeteer-core (`npm i --no-save puppeteer-core`, never added to
// package.json) and a local Chrome or Edge. Writes nothing outside its temp
@@ -53,6 +53,14 @@ const SHOTS = {
scrollTo: ".dash-toggle",
mustShow: ".dash-card:has(.pill.suggested)",
},
// The utility cards sit even lower: scroll until the Git commit card is the
// last row in frame ("cmd:" picks a card by its command).
"dashboard-utilities": {
workflow: "dashboard",
posts: ["dashboard"],
scrollTo: "cmd:/plan2code-git-commit",
mustShow: "cmd:/plan2code-git-commit",
},
question: { workflow: "plan", posts: ["question"] },
doc: { workflow: "plan", posts: ["doc"], tab: "What we've agreed" },
build: { workflow: "implement", posts: ["build"], tab: "Phase 3 tasks" },
@@ -201,11 +209,15 @@ async function openTab(page, label) {
async function scrollTo(page, { scrollTo: top, mustShow }) {
const problem = await page.evaluate(
(topSel, showSel) => {
const node = document.querySelector(topSel);
const find = (sel) =>
sel.startsWith("cmd:")
? [...document.querySelectorAll(".dash-card")].find((c) => c.querySelector(".dash-card-cmd")?.textContent.trim() === sel.slice(4))
: document.querySelector(sel);
const node = find(topSel);
if (!node) return `nothing matched ${topSel}, captured from the top`;
node.scrollIntoView({ block: "start", behavior: "instant" });
node.scrollIntoView({ block: topSel.startsWith("cmd:") ? "end" : "start", behavior: "instant" });
if (!showSel) return null;
const show = document.querySelector(showSel);
const show = find(showSel);
if (!show) return `nothing matched ${showSel}`;
const r = show.getBoundingClientRect();
return r.top >= 0 && r.bottom <= window.innerHeight ? null : `${showSel} is not wholly in view`;
@@ -329,7 +341,7 @@ async function main() {
// A saved role keeps the dashboard's "pick your role" banner out of shot,
// and the Ocean highlight is the console's nearest to the Plan2Code blue
// the landing page uses.
fs.writeFileSync(path.join(HOME, "looks.json"), JSON.stringify({ looks: { role: "engineer", accent: "ocean" } }));
fs.writeFileSync(path.join(HOME, "looks.json"), JSON.stringify({ looks: { role: "engineer", accent: "ocean", welcomeSeen: true } }));
browser = await puppeteer.launch({
executablePath: browserPath,
headless: true,
+46
View File
@@ -0,0 +1,46 @@
// Keeps the "Before you start" guidance identical in meaning across the newcomer docs.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const DOCS = ['README.md', 'docs/index.html', 'QUICK-REFERENCE.md'];
const EM_DASH = String.fromCharCode(0x2014);
function read(file) {
return readFileSync(join(ROOT, file), 'utf8');
}
// The first "Before you start" block: from its heading to the next heading (Markdown)
// or the end of its container (HTML).
function blockOf(file) {
const text = read(file);
const start = text.search(/^#{2,3} Before you start$|<h3>Before you start<\/h3>/m);
assert.ok(start >= 0, `${file} has no "Before you start" block`);
const rest = text.slice(start);
const body = rest.indexOf('\n') + 1;
const next = file.endsWith('.html') ? rest.indexOf('</div>') : rest.slice(body).search(/^#{1,3} /m);
const end = file.endsWith('.html') ? next : next < 0 ? -1 : body + next;
return end > 0 ? rest.slice(0, end) : rest;
}
for (const file of DOCS) {
test(`${file} tells a newcomer how to get started`, () => {
const text = read(file);
const block = blockOf(file);
for (const needle of ['Node.js 18', 'node --version', 'nodejs.org', '/plan2code', '$plan2code']) {
assert.ok(text.includes(needle), `${file} is missing "${needle}"`);
}
assert.match(block, /project you want to (work on|work in)/, `${file} does not say to start from your project`);
assert.ok(!block.includes(EM_DASH), `${file} has an em dash in its "Before you start" block`);
});
test(`${file} puts the guidance before the install command`, () => {
const text = read(file);
const guide = text.indexOf('Before you start');
const install = text.indexOf('npx --allow-git');
assert.ok(guide >= 0 && install >= 0 && guide < install, `${file}: "Before you start" must come before the npx line`);
});
}
+30 -3
View File
@@ -77,6 +77,29 @@ test("launcher: Devin keeps its args ahead of the -- and the prompt", (t) => {
assert.deepEqual(box.argsOf("devin"), ["--permission-mode", "bypass", "--verbose", "--", "/plan2code"]);
});
test("launcher: Codex gets the bypass flag, the forwarded args, then the $plan2code prompt", (t) => {
const box = sandbox(["codex"]);
t.after(box.cleanup);
const result = box.run(["--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("codex"), ["--dangerously-bypass-approvals-and-sandbox", "--verbose", "$plan2code"]);
});
test("launcher: --cli codex picks Codex when it is installed beside another CLI", (t) => {
const box = sandbox(["claude", "codex"]);
t.after(box.cleanup);
const result = box.run(["--cli", "codex"]);
assert.equal(result.status, 0, result.stderr);
assert.equal(box.argsOf("claude"), null);
assert.ok(box.argsOf("codex"));
});
test("launcher: the shipped models.json lists every CLI, and every entry has an id and a label", () => {
const shipped = JSON.parse(fs.readFileSync(path.join(path.dirname(LAUNCHER), "models.json"), "utf8"));
assert.ok(Array.isArray(shipped.codex));
for (const { id, label } of shipped.codex) assert.ok(id && label);
});
test("launcher: a forwarded --model skips the model notice", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
@@ -119,11 +142,12 @@ test("launcher: an unknown --cli exits 2, a missing CLI 127, and nothing is star
const unknown = box.run(["--cli", "bogus"]);
assert.equal(unknown.status, 2);
assert.match(unknown.stderr, /--cli takes claude or devin, not "bogus"/);
assert.match(unknown.stderr, /--cli takes claude, devin, codex, not "bogus"/);
const missing = box.run(["--cli", "devin"]);
assert.equal(missing.status, 127);
assert.match(missing.stderr, /the `devin` CLI was not found/);
assert.ok(missing.stderr.includes("$plan2code"));
assert.equal(box.argsOf("claude"), null);
});
@@ -150,12 +174,15 @@ test("launcher: the shipped models.json is curated Devin at low/medium/high only
}
});
test("launcher: with neither CLI installed it exits 127 naming both", (t) => {
test("launcher: with no CLI installed it exits 127 and says how to run the skill from an agent", (t) => {
const box = sandbox([]);
t.after(box.cleanup);
const result = box.run([]);
assert.equal(result.status, 127);
assert.match(result.stderr, /neither `claude` nor `devin` was found/);
assert.match(result.stderr, /none of `claude`, `devin` or `codex` was found/);
assert.ok(result.stderr.includes("type /plan2code"));
assert.ok(result.stderr.includes("$plan2code (Codex)"));
assert.match(result.stderr, /cd into the project/);
});
test("launcher: a forwarded argument with a space and a cmd metacharacter arrives unchanged", (t) => {
+186
View File
@@ -0,0 +1,186 @@
// Tests for plan2code-changelog's scripts/changelog-state.mjs.
//
// See skill-script-helpers.mjs for how these run.
import { test } from "node:test";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { runScript, tmp, write, read, gitInit } from "./skill-script-helpers.mjs";
const S = (cwd, ...a) => runScript("plan2code-changelog", "changelog-state.mjs", a, { cwd });
const V = (version, body = "### ✨ Added\n\n- **x**: a thing.\n") => `## v${version}\n\n${body}\n`;
const LOG = (...entries) => `# Changelog\n\nAll notable changes.\n\n${entries.join("")}`;
// A repo whose main has CHANGELOG at `top`, plus the runner.
function repo(name, { changelog = LOG(V("1.0.0")), pkg = true } = {}) {
const dir = tmp(name);
const g = gitInit(dir, "main");
write(dir, "CHANGELOG.md", changelog);
if (pkg) write(dir, "package.json", `{\n "name": "x",\n "version": "1.0.0",\n "private": true\n}\n`);
write(dir, "a.txt", "a\n");
g("add", "-A");
g("commit", "-q", "-m", "init");
return { dir, g };
}
const commitAll = (g, msg) => {
g("add", "-A");
g("commit", "-q", "-m", msg);
};
test("changelog-state: not a repository and no CHANGELOG are exit 3", () => {
const plain = tmp("cl-plain");
const a = S(plain, "state");
assert.equal(a.code, 3);
assert.equal(a.json.error, "not-a-repo");
const { dir } = repo("cl-nolog", { changelog: "x" });
execFileSync("git", ["rm", "-q", "CHANGELOG.md"], { cwd: dir });
const b = S(dir, "state");
assert.equal(b.code, 3);
assert.equal(b.json.error, "no-changelog");
});
test("changelog-state: on the default branch there is no new entry and the version is the base's", () => {
const { dir } = repo("cl-main");
const r = S(dir, "state");
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.branch, "main");
assert.equal(r.json.onDefault, true);
assert.deepEqual([r.json.base.ref, r.json.base.version], ["main", "1.0.0"], "no origin: the local default branch is the base");
assert.equal(r.json.topIsNew, false);
});
test("changelog-state: a branch with no entry above main needs a new version, not an extension", () => {
const { dir, g } = repo("cl-noentry");
g("switch", "-q", "-c", "feature/x");
write(dir, "b.txt", "b\n");
commitAll(g, "add b");
const r = S(dir, "state");
assert.equal(r.json.base.version, "1.0.0");
assert.equal(r.json.topIsNew, false);
assert.equal(r.json.canExtend, false);
assert.equal(r.json.entryBump, "none");
assert.deepEqual(r.json.commits.map((c) => c.subject), ["add b"]);
assert.deepEqual(r.json.files, ["b.txt"]);
assert.equal(r.json.entry, "", "main's released entry is not this branch's to compare against");
});
test("changelog-state: an entry above main that nobody else has can be extended", () => {
const { dir, g } = repo("cl-extend");
g("switch", "-q", "-c", "feature/x");
write(dir, "CHANGELOG.md", LOG(V("1.1.0"), V("1.0.0")));
commitAll(g, "changelog 1.1.0");
write(dir, "b.txt", "b\n");
commitAll(g, "later work");
write(dir, "c.txt", "c\n");
const r = S(dir, "state");
assert.equal(r.json.branchTop.version, "1.1.0");
assert.equal(r.json.topIsNew, true);
assert.equal(r.json.entryBump, "minor");
assert.equal(r.json.released, false);
assert.deepEqual(r.json.takenBy, []);
assert.equal(r.json.canExtend, true);
// The gap is what came after the entry was last touched, plus the working tree.
assert.deepEqual(r.json.commits.map((c) => c.subject), ["later work"]);
assert.deepEqual(r.json.files, ["b.txt"]);
assert.deepEqual(r.json.uncommitted, ["c.txt"]);
assert.match(r.json.entry, /^## v1\.1\.0/);
assert.deepEqual(r.json.sectionHeadings, ["### ✨ Added"]);
});
test("changelog-state: a tagged version is released, and one on another branch is taken", () => {
const { dir, g } = repo("cl-spent");
g("switch", "-q", "-c", "feature/x");
write(dir, "CHANGELOG.md", LOG(V("1.1.0"), V("1.0.0")));
commitAll(g, "changelog 1.1.0");
g("switch", "-q", "-c", "feature/other");
write(dir, "o.txt", "o\n");
commitAll(g, "other work");
g("switch", "-q", "feature/x");
assert.deepEqual(S(dir, "state").json.takenBy, ["feature/other"], "a branch that already holds the version");
assert.equal(S(dir, "state").json.canExtend, false);
g("branch", "-D", "feature/other");
g("tag", "v1.1.0");
const r = S(dir, "state");
assert.equal(r.json.released, true);
assert.equal(r.json.canExtend, false);
});
test("changelog-state: a branch that is only part of this one's history is no claim", () => {
const { dir, g } = repo("cl-history");
g("switch", "-q", "-c", "feature/x");
write(dir, "CHANGELOG.md", LOG(V("1.1.0"), V("1.0.0")));
commitAll(g, "changelog 1.1.0");
g("branch", "behind-me");
write(dir, "b.txt", "b\n");
commitAll(g, "more");
assert.deepEqual(S(dir, "state").json.takenBy, []);
});
test("changelog-state: reads the heading style and package.json alignment", () => {
const log = `# Changelog\n\n## [2.0.0] - 2026-01-02\n\n### Fixed\n\n- y\n\n## [1.0.0] - 2025-12-01\n\n### Added\n\n- x\n`;
const { dir } = repo("cl-style", { changelog: log });
const r = S(dir, "state");
assert.equal(r.json.heading.style, "bracketed");
assert.equal(r.json.heading.dated, true);
assert.equal(r.json.heading.separator, "-");
assert.equal(r.json.package.version, "1.0.0");
assert.equal(r.json.package.matches, false, "package.json lags the CHANGELOG's 2.0.0");
const b = S(dir, "bump", "--from", "2.0.0", "--kind", "patch");
assert.equal(b.json.version, "2.0.1");
assert.equal(b.json.heading, "## [2.0.1] - 2026-08-03");
});
test("changelog-state: an Unreleased heading is not a version and package.json is not aligned to it", () => {
const log = `# Changelog\n\n## [Unreleased]\n\n### Added\n\n- soon\n\n## [1.0.0] - 2025-12-01\n\n- x\n`;
const { dir } = repo("cl-unreleased", { changelog: log });
const r = S(dir, "state");
assert.equal(r.json.branchTop.unreleased, true);
assert.equal(r.json.branchTop.version, null);
assert.equal(r.json.topIsNew, false);
assert.equal(r.json.package.matches, false);
assert.match(r.json.entry, /^## \[Unreleased\]/);
});
test("changelog-state bump: kinds and bad input", () => {
const { dir } = repo("cl-bump");
assert.equal(S(dir, "bump", "--from", "1.2.3", "--kind", "major").json.version, "2.0.0");
assert.equal(S(dir, "bump", "--from", "1.2.3", "--kind", "minor").json.version, "1.3.0");
assert.equal(S(dir, "bump", "--from", "v1.2.3", "--kind", "patch").json.version, "1.2.4");
assert.equal(S(dir, "bump", "--from", "1.2.3", "--kind", "huge").code, 2);
const bad = S(dir, "bump", "--from", "one", "--kind", "patch");
assert.equal(bad.code, 4);
assert.equal(bad.json.error, "bad-version");
});
test("changelog-state set-package-version: changes the version field and nothing else", () => {
const { dir } = repo("cl-pkg");
const before = read(dir, "package.json");
const r = S(dir, "set-package-version", "--version", "1.1.0");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual([r.json.from, r.json.to, r.json.changed], ["1.0.0", "1.1.0", true]);
assert.equal(read(dir, "package.json"), before.replace('"1.0.0"', '"1.1.0"'));
assert.equal(S(dir, "set-package-version", "--version", "1.1.0").json.changed, false);
write(dir, "package.json", `{ "name": "x" }\n`);
assert.equal(S(dir, "set-package-version", "--version", "1.1.0").code, 4);
write(dir, "package.json", `{
"config": {
"version": "9.9.9"
},
"version": "1.0.0"
}
`);
const nested = S(dir, "set-package-version", "--version", "1.1.0");
assert.equal(nested.code, 5);
assert.equal(nested.json.error, "ambiguous-version");
assert.equal(read(dir, "package.json").includes("9.9.9"), true, "nothing was written");
});
test("changelog-state: new SKILL.md files are reported", () => {
const { dir, g } = repo("cl-skill");
g("switch", "-q", "-c", "feature/skill");
write(dir, "skills/new-thing/SKILL.md", "---\nname: new-thing\n---\n");
commitAll(g, "add a skill");
assert.deepEqual(S(dir, "state").json.addedSkills, ["skills/new-thing/SKILL.md"]);
});
+299
View File
@@ -0,0 +1,299 @@
// Tests for plan2code-git-commit's scripts/git-state.mjs.
//
// See skill-script-helpers.mjs for how these run.
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { runScript, tmp, write, gitInit } from "./skill-script-helpers.mjs";
const S = (cwd, ...a) => runScript("plan2code-git-commit", "git-state.mjs", a, { cwd });
// A repo with one commit on `branch`, and its git runner.
function repoWithCommit(name, branch = "main") {
const repo = tmp(name);
const g = gitInit(repo, branch);
write(repo, "a.txt", "a\n");
g("add", "-A");
g("commit", "-q", "-m", "init");
return { repo, g };
}
function bareRemote() {
const bare = tmp("origin");
execFileSync("git", ["init", "-q", "--bare", "-b", "main", bare], { stdio: "pipe" });
return bare;
}
/* ============================================================ git-state.mjs state */
test("git-state state: a clean repo with one commit and no remote", () => {
const { repo } = repoWithCommit("gs-clean");
const r = S(repo, "state");
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.branch, "main");
assert.equal(r.json.detached, false);
assert.equal(r.json.hasCommits, true);
assert.equal(r.json.nothingToCommit, true);
assert.deepEqual([r.json.staged, r.json.unstaged, r.json.untracked, r.json.conflicted], [[], [], [], []]);
assert.deepEqual(r.json.remotes, []);
assert.equal(r.json.upstream, null);
assert.equal(r.json.push, null, "no remote, nothing to push");
assert.equal(r.json.inProgress, null);
});
test("git-state state: staged, unstaged, untracked and renamed files land in the right lists", () => {
const { repo, g } = repoWithCommit("gs-files");
write(repo, "b.txt", "b\n");
write(repo, "c.txt", "c\n");
g("add", "-A");
g("commit", "-q", "-m", "more");
write(repo, "a.txt", "changed\n"); // unstaged
write(repo, "b.txt", "changed\n"); // staged...
g("add", "b.txt");
write(repo, "b.txt", "changed again\n"); // ...and unstaged too
g("mv", "c.txt", "d.txt"); // staged rename
write(repo, "u.txt", "new\n"); // untracked
const r = S(repo, "state");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.staged, [
{ path: "b.txt", status: "M" },
{ path: "d.txt", status: "R" },
]);
assert.deepEqual(r.json.unstaged, [
{ path: "a.txt", status: "M" },
{ path: "b.txt", status: "M" },
]);
assert.deepEqual(r.json.untracked, [{ path: "u.txt", status: "?" }]);
assert.ok(![...r.json.staged, ...r.json.unstaged].some((f) => f.path === "c.txt"), "a rename's old path is skipped");
assert.equal(r.json.nothingToCommit, false);
});
test("git-state state: the default branch from origin/HEAD, local main, local master, unborn, or none", () => {
// origin/HEAD
const bare = bareRemote();
const { repo, g } = repoWithCommit("gs-def-origin");
g("remote", "add", "origin", bare);
g("push", "-q", "-u", "origin", "main");
g("remote", "set-head", "origin", "-a");
const fromOrigin = S(repo, "state").json;
assert.equal(fromOrigin.defaultFrom, "origin/HEAD");
assert.equal(fromOrigin.defaultBranch, "main");
assert.equal(fromOrigin.onDefault, true);
// local main, and off the default
const main = repoWithCommit("gs-def-main");
assert.equal(S(main.repo, "state").json.defaultFrom, "local-main");
main.g("checkout", "-q", "-b", "feature/x");
const off = S(main.repo, "state").json;
assert.equal(off.defaultBranch, "main");
assert.equal(off.onDefault, false);
// local master
const master = S(repoWithCommit("gs-def-master", "master").repo, "state").json;
assert.equal(master.defaultFrom, "local-master");
assert.equal(master.defaultBranch, "master");
assert.equal(master.onDefault, true);
// no commits yet, on main
const fresh = tmp("gs-def-unborn");
gitInit(fresh, "main");
const unborn = S(fresh, "state").json;
assert.equal(unborn.hasCommits, false);
assert.equal(unborn.branch, "main");
assert.equal(unborn.defaultFrom, "unborn");
assert.equal(unborn.defaultBranch, "main");
assert.equal(unborn.onDefault, true);
assert.equal(unborn.push, null, "no commits, nothing to push");
// neither main nor master: no default, so no branch offer
const dev = S(repoWithCommit("gs-def-none", "develop").repo, "state").json;
assert.equal(dev.defaultBranch, null);
assert.equal(dev.defaultFrom, null);
assert.equal(dev.onDefault, false);
const devFresh = tmp("gs-def-none2");
gitInit(devFresh, "develop");
assert.equal(S(devFresh, "state").json.defaultBranch, null);
});
test("git-state state: a detached HEAD has no branch and nothing to push", () => {
const { repo, g } = repoWithCommit("gs-detached");
g("remote", "add", "origin", bareRemote());
g("checkout", "-q", "--detach");
const r = S(repo, "state").json;
assert.equal(r.detached, true);
assert.equal(r.branch, null);
assert.equal(r.onDefault, false);
assert.equal(r.unpublished, false);
assert.equal(r.push, null);
});
test("git-state state: the push command for an unpublished branch, one remote or several", () => {
const { repo, g } = repoWithCommit("gs-unpub", "feature/x");
g("remote", "add", "origin", bareRemote());
const one = S(repo, "state").json;
assert.equal(one.unpublished, true);
assert.equal(one.upstream, null);
assert.equal(one.ahead, null);
assert.deepEqual(one.push, { command: "git push -u origin feature/x", setsUpstream: true, remote: "origin", needsRemoteChoice: false });
g("remote", "add", "backup", bareRemote());
const two = S(repo, "state").json;
assert.equal(two.push.remote, "origin", "origin wins when there are several");
assert.equal(two.push.needsRemoteChoice, true);
assert.equal(two.push.command, "git push -u origin feature/x");
g("remote", "remove", "origin");
g("remote", "add", "zeta", bareRemote());
const noOrigin = S(repo, "state").json;
assert.equal(noOrigin.push.remote, "backup", "no origin: the first remote");
assert.equal(noOrigin.push.needsRemoteChoice, true);
});
test("git-state state: ahead of an upstream is a plain git push, pushed is null", () => {
const { repo, g } = repoWithCommit("gs-ahead");
g("remote", "add", "origin", bareRemote());
g("push", "-q", "-u", "origin", "main");
const synced = S(repo, "state").json;
assert.equal(synced.upstream, "origin/main");
assert.equal(synced.ahead, 0);
assert.equal(synced.behind, 0);
assert.equal(synced.unpublished, false);
assert.equal(synced.push, null);
write(repo, "n.txt", "n\n");
g("add", "-A");
g("commit", "-q", "-m", "next");
const ahead = S(repo, "state").json;
assert.equal(ahead.ahead, 1);
assert.equal(ahead.behind, 0);
assert.deepEqual(ahead.push, { command: "git push", setsUpstream: false, remote: "origin", needsRemoteChoice: false });
});
test("git-state state: a merge in progress and its conflicted files", () => {
const repo = tmp("gs-merge");
const g = gitInit(repo, "main");
write(repo, "f.txt", "a\n");
g("add", "-A");
g("commit", "-q", "-m", "base");
g("checkout", "-q", "-b", "x");
write(repo, "f.txt", "b\n");
g("commit", "-q", "-am", "x side");
g("checkout", "-q", "main");
write(repo, "f.txt", "c\n");
g("commit", "-q", "-am", "main side");
assert.throws(() => g("merge", "x"));
const r = S(repo, "state").json;
assert.equal(r.inProgress, "merge");
assert.deepEqual(r.conflicted, [{ path: "f.txt", status: "UU" }]);
assert.ok(!r.staged.some((f) => f.path === "f.txt") && !r.unstaged.some((f) => f.path === "f.txt"), "listed only under conflicted");
assert.equal(r.nothingToCommit, false);
});
test("git-state state: secrets are flagged, examples are not, and large files are listed", () => {
const { repo } = repoWithCommit("gs-risky");
for (const f of [".env", ".env.local", "id_rsa", "id_ed25519.pub", "server.pem", "secrets.json", "credentials.json", ".npmrc", "config/.env"]) write(repo, f, "x\n");
for (const f of [".env.example", ".env.sample", "key.txt", "notes.md"]) write(repo, f, "x\n");
write(repo, "video.bin", Buffer.alloc(6 * 1024 * 1024, 1));
write(repo, "small.bin", Buffer.alloc(1024 * 1024, 1));
const r = S(repo, "state").json;
assert.deepEqual(r.sensitive, [".env", ".env.local", ".npmrc", "config/.env", "credentials.json", "id_ed25519.pub", "id_rsa", "secrets.json", "server.pem"]);
assert.deepEqual(r.large, [{ path: "video.bin", bytes: 6 * 1024 * 1024 }]);
});
test("git-state state: reading leaves the index untouched", () => {
const { repo } = repoWithCommit("gs-readonly");
const index = path.join(repo, ".git", "index");
// Same content, new mtime: a plain git status would refresh and rewrite the index.
const later = new Date(Date.now() + 5000);
fs.utimesSync(path.join(repo, "a.txt"), later, later);
const before = fs.readFileSync(index);
assert.equal(S(repo, "state").code, 0);
assert.ok(before.equals(fs.readFileSync(index)), "the index file is byte-for-byte the same");
});
test("git-state: outside a repository, and a bad subcommand", () => {
const plain = tmp("gs-norepo");
const r = S(plain, "state");
assert.equal(r.code, 3);
assert.equal(r.json.error, "not-a-repo");
assert.match(r.json.next, /init-check/);
assert.equal(S(plain, "branch-check", "--name", "x").code, 3);
assert.equal(S(plain).code, 2);
assert.equal(S(plain, "commit").code, 2);
assert.equal(S(plain, "state", "extra").code, 2);
});
/* ======================================================= git-state.mjs branch-check */
test("git-state branch-check: valid, invalid, taken and clashing names", () => {
const { repo, g } = repoWithCommit("gs-branch");
g("branch", "feat");
const ok = S(repo, "branch-check", "--name", "feature/export-csv");
assert.equal(ok.code, 0, ok.stderr);
assert.deepEqual(ok.json, { ok: true, name: "feature/export-csv", valid: true, exists: false });
for (const bad of ["bad..name", "has space", "-leading", "@{-1}", "ends/"]) {
const r = S(repo, "branch-check", "--name", bad);
assert.equal(r.code, 4, bad);
assert.equal(r.json.error, "invalid-name", bad);
}
assert.match(S(repo, "branch-check", "--name", "bad..name").json.next, /feature\//);
const taken = S(repo, "branch-check", "--name", "main");
assert.equal(taken.code, 4);
assert.equal(taken.json.error, "branch-exists");
assert.match(taken.json.next, /main-2/);
const clash = S(repo, "branch-check", "--name", "feat/x");
assert.equal(clash.code, 4);
assert.equal(clash.json.error, "branch-conflict");
assert.equal(S(repo, "branch-check").code, 2);
});
/* ========================================================= git-state.mjs init-check */
test("git-state init-check: a plain folder is safe and suggests what to ignore", () => {
const dir = tmp("gs-init");
for (const f of ["node_modules/x/index.js", "dist/out.js", ".env", ".env.example", "app.log", "src/a.js"]) write(dir, f, "x\n");
const r = S(dir, "init-check");
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.safe, true);
assert.equal(r.json.reason, undefined);
assert.equal(r.json.insideRepo, false);
assert.equal(r.json.hasGitignore, false);
assert.deepEqual(r.json.suggestedIgnore, ["node_modules/", "dist/", ".env", ".env.*", "!.env.example", "*.log"]);
write(dir, ".gitignore", "x\n");
assert.equal(S(dir, "init-check").json.hasGitignore, true);
const empty = tmp("gs-init-empty");
assert.deepEqual(S(empty, "init-check").json.suggestedIgnore, []);
});
test("git-state init-check: inside a repository, the home folder, and a drive root are not safe", () => {
const { repo } = repoWithCommit("gs-init-repo");
write(repo, "sub/x.txt", "x\n");
const inside = S(path.join(repo, "sub"), "init-check").json;
assert.equal(inside.safe, false);
assert.equal(inside.reason, "inside-repo");
assert.equal(inside.insideRepo, true);
assert.equal(path.resolve(inside.repoRoot).toLowerCase(), repo.toLowerCase());
const home = tmp("gs-init-home");
const asHome = runScript("plan2code-git-commit", "git-state.mjs", ["init-check"], { cwd: home, env: { HOME: home, USERPROFILE: home } });
assert.equal(asHome.json.safe, false);
assert.equal(asHome.json.reason, "home");
const root = path.parse(process.cwd()).root;
const atRoot = S(root, "init-check").json;
if (!atRoot.insideRepo) {
assert.equal(atRoot.safe, false);
assert.equal(atRoot.reason, "root");
}
});
/* ============================================================ the skill's other script */
test("plan2code-git-commit ships commit-msg.mjs with the two -m flags", () => {
const r = runScript("plan2code-git-commit", "commit-msg.mjs", ["--subject", "Add the export", "--files", "src/a.js"]);
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.command, 'git add -- src/a.js && git commit -m "Add the export" -m "AI Assisted"');
});
+20 -15
View File
@@ -228,7 +228,7 @@ test("specs archive: dry-run, move, refuse to clobber", () => {
/* ============================================================ commit-msg.mjs */
test("commit-msg: ticket from the branch, the three -m flags, subject rules", () => {
test("commit-msg: the two -m flags on any branch, subject rules", () => {
const repo = tmp("commit");
const g = gitInit(repo, "feature/ABC-10968-export-csv");
write(repo, "a.txt", "a");
@@ -237,24 +237,29 @@ test("commit-msg: ticket from the branch, the three -m flags, subject rules", ()
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
const ok = C("--subject", "Add the export endpoint", "--add-all");
assert.equal(ok.code, 0, ok.stderr);
assert.equal(ok.json.ticket, "ABC-10968");
assert.equal(ok.json.command, 'git add -A && git commit -m "Add the export endpoint" -m "ABC-10968" -m "AI Assisted"');
assert.equal(ok.json.message, "Add the export endpoint\n\nABC-10968\nAI Assisted");
assert.equal(ok.json.ticket, undefined);
assert.equal(ok.json.branch, undefined);
assert.equal(ok.json.command, 'git add -A && git commit -m "Add the export endpoint" -m "AI Assisted"');
assert.equal(ok.json.message, "Add the export endpoint\n\nAI Assisted");
assert.equal(C("--subject", "x".repeat(101)).code, 4);
assert.equal(C("--subject", 'say "hi"').code, 4);
assert.equal(C("--subject", "costs $5").code, 4);
assert.equal(C().code, 2);
assert.match(C("--subject", "Fix it", "--files", "src/a.ts", "--files", "my file.md").json.command, /^git add -- src\/a\.ts 'my file\.md' && git commit/);
g("checkout", "-q", "-b", "chore/no-ticket-here");
const none = C("--subject", "Fix it");
assert.equal(none.code, 4);
assert.equal(none.json.error, "no-ticket");
assert.equal(C("--subject", "Fix it", "--ticket", "ABC-1").json.ticket, "ABC-1");
assert.equal(C("--subject", "Fix it", "--ticket", "abc-1").code, 4);
g("checkout", "-q", "-b", "PROJ2-7_underscore");
assert.equal(C("--subject", "Fix it").json.ticket, "PROJ2-7");
const fix = 'git commit -m "Fix it" -m "AI Assisted"';
assert.equal(C("--subject", "Fix it").json.commit, fix, "ticket branch");
g("checkout", "-q", "-b", "main");
const onMain = C("--subject", "Fix it");
assert.equal(onMain.json.commit, fix, "main");
assert.equal(onMain.json.message, "Fix it\n\nAI Assisted");
assert.equal(onMain.json.ticket, undefined);
assert.equal(onMain.json.branch, undefined);
const flag = C("--subject", "Fix it", "--ticket", "ABC-1");
assert.equal(flag.code, 2, "--ticket is an unknown flag");
assert.equal(flag.json.error, "unknown-flag");
const notRepo = runScript("plan2code-review", "commit-msg.mjs", ["--subject", "x"], { cwd: tmp("norepo") });
assert.equal(notRepo.code, 3);
assert.equal(notRepo.code, 0, "no repository needed");
assert.equal(notRepo.json.commit, 'git commit -m "x" -m "AI Assisted"');
});
/* ============================================================ agent-files.mjs */
@@ -427,7 +432,7 @@ test("commit-msg: a repo with no commits, stray arguments, and paths quoted for
const repo = tmp("commit2");
gitInit(repo, "feature/ABC-12-x");
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
assert.equal(C("--subject", "Add x").json.ticket, "ABC-12", "no commits yet");
assert.equal(C("--subject", "Add x").json.commit, 'git commit -m "Add x" -m "AI Assisted"', "no commits yet");
const stray = C("--subject", "Fix", "--files", "a.js", "b.js");
assert.equal(stray.code, 2);
assert.equal(stray.json.error, "stray-argument");
@@ -577,7 +582,7 @@ test("commit-msg: @ and - paths are quoted, git add ends its options, risky subj
const files = C("--subject", "Fix", "--files", "@types/x.d.ts", "--files", "-weird.md", "--files", "src/a@b.js");
assert.equal(files.code, 0, files.stderr);
assert.equal(files.json.add, "git add -- '@types/x.d.ts' '-weird.md' src/a@b.js");
assert.equal(files.json.commit, 'git commit -m "Fix" -m "ABC-12" -m "AI Assisted"');
assert.equal(files.json.commit, 'git commit -m "Fix" -m "AI Assisted"');
assert.equal(files.json.command, `${files.json.add} && ${files.json.commit}`);
assert.equal(C("--subject", "Fix", "--add-all").json.add, "git add -A");
const bare = C("--subject", "Fix").json;
+211 -9
View File
@@ -52,6 +52,8 @@ import {
DONE_REPLY,
finishPaused,
fitWithin,
GIT_CLEAN_REASON,
GIT_INIT_NOTE,
handoffShape,
handoffText,
HOME_REPLY,
@@ -66,6 +68,8 @@ import {
recordedAnswer,
resumeCommand,
REVIEW_REPLY,
commitOffer,
pendingNote,
reviewOffer,
SKILL_CATALOG,
SPEC_STATE_LABELS,
@@ -185,6 +189,8 @@ import {
cwdHash,
handOff,
initialWorkspace,
insideGitRepo,
pendingFiles,
latestOpenCaps,
parseArgs,
pendingWorkspaceChanges,
@@ -1044,7 +1050,7 @@ test("help: every number the help quotes matches the code", () => {
const panels = new Map(
[...tpl.matchAll(/<section class="help-panel" data-tab="([^"]+)">([\s\S]*?)<\/section>/g)].map((m) => [m[1], m[2]])
);
const firstSeven = HELP_TABS.slice(0, 7).map((t) => panels.get(t.id)).join("\n");
const firstEight = HELP_TABS.slice(0, 8).map((t) => panels.get(t.id)).join("\n");
const used = [
"closedTabMinutes",
"maxLifeHours",
@@ -1056,7 +1062,7 @@ test("help: every number the help quotes matches the code", () => {
"maxUploadMb",
"cleanupDays",
];
for (const key of used) assert.ok(firstSeven.includes(`data-fact="${key}"`), `tabs 1 to 7 quote ${key}`);
for (const key of used) assert.ok(firstEight.includes(`data-fact="${key}"`), `tabs 1 to 8 quote ${key}`);
});
/* ---------------------------------------------------------- image uploads */
@@ -2442,6 +2448,20 @@ test("a finish can carry the dashboard flag, and only as a boolean", () => {
assert.match(bad.stderr, /"finish\.dashboard" must be true or false \(or left out: no dashboard button\)/);
});
// The Commit it now button is the same kind of opt-in.
test("a finish can carry the commit flag, and only as a boolean", () => {
const base = { headline: "The task is built", command: "git add -A && git commit -m \"x\" -m \"AI Assisted\"" };
for (const commit of [true, false]) {
const res = cli(["post", "--session", sid, "--file", payload("fin-commit.json", { finish: { ...base, commit } })]);
assert.equal(res.json.ok, true);
}
const bad = cli(["post", "--session", sid, "--file", payload("fin-commit-bad.json", { finish: { ...base, commit: "yes" } })], {
expectFail: true,
});
assert.equal(bad.status, 3);
assert.match(bad.stderr, /"finish.commit" must be true or false/);
});
// Taking the review up is the agent posting `"finish": null`: the session goes
// back to work, so the page must stop saying it is over.
test("a finish can be taken back, which puts the session back to work", () => {
@@ -3030,6 +3050,112 @@ test("the project scan reads each spec's pipeline stage off its files", () => {
}
});
// The dashboard's Git commit card offers to start a repository when the folder
// is not one. The scan answers that from the filesystem, never from a git
// process, and a linked worktree (a .git file, not a folder) must count.
test("scanProject reports isGit for a repo, a subfolder, a linked worktree and a plain folder", () => {
const saved = {};
for (const k of ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR"]) {
saved[k] = process.env[k];
delete process.env[k];
}
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-isgit-"));
try {
const repo = path.join(base, "repo");
fs.mkdirSync(path.join(repo, "sub"), { recursive: true });
const git = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
git(repo, "init", "-q");
git(repo, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "x");
git(repo, "worktree", "add", "-q", path.join(base, "wt"));
const plain = path.join(base, "plain");
fs.mkdirSync(plain);
assert.equal(scanProject(repo).isGit, true);
assert.equal(scanProject(path.join(repo, "sub")).isGit, true);
assert.equal(fs.statSync(path.join(base, "wt", ".git")).isFile(), true, "a linked worktree's .git is a file");
assert.equal(scanProject(path.join(base, "wt")).isGit, true);
assert.equal(scanProject(plain).isGit, false);
assert.equal(insideGitRepo(plain), false);
// When git is steered by the environment, git decides: count it as a repo.
process.env.GIT_DIR = path.join(plain, "nowhere");
assert.equal(insideGitRepo(plain), true);
} finally {
for (const [k, v] of Object.entries(saved)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
fs.rmSync(base, { recursive: true, force: true });
}
});
test("the Git commit card stays clickable outside a repository and says what happens", () => {
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-git-commit");
const outside = cardAvailability(entry, { hasAgents: true, isGit: false }, null);
assert.equal(outside.on, true);
assert.equal(outside.note, GIT_INIT_NOTE);
for (const scan of [{ hasAgents: true, isGit: true }, { hasAgents: true }, null]) {
const a = cardAvailability(entry, scan, null);
assert.equal(a.on, true);
assert.equal(a.note, undefined);
}
const scan = { hasAgents: true, isGit: false, specs: [] };
assert.equal(cardPresentation(entry, scan, null).detail, GIT_INIT_NOTE);
// The agent's own detail line still wins over the note.
const withSpec = { hasAgents: true, isGit: false, specs: [{ dir: "specs/x", name: "x", state: "building" }] };
const menu = { details: { "plan2code-git-commit": "Two changes ready" } };
assert.equal(cardPresentation(entry, withSpec, withSpec.specs[0], menu).detail, "Two changes ready");
});
test("the Git commit card shows the pending count and greys out on a clean tree", () => {
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-git-commit");
const clean = cardAvailability(entry, { hasAgents: true, isGit: true, pending: 0 }, null);
assert.equal(clean.on, false);
assert.equal(clean.reason, GIT_CLEAN_REASON);
const dirty = cardAvailability(entry, { hasAgents: true, isGit: true, pending: 3 }, null);
assert.deepEqual(dirty, { on: true, note: "3 files to commit" });
assert.equal(pendingNote(1), "1 file to commit");
// git could not say: stay clickable, and no repository still offers git init.
assert.deepEqual(cardAvailability(entry, { hasAgents: true, isGit: true, pending: null }, null), { on: true });
assert.equal(cardAvailability(entry, { hasAgents: true, isGit: false, pending: 0 }, null).note, GIT_INIT_NOTE);
});
test("pendingFiles counts changed and untracked paths, and says null outside a repository", () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pending-"));
const git = (...a) => spawnSync("git", a, { cwd: repo, encoding: "utf8" });
const repo = path.join(base, "repo");
const plain = path.join(base, "plain");
fs.mkdirSync(repo);
fs.mkdirSync(plain);
try {
if (git("init", "-q").status !== 0) return; // no git on this machine
git("config", "user.email", "t@example.com");
git("config", "user.name", "T");
assert.equal(pendingFiles(repo), 0, "an empty repository is clean");
fs.writeFileSync(path.join(repo, "a.txt"), "a");
git("add", "a.txt");
git("commit", "-q", "-m", "first");
assert.equal(pendingFiles(repo), 0);
fs.writeFileSync(path.join(repo, "a.txt"), "changed");
fs.writeFileSync(path.join(repo, "b.txt"), "new");
assert.equal(pendingFiles(repo), 2, "one modified, one untracked");
git("add", "b.txt");
assert.equal(pendingFiles(repo), 2, "staged counts too");
assert.equal(scanProject(repo).pending, 2);
assert.equal(scanProject(plain).pending, null, "no repository, no count");
} finally {
fs.rmSync(base, { recursive: true, force: true });
}
});
test("the commit offer is read from finish.commit and a pause never carries it", () => {
assert.equal(commitOffer({ headline: "Done", commit: true }), true);
assert.equal(commitOffer({ headline: "Done", commit: false }), false);
assert.equal(commitOffer({ headline: "Done" }), false);
assert.equal(commitOffer({ headline: "Paused here", commit: true }), false);
assert.equal(commitOffer(null), false);
});
test("a verdict's button text never renders blank", () => {
assert.equal(verdictText({ id: "approve", label: "Approve it" }), "Approve it");
assert.equal(verdictText({ id: "approve", text: "Approve it" }), "Approve it");
@@ -5209,7 +5335,8 @@ test("subagents: only the five opted-in workflows offer the switch", () => {
assert.equal(defaultInstruction(w), "");
}
assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 5);
assert.deepEqual(defaultSetting("review"), { workflow: "review", on: false, instruction: null, max: 3 });
assert.deepEqual(defaultSetting("review"), { workflow: "review", on: true, instruction: null, max: 3 });
assert.equal(defaultSetting("plan").on, false, "a skill without the switch is never on");
assert.equal(effectiveInstruction({ workflow: "review", instruction: " " }), defaultInstruction("review"));
assert.equal(effectiveInstruction({ workflow: "review", instruction: " Mine " }), "Mine");
});
@@ -5315,7 +5442,7 @@ test("subagents: the page shows the switch only when offered and supported, and
assert.equal(showTab(on, undefined), false);
assert.equal(showTab(off, [helper]), true, "a helper shows with the switch off (Pathfinder research)");
assert.equal(showTab({ ...on, supported: false }, [helper]), false, "no tab where the switch cannot show");
assert.ok(CHECKIN_LINE.includes("check-ins, not live"));
assert.ok(CHECKIN_LINE.includes("checks in, not live"));
});
test("subagents: helperRows labels each state, shows a result only once a helper ended, and collapses to working alone", () => {
@@ -5382,7 +5509,7 @@ test("subagents: the store round-trips per project and workflow under the consol
if (process.platform === "win32" || process.platform === "darwin") {
assert.deepEqual(out.otherCase, out.saved, "a different-case path reads the same entry");
}
assert.deepEqual(out.unsaved, { on: false, instruction: null, max: 3 });
assert.deepEqual(out.unsaved, { on: true, instruction: null, max: 3 }, "nothing saved means on");
assert.ok(!fs.existsSync(path.join(home, "subagents.json.lock")), "the lock is released");
} finally {
fs.rmSync(home, { recursive: true, force: true });
@@ -5821,6 +5948,11 @@ test("subagents: a change reaches the next pickup once, last in reply, edits nam
const s = subagentsSession();
const extra = tempFolder();
try {
// Nothing saved means on, and open already told the agent. Turn it off and
// let that be said, so the rest of the test starts from an off agent.
assert.equal((await setSubagents(s, { ...ON3, on: false })).status, 200);
assert.equal(subagentLines((await submitAndWait(s)).json.reply).length, 1, "off is said to an agent told on");
const on = await setSubagents(s, ON3);
assert.equal(on.status, 200);
assert.equal(on.body.ok, true);
@@ -5876,7 +6008,11 @@ test("subagents: a change reaches the next pickup once, last in reply, edits nam
});
test("subagents: never on means never a line, and chat hands a pending block over on its own", async () => {
const s = subagentsSession();
// A project that saved "off" starts its next session off and untold.
const first = subagentsSession();
assert.equal((await setSubagents(first, { on: false, instruction: null, max: 4 })).status, 200);
cli(["stop", "--session", first.sid]);
const s = subagentsSession({}, { keepStore: true });
try {
const off = await setSubagents(s, { on: false, instruction: null, max: 4 });
assert.equal(off.status, 200);
@@ -5985,14 +6121,14 @@ test("subagents: a save that matches this session still becomes the project's se
let c = null;
try {
const before = (await frameSubagents(b)).revision;
assert.equal((await setSubagents(a, ON3)).status, 200, "another session turns it on for the project");
const same = await setSubagents(b, { ...ON3, on: false });
assert.equal((await setSubagents(a, { ...ON3, on: false })).status, 200, "another session turns it off for the project");
const same = await setSubagents(b, ON3);
assert.equal(same.status, 200);
assert.equal(same.body.setting.revision, before, "nothing changed for this session's agent");
assert.equal("subagents" in (await submitAndWait(b)).json, false);
c = subagentsSession({}, { keepStore: true });
assert.equal((await frameSubagents(c)).on, false, "the next session starts from the person's latest pick");
assert.equal((await frameSubagents(c)).on, true, "the next session starts from the person's latest pick");
} finally {
for (const s of [a, b, c]) if (s) cli(["stop", "--session", s.sid]);
}
@@ -6899,3 +7035,69 @@ test("update banner: built only on the dashboard, dismissed per session, and Hel
assert.ok(help, "app.js has renderHelpVersion");
assert.match(help[1], /releasesLink\(/, "the help version is a Releases link");
});
// The Changelog card sits left of Git commit, always clickable, and a launch
// from it resumes the session under its own workflow.
test("the Changelog card comes just before Git commit and is always on", () => {
const skills = SKILL_CATALOG.map((e) => e.skill);
assert.equal(skills.indexOf("plan2code-changelog") + 1, skills.indexOf("plan2code-git-commit"));
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-changelog");
assert.equal(entry.workflow, "changelog");
assert.equal(entry.command, "/plan2code-changelog");
for (const scan of [{ hasAgents: true, isGit: false }, { hasAgents: false }, null]) {
assert.equal(cardAvailability(entry, scan, null).on, true);
}
});
/* ------------------------------------------- getting started: stuck help and the finished screen */
const EM = String.fromCharCode(0x2014);
const publicSource = (name) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", name), "utf8");
test("help: the stuck tab is second, with a callout and four symptom rows before the diagram", () => {
assert.equal(HELP_TABS[0].id, "about");
assert.equal(HELP_TABS[1].id, "stuck");
const tpl = helpTemplate();
const panel = tpl.match(/<section class="help-panel" data-tab="stuck">([\s\S]*?)<\/section>/)[1];
assert.match(panel, /<div class="help-callout" role="note">/);
assert.match(panel, /Check this first/);
assert.match(panel, /look at your terminal/);
assert.equal((panel.match(/class="help-row"/g) || []).length, 4, "four symptom rows");
for (const part of ["You see", "Likely cause", "Do this"]) {
assert.equal((panel.match(new RegExp(`<dt>${part}</dt>`, "g")) || []).length, 4, `each row has "${part}"`);
}
assert.ok(panel.indexOf("help-rows") < panel.indexOf("help-figure"), "the rows come before the diagram");
assert.match(panel, /<svg class="help-callout-icon"[^>]*aria-hidden="true"/, "the icon is decoration");
});
test("status line: the quiet and Not running lines offer What to check, opening Help on the stuck tab", () => {
const app = publicSource("app.js");
assert.match(app, /help\.textContent = "What to check"/);
assert.match(app, /openHelpOn\("stuck"\)/);
// Exactly the three lines that carry it: the approval hint, the stale line and the Not running line.
const render = app.slice(app.indexOf("function renderStatus()"), app.indexOf("/* ---------------------------------------------------------------- brief */"));
assert.match(render, /Boolean\(hint\)/);
assert.equal((render.match(/^\s+true\n\s+\);/gm) || []).length, 2, "the stale and Not running lines pass check");
});
test("finished screen: every shape shows Before you close this, with three rows", () => {
const app = publicSource("app.js");
const handoff = app.slice(app.indexOf("function renderHandoff("));
assert.match(handoff.slice(0, handoff.indexOf("\n}\n")), /card\.appendChild\(renderCloseGuide\(shape\)\)/);
const guide = app.slice(app.indexOf("function renderCloseGuide("), app.indexOf("function renderHandoff("));
for (const label of ["Safe to close", "Start fresh", "Carry on", "Before you close this"]) {
assert.ok(guide.includes(label), `the guide says "${label}"`);
}
assert.match(guide, /shape === "paused"/, "a pause changes the Start fresh sentence");
assert.match(guide, /resume command/);
});
test("getting started: the new help, status and finished-screen strings carry no em dash", () => {
const app = publicSource("app.js");
const guide = app.slice(app.indexOf("const GUIDE_ICONS"), app.indexOf("function renderHandoff("));
assert.ok(!guide.includes(EM), "the close guide has no em dash");
const tpl = helpTemplate();
const stuck = tpl.match(/<section class="help-panel" data-tab="stuck">([\s\S]*?)<\/section>/)[1];
const fresh = stuck.slice(0, stuck.indexOf("<h4>Not running, or not connected?</h4>"));
assert.ok(!fresh.includes(EM), "the callout and rows have no em dash");
});
-174
View File
@@ -1,174 +0,0 @@
---
name: plan2code-0-pathfinder
description: "Plan2Code Step 0: Pathfinder Mode - user-initiated workflow step. Do not invoke autonomously."
disable-model-invocation: true
---
# 🧭 PATHFINDER MODE
Start all PATHFINDER MODE responses with '🧭 [PATHFINDER: Chart - Step X: Name]' or '🧭 [PATHFINDER: Work - Step X: Name]'.
## Role
Pathfinder, not architect. An idea has arrived too big or unclear to plan. Chart the way as a map of decision **questions**, then clear them one at a time until nothing is left to decide. Hand off to `/plan2code-1-plan`.
Read references/grilling.md
> Fallback: ≤3 independent probes/turn, each with a recommendation, re-ask any skipped; AskUserQuestion for every question, prose only if unavailable; plain English; facts you look up, decisions are the human's.
## Interface
The FIRST thing you do, before anything else in this file — before Step 0: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow pathfinder` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then <D>/console.md → Pathfinder notes. Switchable anytime. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console.md → Launches), then Step 0.
## Backend
The map lives in ONE of two places — the human's pick at Chart Step 1, never yours:
- **local** (default) — files under `specs/<idea>/pathfinder/`. Private, gitignored, solo.
- **github** — a `pathfinder:map` issue whose questions are sub-issues, driven by `gh`. Shared, visible in the tracker, parallel.
Read references/github-issues.md — REQUIRED on `github`, skip on `local`.
> Fallback: map = a `pathfinder:map` issue titled `Map: <idea>`; questions = its sub-issues, labelled `pathfinder:<type>-<mode>`; blocking = native dependencies; claim = assign `@me`; resolve = `## Answer` comment, then close.
Recorded as the first `## Ground rules` bullet (`**Backend:** local|github`), never re-asked or switched. Either way the PLAN-DRAFT lands in local `specs/<idea>/` — downstream steps read files, not issues.
## Scripts
On `local`, the map's bookkeeping is a script; the decisions are yours. `node "<S>/pathfinder.mjs" <command> specs/<idea>/pathfinder`, run from the project root, where `<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-0-pathfinder/scripts/` globally). It prints one JSON object. Exit 0 is success; anything else carries `message` and `next`, so do what `next` says. Exit 5 (refused) means a rule would break: never work around it by editing the files by hand. `--help` lists every command; they are named at the steps below. It reads local files only: on `github`, the backend playbook does each step with `gh` (except `lint`, which checks the local briefs and PLAN-DRAFT once one exists), and a `no-map` result there is expected, never a cue to chart.
## Project Context
Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it answers. If missing, fold it into the Step 0 gate batch: *"No `AGENTS.md`. Pathfinder can chart without it. Continue, or run `plan2code-init` first?"* Record the outcome as the first line of `## Ground rules`: ``- `AGENTS.md` exists and governs.`` or, when missing, exactly ``- `AGENTS.md` is absent.`` (the handoff reads it).
## Rules
- **Plan, don't do.** Every question resolves a DECISION. The pull to just build it is the edge of the map — hand off.
- **Confirm before creating anything.** No files, no issues, until the Intent Gate (Step 0) and backend pick (Step 1) return.
- **One question at a time** (`research` excepted — parallel); fork-menu between decisions, fresh session after ~3.
- **Refer by name.** "[Export format](<link>)", never "02" or "#42" in prose. Bare ids belong on `Blocked by:` lines and in commands.
- **HITL questions are never self-answered.** Ask and wait; an agent that answers its own grill has broken the skill.
- **Questions are ground truth; the map is a rebuildable index.** A filled `## Answer` beats any state marker; detail lives in one place.
- **Never write implementation code** into the project. Sketches are throwaway, living only under `pathfinder/sketch-NN/`.
- **Reserved names — never create inside `pathfinder/`:** `overview.md`, `phase-<N>.md`, `PLAN-DRAFT-*.md`, `PLAN-CONVERSATION-*.md`.
- **Never emit the loop's completion tokens under `specs/`** — `TASK_COMPLETE`, `PHASE_COMPLETE`, `ALL_TASKS_COMPLETE`, `IMPLEMENTATION_COMPLETE`, `SPEC_COMPLETE`, `WORK_COMPLETE`. It scans for them.
- **No `- [ ]` checkboxes inside question files**, and no `METRICS_JSON` anywhere.
- **Lint before every Session End** (on `github`, once a brief or PLAN-DRAFT is on local disk; it checks those): `lint` checks the rules above, the schema lines, `Blocked by:` targets and cycles, and metrics-scraper bait. Fix every error it lists (exit 4) before you stop.
## Auto-Discovery and Mode Selection
⚠️ `specs/` is gitignored — NEVER use Glob. Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
**Brief/recap/minutes asked?** → read references/brief.md: `reconcile`, then `brief-data --range <range>` (`github`: its brief section), write plain-English `briefs/brief-<YYYYMMDD>.md` from the output, STOP. Never resolves.
**Identify the idea FIRST** (from the argument, or ask), then evaluate for THAT idea — first match wins. An issue URL or number means `github`; else look for a local map, then `gh issue list --label pathfinder:map` for `Map: <idea>`.
| Condition | Route |
|---|---|
| No map, but `specs/<idea>/overview.md` exists | Documented — offer `/plan2code-3-implement`. STOP |
| No map in either backend | MODE A, Step 0 (Intent Gate) |
| Map `**Status:** Charting` | MODE A, resume at Step 6 |
| Map `**Status:** Working` | MODE B |
| Map `**Status:** Cleared` | Point at the PLAN-DRAFT and `/plan2code-1-plan`. STOP |
| Map exists, `**Status:**` unreadable | MODE B — Step 2 rebuilds and sets it |
One idea per session, each with its own map.
## Questions
Read references/questions.md — the `local` format. On `github` the backend playbook's equivalence table replaces it: no checklist, the frontier is a live query.
> Fallback (`local`): `map.md` indexes; `questions/NN-<slug>.md` hold the decisions, `00` is codebase context, six `Key: value` lines each, `Resolved:` dating it. Markers, rebuilt from the files each session: `[ ]` open — **the frontier** · `[/]` claimed · `[x]` resolved · `[!]` blocked · `[-]` out of scope.
## MODE A: Chart
Read references/chart.md
> Fallback: confirm the outcome with the human FIRST; only then grill the destination, then breadth-first; write the map and one question per sharp decision.
0. `[Chart - Step 0: Intent Gate]` **Before creating anything**, use AskUserQuestion for the outcome and WAIT: **chart a map** (foggy — Step 1), **`/plan2code-1-plan`** (clear — STOP), **`/plan2code-quick-task`** (tiny — STOP). HITL, never self-select "chart".
1. `[Chart - Step 1: Name and backend]` Only after the gate says "chart." Confirm the kebab-case idea name, then ask — HITL, never self-picked — **local files or GitHub Issues?** Recommend `local` for solo work; offer `github` only if preflight passes, naming the repo's visibility. THEN the first write.
2. `[Chart - Step 2: Destination]` Grill until it is one or two lines. It fixes scope — settle it first.
3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter.
4. `[Chart - Step 4: Map the frontier]` Grill again **breadth-first**: fan out, never deep on one thread. Surface the open decisions and what is takeable now.
5. `[Chart - Step 5: Create the map]` `**Status:** Charting`, Destination, Ground rules (backend first), an empty index, the fog in `## Not yet specified`. Say once where it lives and who sees it.
6. `[Chart - Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass — on `github`, create all first, wire edges second. The rest stays fog. Include a `grill · HITL` testing-posture question; `/plan2code-1-plan` Phase 1 needs it.
7. `[Chart - Step 7: Index]` `local`: `reconcile` fills `## Question Checklist` from the files (every missing row, with its marker). Either backend: set `**Status:** Working`. `local`: then `lint`.
8. `[Chart - Step 8: Fire research]` One subagent per `research` question, in parallel. Each writes only its `## Evidence`, never decides. **Wait for all** (they die with the terminal), then Session End.
**No fog at Step 4?** Small enough to plan directly: create no map, keep the recon as a local file, attach it to `/plan2code-1-plan`, STOP. Charting resolves nothing by hand — stop at Step 8.
## MODE B: Work
Read references/resolve.md
> Fallback: resolve by type — research reads sources, sketch makes something concrete, grill interviews the human, legwork does the manual work.
Assume NO memory of any prior session.
1. `[Work - Step 1: Load]` Read the map whole. No question yet.
2. `[Work - Step 2: Reconcile]` **Always.** `local`: run `reconcile`. The answer wins: a question whose `## Answer` its state contradicts is resolved, a missing `Resolved:` is backfilled from the claim (today if none), a claim with no `## Answer` (a crash) is released, and every marker is rebuilt from the questions. Tell the human each `repairs` entry in one line. Re-fire every question in `refire` (research cut off before its `Research complete:` line; resolve.md → Interrupted research). `--dry-run` first if the map looks badly off. `github`: the reconcile checks in the backend playbook.
3. `[Work - Step 3: Frontier]` Every question open, unclaimed, and unblocked, first in order. `local`: run `frontier` (`frontier`, `blocked` with each blocker, `stranded`, `nextNN`, `counts`).
4. `[Work - Step 4: Choose and claim]` The one the user named, else first on the frontier. Mark it claimed on the question and the map, **saved before any work** (`local`: `claim <NN>`, which refuses a blocked or non-open question and a second open claim). A `research` pick fires unclaimed instead (resolve.md); then claim the next one.
- Stranded on an `out-of-scope` blocker? Check this first: re-frame or rule out, re-run Step 3.
- Frontier empty but questions remain (`allBlocked`)? Report the chain, STOP.
- Nothing open (`nothingOpen`)? The Clearing Gate.
5. `[Work - Step 5: Zoom]` Read the claimed question in full, plus any closed question it references. Obey `## Ground rules`.
6. `[Work - Step 6: Resolve]` Route by type per the resolve playbook. HITL needs the human's own words.
7. `[Work - Step 7: Record]` Write `## Answer`: the decision, what was rejected and why, consequences, a one-line `**Gist:**` last. Sources under `## Evidence`. Mark it resolved, dated today, index the gist + date on the map, bump `**Updated:**` (`local`: `resolve <NN>` does all four; its `unblocked` list feeds the menu).
8. `[Work - Step 8: Graduate]` Fog now sharp? Write those questions (`local`: numbered from `nextNN`, then `reconcile` to index them), delete the graduated bullets. Past the destination? Rule it out of scope, one line in `## Out of scope` (`local`: `rule-out <NN> --reason "<why>"`; handle anything it reports `stranded`). Invalidated? Re-frame or rule out.
9. `[Work - Step 9: Menu]` Run The Clearing Gate. Not cleared: fork-menu (Form C; resolve.md §Cadence) — pick → Step 4, stop → Session End.
## The Clearing Gate
Read references/handoff.md
> Fallback: write `specs/<idea>/PLAN-DRAFT-<YYYYMMDD>.md` from the map, Status `Phase 3 Complete - Resume at Phase 4`, then route to `/plan2code-1-plan`.
The map clears only when ALL hold:
1. Nothing open, claimed, or blocked
2. `## Not yet specified` is EMPTY
3. The destination is reachable with nothing left to decide
4. All four confidence dimensions score ≥ 18/25
Score the four dimensions (handoff.md rubric) and write them to the map's `**Confidence:**` line. `local`: run `gate`; it checks 1, 2 and 4 against the files, plus the handoff preflight and the Requirements, Feasibility and Risk caps; condition 3, the Integration cap and the scores stay yours (its `judgment` list). Any failing: name it, keep working. All passing: follow the handoff playbook, set `**Status:** Cleared`, run `lint`, stop. The PLAN-DRAFT is always local — `/plan2code-1-plan` cannot read a tracker.
## Trail Footer
Read references/trail.md
> Fallback: once the map exists, end every response with a marker path (`●` done · `◉` here · `○` open · `⊘` blocked · `⊝` out of scope) `START`→`⚑`, a named legend, a plain-English confidence note, then ONE closer: asking → Form B, `WAITING ON YOU`, no command; menu → Form C, `NEXT UP` + `OR START FRESH`; session end → Form A, `NEXT STEP` + resume command with `--web` (map issue URL on `github`).
Close EVERY response with the trail once the map exists. You pick the form by what the turn does. `local`: `trail` draws it from the files, so paste its output verbatim. Asking → Form B, `trail --form B --item "<probe>" ... --text` (one `--item` per open probe, up to three). Menu after a decision → Form C, `trail --form C` WITHOUT `--text`: paste its `text`, then build the question tool from its `menu`. Session end → Form A, `trail --form A --text`. `github`: draw it by hand per the backend playbook.
## Session End
Report each question resolved (name + gist), what graduated, what's still open; offer a brief for today. Nothing to commit — `local` is gitignored, `github` already on the tracker. Then the mascot, then the Trail Footer.
**Web console:** at session end or on a `__stop`, post `finish` (Form A's command) BEFORE `stop` (console.md → Pathfinder).
```
⋅
╭───╮
╲│ ★ │╱
│ ◡ │ One more decision down. The fog is thinner!
╰┬─┬╯
```
**When the map cleared**, the mascot says `The way is clear! Time to plan!` and the footer routes to `/plan2code-1-plan` — or `/plan2code-init` FIRST if `## Ground rules` records `AGENTS.md` absent.
## Abort / Recovery
| Issue | Action |
|---|---|
| Session stops mid-question, or map drift | Release the claim, note why (or leave it: the next reconcile releases a claim with no answer). Work Step 2 repairs both; questions win. Never reconcile mid-question: it would release your own live claim. |
| A script cannot run (no `node`) | Say so once; do the step by hand from questions.md (markers, blocking, schema) and the reference that names the step. Footer by hand: the trail's glyph path, then Form A `NEXT STEP · start a new conversation and run:` + the command, Form B `WAITING ON YOU · answer here, in this conversation:` + the items, or Form C `OR START FRESH · new conversation, paste:` + the command. |
| Frontier empty, fog remains | Not sharp yet. Grill it into a question, or clear the map |
| Reference file missing | Use the fallback blockquote under its `Read` line |
| `gh` fails mid-session on a `github` map | Report and STOP. Falling back to local forks the map |
| User skips to planning | Their call. Name what is undecided, route to `/plan2code-1-plan` |
## Learning Capture
If charting surfaced project-specific insights, suggest `/plan2code-init-update` to capture them in `AGENTS.md`.
@@ -1,102 +0,0 @@
# Brief Playbook
> Loaded when the user's argument asks for a brief. Produces one plain-English report file for a date range — the artifact a PM pastes into Slack or reads aloud in a meeting. The only mutation BRIEF mode ever performs is the Work Step 2 reconcile; it never claims, resolves, or answers a question.
> **Backend note.** The report is IDENTICAL either way — same sections, same plain-English rules — and the brief file always lands on **local disk** under `specs/<idea>/pathfinder/briefs/`, even on `**Backend:** github`. What differs is where the inputs come from: on `github` the range filter reads each question issue's close date instead of a `Resolved:` line, and the open / blocked / out-of-scope sections come from the frontier query rather than the checklist — see `github-issues.md`. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
## When it fires
The argument (or message) asks for a `brief`, `summary`, `recap`, or `minutes` for an idea, with an optional range:
```
/plan2code-0-pathfinder write a brief for today for specs/<idea>/pathfinder
/plan2code-0-pathfinder brief since 2026-08-15 for specs/<idea>/pathfinder
/plan2code-0-pathfinder full brief for specs/<idea>/pathfinder
```
Translate the person's words into the script's range: `today` (the default when unstated) · `this-week` (Monday through today) · `since:<YYYY-MM-DD>` · `<YYYY-MM-DD>..<YYYY-MM-DD>` · `full` (everything since the map was created). Resolve a relative phrase ("since Tuesday") to a date yourself; the script takes dates only and reads today from the clock.
No `map.md` for the idea? There is nothing to brief — say so and route to charting. `**Status:** Cleared`? A brief is still legitimate: cover the full history and point at the PLAN-DRAFT in `## Next step`.
## Procedure
1. **Resolve the idea** exactly as Auto-Discovery does.
2. **Reconcile first**: `node "<S>/pathfinder.mjs" reconcile specs/<idea>/pathfinder`. A brief must never disagree with the map it summarizes, which is why BRIEF mode repairs drift rather than reporting it. Keep its `repairs` for step 5.
3. **Gather**: `node "<S>/pathfinder.mjs" brief-data specs/<idea>/pathfinder --range <range>`. It filters resolved questions by `Resolved:` date and returns every section's source (below), the file to write, and `drift` / `undatedResolved` (both empty after step 2; if not, rerun step 2). Out-of-scope rulings are never date-filtered: standing scope boundaries appear in every brief.
4. **Write** the file at its `file` path (create `briefs/` if absent). The name carries today's date regardless of range; the `**Covers:**` line disambiguates. Same-day re-runs overwrite (`exists: true`): a brief is a report, not a record; the question files remain the record.
5. **Report** in chat: the file path, the range, one line on any reconcile repairs. Then the Trail Footer, Form A (the session is over; the command routes by map status as usual). Run `lint` first: it checks the brief for percent signs and scraper bait.
## The template
Substitute real content; keep the section order. `<in range>` reads naturally per range: "Decided today", "Decided this week", "Decided so far" (full).
```markdown
# Audit log export - decisions brief
**Covers:** 2026-09-02 · **Map:** 6 of 9 decisions made
## Where this is headed
<The destination, verbatim from the map.>
## Decided today
- **Export format** - CSV with a UTF-8 BOM plus a SHA-256 manifest file.
Rejected: JSONL (recipients open these in Excel); XLSX (harder to verify byte-for-byte).
*Recorded as hard to reverse.*
- **Export authorization** - new tenant-scoped compliance role; self-events included but flagged.
Rejected: reusing the admin role (no tenant scoping today).
## Ruled out
- **SIEM push connector** - continuous streaming is a separate effort with its own owner.
## Open - ready to decide next
- **Delivery channel** - can now be decided; the row-count ceiling it was waiting on landed today.
- **Testing posture** - needs Product and Engineering together.
## Open - waiting on something first
- **Redaction rules** - waiting on Legal's answer about exporting raw payloads.
## Still taking shape
- How far back an export may reach - depends on a retention answer nobody has yet.
## How solid is this?
Solid overall, but risk handling is borderline - one limit has no decided behavior past it yet.
## Next step
Run: `/plan2code-0-pathfinder specs/audit-log-export/pathfinder`
---
*Full reasoning behind every decision: `specs/audit-log-export/pathfinder/questions/`*
```
**How each section is built:**
| Section | `brief-data` field | Rendering rule |
|---|---|---|
| Heading + `**Covers:**` | `title`, `covers`, `progress` | `progress` already uses the trail's counting rule (out-of-scope excluded from the total) |
| Where this is headed | `destination` | Verbatim. Never paraphrase it |
| Decided `<in range>` | `decidedHeading`, `decided` (`name`, `gist`, `rejected`, `hardToReverse`) | Question name bold, gist as the first line, each `rejected` entry compressed to ONE line with the why in parentheses. `hardToReverse` renders as *Recorded as hard to reverse.* — never the word "locked". Empty → `note` |
| Ruled out | `ruledOut` | One line each: name + why, link markup dropped |
| Open - ready to decide next | `ready` | Flag each `justUnblockedBy`: "can now be decided; X landed <day>" |
| Open - waiting on something first | `waiting` | Name the blocker in plain words ("waiting on the export format decision"), never `Blocked by: 02` |
| Still taking shape | `fog` | Lightly rephrase each bullet into one plain sentence |
| How solid is this? | `confidence` | Already the plain-English line. Omit the section when it is null |
| Next step | `nextStep` | `command` as given; with a `plan`, point at that PLAN-DRAFT too |
Nothing decided in the range? Keep the file honest: "No decisions were recorded in this period." under Decided, and render the open sections as usual — a meeting that only surfaced questions still gets minutes.
## Rules
- **Zero pathfinder machinery in the file.** No `NN` numbers, no markers, no `Type:`/`State:` tokens, no fog/frontier/grill vocabulary, no `Locked:`. Questions are referred to by name only, no links. The audience may never open a terminal.
- **Scraper safety, same as the PLAN-DRAFT:** no `%`, no raw `NN/25` scores, and no bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number anywhere in the file. The plain-English confidence line is the only rendering permitted.
- **Standing `specs/` rules apply:** no loop tokens, no `- [ ]` checkboxes, no `METRICS_JSON`.
- **Rejections are one line each.** The brief summarizes; the question file argues. The closing pointer line covers readers who want the full reasoning.
- **BRIEF mode does not count as question work.** It does not count toward the session's decision cadence; no claim is ever taken.
- **Do not edit an old brief to "update" it.** Yesterday's brief reflects yesterday's map — write today's instead. Same-day overwrite only.
@@ -1,691 +0,0 @@
# Chart Playbook
> Part of plan2code-0-pathfinder — loaded at the top of MODE A (Chart). Expands the numbered Chart steps.
>
> **Backend note.** Steps 0, 2, and 4 — the gates and the grills — are identical either way, and so is every judgement call below (fog vs question, in scope vs out, the destination test). What differs is where Steps 3 and 5-7 put the bytes: on `**Backend:** github`, `github-issues.md` overrides the `map.md` and question-file templates here, the single-pass rule under *Step 6: Numbering and dependency order*, and the timing of the recon. Read it alongside this file, not instead of it.
Charting produces a map and a set of question files. It resolves nothing by hand. Every judgement below serves one goal: put a sharp question on the map for everything you can phrase now, and leave everything else honestly in the fog.
---
## Step 0: The intent gate
Pathfinder builds an apparatus — a directory, a map, a file per decision. That apparatus earns its keep only when the way to the destination is genuinely foggy. For a small or already-clear ask it is pure overhead, and creating it before the human has agreed to it is the fastest way to make Pathfinder feel heavy and get in the way. So the gate runs **before the first byte hits disk**.
You already have the idea name from Auto-Discovery. Do NOT create the directory yet. Say, in substance:
> "This is Pathfinder. Nothing exists for `<idea>` yet. Pathfinder charts a map of the open decisions when an idea is big or unclear to plan — but that is overhead if this is small or already clear. Three ways to go:
> - **Chart it** — I map the open decisions, we clear them one at a time, then hand a draft to `/plan2code-1-plan`.
> - **Straight to `/plan2code-1-plan`** — the way looks clear enough to plan now.
> - **`/plan2code-quick-task`** — small enough to just do.
>
> My read: `<recommendation with a one-line reason>`. Which?"
Rules for the gate:
- **It is HITL.** You recommend; the human chooses. Never self-select "chart" and start creating files because it is the default path — that is exactly the failure this gate exists to stop.
- **Read the request honestly.** A one-line bugfix, or a change with no open decisions, is not a charting job — recommend an off-ramp and mean it. Reserve "chart" for real fog: several unsettled decisions, unclear scope, or competing designs. A joint Product + Engineering kickoff on a fresh idea is the canonical "chart it" case — a new feature explored by two teams is fog almost by definition.
- **No disk writes.** Naming the idea and talking is free. Creating `specs/<idea>/pathfinder/` is not — it waits for an explicit "chart."
- **On an off-ramp, route and STOP.** Point at `/plan2code-1-plan` or `/plan2code-quick-task`, create nothing, end the session. If `AGENTS.md` is absent, mention `/plan2code-init` first, as with any handoff.
This gate and the Step 4 no-fog off-ramp are the same instinct at two moments: the gate is the human's call before any work; the off-ramp is your call once the breadth-first grill has proven there was no fog after all. Either one ending the session without a map is a success, not a failure.
---
## Step 2: The destination grill
The destination is settled **first** because it fixes scope. Every later judgement — is this a question or fog, is this in scope or past the edge, is this map cleared — is measured against it. A vague destination makes all three unanswerable, and you will spend the rest of the map arguing about boundaries instead of decisions.
A destination is **one or two lines** describing what exists when the map clears. It is not a feature description. It is not a value proposition. It names the artifact and draws the edge.
### The script
Recommend an answer with each probe — the human corrects faster than they compose. Follow the grilling playbook for tone, cadence, and the batching rules; this is the content.
**Six probes, two batches.** They do not all pass the independence test, so they split:
| Batch | Probes | Why they go together |
|---|---|---|
| First | 1 (artifact), 2 (person), 6 (forcing function) | Each stands alone. None reads differently under the others' answers. |
| Second | 3 (sacrificial boundary), 4 (smallest arrival), 5 (arrival signal) | All three presuppose an artifact and an actor. Sending them before batch 1 lands asks the human to draw an edge around something unnamed. |
Two round trips, not six. Three probes each — exactly the cap, so neither batch needs splitting.
Batch 2 bends the independence test on purpose. The arrival signal (5) can shift under the smallest arrival (4), so strictly it should be held back — but holding it costs a third round trip to catch a conflict that is rare and cheap to spot. The trade is to send them together and reconcile at the recap: if the smallest arrival comes back materially smaller than the artifact you were told about, re-check the arrival signal against it before writing the destination. A knowing trade here, not a licence to batch dependent probes elsewhere.
**Both batches go through the structured question tool.** Give each probe genuine candidate options with trade-offs and a recommendation; the built-in `Other` path is where the human composes the actor, a further feature to leave out, the arrival signal, or forcing-function detail in their own words. A clicked option is not written verbatim as the destination — the recap-confirmation tool call turns all six answers into the agreed one-or-two-line destination before disk write.
**Probe 1 — the artifact**
> "When we are done here, what exists that does not exist now: a plan you hand to `/plan2code-1-plan`, a decision recorded before anyone plans, or a change already made in the codebase? My guess: a plan."
*Fishing for:* the shape of the destination. Push back if the answer is "the feature working" — that is past the edge of every pathfinder map. Say so plainly: "That is the build. The map ends at the plan for the build."
**Probe 2 — the person on the other end**
> "Who uses the result, and what do they do with it the day it lands?"
*Fishing for:* the actor and the moment of use. Vague actors ("users", "the business") produce vague scope. Push until you get a role someone could name in an approval — compliance officer, on-call SRE, tenant admin.
**Probe 3 — the sacrificial boundary**
> "Which of these features are we leaving out this time?"
Deliver it as a multi-select (`multi` on the web console) of 3–5 features a reasonable person might expect to be included. Every option names a feature ("Scheduled exports"), never a rule to keep ("Exports stay manual"). Each option's description ends "(Leaving this out = …)", naming what that leaves. Offer a recommended preset of the ones you would leave out; the free-text path lets them name another feature.
*Fishing for:* the first `## Out of scope` bullets — the ticked features become them. This probe does more work than any other. If nothing is ticked, push once: a destination nobody has excluded anything from has not been thought about. The preset is the push.
**Probe 4 — the smallest arrival**
> "What is the smallest version that would still count? If only that existed, would you call it done or would you feel cheated?"
*Fishing for:* the difference between the destination and the wish list. Everything above the smallest arrival is a candidate for out of scope or for a later effort.
**Probe 5 — the arrival signal**
> "How will you know it's done — what do you look at?"
*Fishing for:* a checkable condition. "It feels right" is not one. "Every open decision has an answer and I can hand the draft to planning without re-litigating format" is one.
**Probe 6 — the forcing function**
> "What made this come up now? A deadline, an incident, an audit, a customer?"
*Fishing for:* constraints that will shape half the questions and that nobody volunteers unprompted. A regulatory deadline changes the delivery question, the testing posture question, and the out-of-scope line all at once.
**The probe names above are internal labels, not headings the human reads.** Head each Q block plainly — *What you end up with*, *Who uses it*, *Leave for later*, *Smallest version that counts*, *How you know it's done*, *Why now* — and keep the probe text itself as plain as the quotes above. "The sacrificial boundary" and "the arrival signal" mean something to this playbook and nothing to the person answering. Full rule in the grilling playbook, *Say it in plain English*.
### Worked example — same idea, two destinations
**Idea:** "we should let people export audit logs"
**BAD destination**
> Let users export audit logs so they have their data.
Why it fails, concretely:
| Failure | Consequence downstream |
|---|---|
| No artifact named | Nobody knows whether the map clears at a plan or at shipped code |
| "Users" is not a role | The authorization question cannot even be phrased |
| No edge | Live streaming, SIEM push, and a schema redesign all argue their way in |
| No arrival signal | The Clearing Gate has nothing to check against |
| "their data" is a rationale, not a boundary | Every fog bullet reads as in scope |
**GOOD destination**
> A locked implementation plan for a compliance officer to export a filtered range of audit events from the admin UI and receive them as a single downloadable file. The map ends at the plan, not at shipped code. Continuous streaming to external systems is not on the route.
Three sentences, two lines of substance: artifact (a plan), actor (compliance officer), trigger surface (admin UI), shape of the result (one downloadable file), and an explicit edge (no streaming). Every one of those clauses will be cited later when you decide whether something is a question, fog, or out of scope.
**Write the destination into `map.md` verbatim as agreed.** Do not improve it afterwards. If it needs changing, change it with the human present — a silently redrawn destination invalidates every scope call already made.
---
## Step 3: Codebase recon
Recon is `legwork · AFK` — you do it alone, and you write it down **already resolved**. It exists so that no later session re-reads the same directories, and so that the handoff carries the ground truth `/plan2code-1-plan` Phase 2 (System Context Examination) would otherwise have to rediscover.
`questions/00-codebase-context.md` is always `00`. It always exists. It is created with `State: resolved` and a filled `## Answer` in the same write.
### What to explore
| Area | What to establish | Where to look |
|---|---|---|
| **Directory structure** | The map of the repo at the depth that matters for this destination — not every folder, the ones the work will touch | Top-level listing, then two levels into the relevant subtrees |
| **Key components** | The modules that would be read, changed, or called. Name, path, responsibility | Entry points, route/controller registries, service layers |
| **Patterns and conventions** | How this codebase does the thing you are about to plan: error handling, validation, config, module layout, naming, async style | Two or three recent files in the target area, plus `AGENTS.md` |
| **Integration points** | External systems, queues, storage, auth providers, feature-flag services the work will cross | Config files, environment variable references, client wrappers |
| **Technical debt in the blast radius** | Only debt the destination would collide with. Not a repo-wide audit | Long files in the target area, duplicated helpers, stale TODO markers with no owner |
| **System boundaries** | What this effort owns versus what it merely calls. Where the change stops | Package boundaries, ownership files, API contracts |
Two disciplines keep this file useful:
- **Verify behaviour against actual code, never against a filename.** A file called `auditLogger.ts` may log nothing.
- **Scope the recon to the destination.** A recon of the whole repo is unreadable and stale in a week. If a subtree cannot plausibly be touched by the destination, say so in one line and move on.
Record what you could **not** determine as an explicit gap. Gaps at recon time are often the first real fog bullets.
### The literal file
```markdown
> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.
# Codebase context
Type: legwork · AFK
State: resolved
Blocked by: none
Claimed: 2026-08-03 09:12
Resolved: 2026-08-03
Locked: no
## Question
What does this codebase already provide, constrain, and forbid for an operator-initiated
audit-log export? Establish structure, components, conventions, integrations, debt in the
blast radius, and boundaries — enough that no later session re-reads the same ground and
enough to hand to `/plan2code-1-plan` as its system context.
## Answer
### Directory structure
- `src/api/` — Express routers, one file per resource. `src/api/admin/` is the admin surface.
- `src/services/` — business logic; the only layer allowed to touch `src/db/`.
- `src/db/` — Knex query builders and migrations. `audit_events` lives here.
- `src/jobs/` — BullMQ workers. Existing precedent for long-running work.
- `src/web/admin/` — React admin UI, TanStack Query, colocated route components.
- `test/` — Vitest, mirroring `src/` one-to-one.
Untouched by this destination: `src/billing/`, `src/web/marketing/`.
### Key components
| Component | Path | Responsibility |
|---|---|---|
| `auditEvents.record()` | `src/services/auditEvents.ts` | Sole writer of `audit_events`; called from 31 sites |
| `adminRouter` | `src/api/admin/index.ts` | Mounts admin routes; applies `requireAdmin` |
| `requireAdmin` | `src/api/middleware/auth.ts` | Session check plus role check; no per-tenant scoping today |
| `reportQueue` | `src/jobs/reportQueue.ts` | BullMQ queue used by the existing billing report export |
| `signedUrl()` | `src/services/storage.ts` | S3 pre-signed URL helper, fixed 15-minute expiry |
### Patterns and conventions
- Errors: typed error classes thrown from services, mapped to HTTP by `errorHandler`. Never raw `res.status(500)`.
- Validation: Zod schema per route, exported next to the handler.
- Config: everything through `src/config.ts`; no direct `process.env` reads outside it.
- Async: `async`/`await` throughout. No callback style remains.
- Long-running work: enqueue to BullMQ, return `202` with a job id. Established by billing reports.
- Tests: Vitest, colocated fixtures, no shared mutable state between cases.
### Integration points
- **Postgres 15** via Knex. `audit_events` is ~180M rows, partitioned monthly.
- **Redis** backing BullMQ.
- **S3** for generated artifacts; the billing export already writes there.
- **SES** for transactional mail; templates in `src/mail/templates/`.
- No SIEM, log-shipping, or streaming integration exists today.
### Technical debt in the blast radius
- `audit_events` has an index on `(tenant_id, created_at)` but none on `actor_id`. Any
actor-filtered export will sequential-scan a partition.
- `requireAdmin` does not scope by tenant — a platform admin currently sees all tenants.
Any authorization decision here inherits that gap.
- The billing export writes CSV by hand-rolled string concatenation with no escaping.
Do not copy it.
### System boundaries
Owned by this effort: a read path over `audit_events`, an admin UI surface, an artifact
written to S3, and a delivery notification. Not owned: the write path (`auditEvents.record()`
is untouched), the audit event schema, tenancy semantics in `requireAdmin`.
### Gaps
- Retention policy for `audit_events` is not expressed anywhere in code. Someone outside
engineering owns it.
- No load figures exist for the largest tenant's monthly event count.
**Gist:** Node/Express/Knex/React with an established BullMQ-to-S3 export precedent from
billing; `audit_events` is 180M rows partitioned monthly with no `actor_id` index, and
`requireAdmin` has no per-tenant scoping.
## Evidence
- `src/api/admin/index.ts`, `src/api/middleware/auth.ts`
- `src/services/auditEvents.ts`, `src/services/storage.ts`
- `src/jobs/reportQueue.ts` and the billing export job it drives
- `src/db/migrations/20240914_partition_audit_events.js`
- `AGENTS.md` (conventions section)
```
---
## Step 4: The breadth-first frontier grill
The destination grill went **deep on one thing**. This grill goes **wide on everything**. They are different activities and mixing them is the most common way to produce a bad map.
| | Destination grill (Step 2) | Frontier grill (Step 4) |
|---|---|---|
| Goal | One or two settled lines | An inventory of open decisions |
| Movement | Drill until it is precise | Fan out until you stop finding new areas |
| Follow-ups | Chase every hedge | One clarifier at most, then move on |
| Success | The human commits to a boundary | You can name the areas, sharp and unsharp alike |
| Failure mode | Accepting a slogan | Solving a question instead of finding the next one |
**You are not resolving anything here.** You are taking inventory. The instant an answer feels satisfying, you are probably going deep.
### Recognising that you have gone deep
Watch for these. Any one of them means stop and pull back:
- You have asked three consecutive probes about the same area.
- You are discussing an implementation detail (a column type, a library, a retry count) rather than a decision.
- You are proposing a design instead of asking what has to be decided.
- The human is enjoying it. Depth is more fun than breadth; that is exactly why it steals the session.
- You have written something down that reads like an answer.
### Pulling back
Say it out loud so the human tracks the move, then jump:
> "Good — that is one for the map, not for now. Parking it as *Export format*. Different corner: who is allowed to run an export at all?"
Two mechanics keep the fan-out honest:
1. **Round-robin the areas.** Before you start, list the axes you intend to cross — engineering axes (data, surface, permissions, volume, delivery, failure, operations, testing) AND product axes (user value, success measurement, target user, rollout, analytics, support & docs, legal/compliance). Not every axis applies to every destination: name the ones that do before the first probe, say which you are skipping and why, then take one probe per axis before any second probe on any axis.
2. **Ask for the axis you have not touched.** Near the end: "What have I not asked about that would embarrass us to discover in week three?"
**Breadth-first is the ideal batch.** One probe per axis means the probes are independent by construction — that is what breadth-first *means* — so this grill should run as batches of three, not as a stream of singles. If you catch yourself wanting to batch two probes on the same axis, that is depth wearing a batch's clothes; pull back.
**With Product in the room, the product axes are not optional.** A joint Product + Engineering session that only fans out across engineering axes produces a map Product cannot answer for — and vice versa. Alternate: an engineering batch, then a product batch, so neither team spectates for three turns straight.
### Sample breadth probes
Each opens a different axis. Batch three at a time in list order (skipping axes you ruled inapplicable), with probe 7 riding alongside the "what have I not asked about" closer above; note each answer and move.
**Every batch goes through the structured question tool.** The output is a *sort* into sharp question or fog, so the option descriptions carry the framing and the built-in `Other` path captures elaboration the named choices miss. Never ask these probes as a prose list when the tool exists.
1. **Data** — "What is the smallest and largest thing an operator could reasonably ask for in one export? Give me both ends."
2. **Surface** — "Where does this start: a button in the admin UI, a scheduled thing, an API call someone scripts?"
3. **Permissions** — "Who is allowed to run one, and can they export events about people other than themselves?"
4. **Volume and time** — "If an export takes four minutes, is that fine, bad, or a redesign?"
5. **Delivery and failure** — "The export succeeds but the download link expires before they click it. What should have happened?"
6. **Operations** — "Six months from now someone asks who exported what. Does this feature audit itself?"
7. **Testing** — "What would you need to see pass before you would let this near a customer's compliance data?" *(This one always runs — see the mandatory testing-posture question below.)*
The product axes, same style — one sample probe each:
8. **User value** — "A compliance officer gets this feature Monday morning. What stops being painful for them that day?"
9. **Success measurement** — "Three months after ship, what number or behavior tells you this was worth building?"
10. **Target user** — "Who is this for first — every tenant, one segment, one named customer who asked?"
11. **Rollout** — "Does this land for everyone at once, behind a flag, or piloted with one tenant first?"
12. **Analytics** — "What do you want to know about how people actually use it — and is any of that instrumented today?"
13. **Support & docs** — "A support ticket about this lands in week one. What does the agent need to see to answer it without escalating?"
14. **Legal / compliance** — "Does anything here touch data retention, privacy, or a regulator's definition of a record?"
Record each answer as one line in your working notes with an area label. At the end of the grill you will have two piles: lines you can turn into a sharp question, and lines you cannot. The second pile is the fog.
---
## The fog-vs-question test
This is the single most important judgement in the skill. Get it wrong toward questions and the map fills with unanswerable stubs that block the frontier. Get it wrong toward fog and the map has nothing takeable on it.
> **The test is whether you can STATE the question precisely now — not whether you can ANSWER it now.**
- **Write a question file** when the question is already sharp — *even if it is blocked and nobody can act on it yet*. Blocked questions are real questions; they get `Blocked by:` and a `[!]` row and they wait. Blocked is not the same as unformed.
- **Leave it in `## Not yet specified`** when you cannot yet phrase it that sharply. You can see there is something there; you cannot say what is being asked.
**Do not pre-slice the fog.** A fog patch is deliberately coarser than a question. One patch may graduate into three questions, or one, or none once the frontier reaches it. Splitting fog into question-shaped fragments before it is sharp invents a structure that the answers will contradict, and it costs a later session the work of deleting your guesses. Write the patch as loosely as the view allows.
A useful forcing check: **could a different person, reading only this line, know what a good answer looks like?** If yes, it is a question. If they would have to ask you what you meant, it is fog.
### Worked examples
| Candidate | Verdict | Reasoning |
|---|---|---|
| "CSV or JSONL for the export file?" | **Question** | Two named options, one decision, one sitting. A reader knows what an answer looks like. `grill · HITL`. |
| "Which roles may export events about other users?" | **Question**, blocked | Sharp today, but it depends on the tenant-scoping decision. Write it, set `Blocked by:`, mark the row `[!]`. Blockedness never demotes a sharp question to fog. |
| "Something about how big exports behave" | **Fog** | "Big" has no meaning until the volume ceiling lands. You cannot say whether the question is about pagination, streaming, timeouts, or refusal. One line in `## Not yet specified`. |
| "There is probably something about PII redaction" | **Fog** | The area is visible, the question is not. Once Legal answers, this may graduate into *which fields are redacted*, *who configures it*, and *does redaction apply to the actor or the subject* — or into nothing, if the answer is "export raw." Slicing it now guesses all three. |
| "How should we architect the export pipeline?" | **Neither — split it** | No single answer closes it; it bundles at least four decisions (sync vs queued, storage target, artifact lifetime, notification). Ask what the parts are. The sharp parts become questions, the rest becomes fog. A candidate no single answer closes is not a question. |
**What never belongs in `## Not yet specified`:** anything already decided (it is a resolved question with a gist on its row), anything that already has a question file, and anything past the destination (that is out of scope).
---
## Out of scope versus fog
Fog gathers **only toward the destination**. The destination fixes the scope, so work beyond it is not dim — it is *excluded*. It is not fog, and it must never sit in `## Not yet specified`, where a later session would try to graduate it.
**The distinction is SCOPE, not sharpness.** This is the part people get wrong. An out-of-scope item can be perfectly sharp — "should the export push to Splunk on a schedule?" is a crisp question with a crisp answer. It is still out of scope, because the destination said the map ends at an operator-initiated export. Sharpness decides *fog versus question*. Position relative to the destination decides *in scope versus out*.
| | Fog (`## Not yet specified`) | Out of scope (`## Out of scope`) |
|---|---|---|
| Position | Before the destination | Past the destination |
| Why it is not a question | Cannot be phrased sharply yet | Could be phrased perfectly — it just is not ours |
| Future | Graduates into questions as the frontier advances | Never graduates |
| Reopening | Automatic, as answers land | Only if the destination is redrawn — and then as a fresh effort, not a resumption |
| The act | An admission of ignorance | A scoping decision |
Ruling something out of scope is a **scoping act, not a step on the route**. When a question you already created turns out to sit past the destination — mis-scoped in during charting, or exposed by a later answer — run `rule-out <NN> --reason "<why>"` (resolve.md, Ruling a question out of scope mid-work): it sets `State: out-of-scope`, marks its row `[-]` and leaves one linked line in `## Out of scope` with the reason. Then handle anything it reports `stranded`. It does not get an `## Answer` and it is not a decision the route walked.
Watch for **stranded** questions: a live question whose `Blocked by:` names something now out of scope will never unblock. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
---
## Step 6: Numbering and dependency order
Upstream wayfinder creates every unit first and wires the blocking edges in a **second pass**, because a server-side tracker assigns ids and nothing can reference a sibling until it has one. On `**Backend:** local` that constraint does not exist — **you choose `NN` yourself**, so charting is a **single pass**: decide the order, then write each file complete, `Blocked by:` filled at the moment of writing.
(On `**Backend:** github` the constraint comes back, and so does the two-pass shape. Rules 1, 6, 7, and 8 below still hold — they are about dependency reasoning, not about ids. Rules 2-5, which are about `NN`, are replaced by sub-issue order; see `github-issues.md`.)
The rules:
1. **Sort by dependency before you write anything.** Sketch the edges on paper first: which decisions must land before which others can even be discussed.
2. **Blockers get lower numbers.** If *Row-count ceiling* blocks *Delivery channel*, the ceiling is `02` and delivery is `05`. This makes `Blocked by: 02` readable at a glance and makes "lowest `NN` first" on the frontier a sane traversal order.
3. **`00` is always the codebase context.** Never anything else.
4. **`NN` is never reused and never renumbered.** Not when a question is ruled out of scope, not when one is deleted, not to close a gap in the sequence. Links and `Blocked by:` lines would rot silently. Gaps in the numbering are normal and harmless.
5. **The next number is max + 1**, and `frontier` reports it as `nextNN`: one past the highest `NN` in the directory listing, on any `Blocked by:` line, or in any `questions/NN-` link in the map or a question file, and never below the map's `**Next NN:**` line. That line is a high-water mark the script keeps (every write command updates it, and it only rises), so even a deleted question that nothing links to any more never has its number handed out again. Never edit it by hand.
6. **Only depend on what genuinely gates the question.** A `Blocked by:` chain that is really a preference for reading order strangles the frontier. Ask: could this question be answered — badly but honestly — without the blocker? If yes, it is not blocked.
7. **Cycles are a phrasing bug.** If A blocks B and B blocks A, the two are one decision. Merge them or re-frame one to drop the edge.
8. **Refer by name in prose.** Bare numbers appear only on `Blocked by:` lines.
A worked ordering for the audit-log export map:
| `NN` | Name | Type | Blocked by | Why here |
|---|---|---|---|---|
| `00` | Codebase context | `legwork · AFK` | none | Always first, always resolved |
| `01` | Export format | `grill · HITL` | none | Nothing gates it; it gates the artifact shape |
| `02` | Row-count ceiling | `research · AFK` | none | A fact about the data, independent of every preference |
| `03` | Export authorization | `grill · HITL` | none | Independent axis; can be argued today |
| `04` | Testing posture | `grill · HITL` | none | Mandatory; independent of everything else |
| `05` | Delivery channel | `grill · HITL` | `02` | Synchronous download versus queued link turns entirely on volume |
| `06` | SIEM push connector | `grill · HITL` | none | Created, then immediately ruled out of scope during charting — `State: out-of-scope`, no `## Answer` |
---
## The `map.md` template
Below is a complete, realistic map for the audit-log export effort **partway through MODE B**, after two questions have resolved — it shows every marker in use. At Chart Step 5 the same file carries `**Status:** Charting`, an empty `## Question Checklist`, and no `[x]` row except `00`. Copy the structure exactly, including the HTML comments — they are written **for the next session**, which has no memory of this one.
`**Status:**` is `Charting` while Step 5 and Step 6 run, becomes `Working` at Step 7, and becomes `Cleared` only at handoff. It is how the orchestrator routes a fresh session, so it must be accurate before you stop.
Set `**Confidence:**` honestly at Step 5 and re-score it every time a question resolves. Charting scores are low by construction — that is the point. The Clearing Gate needs every dimension at 18/25 or better. Never inflate to make the gate pass.
Write the four dimension labels **hyphenated exactly as shown** — `Requirements-clarity`, `Feasibility-technical`, `Integration-points`, `Risk-assessment` — in the `NN/25` form, with no percent symbol anywhere in the file. The metrics collector scrapes planning documents by regex for a bare dimension word followed by whitespace, a colon, or a pipe and then digits; the hyphen breaks that match. A percent sign or a bare `Requirements 18` would be ingested as a completed planning step's confidence score that no planning step ever produced.
Say once, at Step 5: *"This map lives in gitignored `specs/` — local to you, not shared. `git add -f` it to track it."*
```markdown
> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.
# Map: audit-log-export
*Decisions live in `questions/` — one file each. This file is just the index.*
**Status:** Working
**Updated:** 2026-08-03
**Confidence:** Requirements-clarity 18/25 · Feasibility-technical 14/25 · Integration-points 16/25 · Risk-assessment 14/25
**Next NN:** 07
<!-- Status: Charting while the map is being built (Chart Steps 1-6) -> Working once the
checklist is indexed (Chart Step 7) -> Cleared only when the Clearing Gate passes.
A fresh session routes on this line, so it must be correct before the session ends. -->
<!-- Next NN: the number the next new question file takes. Kept by the script (reconcile
adds it at Chart Step 7 and every write command raises it); it never goes down, so a
deleted question's number is never reused. Leave it out at Step 5; never edit it. -->
<!-- Confidence: four dimensions, each scored out of 25, re-scored at every resolution.
The Clearing Gate requires all four at 18/25 or better. Score against evidence. -->
## Destination
A locked implementation plan for a compliance officer to export a filtered range of audit
events from the admin UI and receive them as a single downloadable file. The map ends at the
plan, not at shipped code. Continuous streaming to external systems is not on the route.
<!-- Settled at Chart Step 2 and quoted as agreed. Every question is measured against it:
in scope or past the edge, still needed or now moot. Change it only with the human
present — a silent redraw invalidates every scope call already made. -->
## Ground rules
<!-- Standing constraints for every session on this map. Read before choosing a question,
obeyed while resolving it. Nothing here is re-asked. The first line records AGENTS.md:
"- `AGENTS.md` exists and governs." or, when it is missing, exactly
"- `AGENTS.md` is absent." (the handoff then routes to /plan2code-init first). -->
- `AGENTS.md` exists and governs. Its conventions are not re-litigated by any question here.
- One question _file_ at a time; the fork-menu between decisions; a fresh session recommended after ~3. `research` questions may run as parallel subagents.
- Every user-facing question uses the structured question tool when available; probes batch at most three. Prose Q blocks are fallback only when the tool is unavailable.
- Questions are put to the human in plain English. Technical terms only where the term is the decision.
- HITL questions are answered by the human in their own words. Never self-answered.
- No new runtime dependency is assumed without a `research` question backing it.
- Compliance language is reviewed by Dana before anything user-facing is finalised.
- Sketches are throwaway and live only under `pathfinder/sketch-NN/`.
## Glossary
<!-- Terms this effort uses precisely. Prevents two sessions meaning different things by
the same word — the cheapest correctness win on the whole map. -->
| Term | Meaning here | Avoid |
|---|---|---|
| Audit event | One row in `audit_events`: actor, tenant, action, target, timestamp, payload | log line, activity record |
| Compliance officer | Tenant-scoped role that reviews activity; not a platform admin | admin, auditor |
| Export | One operator-initiated request producing one artifact for one filtered range | download, dump, extract |
| Retention window | How far back `audit_events` is queryable; owned outside engineering | archive period |
| Signed artifact | The generated file plus a checksum a recipient can verify independently | signed file, bundle |
## Question Checklist
<!-- Rebuilt from questions/ every session — the files are ground truth, this is an index.
[ ] open (the frontier) · [/] claimed · [x] resolved · [!] open but blocked
[-] out of scope. Resolved rows carry the one-line gist from the question's Answer,
then the Resolved: date in italics — briefs filter on these dates. -->
- [x] [Codebase context](./questions/00-codebase-context.md) — Node/Express/Knex/React with a BullMQ-to-S3 export precedent; `audit_events` is 180M rows partitioned monthly, no `actor_id` index, `requireAdmin` has no tenant scoping. *(2026-08-03)*
- [x] [Export format](./questions/01-export-format.md) — CSV with a UTF-8 BOM and RFC 4180 quoting, plus a sidecar SHA-256 manifest; JSONL rejected because recipients open these in Excel. *(2026-08-03)*
- [/] [Row-count ceiling](./questions/02-row-count-ceiling.md)
- [ ] [Export authorization](./questions/03-export-authorization.md)
- [ ] [Testing posture](./questions/04-testing-posture.md)
- [!] [Delivery channel](./questions/05-delivery-channel.md) — Blocked by 02
- [-] [SIEM push connector](./questions/06-siem-push-connector.md) — out of scope, see below
## Not yet specified
<!-- The fog: in-scope areas you can see but cannot yet phrase as a question. Graduates into
question files as answers land, and the graduated bullet is deleted from here.
Do NOT pre-slice these into question-sized pieces — one bullet may become three
questions, or none. Nothing already decided, already a question, or out of scope. -->
- How far back an export may reach. There is a retention answer somewhere outside engineering
and nobody has it yet; until then we cannot say whether the question is about a hard limit,
a warning, or a per-tenant setting.
- Redaction of event payloads. Legal may say "export raw", in which case this evaporates —
or it may become several decisions about which fields, who configures them, and whether the
rule follows the actor or the subject. Revisit after Export authorization.
- What happens when an export range straddles a monthly partition that was migrated mid-range.
Cannot phrase this sharply until Export format is applied to a real query plan.
- Whether the export feature audits itself, and if so at what granularity. Suspect this is one
small question but it may turn on the authorization model.
## Out of scope
<!-- Work consciously ruled past the destination. Never graduates; returns only if the
destination is redrawn, and then as a fresh effort. One line each: gist plus why. -->
- [SIEM push connector](./questions/06-siem-push-connector.md) — scheduled push to Splunk or
similar. The destination ends at an operator-initiated export; anything continuous is a
different effort with a different owner.
- Redesign of the `audit_events` schema. The write path is untouched by this destination;
changing it would pull in all 31 call sites of `auditEvents.record()`.
- Adding the missing `actor_id` index. Real, and it will hurt, but it is a database change
with its own review path. Recorded here so the plan can reference it as a dependency
rather than absorb it.
```
---
## The question-file template
Six contiguous `Key: value` lines after the H1. Not YAML. No frontmatter delimiters. No `- [ ]` checkboxes anywhere inside a question file — use plain bullets, including for legwork checklists.
`## Question` is written at charting. `## Answer` is appended only when the question resolves. `## Evidence` holds sources, links, and artifacts, and a `research` subagent writes into it during Chart Step 8 without deciding anything.
### An open question
```markdown
> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.
# Export authorization
Type: grill · HITL
State: open
Blocked by: none
Claimed: none
Resolved: none
Locked: yes
## Question
Who may run an audit-log export, and over whose events?
Three sub-decisions, all of which must land together because any two of them constrain the third:
- Which role gates the export action — the existing `admin` role, a new `compliance` role, or
a per-tenant grant?
- May an exporter include events where they are the actor, or must self-events be excluded to
keep the export usable as evidence?
- `requireAdmin` currently does not scope by tenant, so a platform admin sees every tenant's
events. Does the export inherit that, or does it enforce a tenant scope the rest of the
admin surface does not?
Recommended answer to react to: a new tenant-scoped `compliance` role; self-events included
but flagged in a column; the export enforces tenant scope even though the surrounding admin
surface does not.
Marked `Locked: yes` — the third sub-decision creates a precedent that later admin features
will follow, and reversing it later means re-auditing every export already delivered.
## Evidence
- `src/api/middleware/auth.ts` — `requireAdmin` checks session and role, no tenant predicate.
- Codebase context records the same gap under technical debt.
```
### A resolved question
```markdown
> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.
# Export format
Type: grill · HITL
State: resolved
Blocked by: none
Claimed: 2026-08-03 10:41
Resolved: 2026-08-03
Locked: yes
## Question
What file format does an export produce, and what does a recipient need in order to trust the
file has not been altered?
## Answer
**Decision.** CSV, UTF-8 with a byte-order mark, RFC 4180 quoting, one header row, timestamps
in ISO 8601 UTC. Alongside it a sidecar `.sha256` manifest listing the artifact filename and
its digest.
**Rejected.**
- *JSONL* — better for nested payloads and trivially streamable, but every named recipient
opens these in Excel and would need a conversion step during an audit. The people who
prefer JSONL are not the people receiving the file.
- *XLSX* — solves the Excel encoding problems outright, but adds a generation library and
makes byte-level verification of the artifact meaningfully harder.
- *Detached signature instead of a checksum* — real integrity guarantees, but requires key
management nobody has scoped, and no recipient has asked to verify a signature.
**Consequences.**
- Nested `payload` is flattened to one JSON string column. Anyone needing structure parses
that column.
- The BOM is required or Excel mangles non-ASCII actor names. This must be an explicit test.
- Do not reuse the billing export's CSV writer — it concatenates strings with no escaping.
A quoting-correct writer is now in scope for the plan.
- The checksum makes the artifact self-verifying, which lets Delivery channel consider a
short-lived link without weakening the integrity story.
**Gist:** CSV with a UTF-8 BOM and RFC 4180 quoting, plus a sidecar SHA-256 manifest; JSONL
rejected because recipients open these in Excel.
## Evidence
- RFC 4180, sections 2.5-2.7 (quoting and embedded delimiters).
- `src/jobs/billingExport.ts` — the hand-rolled writer that must not be copied.
- Dana confirmed on 2026-08-03 that external auditors accept a published checksum.
```
---
## Step 4: The no-fog off-ramp
If the breadth-first grill surfaces **no fog** — every area you opened produced either a settled answer or a question you could phrase immediately, and `## Not yet specified` would be empty — then the way to the destination is already visible. The journey is small enough to plan directly and a map would be pure overhead.
Do this, in order:
1. **Keep `questions/00-codebase-context.md`.** This is the important part. It is exactly what `/plan2code-1-plan` Phase 2 (System Context Examination) has to produce anyway, and you have already produced it. Throwing the recon away to "clean up" wastes the most valuable artifact of the session.
2. **Do not create `map.md`.** The off-ramp fires at Step 4 and the map is not written until Step 5, so in the normal flow there is nothing to delete — just stop before writing it. (If you reached Step 4 with a `map.md` already on disk, delete it: a map with empty fog and no open questions will confuse the next session into resuming something that does not exist.)
3. **Tell the user plainly what happened and what to do:**
> "No fog surfaced — the way to the destination is already visible, so this does not need a map. I kept the codebase recon at `specs/audit-log-export/pathfinder/questions/00-codebase-context.md`; attach that file to a `/plan2code-1-plan` session and it covers Phase 2 outright."
4. **Stop.** Do not chart anyway "just in case", do not create questions, do not start planning in this session.
Be honest about the trigger. If two areas are genuinely unformed, that is fog and the map earns its keep. The off-ramp is for the case where you fanned out across every axis and kept landing on solid ground.
---
## Step 6: The mandatory testing-posture question
**Every map includes a `grill · HITL` question on testing posture.** No exceptions, including maps where testing feels obvious.
The reason is mechanical: `/plan2code-1-plan` Phase 1 asks for three things — testing types, whether tests run after each implementation phase, and a coverage target — and `/plan2code-2-document` **string-matches** that answer, either appending a testing block to every phase, creating a dedicated final testing phase, or omitting testing entirely. A map that clears without this answer hands the human a planning session that stalls on its first question. Ask it while there is still someone in the room.
Record the answer in the literals downstream matches on, not in paraphrase. ("Phase" here names `/plan2code-1-plan`'s implementation phases and is a downstream contract string — it is never a pathfinder unit of work.)
It is almost never blocked. Give it whatever number the dependency ordering leaves free, and expect it to sit on the frontier from day one.
```markdown
> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.
# Testing posture
Type: grill · HITL
State: open
Blocked by: none
Claimed: none
Resolved: none
Locked: no
## Question
What testing does this work carry, so `/plan2code-1-plan` Phase 1 can be answered without
stalling? Three parts, all needed:
- **Types** — unit, integration, end-to-end, some combination, or none.
- **Phase testing** — record one of the two literals `/plan2code-2-document` matches:
`Run after each phase` (a testing block closes every implementation phase) or
`Dedicated phase only` (one final testing phase).
- **Coverage target** — record one of Phase 1's three literals: `Critical paths`,
`Moderate (~60-80%)`, or `Comprehensive (>80%)`.
Recommended answer to react to: unit plus integration; `Run after each phase`;
`Critical paths`. Rationale — this touches compliance data, so the correctness of the
CSV writer and the authorization predicate must be pinned by tests, but the admin UI is thin
enough that end-to-end coverage would cost more than it catches.
Two specific cases worth naming in the answer regardless of the general posture, because
Codebase context shows both are easy to get wrong here:
- The UTF-8 BOM survives Excel round-tripping for non-ASCII actor names.
- The tenant-scope predicate actually excludes other tenants' events, asserted against seeded
cross-tenant data rather than a mock.
Note for whoever resolves this: the coverage target is a number the human owns. Do not infer
it from the codebase's current coverage, and do not soften it to whatever the repo already
achieves.
## Evidence
- `AGENTS.md` records Vitest as the runner with fixtures colocated under `test/`.
- Codebase context: no end-to-end harness exists today; adding one is a real cost, not a flag.
```
@@ -1,474 +0,0 @@
# GitHub Issues Backend
> Part of plan2code-0-pathfinder — loaded at the top of EVERY session whose map lives on GitHub Issues. It re-expresses the local-file model in issue terms: where the map lives, where a question lives, how blocking, claiming, and resolving are done, and what stays on local disk regardless.
>
> **Local-file maps never load this file.** If `## Ground rules` says `**Backend:** local`, close it and use `questions.md`.
Everything the skill says about *judgement* is unchanged by the backend: the fog-vs-question test, the destination grill, one question at a time, the decide-menu-checkpoint cadence, HITL is never self-answered, the Clearing Gate rubric. This file changes only *where the bytes go*.
---
## Why a second backend exists
Local files are private scratch — `specs/` is gitignored, so the map is yours alone and nobody else can see it, comment on it, or resolve a question in parallel. That is the right default for a solo effort.
A map on GitHub Issues buys three things local files cannot:
| | Local files | GitHub Issues |
|---|---|---|
| Visibility | One machine, one person | Anyone with repo access, in a UI they already have open |
| Blocking | A `Blocked by:` line only an agent reads | Native issue dependencies — GitHub greys out blocked issues in its own UI |
| Concurrency | One session at a time by construction | Several people can work unblocked questions at once; the assignee is a real lock |
It costs three things too, and the human must know all three before they pick it:
1. **Issues on a public repo are public.** The destination, the rejected alternatives, the codebase recon, the technical debt in the blast radius — all of it is world-readable the moment it is written. Never chart to a public repo's tracker anything that would embarrass the project or leak a customer.
2. **It writes to shared state.** A local map costs nothing to abandon. Twelve stale issues labelled `pathfinder:grill-hitl` on a team's tracker is litter someone has to clean.
3. **It needs `gh`, auth, and issues enabled.** More that can break, in a step whose whole job is to remove friction.
---
## Preflight — before the first write
Run these once, at Chart Step 1, **before** offering GitHub as an option. Any failure means GitHub is not offered at all; say why in one line and continue with local files.
| # | Check | Command | On failure |
|---|---|---|---|
| 1 | `gh` is installed | `gh --version` | Not offered — "no `gh` on this machine" |
| 2 | Authenticated | `gh auth status` | Not offered — "`gh` is not logged in" |
| 3 | Inside a repo with a GitHub remote | `gh repo view --json nameWithOwner,visibility,hasIssuesEnabled` | Not offered — "no GitHub remote here" |
| 4 | Issues are enabled | same call, `hasIssuesEnabled` | Not offered — "issues are disabled on this repo" |
| 5 | Write access | `gh api repos/<owner>/<repo> --jq .permissions.push` | Not offered — read-only access cannot chart |
Record `nameWithOwner` and `visibility` from check 3 — **`visibility` is not optional detail.** If it is `PUBLIC`, the offer must say so in the same breath, e.g. *"GitHub Issues — note `jparkerweb/plan2code` is public, so the whole map is world-readable."*
Once a map exists, preflight shrinks to checks 1 and 2. A session that cannot reach `gh` cannot work a GitHub map: say so and stop, rather than silently starting a local one.
### Labels
Create the label set at **Chart Step 5**, with the map issue — never during preflight, which must stay read-only until the human has actually picked `github`. `--force` makes it idempotent, so it is safe to re-run every session:
```bash
gh label create "pathfinder:map" --color 5319E7 --description "Pathfinder map" --force
gh label create "pathfinder:grill-hitl" --color 1D76DB --description "Decision only the human can make" --force
gh label create "pathfinder:research-afk" --color 0E8A16 --description "Fact-finding, agent alone" --force
gh label create "pathfinder:sketch-hitl" --color FBCA04 --description "Human reacts to something concrete" --force
gh label create "pathfinder:legwork-hitl" --color D93F0B --description "Manual work needing a human" --force
gh label create "pathfinder:legwork-afk" --color D93F0B --description "Manual work the agent can do" --force
gh label create "pathfinder:locked" --color B60205 --description "Hard to reverse; consequences recorded" --force
gh label create "pathfinder:out-of-scope" --color CFD3D7 --description "Ruled past the destination" --force
```
**Type and mode share one label** — `grill-hitl`, not `grill` plus `hitl` — for the same reason the local `Type:` line is one token: two labels can drift apart, and a `research` question that has quietly become HITL is a question nobody is driving.
---
## The equivalence table
This is the whole mapping. Everything below expands a row.
| Local file model | GitHub Issues model |
|---|---|
| `specs/<idea>/pathfinder/map.md` | One issue, labelled `pathfinder:map`, titled `Map: <idea>` |
| `questions/NN-<slug>.md` | A **sub-issue** of the map, titled with the question name |
| `NN` ordering | The map's sub-issue order — the order they were created, which is dependency order |
| `## Question` in the file | The issue body |
| `## Answer` appended | A comment on the issue, opening `## Answer` |
| `## Evidence` | A comment opening `## Evidence` (a research subagent writes its own) |
| `Type:` line | The `pathfinder:<type>-<mode>` label |
| `State: open` | Issue open, **no assignee** |
| `State: claimed` | Issue open, **assigned** |
| `State: resolved` | Issue **closed as completed**, with an `## Answer` comment |
| `State: out-of-scope` | Issue **closed as not planned**, labelled `pathfinder:out-of-scope`, no `## Answer` |
| `Blocked by: 02, 04` | Native issue dependencies (`dependencies/blocked_by`) |
| `Locked: yes` | The `pathfinder:locked` label |
| `Claimed: <timestamp>` | GitHub's own assignment event in the timeline |
| `Resolved: <YYYY-MM-DD>` | The issue's own close timestamp (`closedAt`) — nothing to write, nothing to backfill |
| `## Question Checklist` in `map.md` | **Nothing** — the frontier is a live query, not a written list |
| `## Not yet specified`, `## Out of scope`, `## Ground rules`, `## Destination`, `## Glossary` | The same sections, in the map issue body |
| `sketch-NN/` | Still local disk — see *What stays on local disk* |
| `PLAN-DRAFT-<YYYYMMDD>.md` | Still local disk — see *Handoff* |
### The checklist is deleted, not ported
In local mode `map.md` carries a `## Question Checklist` because a directory of files has no queryable state. GitHub has queryable state, so **the map issue body carries no checklist at all.** Closed questions get one line each under `## Decisions so far`; open questions are not listed anywhere.
This kills the single largest source of drift in the local backend — a checklist that disagrees with the files — and it is why Work Step 2's reconcile pass is much shorter here.
---
## Refer by name
Unchanged, and harder to get right here because GitHub hands you a number for everything. In prose the human reads, write `[Export format](https://github.com/o/r/issues/42)` — never `#42`, never "issue 42", never a bare number. A wall of `#42, #43, #44` is illegible; names read at a glance.
Bare `#<n>` appears in exactly two places: inside a fallback `Blocked by:` body line when native dependencies are unavailable, and inside a `gh` command.
---
## Chart Steps 3-4 — hold the recon, protect the off-ramp
In `local` mode Step 3 writes `questions/00-codebase-context.md` the moment the recon is done, because a file in gitignored scratch costs nothing if the session then takes the Step 4 off-ramp. **On a shared tracker it costs something**: a stray issue nobody asked for, on a repo other people are watching.
So on `github`, Step 3 does the recon and **holds it in the session**. It becomes an issue at Step 6, alongside the other questions.
If the Step 4 breadth-first grill surfaces **no fog**, the off-ramp fires before anything has been created:
1. Write the recon to `specs/<idea>/pathfinder/questions/00-codebase-context.md` — a **local file**, exactly as the local backend would. It is what `/plan2code-1-plan` Phase 2 needs, and it is too valuable to throw away.
2. Create **nothing** on the tracker. No map issue, no question issues, no labels.
3. Tell the user plainly and STOP.
The tracker only ever sees an effort that earned a map.
---
## Creating the map (Chart Step 5)
Title is `Map: <idea>` — the kebab-case idea name, verbatim, so `gh issue list --label pathfinder:map` reads as an index of efforts.
```bash
gh issue create --label "pathfinder:map" --title "Map: audit-log-export" --body-file - <<'EOF'
> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.
**Status:** Charting
**Updated:** 2026-08-08
**Confidence:** Requirements-clarity 8/25 · Feasibility-technical 6/25 · Integration-points 6/25 · Risk-assessment 5/25
<!-- Status: Charting (Chart Steps 5-6) -> Working (Chart Step 7) -> Cleared at the gate.
A fresh session routes on this line, so it must be correct before the session ends. -->
## Destination
A locked implementation plan for a compliance officer to export a filtered range of audit
events from the admin UI and receive them as a single downloadable file. The map ends at the
plan, not at shipped code. Continuous streaming to external systems is not on the route.
## Ground rules
- **Backend:** github — this issue is the map; questions are its sub-issues.
- `AGENTS.md` exists and governs. Its conventions are not re-litigated by any question here.
- One question _issue_ at a time; the fork-menu between decisions; a fresh session recommended after ~3. `research` questions may run as parallel subagents.
- Every user-facing question uses the structured question tool when available; probes batch at most three. Prose Q blocks are fallback only when the tool is unavailable.
- HITL questions are answered by the human in their own words. Never self-answered.
- Sketches are throwaway and live on local disk only, under `specs/audit-log-export/pathfinder/sketch-<issue>/`.
## Glossary
| Term | Meaning here | Avoid |
|---|---|---|
| Audit event | One row in `audit_events`: actor, tenant, action, target, timestamp, payload | log line |
## Decisions so far
<!-- The index — one line per CLOSED question: enough to judge relevance, then open the
issue for the detail. Open questions are NOT listed; they are open sub-issues. -->
## Not yet specified
<!-- The fog: in-scope areas you can see but cannot yet phrase as a question. Graduates into
sub-issues as answers land, and the graduated bullet is deleted from here. -->
## Out of scope
<!-- Work consciously ruled past the destination. Never graduates. One line each: gist plus why. -->
EOF
```
Two things that must be exact:
- **`**Status:**` is still a literal line in the body.** It is how a fresh session routes, exactly as in local mode. `Charting` → `Working` → `Cleared`.
- **`**Backend:** github` is the first `## Ground rules` bullet.** It is how a fresh session knows to load this file at all. Without it, a session that opens the map issue has no way to know which playbook it is in.
Confidence keeps the hyphenated `Requirements-clarity 8/25` form for the same reason it does in local mode — the metrics collector scrapes bare dimension words followed by digits, and would ingest a planning confidence nobody scored.
**Say once, at Step 5:** *"The map lives on `<owner>/<repo>`'s issue tracker — `<PUBLIC or PRIVATE>`, so `<world-readable / visible to anyone with repo access>`. Everything charted here is visible there."*
---
## Creating the questions (Chart Step 6) — two passes, not one
The local backend charts in a **single pass** because you choose `NN` yourself and can write `Blocked by: 02` into a file before `02` exists. **On GitHub that is impossible** — an issue has no id until the server assigns one, and a dependency edge needs the blocker's id. So charting here reverts to upstream's shape:
**Pass 1 — create every question issue, in dependency order.** Blockers first. The creation order becomes the sub-issue order, which becomes the reading order for the frontier and the trail, so it is doing the job `NN` does locally. Capture each new issue's number *and* database id as you go.
```bash
# Create, capturing the URL; the number is its last path segment.
gh issue create --label "pathfinder:grill-hitl" --title "Export format" --body-file - <<'EOF'
> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.
## Question
What file format does an export produce, and what does a recipient need in order to trust
the file has not been altered?
Recommended answer to react to: CSV with a UTF-8 BOM plus a sidecar SHA-256 manifest.
EOF
# The database id — needed for BOTH wiring steps below. Not the #number, not the node_id.
gh api repos/<owner>/<repo>/issues/<number> --jq .id
```
**Pass 2 — wire the structure.** Two edges per question, both keyed on **database ids**:
```bash
# a) Attach as a sub-issue of the map. sub_issue_id is the CHILD's database id.
gh api --method POST repos/<owner>/<repo>/issues/<map-number>/sub_issues \
-F sub_issue_id=<child-db-id>
# b) Add each blocking edge. issue_id is the BLOCKER's database id.
gh api --method POST repos/<owner>/<repo>/issues/<blocked-number>/dependencies/blocked_by \
-F issue_id=<blocker-db-id>
```
**The database id is the single most common failure in this backend.** `gh api repos/o/r/issues/42 --jq .id` returns something like `2716143027`. The `42` is the *number*; `I_kwDO...` is the *node id*. The node id is rejected outright. The *number* is worse: a small integer like `42` is itself a perfectly valid database id — of some unrelated issue created years ago — so the call can succeed and silently attach the wrong thing. Fetch `.id` for every issue you are about to reference, and never hand-assemble one.
Charting still writes `00-codebase-context`'s equivalent — the Step 3 recon you held. Create it **first**, labelled `pathfinder:legwork-afk`, post the recon as an `## Answer` comment, and close it as completed in the same pass. It is resolved on arrival, exactly as in local mode, and it is what the handoff's `## System Context` is built from.
### If the endpoints are unavailable
Sub-issues and dependencies are recent GitHub features. On an instance that rejects either endpoint, fall back in the body — and say plainly, once, that the frontier will not render in GitHub's UI:
| Missing | Fallback |
|---|---|
| Sub-issues | Put `Part of #<map>` on the first line of each question body, and a task list of the questions in the map body |
| Dependencies | Put `Blocked by: #12, #14` on its own line at the top of the question body |
Prefer the native mechanisms every time they work. The whole reason to pay GitHub's costs is that the human sees the frontier in the UI without opening the map.
---
## The frontier query (Work Step 3)
The frontier is every question that is **open, unblocked, and unassigned**. Lowest position in sub-issue order wins — the same traversal `lowest NN first` gives locally.
```bash
# 1. The map's children, in order, with the state you need to filter on.
gh api repos/<owner>/<repo>/issues/<map-number>/sub_issues \
--jq '.[] | {number, title, state, assignee: .assignee.login,
blocked: .issue_dependencies_summary.blocked_by,
labels: [.labels[].name]}'
```
Then, in order:
1. Drop anything `state: closed` — that is resolved or out of scope.
2. Drop anything with an `assignee` — claimed by another session.
3. Drop anything still blocked.
4. The first survivor is the next question.
For step 3, `issue_dependencies_summary.blocked_by` counts **open** blockers, which is exactly the live gate — a blocker that closes drops the count without anyone editing anything. **Treat it as a fast pre-filter, not the authority.** If it comes back `null` or absent from the list response, or you need to *name* the blockers for the trail footer or a fully-blocked report, ask the endpoint that owns the answer:
```bash
gh api repos/<owner>/<repo>/issues/<n>/dependencies/blocked_by --jq '.[] | {number, title, state, reason: .state_reason}'
```
A question is unblocked when every blocker listed there is closed. That call is also the only way to see the next trap:
**A blocker closed as `not planned` is out of scope and will never resolve.** Its dependent is not merely blocked, it is *stranded* — the same trap as locally. Re-frame the dependent's body to drop the dependency, cut the edge, or rule it out too. Never leave it sitting: the summary count cannot tell you the difference, so this check is on you.
```bash
# Cut a dependency edge. The blocker's database id goes in the PATH here, not the body.
gh api --method DELETE \
repos/<owner>/<repo>/issues/<blocked-number>/dependencies/blocked_by/<blocker-db-id>
```
---
## Claim (Work Step 4)
```bash
gh issue edit <n> --add-assignee "@me"
```
**The session's first write, before any work.** The assignee *is* the claim — GitHub timestamps it for you, so there is no `Claimed:` line to maintain. An open, unassigned question is unclaimed; that is the whole protocol.
Unlike the local backend, other people may genuinely be working this map at the same time. Re-read the issue immediately after assigning; if someone else's login is on it, you lost the race — release yours and take the next frontier item.
---
## Resolve (Work Step 7)
Three writes, in this order. The order matters: the answer must exist before the issue closes, or a crash between them leaves a closed question with no decision in it.
```bash
# 1. The answer, as a comment. Same anatomy as a local ## Answer:
# decision, rejected alternatives with reasons, consequences, one-line **Gist:**.
gh issue comment <n> --body-file - <<'EOF'
## Answer
**Decision.** CSV, UTF-8 with a byte-order mark, RFC 4180 quoting, one header row.
Alongside it a sidecar `.sha256` manifest.
**Rejected.**
- *JSONL* — trivially streamable, but every named recipient opens these in Excel.
- *XLSX* — fixes Excel encoding, but adds a library and makes byte-level verification harder.
**Consequences.**
- Do not reuse the billing export's CSV writer; it concatenates strings with no escaping.
- Makes [Delivery channel](https://github.com/o/r/issues/45) sharper — the artifact is
self-verifying, so a short-lived link no longer weakens the integrity story.
**Gist:** CSV with a UTF-8 BOM and RFC 4180 quoting, plus a sidecar SHA-256 manifest;
JSONL rejected because recipients open these in Excel.
EOF
# 2. Close as completed.
gh issue close <n> --reason completed
# 3. Append the gist to the map's Decisions so far (read body, edit, write back).
gh issue view <map-number> --json body --jq .body > /tmp/map.md
# ...append: - [Export format](<issue-url>) — <gist> *(YYYY-MM-DD)*
gh issue edit <map-number> --body-file /tmp/map.md
```
Then bump `**Updated:**` and re-score `**Confidence:**` in the same map edit.
**The close date IS the `Resolved:` date.** There is no line to set and none to backfill — `closedAt` is written by GitHub the moment step 2 runs, and a brief filters on it. Stamp the same date in italics on the `## Decisions so far` line so the map reads as a dated record on its own.
**Never edit the question body to hold the answer.** The body is the question as asked; the comment is the answer. Editing the body rewrites history and destroys the record of what was actually put to the human — which is half of why the answer is defensible three weeks later.
### Editing the map body safely
Every map mutation is read-modify-write on a body other sessions may be editing concurrently. Read it fresh immediately before the edit, apply your change to *that* text, and write it straight back. Never edit from a copy you read at the top of the session — you will silently revert whatever landed in between.
---
## Ruling a question out of scope (Work Step 8)
```bash
gh issue edit <n> --add-label "pathfinder:out-of-scope"
gh issue close <n> --reason "not planned"
```
Then one line under the map's `## Out of scope`, giving the name as a link plus the reason. **No `## Answer` comment** — there is no decision here, only a scope boundary. Add one comment saying why it is out, so the closed issue explains itself.
`not planned` versus `completed` is the load-bearing distinction: it is how a later session tells a decision that was made from a question that was ruled off the route, and it is what GitHub's UI shows at a glance. Getting it backwards puts a scope boundary into the Provenance table of the plan.
---
## Reconcile (Work Step 2)
Much shorter here — the tracker holds the state, so there is no checklist to rebuild. Four checks:
| Check | Symptom | Repair |
|---|---|---|
| Crashed mid-answer | Open, assigned, and an `## Answer` comment already exists | The comment wins. Close as completed, add the gist to Decisions so far, say so. |
| Stale claim | Open, assigned, no `## Answer`, and the assignee is you from a dead session | Unassign, say so, put it back on the frontier. **If it is someone else's login, leave it** — that is a live session, not a crash. |
| Interrupted research | An open `research` question with no `## Evidence` comment ending in `**Research complete:**` | Re-fire its subagent (`resolve.md` → Interrupted research), say so in one line. |
| Index drift | A closed, completed question with no line under `## Decisions so far` | Read its `## Answer` comment, append the gist. |
Then re-read `## Not yet specified` in full — that part is identical to local mode, and the bullet left behind after its question exists is just as corrosive here.
Local mode's `Resolved:` backfill has no counterpart here: `closedAt` cannot be absent on a closed issue. If a `## Decisions so far` line is missing its date, take the date from `closedAt` during the index-drift repair above.
---
## What stays on local disk
Three things never move to the tracker, whatever the backend:
| Artifact | Where | Why |
|---|---|---|
| Runnable sketches | `specs/<idea>/pathfinder/sketch-<issue-number>/` | Throwaway code has no business in an issue, and the quarantine rule (never in the project's own source tree) is unchanged. Link the path from the issue and note the reader needs the repo checked out. |
| `PLAN-DRAFT-<YYYYMMDD>.md` | `specs/<idea>/` | `/plan2code-1-plan` reads a **file**. This is a hard downstream contract — see Handoff. |
| Anything secret | Nowhere | Credentials, tokens, customer data. A `legwork` checklist says *where* a credential lives, never what it is — and on a public tracker that rule stops being a convention and starts being an incident. |
Sketch directories are named for the issue number rather than a local `NN`, so `sketch-42` belongs to the question at `#42`. Same rules otherwise: throwaway, one command to run, never merged.
Research subagents work the same way with one substitution: the brief carries the **issue URL** instead of a file path, and the instruction is to post findings as a comment opening `## Evidence` via `gh issue comment` — and to decide nothing. The comment ends with the `**Research complete:** <YYYY-MM-DD>` line, and the firing session waits for every subagent before Session End, exactly as on local disk. `## Answer` and the close are still written by the session that fired it.
---
## The trail footer
Identical in shape; the inputs come from the query instead of the checklist.
- **Heading** — `🧭 <idea> · <Status> · <closed>/<total> cleared`, where `<total>` excludes anything labelled `pathfinder:out-of-scope`.
- **Glyph order** — sub-issue order, the same order Chart Step 6 created them in.
- **Glyphs** — `●` closed as completed · `◉` open and assigned to you · `○` open, unassigned, unblocked · `⊘` open with `blocked_by > 0` · `⊝` closed as not planned.
- **Named legend** — names, never `#numbers`. `(blocked:<name>)` names the blocker rather than numbering it, since there is no stable `NN` to point at.
- **Confidence** — the plain-English line, from the map body's `**Confidence:**`.
Form A's resume command changes, because there is no local path to resume from:
```
NEXT STEP · start a new conversation and run:
`/plan2code-0-pathfinder https://github.com/<owner>/<repo>/issues/<map-number>`
```
Form B is unchanged — a turn that asks the human something still says `WAITING ON YOU`, still names the outstanding probes, and still emits no resume command.
Form C — the fork-menu after a recorded decision — is unchanged in shape, with two substitutions: the takeable options come from the frontier query rather than the checklist rows, and the `OR START FRESH` command carries the map issue URL. The `RECOMMENDED` marker and the ~3-decision checkpoint work exactly as `trail.md` describes.
With no script to draw them, the labels are exact: Form A `NEXT STEP · start a new conversation and run:`, Form B `WAITING ON YOU · answer here, in this conversation:`, Form C `OR START FRESH · new conversation, paste:`. The Form C question tool uses the header `Next step` and the question "Continue here, or start fresh? Everything is saved." (add "I recommend starting fresh, to keep me sharp." at the ~3-decision checkpoint). Its options are up to three takeable question names plus `Start fresh`, one marked `RECOMMENDED`.
---
## BRIEF mode
The report is identical either way, and the file still lands on **local disk** at `specs/<idea>/pathfinder/briefs/brief-<YYYYMMDD>.md` — a brief is a plain-English artifact for people, not tracker state, and writing it as an issue comment would bury it. Three substitutions against `brief.md`:
| `brief.md` says | Here |
|---|---|
| Filter resolved questions by `Resolved:` in range | Filter the map's sub-issues closed as completed by `closedAt` in range |
| Reconcile backfills absent `Resolved:` dates | Nothing to backfill; run the four reconcile checks above instead |
| Open / blocked / out-of-scope sections read the checklist | They read the frontier query — unassigned-unblocked, `blocked_by > 0`, and `pathfinder:out-of-scope` respectively |
`## Not yet specified`, `## Destination`, and `**Confidence:**` come from the map issue body, same as always. The no-machinery rule tightens rather than relaxes: no `#numbers`, no label names, no `gh` commands in the file. The reader may never have opened the tracker either.
---
## Handoff (The Clearing Gate)
The gate's four dimensions, the 18/25 bar, the hard caps, and the honesty rules are unchanged. Only the preflight and the plumbing differ.
**Preflight, GitHub form:**
| # | Check |
|---|---|
| 1 | Reconcile pass run (above) |
| 2 | Zero open sub-issues — `gh api .../sub_issues --jq '[.[] \| select(.state=="open")] \| length'` returns `0` |
| 3 | `## Not yet specified` in the map body is empty |
| 4 | Every completed question has an `## Answer` comment carrying a `**Gist:**` |
| 5 | `ls specs/<idea>/` shows no existing `PLAN-DRAFT-*.md` |
| 6 | No `## Answer` defers a choice to "whoever implements this" |
**The draft is written to local disk**, at `specs/<idea>/PLAN-DRAFT-<YYYYMMDD>.md`, with the byte-exact status line `**Status:** Phase 3 Complete - Resume at Phase 4`. This is not a preference. `/plan2code-1-plan` discovers its input with `ls specs/`; it has no notion of an issue tracker, and a draft that exists only as an issue is a draft the rest of plan2code cannot see. Create `specs/<idea>/` if charting never needed it.
Three substitutions inside the template:
| Local | GitHub |
|---|---|
| `**Planning record:** specs/<idea>/pathfinder/map.md` | `**Planning record:** <map issue URL>` |
| `[Export format](./pathfinder/questions/01-export-format.md)` | `[Export format](https://github.com/o/r/issues/42)` |
| `## Out of scope` copied line for line, only the link prefix changing | Copied line for line, links already absolute — **nothing changes at all** |
Everything else — the mapping table, Section 5 left empty, the two load-bearing `**Next:**` bullets, no scrapable confidence numbers — is unchanged.
**Freeze the map:**
1. Set `**Status:** Cleared` in the map issue body.
2. Bump `**Updated:**`.
3. Add `**Plan:** specs/<idea>/PLAN-DRAFT-<YYYYMMDD>.md` under the status line.
4. `gh issue close <map-number> --reason completed`.
5. **Close nothing else, delete nothing, edit no answers.** Every question issue stays exactly as it is — it is the rationale record behind the plan.
Closing the map is the one addition over local mode, and it earns its place: `gh issue list --label pathfinder:map --state open` then reads as *the efforts still being charted*, which is the question a person scanning the tracker actually has.
A later session that opens a map issue reading `Status: Cleared` must not resume it. Point at the PLAN-DRAFT and `/plan2code-1-plan`, and stop. A redrawn destination is a fresh effort with a fresh map issue.
---
## Failure modes
| Symptom | Cause | Fix |
|---|---|---|
| `Not Found` from a `sub_issues` or `dependencies` POST | An issue *number* was passed where a database *id* is required | `gh api repos/o/r/issues/<n> --jq .id`, retry with that |
| The wrong issue got attached | A number from another repo happened to be a valid id | Detach, re-fetch `.id` from the right repo, re-attach |
| Frontier is empty but open questions remain | Every one is blocked, or every one is assigned | Name the chain and stop — or, if the assignees are stale claims from your own dead sessions, reconcile first |
| A blocked question never unblocks | Its blocker was closed as `not planned` | Stranded. Re-frame to drop the dependency and cut the edge, or rule it out too |
| Two sessions resolved the same question | The claim was written after the work, not before | Claim is the *first* write. Merge the two answers into one comment, keep one close |
| A map edit lost someone's line | The body was edited from a stale copy read earlier in the session | Re-read the body immediately before every map write |
| `/plan2code-1-plan` finds nothing to resume | The PLAN-DRAFT was posted as an issue instead of written to `specs/<idea>/` | Write the file. The draft is always local |
| Secrets in the tracker | A `legwork` answer pasted a credential | Rotate the credential first, then delete the comment. Editing it is not enough — GitHub keeps the edit history |
@@ -1,388 +0,0 @@
# Grilling Playbook
> Part of plan2code-0-pathfinder — loaded once per session, used by Chart and Work alike.
Grilling is how a `grill · HITL` question resolves, how Chart Step 2 names the destination, and how Chart Step 4 maps the frontier. It is also the fallback for any question whose type gives you no better route. The output of a grill is a decision in the human's own words — never a decision you made on their behalf.
**Probe ≠ question file.** A *probe* is one turn of the interrogation; a *question file* is one `questions/NN-<slug>.md` on the map. Batching applies to probes only. **One question file at a time still holds** — a batch of three probes resolves ONE file; a session moves to the next file only through the fork-menu between decisions (resolve.md §Cadence), never by interleaving two grills.
**Grilling a room.** When several people answer — a Product + Engineering session — the mechanics are unchanged, plus three rules: address probes to the room, not a person, unless one person owns the call; the recap must capture the decision in the room's words, and whose call broke any tie is worth a clause in the `## Answer`; and a contested pick is NOT a decision — when Product and Engineering disagree, record both positions under `## Evidence`, leave the question `open`, and move on (or offer a `sketch` — reacting to something concrete resolves more standoffs than argument). Never average two positions into an answer nobody actually gave.
## The interview protocol
**Grilling is batched.** Put up to **three independent probes** to the human per turn, then wait. Never more than three, and never two probes where one's wording depends on the other's answer.
The old rule here was one probe per turn. It was safe and it was unusably slow: a charted map carries a dozen open questions, and a decision that costs one round trip per probe is a decision the human abandons half-finished. Batching is the default now; the discipline moved from *ask one* to *prove they are independent, then send three*.
| Rule | Why |
|---|---|
| Up to 3 probes per turn, never more | Past three the human skims, and a skimmed answer is worse than none. Three is a ceiling, not a quota — send two if only two are independent. |
| Only batch mutually independent probes | The independence test below. A probe whose wording or recommendation shifts based on another probe's answer waits for the next turn. |
| Use the structured question tool for every question when available | The built-in UI is the primary experience: selectable answers, visible skips, and `Other` for composition. Prose provides context, never the answer control. |
| Keep detail in descriptions, context, and `Other` | Batching buys round trips; it must never buy them by shrinking a decision to fit a picker. |
| Wait for the whole batch before sending the next | Their answers reshape what comes next. Pre-writing turn 2 wastes it. |
| Recommend an answer with every probe | A bare question makes the human do all the work. A recommendation gives them something to push against, which is faster and sharper. |
| Write it in plain English; keep the technical word only where that word IS the decision | A probe the human has to decode is a probe they answer approximately. See *Say it in plain English*. |
| Track the batch; re-ask what came back unanswered | This is what buys the batch. Dropped probes going unnoticed was the entire case for asking one at a time. |
| Walk one branch of the decision tree at a time | Batch across the branch's width, never down its depth. Do not ask about export scheduling before you know whether exports exist. |
| Do not act until they confirm shared understanding | Recap, get the confirmation, then write. No `## Answer` before the confirmation. |
| Never write implementation code during a grill | Grilling produces decisions. If you feel the pull to build, you have reached the edge of the map — say so and hand off. |
Shape of a single probe, batched or not:
```
Question — one decision, stated so it can be answered in a sentence.
Why it — one line: what it blocks, what breaks if it goes the other way.
matters
Recommend — your pick, with the reason. One line.
Options — the genuine alternatives, if there are more than two.
```
Worked probe, from a grill on `[Export format](./questions/04-export-format.md)`:
> **Q:** When a custodian exports a conversation that includes a 40 MB video attachment, does the export bundle the file or link to it?
> **Why it matters:** Bundling sets the size ceiling on an export job and decides whether exports can stream; linking makes the export useless once retention expires the blob.
> **Recommendation:** Bundle, with a per-job size cap of 2 GB and an automatic split into part files above that — reviewers open exports offline in tools that cannot follow links.
> **Alternatives:** Link-only (smaller, breaks offline); hybrid by MIME type (two code paths, two failure modes).
Batching does not shrink a probe. Three probes means three of these, each with its own why-it-matters and its own recommendation. Three bare questions in a list is not a batch, it is a form to fill in.
### Say it in plain English
Every probe gets read once, by a busy human, in a terminal. Write it the way you would say it out loud to a colleague who knows the product but has never read this skill. Plain is not vague — the two failures are opposite and both cost you the decision: woolly wording gets a woolly answer, dense wording gets a guessed one.
**Default to everyday words.** Short sentences, concrete nouns. "What should happen when the export is too big to email?" beats "what are the failure semantics of the artifact delivery path under a size-limit violation?" Same decision, one of them answerable on the first read.
**Keep the technical term where that term IS the decision.** A format name, a real file path, a column name, a version number, a limit, a `## Glossary` term the map already settled — those are load-bearing, and softening them makes the probe unanswerable. `.eml`-in-a-ZIP versus NDJSON *is* the choice; "normal email files versus one big machine-readable stream" is the gloss you put beside it, never the replacement for it.
> The test: would swapping the term for a plain phrase lose information the human needs in order to choose? Lose information — keep the term and gloss it. Lose nothing — cut it.
**Gloss an unavoidable term once, inline, then use it freely:** "…stored under Object Lock (S3's write-once mode — once it is set, even we cannot delete early)." Once per session, not once per probe. Re-explaining a term to the person who owns the system is its own insult.
**Never put Pathfinder's machinery in front of the human.** They are deciding something about their product; the vocabulary below is internal bookkeeping and buys them nothing:
| Do not say | Say |
|---|---|
| "this is a `grill · HITL`" | "this one is yours to call" |
| "the frontier holds two takeable questions" | "two things we can decide right now" |
| "graduating this out of the fog" | "this is sharp enough to write down as a real question now" |
| "the sacrificial boundary" | "which of these features are we leaving out this time?" |
| "shall I set `Locked: yes`?" | "worth recording why we picked this, so nobody re-opens it in six months?" |
| "Q3 is blocked by 02" | "the export format question has to land before this one" |
| "the UI cannot handle this question" | nothing — put context before the tool and preserve `Other` |
**Refer to questions by name, never by number** — "[Export format](./questions/04-export-format.md)", not "04". The number means something to the file system and to nobody else.
**No metaphor where a fact fits.** Maps, fog, and trails belong in the footer and the mascot. Inside a probe they cost a translation step: "three things here are still undecided" beats "the fog is thick in this quarter of the map."
**On a what-to-drop question, name the thing dropped.** Whenever a question asks what gets dropped, left out or cut, every option names the thing being dropped, never a rule to keep. Otherwise ticking an option reads as a double negative, and the person has to work out whether a tick means yes or no. Bad: "☐ Exports stay manual" · Good: "☐ Scheduled exports (Leaving this out = someone runs each export by hand)"
The same discipline covers everything else the human reads — the recap turn in *Landing the grill*, the option labels and descriptions in the structured tool, the sketch probes, and the HITL checklists in the resolution playbook. Plain in the question, precise in the term that carries the decision.
### The independence test
A probe may join the current batch only if **all three** hold:
| Test | Fails when |
|---|---|
| Its wording would not change under any answer to another probe in the batch | "How do we name the part files?" reads differently if the format turns out to be a single stream |
| Its recommendation would not change either | You would recommend a 2 GB cap under ZIP parts and no cap under NDJSON |
| It does not presuppose another probe's answer | "How often do scheduled exports run?" assumes scheduled exports exist |
In doubt, hold it back. A held probe costs one extra round trip. A dependent probe sent early costs a wrong answer recorded as a decision, and you will not find out until the plan contradicts itself.
Independent probes are usually the ones that came from **different areas** — data, interface, security, operations, testing. Dependent probes are usually consecutive steps down one thread.
### Delivering a batch: structured UI first
**Use the environment's structured question tool for every user-facing question when it is available.** This includes destination probes, frontier probes, claimed-question grills, recap confirmations, lock offers, sketch reactions, intent gates, and fork-menus. The built-in UI is faster to scan, preserves visible skips, and always provides an `Other` path for composed answers. Numbered prose Q blocks exist only as the fallback when the tool is unavailable.
One question object per probe, up to three per call. Never split a batch between a tool popup and prose — the prose half gets lost when the human answers in the UI.
**Composed answers still use the tool.** Do not invent a false-complete option set merely to make a picker. Offer the genuine candidates you know; the automatic `Other` option is where the human composes a boundary, rationale, hybrid, old-incident detail, or alternative you could not know. When no genuine candidate exists, offer useful control choices such as `Use recommendation` and `Defer for now`; the human writes the real answer through `Other`. A click is still followed by the normal recap-confirmation turn, which captures reasoning in the human's words.
**Artifacts do not force prose questions.** Show the state table, fake request/response, ASCII UI, or worked example in the response, then immediately invoke the structured tool for the pointed reaction probes. The artifact is prose; the questions are UI controls. Never ask "thoughts?" outside the tool.
**Never reshape the decision to fit the tool.** Descriptions carry trade-offs; `Other` carries composition. Split bundled decisions into separate probes and rename colliding short headers. Do not cut a real alternative or hide complexity. If the UI cannot represent the question faithfully even with descriptions + `Other`, state the full context immediately before the tool and keep the actual answer control in the tool.
The turn closes with the waiting footer (Form B in `trail.md`): it names outstanding probes and carries no resume command. The recap confirmation is also asked through the tool and remains Form B.
#### The structured tool
The primary channel. One question object per probe, up to three in a single call:
- **Header** — the decision in two or three plain words (`Export format`, `Size cap`). Not a type, not a marker, not a number.
- **Question** — the probe, with its why-it-matters. This is prose and it is not rationed; the same sentences you would have written in a Q block go here.
- **Options** — the genuine alternatives, each described by its trade-off, with the recommended one named as such in its description. Two to four; the free-text escape hatch covers the rest. Label plainly, then let the description carry the precise term: `One file per message` labelling the `.eml`-in-a-ZIP option, with `.eml` named in the description.
A short *label* is not a short *decision*. The label is a handle — `Fixed tick count` — and the description carries the trade-off that makes it choosable. A label bundling several independent answers is a probe that wants splitting.
**A click is a decision, not a sentence.** The HITL rule wants an `## Answer` traceable to something the human actually said, and a selected option label is thin evidence on its own. What makes tool-delivered answers legitimate is the recap turn in *Landing the grill* — you play the choices back in the tool's question text and they confirm or correct in their own words. Never skip the recap on the grounds that the tool already captured the answer; the tool captured the *pick*, and the recap captures the *agreement*.
**If a reply comes back thinner than the decision** — a bare click on something you now realise carries weight — do not paper over it. Fold the why into the recap turn as one more probe before writing the `## Answer`.
#### Numbered Q blocks
Fallback ONLY when the structured question tool does not exist or its call fails. Never choose prose merely because the answer is detailed, composed, architectural, `Locked: yes`, or attached to an artifact — descriptions + `Other` + context immediately before the tool cover those cases.
**Copy this shape exactly.** The blank lines are load-bearing, not decoration:
````markdown
Three independent decisions are open. Answer in any order, skip any you want to punt — "Q2: a, c; Q3: the hybrid" is a perfectly good reply.
---
**Q1 — Export format**
When a custodian exports a year of a channel, what do they get back?
*Why it matters:* fixes the size ceiling, decides whether exports can stream, and determines whether the review vendors can ingest without a conversion step.
*Recommendation:* **(a)** — both vendors named in Codebase context read `.eml` natively.
- **a)** ZIP of one `.eml` per message, plus `manifest.csv`
- **b)** A single NDJSON stream — compact and streamable, but nobody downstream parses it
- **c)** PST — what Legal asked for by name, but single-writer with a ~50 GB ceiling
---
**Q2 — Leave for later**
Which of these features are we leaving out this time? Tick any number.
*Why it matters:* the ones you tick become the first things written down as out of scope, and every later "is that in or out?" call is measured against them. A destination nobody has excluded anything from has not been thought about.
*Recommendation:* **(a)** and **(c)** — neither is needed for the first review hand-off.
- **a)** Scheduled exports (Leaving this out = someone runs each export by hand)
- **b)** Exports of deleted messages (Leaving this out = anything already purged stays out of the file)
- **c)** Export to a cloud bucket (Leaving this out = the file downloads to the custodian's machine only)
- **d)** Redaction inside the export (Leaving this out = the review vendor redacts after ingest)
````
Number them, keep the numbers stable across turns and sessions, and say out loud that partial answers are welcome — the invitation is what makes the skip visible instead of silent.
#### Formatting rules for a Q block
A batch is only worth sending if the human can read it. These are mechanical, and getting them wrong turns three careful probes into one unreadable paragraph:
| Rule | Why |
|---|---|
| **A blank line between every element** — the `**Qn — Name**` line, the question, *Why it matters*, *Recommendation*, and the option list | Markdown joins consecutive non-blank lines into a single paragraph. Without blank lines the entire batch renders as a wall of text and the human skims it, which is the failure the three-probe cap exists to prevent. |
| **Never hard-wrap a sentence across source lines** | The wrap is invisible to the renderer, so it buys nothing and costs you the paragraph break. Write each sentence as one logical line however long it is; the terminal wraps it. |
| **Options are a bullet list, one option per bullet** — `- **a)** …` | Indented continuation lines are the specific thing that collapses: under four spaces the indent is stripped, at four or more it becomes a code block. A bullet list survives every renderer and keeps the options scannable. |
| **`---` between probes** | Three probes run together is one block of text. The rule gives the eye a stop and makes "answer Q2 and Q3" easy to aim at. |
| **The question itself gets its own line, not a run-on with the heading** | `**Q1 — Export format.** When a custodian…` buries the decision inside a paragraph. Name it, break, then ask it. |
| **Never use spaces to convey structure** | Whatever hierarchy you indent by hand disappears on render. Structure comes from blank lines, bullets, and bold — nothing else. |
For the recap in *Landing the grill*, summarize each decision in the structured tool's question text and ask the human to confirm or correct it; use `Other` for corrections.
### When answers come back partial
Assume they will. The human answers two and drops one, and the dropped one is often the hardest and most valuable.
1. **Diff what came back against what you sent.** Skipped, answered with "Other: skip", or silently omitted all count as unanswered.
2. **Lead the next tool call with the unanswered probes**, using their original headers and full wording. Not "you missed Export scope" — the whole probe again, with its recommendation, because they have lost the context by now. Unanswered probes come *before* any new probe, and they count against the cap of three.
3. **Skipped twice, stop pushing.** Record it under `## Evidence` as an open probe with your recommendation verbatim, then either narrow it into something answerable or spin it out — a fresh question file if you can phrase it sharply, a `## Not yet specified` line if you cannot.
4. **Never promote your own recommendation into `## Answer`.** A probe the human declined twice is unanswered, not decided. Writing it up as decided is self-answering a HITL question, which breaks the skill.
Never let a dropped probe fall off the end of the session unrecorded.
## Facts you look up, decisions you ask
This is the single rule that keeps a grill from feeling like an interrogation. If a **fact** can be found by exploring the environment — filesystem, codebase, tools, docs, config, git history, the map's own resolved questions — go find it. The **decisions** are the human's; put each one to them and wait.
| You look it up | You ask |
|---|---|
| Which Postgres version the app runs against | Whether the export index is allowed to add a new table |
| Whether `ExportJob` already has a `status` column | What states that column is allowed to hold |
| How the current retention sweep is scheduled | Whether exports must survive a retention sweep |
| Whether the repo uses Vitest or Jest | Whether these paths get unit tests, integration tests, or neither |
| What the S3 bucket lifecycle rule is today | Whether we are allowed to change it |
| What `AGENTS.md` says about naming conventions | Anything `AGENTS.md` does not already answer |
Look first, then ask. A question that opens with "I checked `src/export/job.ts` — it already has a `status` enum with `queued | running | failed`. Does a partial success need a fourth state?" is worth three of "how should export status work?"
**Never ask what `AGENTS.md`, the map's `## Ground rules`, or a resolved question already answers.** Re-asking a settled decision reopens it by accident and costs you the human's trust for the rest of the session.
**When the lookup is expensive**, that is not a grill — it is a `research · AFK` or `legwork` question. Say so, note it, and keep grilling the decisions you can still put to the human.
## The HITL rule, stated hard
An agent that answers its own grill has broken the skill.
A `grill · HITL` question resolves **only** through live exchange with the human. Not from the codebase, not from a plausible default, not from "the obvious industry standard," not from what you would have picked. The whole value of the question is that a human with context you do not have chose one branch over another.
Signs you are about to break it:
- You wrote a recommendation and then wrote the `## Answer` without a reply in between.
- You wrote "assuming the user would want X" anywhere.
- You resolved a question in a session where the human said nothing but "go".
- The `## Answer` contains no sentence traceable to something the human actually said.
**When the human goes unreachable mid-grill:**
1. The claim **stays**. `State: claimed` and `Claimed:` are left exactly as they are.
2. Append to `## Evidence` — never `## Answer` — the exchange so far: the probes already answered, **every probe of the last batch still outstanding**, and your recommendation for each, verbatim.
3. End the session. Report the question by name and say it is mid-grill and waiting on the human. This one IS a session end, so the Trail Footer takes **Form A** — the pathed resume command, not `WAITING ON YOU`.
4. Invent nothing. No provisional answer, no "pending confirmation" answer, no default recorded as a decision.
The next session picks the claim back up and re-sends the outstanding batch. If the session was truly abandoned rather than paused, Work Step 2 reconciliation resets it to `open` on its own — that is its job, not yours.
## The four disciplines
Run all four continuously during any grill. They are not stages; they fire whenever the trigger appears in what the human just said.
### Challenge against the glossary
When a term conflicts with the map's `## Glossary`, call it out immediately, mid-sentence if necessary.
> "The glossary defines **Export** as a completed archive file delivered to a custodian. You just used it for the background job that builds one. Which do you mean — or do we need a second term?"
### Sharpen fuzzy or overloaded language
When a term is vague or carries two meanings, propose a precise canonical term and get a ruling.
> "You keep saying 'account.' Sometimes you mean the organization paying us, sometimes the individual login. Those are a **Customer** and a **User** and they have different retention rules. Which one owns the export quota?"
### Stress-test relationships with concrete invented scenarios
Do not ask abstractly whether a relationship holds. Invent a specific scenario that probes the edge and force a precise boundary.
> "A custodian leaves the company on the 3rd. Their retention policy expires their messages on the 5th. Legal opens a hold on the 4th. On the 6th, does the export still contain those messages?"
Invent the numbers, names, and dates. Vague scenarios get vague answers.
### Cross-reference claims against the actual code
When the human states how something works, check whether the code agrees, and surface contradictions instead of quietly picking a side.
> "You said retention deletes rows. `RetentionSweep.run()` sets `deleted_at` and leaves the row in place — a soft delete. Which is the behavior we are designing against?"
A contradiction is a finding, not an embarrassment. Surface it in the same turn you found it.
## The glossary
Domain modeling would write a `CONTEXT.md`. Pathfinder does **not** — plan2code owns `AGENTS.md`, and a competing root glossary file would collide with it. The map's `## Glossary` section is the one place resolved terms live.
Entry format — one row in the map's `## Glossary` table: the term, a one-or-two-sentence definition, and the rejected synonyms in the Avoid column:
```
| Term | Meaning here | Avoid |
|---|---|---|
| Export | A completed, immutable archive file delivered to a custodian. Always the artifact, never the process that produces it. | download, extract, dump |
| Export Job | The background unit of work that produces an Export. Has states; an Export does not. | export run |
| Custodian | The person whose communications an Export contains. Not necessarily the person who requested it. | user, owner, subject |
```
Rules:
| Rule | Detail |
|---|---|
| Update inline, never defer | The moment a term is resolved, write it into `## Glossary` and save. A term you meant to add at the end of the session is a term you lost. |
| Be opinionated | When several words compete, pick one and put the rest in the Avoid column. A glossary that lists synonyms as equals has decided nothing. |
| Keep definitions tight | One or two sentences. Define what it **is**, not what it does. |
| Only project-specific terms | "Retention Policy" belongs. "Timeout", "retry", "DTO" do not, however heavily the project uses them. |
| It is a glossary and nothing else | No implementation details, no open questions, no scratch notes, no decisions. Decisions live in question files. |
| Group under sub-bullets only when clusters emerge | A flat list is fine for one cohesive area. |
Every term you resolve is a term no later session re-litigates. That is the whole return on the discipline.
## The Lock test
Domain modeling would offer an ADR here. Pathfinder sets `Locked: yes` on the question instead — the decision record and the question are the same file.
Offer `Locked: yes` **only** when all three hold:
| Test | Meaning | Fails when |
|---|---|---|
| Hard to reverse | Changing your mind later costs real time or migration | You could flip it in an afternoon |
| Surprising without context | A future reader will ask "why did they do it this way?" | It is the obvious choice anyone would make |
| A real trade-off | There were genuine alternatives and one was picked for specific reasons | There was only ever one option |
If any one is missing, skip it. An easy-to-reverse decision will just get reversed. An unsurprising one raises no questions to answer. One with no alternative records nothing beyond "we did the obvious thing."
**What earns a lock:** architectural shape ("the export index is a materialized view, not a table"); integration patterns between components ("retention and export communicate by event, never by direct call"); technology choices carrying lock-in (database, message bus, auth provider — not every library, just the ones that would take a quarter to swap); boundary and scope decisions, including the explicit no-s; deliberate deviations from the obvious path ("hand-written SQL here, not the ORM, because the ORM cannot express the retention join"); constraints invisible in the code ("no cross-region replication — the data residency contract forbids it"); and non-obvious rejections ("we considered and rejected GraphQL, for reasons someone will otherwise re-propose in six months").
**What `Locked: yes` obliges the `## Answer` to contain:**
1. The decision itself, in one or two sentences.
2. **Every alternative genuinely considered, and why each was rejected.** This is the part that makes a lock worth having. "We rejected X" with no reason is not a lock.
3. The consequences a later reader would not guess.
4. The one-line `**Gist:**` that Work Step 7 requires, same as any answer.
Offer it, do not impose it: *"This one looks hard to reverse and the reasoning will not be obvious in six months. Lock it?"* The human decides.
**Where locks go at handoff:** the handoff playbook lifts every `Locked: yes` question into the PLAN-DRAFT's **Architecture** section, and their rejected alternatives and standing constraints into **Assumptions**. Unlocked answers still inform the draft, but locks are the ones that survive verbatim into planning. Grill them harder for that reason.
## The one grill every map must resolve, and the lens applied to all of them
### 1. Testing posture — `grill · HITL`
Chart Step 6 requires this question. It exists because `/plan2code-1-plan` Phase 1 asks for exactly three things and stalls without them: testing types, whether tests run after each phase, and the coverage target. A map that clears without answering them hands the human a plan session that immediately re-asks.
The first three probes below pass the independence test against each other — none reads differently under another's answer — so **send all three as one structured-tool batch**. Every probe has named alternatives and fixed literals; `Other` remains available.
| Probe | Recommend by default |
|---|---|
| Which types are in scope — unit, integration, E2E, or none? | Unit plus integration; E2E only where a real browser or real broker is the only honest test |
| Does the suite run after each implementation phase, or once at the end? | `Run after each phase` — work that cannot be verified when it lands cannot be signed off |
| Coverage target: critical paths, moderate (~60-80%), or comprehensive (>80%)? | Critical paths, named explicitly, rather than a percentage nobody defends |
| What is deliberately not tested, and why? | **Fourth probe, and it does not ride in the batch.** It has no option set — the explicit no-s have to be composed — and it reads differently once the types are settled. Fold it into the recap turn, where you are already waiting on them. |
| What is already there — runner, fixtures, CI wiring? | **Not a probe.** Look it up before you send the batch, and cite it in the probes above |
Record the answer in the exact literals `/plan2code-2-document` string-matches: the types; `Run after each phase` or `Dedicated phase only`; and `Critical paths`, `Moderate (~60-80%)`, or `Comprehensive (>80%)`. Not prose — a paraphrase matches no branch downstream.
### 2. Test seams and verifiability — a lens, not a question file
For each major decision on the map, ask the same question: **how will anyone know it works?** A decision nobody can verify is a decision that silently rots.
This is not a question of its own and never gets a file or an `NN`. Run it inside whatever grill is claimed; anything it surfaces that needs deciding separately becomes a new question at Work Step 8.
These six all interrogate one decision from different sides, so they batch cleanly — but they ride along inside the claimed grill rather than owning a turn. Fold the two or three that bite into the batch you were already sending; never spend a whole turn on all six.
| Probe | What it flushes out |
|---|---|
| What observable behavior changes if this decision is implemented correctly? | Decisions with no observable effect — usually a sign the question was about implementation, not design |
| What is the cheapest thing that fails when it breaks? | The seam. If the answer is "a customer complains," there is no seam yet |
| Can this be tested without a live third-party account, a real S3 bucket, a wall-clock sleep? | Untestable-by-construction designs, while they are still cheap to change |
| Where does the boundary go so a test can stand at it — an interface, a queue, an HTTP edge, a pure function? | The seam the plan will need to name |
| What does the failure look like in production — log line, metric, alert, dead-letter queue? | Verifiability after ship, not just in CI |
| If we get this wrong, how long before we find out? | Decisions that need a canary or a feature flag rather than a test |
If a decision survives all six with no answer, it is not ready to leave the map. Either re-frame the question, or add the seam as a constraint in the `## Answer` so the plan inherits it.
## Anti-patterns
| Failure mode | What it looks like | Fix |
|---|---|---|
| Batching **dependent** probes | "What format, what do we name the part files, and how big is a part?" | Only the first is independent. Send it; hold the other two — they are unanswerable until format lands. |
| Drip-feeding one probe at a time | Twelve open questions on the map, one probe per response, the human gives up on session four | Batch up to three independent probes. On a charted map the human's round trips are the scarce resource, not your token budget. |
| Losing a probe the human skipped | Sent three, got two back, moved on and never mentioned the third | Diff the batch. Lead the next turn with what came back empty, restated in full. |
| A batch of naked questions | Three one-liners with no recommendations and no why-it-matters | Every probe in a batch carries its own recommendation and its own stake. Otherwise you have offloaded the thinking, not the round trips. |
| Asking in prose when the tool exists | Numbered Q blocks or a loose "which one?" despite AskUserQuestion being available | Put every answer control in the structured UI. Use descriptions for trade-offs and `Other` for composition. Prose may provide context or an artifact immediately before the tool, never the question itself. |
| Flattening a gnarly probe into labels | An architectural decision reduced to three option labels with no useful descriptions | Keep the tool, not the flattening: put the real trade-off in each description, preserve `Other`, and recap the reasoning before recording. |
| Treating an artifact as an excuse for prose | An ASCII UI followed by "thoughts?" | Show the artifact, then invoke the structured tool with pointed reaction probes naming the rows/elements. |
| Retreating to prose over a fixable batch | Two probes collide on the short header, or one label bundles three answers | Rename the headers; split the bundled probe. Reshape the batch, never the decision. |
| Sending four probes because the tool accepts four | A fourth probe added to a clean batch of three because there was room in the call | The cap is three regardless of what the environment allows. The ceiling is the human's attention, not the tool's schema. |
| Grilling in Pathfinder's own vocabulary | "The frontier has one takeable `grill · HITL` — shall we graduate 02 out of the fog and lock it?" | Plain English. Markers, types, `NN` numbers, and fog are your bookkeeping; the human is deciding about their product. |
| Plain-washing the load-bearing term | "Do you want the friendly file or the compact one?" where the real choice is `.eml`-in-a-ZIP versus NDJSON | Plain wording, precise nouns. Name the formats and gloss them; a decision made on a euphemism cannot be written into `## Answer`. |
| Asking what the codebase already answers | "Do you use Postgres or MySQL?" | Look. Every avoidable question spends trust you need for the hard ones. |
| Accepting a vague answer and moving on | "Handle it sensibly" → recorded as the decision | Push once more, concretely: "Sensibly meaning we drop the attachment, or fail the whole job?" A vague answer is not an answer. |
| Leading the human to your preferred answer | "You'd want Postgres here, right?" | Recommend openly, then present the real alternatives with their real merits. A recommendation invites a fight; a leading question suppresses one. |
| Grilling past the decision into implementation | "Should the retry helper take a callback or return a promise?" | That is the plan's job, or the implementer's. Stop at the decision. The pull to keep going is the edge of the map. |
| Drifting off the claimed question | Claimed `[Export format](./questions/04-export-format.md)`, forty minutes later deep in auth | Name the drift out loud, capture the new thread as a fresh question or as a line in `## Not yet specified`, and return. One question _file_ at a time — switching happens at the menu, not mid-grill. |
| Self-answering a HITL question | An `## Answer` with no words the human said | Delete it. Reopen the question. See the HITL rule. |
| Recording the decision but not the rejections | "We chose event-driven." | Rejections are half the record — and mandatory when `Locked: yes`. Ask what else was on the table before you close. |
| Grilling a fact | "How long does the retention sweep take?" | If it is measurable, measure it — or make it a `research · AFK` question. Do not make the human guess at their own system. |
| Letting the glossary go stale | Three terms resolved, none written down | Write each one the moment it lands. Deferring loses them. |
| Closing without confirmation | Answer written straight after the last reply | Recap the whole chain of decisions, get the explicit confirm, then write. |
## Landing the grill
When the branch is walked out. **Steps 1-3 are ONE turn, not three** — recap, confirmation request, and lock offer go out together, because a lock offer sent after a separate confirmation costs a round trip to ask a yes/no the human could have answered alongside the recap.
1. Recap the decisions in order, in the human's own terms, using glossary vocabulary. Include anything a structured-tool reply left implicit, so the confirmation covers the reasoning and not just the picks.
2. Ask for confirmation through the structured question tool (`Confirm` / `Correct via Other`). Do not skip this — the recap is where the human catches the one thing you misheard, and where a clicked option becomes words they said.
3. Apply the Lock test as another question in the same tool call. Offer, do not impose.
4. Write `## Answer` per Work Step 7: the decision, what was rejected and why, consequences, and a one-line `**Gist:**`. Evidence, links, and transcript fragments go under `## Evidence`.
5. Anything the grill surfaced that belongs to a different question goes to the map — a fresh question if you can phrase it sharply, `## Not yet specified` if you cannot, `## Out of scope` if it sits past the destination.
@@ -1,423 +0,0 @@
# Handoff Playbook — Clearing the Map into a PLAN-DRAFT
Loaded at The Clearing Gate. Turns a cleared map into `specs/<idea>/PLAN-DRAFT-<YYYYMMDD>.md` that `/plan2code-1-plan` resumes from at Phase 4, then freezes `pathfinder/` as the rationale record.
**Backend note.** The scoring rubric, the hard caps, the honesty rules, the template, and the mapping table are the same either way — and the draft is written to local disk either way, because `/plan2code-1-plan` reads a file, not a tracker. On `**Backend:** github`, `github-issues.md` replaces only the preflight table, the question links (issue URLs, already absolute), and the freeze steps. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
Nothing here is creative. The gate is scored, the mapping is fixed, the template is literal. Follow it exactly or the resuming plan session silently loses work.
## Preflight — before scoring anything
Run `reconcile`, then `node "<S>/pathfinder.mjs" gate specs/<idea>/pathfinder`. Its `checks` cover the mechanical preflight, read from the files:
| `checks` id | Means | If it fails |
|---|---|---|
| `markers-match-files` | The map's markers are the files' (reconcile ran) | Run `reconcile`. Markers are derived, never authored. |
| `no-open-claimed-blocked` | Zero `[ ]`, `[/]`, `[!]` | Not cleared. Return to the frontier. |
| `fog-empty` | `## Not yet specified` is empty | Not cleared. Graduate the fog into questions, or admit it is out of scope. |
| `every-resolved-has-gist` | Every resolved file has a real `## Answer` with a `**Gist:**` | The file wins over the marker. Repair, then re-check. |
| `hard-caps` | None of the Requirements, Feasibility or Risk caps below holds (the Integration cap is yours to check) | That dimension cannot exceed 17: fix the record first. |
| `scores-at-least-18` | The map's `**Confidence:**` line has all four at 18 or better | Not cleared. Keep working the weak dimension. |
`existingPlanDraft` lists a `PLAN-DRAFT-*.md` already in `specs/<idea>/`: read it and update it in place, never add a second dated draft. `planDraftPath` is the file to write either way.
One preflight item stays yours: **the destination is reachable with nothing left to decide**: no `## Answer` defers a choice to "whoever implements this". If one does, the map is not cleared: name the open decision and graduate it into a question.
Score the four dimensions (below), write them to the map's `**Confidence:**` line, and rerun `gate` until `mechanicalPass` is true.
## The clearing-gate scoring rubric
Four dimensions, 0-25 each, scored against **written evidence in `questions/`** — never against your recollection of the conversation. The gate needs **every dimension at 18/25 or better**. There is no averaging: 25/25/25/14 fails.
### Band scale (applies to all four)
| Band | Meaning |
|---|---|
| 23-25 | Decided, written down, and consequences recorded. A developer could act on it without asking a question. |
| 18-22 | Decided and written down. Residual detail remains, but it is *specification* detail that Phase 5/6 settles — not a decision anyone still has to make. |
| 12-17 | A real decision is still open, or an answer exists with no evidence behind it. **Gate fails.** |
| 0-11 | The area was never charted. **Gate fails**, and the map was cleared prematurely. |
The 18-boundary is the honest line between *"needs designing"* and *"needs deciding"*. Pathfinder owns deciding. If someone still has to decide, you are not done.
### What each dimension scores
| Dimension | Scores | Raises it | Lowers it |
|---|---|---|---|
| **Requirements Clarity** | Are the requirements unambiguous? | Every resolved `grill` answer states the decision AND what was rejected; the testing-posture answer names types, cadence, and coverage | Answers phrased as preferences ("probably NDJSON") instead of decisions; a requirement that only exists in the map gist and not in a question file |
| **Technical Feasibility** | Do we know HOW to build each component? | Resolved `sketch` questions with a real artifact under `sketch-NN/`; `research` answers citing primary sources under `## Evidence`; `00-codebase-context.md` naming the actual files that change | A mechanism nobody has exercised in this codebase; a research answer whose `## Evidence` is empty or cites only a blog post |
| **Integration Points** | Are all external dependencies identified? | Every system named in `## Destination` has a resolved question touching it; auth, quota, and failure behavior named per integration | An integration mentioned in an answer but never questioned; a config store that was read but never written to during a sketch |
| **Risk Assessment** | Are blockers documented with mitigations? | Answers that record consequences; `Locked: yes` answers that say what breaks if reversed; ceilings with a stated behavior at the ceiling | A recorded limit with no decided behavior past it; a `Locked: yes` answer with no consequences section |
### Hard caps
A cap overrides your judgment. While a cap condition holds, the dimension **cannot** exceed 17, so the gate cannot pass. `gate` reports the Requirements, Feasibility and Risk caps from the files (`caps`); the Integration cap needs you to match the destination's systems to questions.
| Cap | Condition |
|---|---|
| Requirements ≤ 17 | The testing-posture question is not `resolved`, or its answer omits any of types / cadence / coverage |
| Feasibility ≤ 17 | Any `research` question is `resolved` with an empty `## Evidence` |
| Integration ≤ 17 | A system named in `## Destination` has no resolved question touching it |
| Risk ≤ 17 | Any `Locked: yes` answer records no consequences |
### Honesty rules
- Score the **written record**, not the conversation. If the human agreed to something in a session and nobody wrote it into a `## Answer`, it does not exist and it does not earn points.
- A filled `## Answer` is not automatically 25. An answer that decides but records no consequences tops out around 20.
- Never round up to clear the gate. A 17 that "feels like an 18" is the exact case the gate exists to catch.
- Never move a decision to `## Out of scope` to raise a score. Out-of-scope is a scoping act with a reason; scope-cutting to pass a gate is score inflation with extra steps.
- If two dimensions are borderline, write the one-line justification for each score into the Session End report. Justifications that cannot be written are scores that cannot be defended.
### Worked example — idea `audit-log-s3-export`
Destination: *"A spec a developer can implement: nightly export of tenant audit logs to customer-owned S3 buckets, with a signed manifest per run."*
Resolved questions: [Codebase context](./questions/00-codebase-context.md), [Export format](./questions/01-export-format.md), [Scheduling model](./questions/02-scheduling-model.md), [Destination auth](./questions/03-destination-auth.md), [Retention and replay](./questions/04-retention-and-replay.md), [Testing posture](./questions/05-testing-posture.md), [Throughput ceiling](./questions/06-throughput-ceiling.md). Ruled out: [Failure notification](./questions/07-failure-notification.md).
**First scoring pass:**
| Dimension | Score | Justification against evidence |
|---|---|---|
| Requirements Clarity | 22/25 | Four `grill` answers state decisions and rejections (NDJSON chosen, CSV rejected for nested actor payloads). Testing posture settled: integration + unit, run after each phase, moderate coverage. Minus 3: the manifest's exact field list is unspecified — a Phase 5 spec detail, not an open decision. |
| Technical Feasibility | 21/25 | `sketch-02` uploaded a 400 MB multipart object to a real bucket end to end. `00-codebase-context.md` names `AuditExportJob` and the existing Hangfire registration as the extension points. Minus 4: no component in this codebase has ever assumed a cross-account IAM role; the pattern is documented in AWS docs cited under `## Evidence` but unexercised here. |
| Integration Points | 23/25 | Three integrations, each with a resolved question: S3 (Destination auth), Hangfire (Scheduling model), tenant config store (Codebase context). Auth and quota named per integration. Minus 2: the tenant config store's write path was read but never exercised by a sketch. |
| Risk Assessment | **16/25** | Consequences recorded on Export format and Destination auth. But Throughput ceiling establishes 200 MB per tenant per day at p95 and **records no decided behavior above it** — truncate, spill to the next run, or fail the run is still undecided. |
**Gate result: FAIL** on Risk Assessment (16 < 18), and the orchestrator third clearing condition — the destination reachable with nothing left to decide — fails with it: a decision is genuinely still open. Do not write a PLAN-DRAFT. Name the failure, graduate `questions/08-overflow-behavior.md` (`grill · HITL`, `Blocked by: none`) from the gap, and end the session on the frontier.
**Second scoring pass, one session later**, with [Overflow behavior](./questions/08-overflow-behavior.md) resolved (spill to the next run, alarm at three consecutive spills):
| Dimension | Score |
|---|---|
| Requirements Clarity | 22/25 |
| Technical Feasibility | 21/25 |
| Integration Points | 23/25 |
| Risk Assessment | 20/25 |
All four at 18 or better. Gate passes. Proceed to the mechanism.
## The mechanism, stated plainly
Pathfinder writes `specs/<idea>/PLAN-DRAFT-<YYYYMMDD>.md` with the header line:
`**Status:** Phase 3 Complete - Resume at Phase 4`
`/plan2code-1-plan` **already recognises that exact string.** Its "Check for Existing Progress" block, which runs before Phase 1, reads:
`- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4`
That is the whole handoff. The string is the contract, and it needs **zero changes to the planning skill** — pathfinder is impersonating the Large-project Context Checkpoint that 1-plan's own Phase 3 performs, which writes the same status for the same reason.
Consequences of that being a literal string match:
- Copy it byte for byte. Plain ASCII hyphen-minus surrounded by single spaces. An en dash, a colon, or "Phase 3 complete" in lower case breaks the match and 1-plan starts over at Phase 1 — throwing away every decision the map holds.
- It goes on its own `**Status:**` line in the header block, not buried in prose.
- The file must be named `PLAN-DRAFT-<YYYYMMDD>.md` and live directly in `specs/<idea>/`. `PLAN-DRAFT-*.md` is a reserved name inside `pathfinder/` — never write it there.
- Use the date in `gate`'s `planDraftPath` (it reads the clock). Do not guess it. On `github` (no `gate`), take today's date from the shell and check `ls specs/<idea>/` for an existing draft.
**Discovery is shell-only.** `specs/` is gitignored, so Glob silently returns nothing and every downstream skill would report "no PLAN-DRAFT found". Use `ls specs/` and `ls specs/<idea>/` (Bash) or `Get-ChildItem specs/` (PowerShell) — the same rule 1-plan and `/plan2code-2-document` follow when they look for the file you are about to write.
**Do not append `## Planning Metrics` or any metrics comment.** Pathfinder is not a metered step. 1-plan's Phase 7 owns that block and will add it when it finishes the plan. Do not emit any of the loop's completion tokens listed in the skill's Rules anywhere under `specs/`.
## Map to PLAN-DRAFT mapping
Everything in the draft traces to something on the map. Nothing is invented at handoff time — if a section has no source, that is a gate failure you missed, not a paragraph to write from imagination.
| Source on the cleared map | Becomes |
|---|---|
| `## Destination` | Section 1 Executive Summary (2-3 sentences, present tense) and Section 7 Success Criteria (the destination restated as checkable outcomes) |
| Resolved `grill` answers describing behavior | Section 2.1 Functional Requirements, one `FR-N` per decided behavior |
| Resolved `grill` answers describing performance, security, scale, operability | Section 2.2 Non-Functional Requirements, one `NFR-N` each |
| `## Out of scope` | Section 2.3 Out of Scope — copied line for line, wording and order intact. The ONLY permitted change is the link prefix: `./questions/` becomes `./pathfinder/questions/`, because the draft sits one level above the map. Do not re-word, re-order, or summarise; a re-worded scope boundary is a re-litigated one. |
| The testing-posture question's answer | Section 2.4 Testing Strategy table (Types / Phase Testing / Coverage) |
| Resolved `research` answers and their `## Evidence` | Section 3 Tech Stack — the cited source becomes the Justification cell |
| `questions/00-codebase-context.md` | The `## System Context` section, and the components table in 4.3 |
| Answers with `Locked: yes` | Section 4 Architecture (4.1 Pattern rationale, 4.4 Data Model, 4.5 API Design) **and** Section 9 Assumptions — a locked decision is an assumption downstream work is allowed to rely on |
| Consequences recorded across all `## Answer` sections | Section 6 Risks and Mitigations — the consequence is the Risk, the decision that bounds it is the Mitigation |
| `## Ground rules` | The `AGENTS.md` line in `## System Context`; conventions the plan must not violate |
| The shape of the map (question count, integrations touched, components named) | The `## Scope Assessment` section |
| Resolved `sketch` questions and their artifacts | Section 3 Justification cells and Section 6 Mitigation cells ("proven by `pathfinder/sketch-02/`") |
| Every resolved question, by name | `## Pathfinder Provenance` |
| — | **Section 5 Implementation Phases stays empty.** 1-plan Phase 6 breaks the work into phases. Pathfinder decides; it does not slice. Leave the placeholder note in place and do not put implementation checkboxes there. |
Questions ruled `out-of-scope` never appear in Provenance and never become requirements. Their one line in `## Out of scope` is their only trace — that is the point of the marker.
## The PLAN-DRAFT template
Write this literally, substituting real content. Keep the section numbering exactly as shown — 1-plan and `/plan2code-2-document` both address sections by number.
````markdown
> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.
# Audit Log Export - Implementation Plan
**Created:** 2026-08-03
**Status:** Phase 3 Complete - Resume at Phase 4
**Charted by:** `/plan2code-0-pathfinder` over 9 sessions
**Planning record:** `specs/audit-log-s3-export/pathfinder/map.md` (no PLAN-CONVERSATION - this plan was charted, not conversed)
**Confidence (pathfinder):** Requirements-clarity 22/25 · Feasibility-technical 21/25 · Integration-points 23/25 · Risk-assessment 20/25
---
## 1. Executive Summary
Tenants can have their audit logs exported nightly to an S3 bucket they own, with a
signed manifest per run so they can prove completeness. Export runs on the existing
Hangfire schedule, writes NDJSON, and assumes a customer-provided cross-account IAM
role with an external ID. Runs that exceed the per-tenant daily ceiling spill into the
next run rather than truncating.
## 2. Requirements
### 2.1 Functional Requirements
- [ ] **FR-1:** Export each tenant's prior-day audit events as newline-delimited JSON, one object per event, UTF-8, no BOM
- [ ] **FR-2:** Write a per-run manifest listing object keys, event counts, byte counts, and a SHA-256 per object
- [ ] **FR-3:** Sign the manifest with the platform export key; publish the public key at a stable URL
- [ ] **FR-4:** Assume the tenant-configured IAM role with the tenant's external ID; never use platform-owned credentials against a customer bucket
- [ ] **FR-5:** Allow an operator to replay any run within a 7-day window without duplicating manifest sequence numbers
- [ ] **FR-6:** Spill events above the per-tenant daily ceiling into the next scheduled run, oldest first
- [ ] **FR-7:** Raise an alarm after three consecutive spilling runs for the same tenant
### 2.2 Non-Functional Requirements
- [ ] **NFR-1:** Sustain 200 MB per tenant per day at p95 without extending the nightly window past 04:00 UTC
- [ ] **NFR-2:** Never log tenant event bodies, bucket names, or assumed-role ARNs above debug level
- [ ] **NFR-3:** A failed run must leave no partial objects visible in the customer bucket
- [ ] **NFR-4:** Export must add no schema changes to the audit event write path
### 2.3 Out of Scope
<!-- copied line for line from pathfinder/map.md ## Out of scope; only the link prefix changes -->
- [Failure notification](./pathfinder/questions/07-failure-notification.md) — email/webhook delivery of run failures belongs to the platform alerting effort, not this export. The alarm in FR-7 is raised, not delivered.
- **On-demand export from the tenant UI** — the destination is the scheduled export. A user-triggered export is a separate effort with its own map.
- **Log formats other than NDJSON** — Parquet was raised and ruled past the destination.
### 2.4 Testing Strategy
| Aspect | Decision |
|---|---|
| Types | Unit + Integration |
| Phase Testing | Run after each phase |
| Coverage | Moderate (~60-80%) |
## System Context
**Project type:** Existing codebase — .NET 8 service, `src/Platform.Audit/`
| Aspect | Finding | Source |
|---|---|---|
| Entry points to change | `AuditExportJob`, registered in `HangfireStartup.ConfigureRecurringJobs()` | [Codebase context](./pathfinder/questions/00-codebase-context.md) |
| Existing patterns to follow | Jobs resolve tenant scope via `ITenantScopeFactory`; no job reads config directly | [Codebase context](./pathfinder/questions/00-codebase-context.md) |
| Integration surfaces | S3 (customer-owned), Hangfire scheduler, `TenantConfigStore` | [Destination auth](./pathfinder/questions/03-destination-auth.md), [Scheduling model](./pathfinder/questions/02-scheduling-model.md) |
| Technical debt in the path | `AuditQuery` materialises full result sets; streaming reader needed before FR-1 | [Codebase context](./pathfinder/questions/00-codebase-context.md) |
| System boundaries | Read-only against the audit store; writes only to customer buckets and the run-log table | [Retention and replay](./pathfinder/questions/04-retention-and-replay.md) |
| Conventions in force | `AGENTS.md` present and read; its logging and DI conventions govern | `pathfinder/map.md` ## Ground rules |
## Scope Assessment
**Assessment: Medium** — 11 requirements across 3 integrations, 5 components touched. No Large threshold is met.
| Indicator | Value |
|---|---|
| Requirements decided | 11 (7 FR + 4 NFR) |
| Components | 5 (`AuditExportJob`, `NdjsonWriter`, `ManifestSigner`, `S3RoleAssumer`, `ExportRunLog`) |
| Integrations | 3 (S3, Hangfire, `TenantConfigStore`) |
| Decisions charted | 8 resolved, 1 ruled out of scope |
## 3. Tech Stack
<!-- Phase 4 completes this table. Rows below are decided; do not re-open them. -->
| Category | Technology | Version | Justification |
|---|---|---|---|
| Serialization | `System.Text.Json` NDJSON writer | .NET 8 | [Export format](./pathfinder/questions/01-export-format.md) — no new dependency; CSV rejected for nested actor payloads |
| Object storage | `AWSSDK.S3` multipart upload | 3.7.x | [Throughput ceiling](./pathfinder/questions/06-throughput-ceiling.md) — proven in `pathfinder/sketch-02/` against a real bucket at 400 MB |
| Cross-account auth | STS `AssumeRole` + external ID | — | [Destination auth](./pathfinder/questions/03-destination-auth.md) — AWS confused-deputy guidance cited in that file's `## Evidence` |
| Scheduling | Existing Hangfire recurring job | in-repo | [Scheduling model](./pathfinder/questions/02-scheduling-model.md) — a new scheduler was rejected |
## 4. Architecture
### 4.1 Pattern
Pipeline inside the existing job host: query → stream → chunk → upload → manifest → sign.
Chosen because the audit store is the only source and the export is strictly one-way.
[Locked] A separate export microservice was rejected — see [Scheduling model](./pathfinder/questions/02-scheduling-model.md).
### 4.2 System Context Diagram
<!-- Phase 5 refines. Boundaries above are settled. -->
### 4.3 Components
| Component | Responsibility | Inputs | Outputs | Depends on |
|---|---|---|---|---|
| `AuditExportJob` | Orchestrates one tenant-run | Tenant id, run date | Run result | `TenantConfigStore` |
| `NdjsonWriter` | Streams events to chunked NDJSON | Event stream | Byte stream, counts | — |
| `S3RoleAssumer` | Assumes the tenant role, returns a scoped client | Role ARN, external ID | `IAmazonS3` | STS |
| `ManifestSigner` | Builds and signs the run manifest | Object metadata | Signed manifest | Platform export key |
| `ExportRunLog` | Records runs for replay and spill detection | Run result | Run rows | Platform DB |
### 4.4 Data Model
Manifest sequence numbers are per tenant, monotonic, and reused on replay.
[Locked] See [Retention and replay](./pathfinder/questions/04-retention-and-replay.md).
### 4.5 API Design
<!-- Phase 5 fills. No public API surface was decided during pathfinding. -->
## 5. Implementation Phases
<!-- Intentionally empty. Phase 6 of /plan2code-1-plan breaks the requirements
above into implementation phases. Pathfinder decides; it does not slice. -->
## 6. Risks and Mitigations
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| Cross-account role assumption is unexercised in this codebase | Medium | High | Spike `S3RoleAssumer` against a second AWS account before any other component |
| A tenant exceeds the daily ceiling indefinitely | Medium | Medium | Spill oldest-first plus a three-run alarm — [Overflow behavior](./pathfinder/questions/08-overflow-behavior.md) |
| Partial objects visible after a failed run | Low | High | Upload to a run-scoped prefix, publish the manifest last — the manifest is the commit point |
| `AuditQuery` materialises full result sets | High | High | Streaming reader is a prerequisite, not an optimisation |
| Customer revokes the role mid-run | Low | Medium | Fail the run whole; replay window covers recovery |
## 7. Success Criteria
- [ ] A tenant with a configured role receives NDJSON and a signed manifest for the prior day, nightly
- [ ] The published public key verifies the manifest signature
- [ ] A 250 MB tenant-day completes without extending the window past 04:00 UTC
- [ ] A replay inside 7 days reproduces the run without a new sequence number
- [ ] A failed run leaves nothing visible in the customer bucket
## 8. Open Questions
<!-- 1-plan's template removes this section when empty; pathfinder keeps it with "None" so a
resuming session can see the map cleared clean, rather than that the section was forgotten. -->
None. The map cleared with zero open questions.
## 9. Assumptions
- Tenants can create an IAM role in their own account — [Destination auth](./pathfinder/questions/03-destination-auth.md) [Locked]
- The nightly Hangfire window remains available and is not contended by other jobs — [Scheduling model](./pathfinder/questions/02-scheduling-model.md) [Locked]
- Manifest sequence reuse on replay is acceptable to tenant compliance teams — [Retention and replay](./pathfinder/questions/04-retention-and-replay.md) [Locked]
- Audit events are immutable once written, so a replay reproduces byte-identical output
## Pathfinder Provenance
Charted over 9 sessions. Each requirement above traces to a decision below; open the
question for what was rejected, why, and what it costs.
| Question | Gist |
|---|---|
| [Codebase context](./pathfinder/questions/00-codebase-context.md) | `AuditExportJob` and `HangfireStartup` are the extension points; `AuditQuery` needs a streaming reader first |
| [Export format](./pathfinder/questions/01-export-format.md) | NDJSON with a per-run signed manifest; CSV rejected for nested actor payloads |
| [Scheduling model](./pathfinder/questions/02-scheduling-model.md) | Reuse the existing Hangfire recurring job; a dedicated export service was rejected |
| [Destination auth](./pathfinder/questions/03-destination-auth.md) | Customer-owned bucket via assumed role plus external ID; no platform-held customer credentials |
| [Retention and replay](./pathfinder/questions/04-retention-and-replay.md) | 7-day replay window, sequence numbers reused on replay |
| [Testing posture](./pathfinder/questions/05-testing-posture.md) | Unit + integration, run after each phase, moderate coverage |
| [Throughput ceiling](./pathfinder/questions/06-throughput-ceiling.md) | 200 MB per tenant per day at p95; multipart upload proven in `pathfinder/sketch-02/` |
| [Overflow behavior](./pathfinder/questions/08-overflow-behavior.md) | Spill oldest-first into the next run; alarm after three consecutive spills |
Ruled out of scope: [Failure notification](./pathfinder/questions/07-failure-notification.md) — recorded in 2.3.
---
**Next:** Resume with `/plan2code-1-plan` at Phase 4 (Tech Stack).
- **Phase 7 verification:** sections 1, 2, System Context and Scope Assessment are already settled — their source of truth is `specs/audit-log-s3-export/pathfinder/map.md`, not this conversation. Verify sections 3-7 only.
- **Phase 7:** replace THIS file in place. Do not create a second PLAN-DRAFT in this folder.
````
### Two things in that template that are not optional
**No scrapable confidence numbers anywhere in the file.** Write the confidence as `Requirements-clarity 22/25 · Feasibility-technical 21/25 · Integration-points 23/25 · Risk-assessment 20/25` — hyphenated dimension labels, sub-scores over 25, no total, no percent sign.
The reason is exact. When a PLAN-DRAFT carries no `METRICS_JSON` comment, the metrics collector falls back to scraping it by regex: an overall-confidence pattern that requires a literal `%`, and four breakdown patterns that match a bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed directly by whitespace, a colon, or a pipe and then digits. **The breakdown patterns do not require a percent sign.** A pathfinder-written draft always lacks that comment until `/plan2code-1-plan` Phase 7 appends one, so both the percent sign *and* the bare dimension words have to be kept off the page — otherwise the pipeline records a planning-step confidence that no planning step ever produced. The hyphen in `Requirements-clarity` breaks the match; a table row reading `| Requirements | 11 |` does not, which is why the Scope Assessment row is labelled `Requirements decided`.
**The `**Next:**` footer must ship with both bullets.** Pathfinder cannot edit the planning skill, so those two instructions travel inside the artifact:
- *Without the verification bullet*, 1-plan's Phase 7 does exactly what it is told to do — "re-read conversation as source of truth" — finds a fresh conversation that starts at Phase 4 and contains no requirements discussion at all, concludes sections 1 and 2 are unsupported, and silently drops the requirements that N pathfinder sessions produced. The bullet redirects the source of truth for the settled sections to `map.md`.
- *Without the replace-in-place bullet*, 1-plan's Phase 7 creates `PLAN-DRAFT-<its own date>.md` alongside yours. `/plan2code-2-document` then finds two drafts in the folder, hits its "Multiple found: List all, ask which to document" branch, and asks the user to disambiguate between a pathfinder draft and a plan draft that partially supersedes it.
Never drop the footer to make the file tidier. It is load-bearing.
After writing the draft, run `lint`: it scans a pathfinder-written PLAN-DRAFT with the metrics collector's own patterns and names any bait that reached the page.
## System Context and Scope Assessment — why they buy you Phase 4
These two named, unnumbered sections are what make "Resume at Phase 4" legitimate rather than a shortcut. They stand in for the phases pathfinder already did the work of:
| Draft section | Satisfies | Because pathfinder already |
|---|---|---|
| Sections 1 and 2 (including 2.4 Testing Strategy) | 1-plan **Phase 1: Requirements Analysis** | Grilled every functional and non-functional decision, and always charted a testing-posture question — that question exists specifically so Phase 1's testing prompt is already answered |
| `## System Context` | 1-plan **Phase 2: System Context Examination** | Wrote `questions/00-codebase-context.md` at Chart Step 3: directory structure, key components verified against actual code, patterns and conventions, integration points, technical debt, boundaries — Phase 2's own checklist, item for item |
| `## Scope Assessment` | 1-plan **Phase 3: Scope Assessment** | Produced the counts Phase 3 measures — requirements, components, integrations — as a byproduct of charting. Map the totals onto Phase 3's Small / Medium / Large table and state the verdict |
Populate `## System Context` from `00-codebase-context.md` and nothing else. It is the one question guaranteed to exist on every map, it was resolved on the spot with the codebase open, and it is a `legwork · AFK` answer — factual, not preferential. Cite it in the Source column so a skeptical reader can check the finding against the file.
Populate `## Scope Assessment` from the shape of the map. Count resolved questions that produced requirements (not `00-codebase-context.md`, not out-of-scope ones), count distinct components named across the answers, count distinct external systems. Apply Phase 3's thresholds honestly: Large if **any** threshold is met. Score the counts, never the session count — a map can take nine sessions to clear and still be Medium, and the `Phase 3 Complete - Resume at Phase 4` status string works regardless of the verdict, so there is nothing to gain by inflating it. Pathfinder cannot count implementation phases (Section 5 is deliberately left empty), so assess on requirements, components, and integrations only.
If the charting session found `AGENTS.md` absent, say so in the `Conventions in force` row rather than leaving it blank. The plan session needs to know the conventions were never available, not guess that they were checked.
## Freeze the map
Once the PLAN-DRAFT is written and saved:
1. Set `**Status:** Cleared` in `map.md`.
2. Bump `**Updated:**` to today.
3. Add a plan pointer line under the status: `**Plan:** ../PLAN-DRAFT-20260803.md`.
4. Leave **everything** under `pathfinder/` exactly where it is — `map.md`, every file in `questions/`, every `sketch-NN/` directory.
**Never delete `pathfinder/`.** It is the rationale record behind the plan: what was decided, what was rejected, why, and what it costs. It sits in the same class as `PLAN-CONVERSATION-*.md` — the transcript a plan is defensible against — and `/plan2code-4-finalize` archives it alongside `PLAN-DRAFT.md` and `PLAN-CONVERSATION-*.md` into `specs--completed/<idea>/`. Deleting it turns every locked decision in the plan into an unexplained constraint six months from now.
Do not tidy it either. Do not collapse resolved questions into the map, do not prune `## Evidence`, do not remove sketch directories because the code is throwaway. The sketch is the proof behind a feasibility score.
**A later session that finds `Status: Cleared` must not resume work on it.** The map is finished; there is nothing left to decide inside it. Point at the PLAN-DRAFT and `/plan2code-1-plan`, and stop. If the destination has been redrawn — the scope grew, an out-of-scope item came back, the goal changed — that is a **fresh effort with a fresh map**, not a resumption: a new kebab-case idea name, a new `specs/<new-idea>/pathfinder/`, charting from Step 1. The frontier stops at the destination, so a new destination gets a new frontier. Reopening a cleared map silently invalidates the PLAN-DRAFT that was built from it, and nothing downstream would notice.
## What to tell the user
Session End for the cleared case reports six things, in this order:
| # | Report |
|---|---|
| 1 | The destination, restated — what the map was finding its way to, now reached |
| 2 | How many decisions were made, and the headline ones **by name** |
| 3 | What was ruled out of scope, and why (one line each) |
| 4 | The four confidence scores, with a one-line justification for any below 21 |
| 5 | The PLAN-DRAFT path |
| 6 | The next command — carried by the Trail Footer, which at `Cleared` routes to `/plan2code-1-plan` |
Example:
> **Destination reached:** a spec a developer can implement for nightly audit-log export to customer-owned S3 buckets with a signed manifest.
>
> **8 decisions made** across 9 sessions. The load-bearing ones: [Export format](./questions/01-export-format.md) settled on NDJSON with a signed manifest; [Destination auth](./questions/03-destination-auth.md) settled on assumed roles with an external ID so we never hold customer credentials; [Overflow behavior](./questions/08-overflow-behavior.md) settled on spilling rather than truncating.
>
> **Ruled out of scope:** failure-notification delivery (belongs to the platform alerting effort), on-demand export from the tenant UI (its own effort), Parquet output (past the destination).
>
> **Confidence:** Requirements-clarity 22/25 · Feasibility-technical 21/25 · Integration-points 23/25 · Risk-assessment 20/25. Feasibility is held at 21 because cross-account role assumption is unexercised in this codebase — it is a documented pattern, not a proven one here, and it is the first thing to spike.
>
> **Written:** `specs/audit-log-s3-export/PLAN-DRAFT-20260803.md`. It resumes planning at Phase 4 — sections 1, 2, System Context and Scope Assessment are already settled. The reasoning behind every one of them stays in `specs/audit-log-s3-export/pathfinder/`; do not delete it.
Then the closing block from the skill's Session End — the mascot with the message *The way is clear! Time to plan!* followed by the Trail Footer, whose trail shows every stop walked to the `⚑` destination and whose command is `/plan2code-1-plan`.
**One branch.** If `## Ground rules` records `AGENTS.md` as **absent**, recommend `/plan2code-init` FIRST, and offer `questions/00-codebase-context.md` as its input:
> Before planning: this project has no `AGENTS.md`, and `/plan2code-1-plan` blocks on that. Run `/plan2code-init` first and attach `specs/audit-log-s3-export/pathfinder/questions/00-codebase-context.md` — the recon pass already established the structure, conventions, and integration points it asks for. Then `/plan2code-1-plan`.
Nothing to commit — `specs/` is gitignored. Say so once, then stop.
## Failure modes
| Symptom | Cause | Fix |
|---|---|---|
| 1-plan starts at Phase 1 and re-asks for requirements | The status string does not match byte for byte | Compare against the quoted line above; watch for en dashes and casing |
| 1-plan cannot find the draft at all | Glob was used to discover `specs/` | Shell only: `ls specs/` |
| `/plan2code-2-document` asks which of two drafts to use | The replace-in-place bullet was dropped from the footer | Merge the two drafts into the pathfinder-dated one, delete the other, restore the footer |
| The finished plan is missing requirements the map decided | The verification bullet was dropped from the footer | Re-derive 2.1 and 2.2 from the resolved answers, restore the footer |
| Metrics report a planning confidence nobody scored | A percent sign, or a bare dimension word followed by a number, reached the file | Hyphenate the dimension labels and drop the percent sign |
| A locked decision in the plan has no visible reason | `pathfinder/` was deleted or pruned | Unrecoverable. This is why the freeze step exists |
| Gate passes but the first implementation session immediately hits an undecided question | A dimension was rounded up | The gate was the check. Score the written record, not the feeling |
@@ -1,47 +0,0 @@
# Questions & Map Format
> Part of plan2code-0-pathfinder — the on-disk format both modes share: directory layout, `NN` numbering, the question-file schema, `Type:` vocabulary, and the marker / blocking rules. The main file keeps only the marker legend and a layout gist; the authority is here.
>
> **This file describes the `local` backend only.** If `## Ground rules` says `**Backend:** github`, the equivalence table in `github-issues.md` replaces every rule below — there are no files, no `NN`, no schema lines, and no checklist.
## Layout
```
specs/<idea>/
├── pathfinder/
│ ├── map.md <- the index
│ ├── questions/NN-<slug>.md <- 00-codebase-context.md always exists
│ ├── briefs/brief-<YYYYMMDD>.md <- plain-English reports, written by BRIEF mode only
│ └── sketch-NN/ <- optional runnable sketch, throwaway
└── PLAN-DRAFT-<YYYYMMDD>.md <- written ONLY when the map clears
```
`questions/` is ground truth; `map.md` is a rebuildable index that gists and links. A filled `## Answer` beats any `State:` line. Detail lives in exactly one place — the question file.
## Numbering
`NN` is zero-padded from `00`, assigned in dependency order (blockers lower), **never reused or renumbered** — links and `Blocked by:` would rot silently. Next = max + 1 (`frontier`'s `nextNN`), never below the map's `**Next NN:**` high-water line, which the script keeps so a deleted question's number stays retired (chart.md, Step 6 rule 5). A one-digit file name (`1-export.md`) still reads as `01`, but `lint` asks for the rename. `00` is always `00-codebase-context.md`, never anything else. Gaps in the sequence are normal and harmless.
## The six schema lines
Each question file carries six contiguous `Key: value` lines after its H1 — NOT YAML frontmatter, no `---` delimiters:
| Line | Values |
|---|---|
| `Type:` | `grill · HITL` \| `research · AFK` \| `sketch · HITL` \| `legwork · HITL` \| `legwork · AFK` — one token, so type and mode cannot drift |
| `State:` | `open` \| `claimed` \| `resolved` \| `out-of-scope` |
| `Blocked by:` | `none` \| `02, 04` |
| `Claimed:` | `none` \| `<YYYY-MM-DD HH:mm>` — a work-in-progress lock, not a completion record |
| `Resolved:` | `none` \| `<YYYY-MM-DD>` — set in the same write as `State: resolved` (Work Step 7). The date the decision landed; briefs filter on it |
| `Locked:` | `yes` only when hard to reverse AND surprising without context AND a real trade-off |
**Backfill (older maps):** a file with a filled `## Answer` but `Resolved: none` (or no `Resolved:` line at all) gets the line backfilled at reconcile — from the `Claimed:` date, or today if `Claimed: none`. Say so once in the session report.
**Type meanings.** **grill** (default) — a decision only the human can make. **research** — a fact outside this directory gates it. **sketch** — the human needs something concrete to react to. **legwork** — manual work that must happen before a decision is possible.
## Markers and blocking
**Map markers**, rebuilt from the files every session: `[ ]` open — **these rows ARE the frontier** · `[/]` claimed · `[x]` resolved · `[!]` open but blocked · `[-]` out of scope. Resolved rows carry the gist plus the `Resolved:` date in italics: `— <gist> *(YYYY-MM-DD)*`.
`scripts/pathfinder.mjs` implements exactly these rules (`reconcile` rebuilds the markers, `frontier` computes blocking, `lint` checks the schema), so this file is the reference for reading its output and for writing a question file. Apply the rules by hand only when the script cannot run.
**Unblocked** ⟺ every `NN` in `Blocked by:` is `resolved`. **Stranded:** a blocker gone `out-of-scope` never resolves — the question is not merely blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
@@ -1,566 +0,0 @@
# Resolution Playbook
> Loaded at the top of MODE B. Work Step 6 routes here by `Type:`; Work Step 8 uses the fog procedure at the end.
>
> **Backend note.** Every resolution technique here is backend-independent — the type table, the primary-source rule, the sketch tiers, the checklist discipline, the `## Answer` anatomy. On `**Backend:** github`, `Type:` is a `pathfinder:<type>-<mode>` label, `## Answer` and `## Evidence` are comments rather than file sections, and a research subagent gets an issue URL instead of a path; see `github-issues.md`. Sketches stay on local disk regardless. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
Every question resolves into the SAME shape — a filled `## Answer` plus whatever `## Evidence` backs it. The type only decides how you get there.
| `Type:` | Who drives | Parallel? | What "resolved" means |
|---|---|---|---|
| `research · AFK` | Subagent, alone | **Yes** — many at once | Facts found and cited; no decision made |
| `sketch · HITL` | Agent builds, human reacts | No | The human reacted and chose |
| `legwork · AFK` | Agent, alone | No | The work is done; resulting facts recorded |
| `legwork · HITL` | Human does, agent waits | No | The human confirmed it is done |
| `grill · HITL` | Human decides, agent interrogates | No — but probes batch, up to 3 per turn | The human said it in their own words |
**One question _file_ at a time** holds for every row except `research` — several may resolve in one session, but strictly in sequence, per the Cadence below. `research` is also the one type that is **never claimed**: its subagents fire unclaimed (the file stays `State: open`), so `claim` and its one-claim rule govern grill, sketch and legwork only, and a grill can be claimed while research runs. A research question is finished with `## Answer` plus `resolve` once its subagent is back, or re-fired from `reconcile`'s `refire` if it was cut off. HITL rows are never self-answered — an agent that writes its own `## Answer` on a `grill` has broken the skill.
Every file you create along the way — question files, sketch READMEs — opens with the banner:
`> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.`
---
## Cadence: decide → menu → checkpoint
The Work loop no longer ends after one decision. It ends when the human stops it, or when the checkpoint recommends stopping — whichever comes first. This holds for a solo developer and for a Product + Engineering room alike; a meeting is just a session with more people answering, and needs no special invocation.
```
claim ONE → resolve → recap → confirm → record → mark map [x]
→ MENU (trail.md Form C): takeable frontier + resume command, human picks or stops
→ claim the next … repeat …
```
**The menu turn.** After every recorded decision, use the structured question tool per trail.md §Form C: offer up to three takeable questions (from the map's checklist rows — name + gist, no file re-reads) plus `Start fresh`; `Other` covers another frontier name. Flag anything just unblocked, mark exactly one description `RECOMMENDED`, and print the resume command under `OR START FRESH` before the tool. Lowest `NN` stays the *recommendation* default, never the selection — the human picks.
**The checkpoint is the menu with the recommendation flipped.** The old one-per-session rule had two jobs: crash-safety and context hygiene — a fresh window per decision keeps the model sharp. Sequential claims preserve the first. The checkpoint preserves the second: after **~3 questions resolved this session** (soft cap), or earlier after a heavy, contested, or `Locked: yes` decision that would benefit from settling overnight, mark the tool's `Start fresh` option RECOMMENDED and say why in the question text — "to keep me sharp." The human can override in either direction; a recommendation is something to push against, not a gate.
The restart costs one paste and loses nothing: every claim, answer, and map update hits disk before anything else happens, and the next session assumes no memory anyway. The fresh session reconciles, renders the trail, and presents the menu again.
**In-loop hygiene** — what keeps each cycle lean between checkpoints:
- Read only what the cycle needs: the claimed question file plus resolved neighbors' *gists* (Work Step 5). Never re-read the whole `questions/` directory between cycles — reconcile ran once at session start, and this session is the only writer.
- The menu renders from the map's checklist rows, never from re-reading question files.
- Strictly one claim open at any moment. Claim → record → release, then the menu. Never two. (Research subagents run unclaimed beside it; see the top of this file.)
**Group sessions.** When Product and Engineering (or any room) work the map together, the grilling playbook's group-session rules apply: probes address the room, the recap captures the decision in the room's words, and a contested pick is never recorded as decided — both positions go under `## Evidence`, the question stays `open`, and the menu moves on (or offer to convert it to `sketch`; reacting to something concrete resolves more standoffs than argument). At Session End, offer `write a brief for today` — the brief doubles as the meeting minutes.
**Stopping is always legitimate.** Ending after one decision is fine. The skill no longer forces deliberation time between decisions; it *advises* it, via the checkpoint, where a decision was heavy enough to deserve settling overnight.
---
## `research · AFK`
The only type an agent resolves alone, and the only type that may run several at once. Charting fires them in a batch at Chart Step 8; MODE B fires any that appear later the same way, unclaimed: never run `claim` on a research question. When one tops the frontier at Work Step 4, fire it, then claim the first non-research question.
### Spin up a subagent
One subagent per research question. Do not read the docs yourself in the main session — the point is that the main session's context stays clean for the decision work.
The subagent's brief must carry, verbatim:
1. The absolute path of the question file it owns.
2. The `## Question` text.
3. The instruction to write into `## Evidence` of THAT file and nothing else — `## Answer` and `State:` are written by the session that fired it, at Work Step 7.
4. The primary-source rule below.
5. The no-deciding rule below.
6. The instruction to end `## Evidence` with `**Research complete:** <YYYY-MM-DD>` as its last line, written only once every claim is in. Without that line, the next session cannot tell finished research from research that was cut off.
### Wait for every subagent
Subagents run inside this session's process, even when the harness runs them in the background. Close the terminal, or end the session, and they die mid-write, leaving `## Evidence` half-filled. So:
- **Do not reach Session End, or post a web console `finish`, while any research subagent is still running.** Wait for each one to report back. The main session does not read the sources while it waits; it only collects completions.
- While waiting in the web console, post `{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}` and update the count as each returns, so the page never says "done" while work is still in flight.
- Never tell the human the research "will finish on its own" or is "running in the background, ready for next time". It is not: it lives in this terminal.
- Once all are back, Session End reports each research question with a one-line summary of what was found (not decided).
### Interrupted research
At Work Step 2, `reconcile` lists in `refire` every research question that is not resolved and whose `## Evidence` lacks the `**Research complete:**` line (with its path and `## Question` text for the brief): it was never finished, by a closed terminal, a crash, a rate limit. Re-fire its subagent with the same brief, plus one instruction: keep what is already in `## Evidence`, verify it, fill the gaps, then write the line. Say so in one line to the human. A map written before this line existed shows the same symptom; re-firing it costs a little time and nothing else.
### Primary sources only
Investigate against **primary sources** — official documentation, the library's own source code, the RFC or spec text, the first-party API reference, the vendor's own pricing page, the actual response from a live endpoint. Never a secondary write-up of them. A blog post, a Stack Overflow answer, or a model's recollection is a *lead*, not a source: follow every claim back to the source that owns it, and cite that.
| Claim about | Source that owns it |
|---|---|
| A library's behavior | That library's source or its own docs for the installed version |
| An HTTP API's shape | The vendor's API reference, or a real captured request/response |
| A file format | The format specification |
| A limit or quota | The vendor's own limits page, dated |
| This project's behavior | The code in this repo, by path |
If no primary source can be found, say so explicitly in `## Evidence` and mark the claim UNVERIFIED. An honest gap is worth more than a confident secondhand sentence — the gap becomes a `legwork` question (go run it and see) or a `grill` (the human decides under uncertainty).
**Version-pin everything.** "Node supports it" is not a finding. "Node 20.11 supports it; the project's `.nvmrc` pins 18.19, which does not" is.
### It does not decide
A research question's `## Answer` states the FACTS FOUND and what they imply. It never picks. The moment the findings enable a choice, that choice becomes a **separate `grill`** question, written at Work Step 8.
This split is the whole reason research is safe to run AFK. An agent that reads three storage options and then declares a winner has quietly made an architectural decision the human never saw.
### The dropped git branch
Upstream captures each prototype and research run on a throwaway git branch. **Pathfinder deliberately drops that.** `specs/` is already untracked scratch space, and plan2code never touches git during pathfinder. The question file IS the durable capture. Do not create branches, do not commit, do not mention branches in the `## Answer`.
### Worked example
`questions/04-object-lock-retention.md` after Work Step 7 recorded its subagent findings:
```markdown
> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.
# Object Lock retention semantics for the archive bucket
Type: research · AFK
State: resolved
Blocked by: none
Claimed: 2026-08-03 14:02
Resolved: 2026-08-03
Locked: no
## Question
If archived messages land in S3 under Object Lock, what retention modes exist,
which of them can be shortened or lifted after the fact, and what does each
require of the bucket at creation time? We need the facts before deciding
whether a 7-year hold can coexist with a customer's right-to-delete request.
## Answer
**Facts found**
1. Object Lock supports two retention modes: GOVERNANCE and COMPLIANCE.
2. Under GOVERNANCE, a principal holding `s3:BypassGovernanceRetention` can
shorten or remove a retention period on an object version.
3. Under COMPLIANCE, no principal — including the account root — can shorten
or remove it until the retain-until date passes.
4. Object Lock can only be enabled at bucket creation, and enabling it forces
versioning on permanently.
5. A legal hold is independent of retention mode, has no expiry, and is
toggled by any principal with `s3:PutObjectLegalHold`.
**What this implies**
- A right-to-delete request is satisfiable under GOVERNANCE and is NOT
satisfiable under COMPLIANCE before the retain-until date. These two
obligations cannot both be met on the same object version.
- Retrofitting Object Lock onto the existing `archive-prod` bucket is not
possible; it would require a new bucket and a full copy.
**Decision this enables (not made here)**
Which mode the archive uses, and how right-to-delete is honored under it,
is now a sharp question — see Work Step 8, spun off as a grill.
**Gist:** COMPLIANCE mode is irreversible even for root; GOVERNANCE is
bypassable — and Object Lock cannot be added to the existing bucket.
## Evidence
- Two modes, and the governance-bypass permission —
AWS S3 User Guide, "Object Lock overview", section "Retention modes".
https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock-overview.html
(retrieved 2026-08-03)
- COMPLIANCE cannot be shortened by any user including the root user —
same page, "Compliance mode" paragraph, verbatim: "no user can overwrite or
delete the object version during the retention period."
- Enable-at-creation-only, and forced versioning —
AWS S3 User Guide, "Enabling Object Lock", first note block.
https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock-configure.html
- Legal hold independence and no expiry —
same guide, "Legal holds" section.
- Existing bucket has Object Lock disabled — verified against this account:
`aws s3api get-object-lock-configuration --bucket archive-prod`
returns `ObjectLockConfigurationNotFoundError`. (run 2026-08-03)
- UNVERIFIED: whether our compliance counsel treats GOVERNANCE as sufficient
for the SEC 17a-4 attestation. No primary source exists for this — it is a
human judgment, not a fact. Belongs in a grill.
**Research complete:** 2026-08-03
```
Note what the example does: every claim carries its own citation, a live command counts as a primary source, the one thing that cannot be sourced is flagged rather than smoothed over, and the closing `**Research complete:**` line marks the subagent's work as whole.
---
## `sketch · HITL`
Raise the fidelity of the discussion by making something cheap and concrete for the human to react to. "How should this behave?" and "what should this look like?" produce vague answers in the abstract and sharp ones in front of an artifact.
Two tiers. **Start at Tier 1 every time.**
### Tier 1 — paper sketch (the default)
No executable code. You write a concrete thing into the question's `## Evidence`, show it to the human, and they react. Most sketch questions never need more than this.
Shapes that work:
| Shape | Use when the question is |
|---|---|
| Outline | "What are the steps, and in what order?" |
| State table | "What states exist and which transitions are legal?" |
| Worked example with real numbers | "Does this rule produce sane results?" |
| Fake request/response pair | "What should this API actually look like?" |
| ASCII UI | "What goes on this screen and what is primary?" |
| Decision table | "Under which conditions do we do which thing?" |
Rules for a paper sketch: use REAL-looking content, never placeholders. Real customer names, real message counts, real timestamps, real error strings. A table full of `foo` and `item 1` gets nodded at; a table with `retention_expired` in it gets argued with, and the argument is the point.
Present it, then ask the pointed questions the sketch actually opens — up to three, batched, in the same turn as the artifact. A sketch is the one place where several probes come free: the human has the whole picture in front of them, so a second and third question cost them almost nothing, and a state table with three questionable rows should not take three sessions.
Pointed is the discipline that survives batching. Never "thoughts?" — every probe names its row or element: "row 5 says a flagged message still archives when retention expires. Right, or does the hold pin it in place?" Show the artifact inline, then immediately invoke the structured question tool for up to three pointed reaction probes. The artifact stays in prose; every answer control stays in the UI, with `Other` available for hybrids and corrections.
Follow the structured-tool rules in `grilling.md`: short distinct headers, the pointed question plus why-it-matters in the question field, genuine alternatives with trade-offs in descriptions, and one recommendation per probe.
Putting up a sketch is a **Form B turn** in `trail.md`: close it with `WAITING ON YOU` naming the probes, never a resume command. The human is meant to react to the artifact in this conversation, and a footer telling them to start a new one throws the sketch away.
#### Paper sketch example A — state table
For `questions/06-review-lifecycle.md`:
```markdown
| From | Event | To | Legal? |
|--------------|----------------------|--------------|-------------|
| ingested | policy match | flagged | yes |
| ingested | no match, 24h passes | archived | yes |
| flagged | reviewer clears | archived | yes |
| flagged | reviewer escalates | escalated | yes |
| flagged | retention expires | archived | ← QUESTION |
| escalated | case closed | archived | yes |
| escalated | retention expires | escalated | stays put |
| archived | legal hold applied | held | yes |
| held | hold released | archived | yes |
| held | retention expires | held | hold wins |
Open on this sketch: an item sitting in `flagged` when its retention window
expires. Row 5 currently drops it to `archived` unreviewed. The alternative is
that expiry cannot fire while a human review is outstanding — retention pauses.
```
#### Paper sketch example B — fake request/response pair
For `questions/09-export-job-api.md`:
```markdown
POST /v1/exports
{
"channel_ids": ["ms-teams-legal", "ms-teams-trading"],
"from": "2025-01-01T00:00:00Z",
"to": "2025-12-31T23:59:59Z",
"format": "eml",
"include_attachments": true
}
202 Accepted
{
"export_id": "exp_9fK2mQ",
"state": "queued",
"estimated_messages": 418377,
"estimated_bytes": 12884901888,
"poll_url": "/v1/exports/exp_9fK2mQ",
"expires_at": "2026-08-10T14:00:00Z"
}
GET /v1/exports/exp_9fK2mQ
200 OK
{
"export_id": "exp_9fK2mQ",
"state": "partial_failure",
"messages_written": 418202,
"messages_failed": 175,
"failure_manifest_url": "https://.../exp_9fK2mQ-failures.csv",
"download_urls": ["https://.../exp_9fK2mQ-part-001.zip", "..."]
}
Open on this sketch: `partial_failure` hands back a download plus a manifest of
what is missing. The alternative is all-or-nothing — 175 failures void the whole
12 GB export. Which does a compliance officer actually want at 4pm on a Friday?
```
#### Paper sketch example C — ASCII UI
For `questions/11-reviewer-queue-layout.md`:
```markdown
+----------------------------------------------------------------+
| Review Queue [ Mine 42 ] [ Team 318 ] [ Overdue 7 ] |
+---------------------------+------------------------------------+
| ! 2d K. Ondrusek | From: Kamil Ondrusek |
| "…move the block…" | To: trading-desk (14 members) |
| trading-desk | 2026-08-01 09:14 MS Teams |
|---------------------------| |
| 1d A. Whitfield | Policy hit: BLOCK-TRADE-LANGUAGE |
| "confirming size" | Confidence: 0.91 |
| trading-desk | |
|---------------------------| > can you move the block before |
| 4h R. Iyer | the close? size is 40k |
| "attached the deck" | |
| legal-general | [ Clear ] [ Escalate ] [ Hold ] |
+---------------------------+------------------------------------+
Open on this sketch: the policy hit and its confidence sit in the detail pane,
so the list gives no reason to pick one item over another beyond age. Should the
list rank by confidence instead of age, and show the rule name per row?
```
### Tier 2 — runnable sketch (available, and gated)
Every other plan2code step forbids writing code during planning. **Pathfinder is the one exception**, because some questions genuinely cannot be settled on paper: "does this state model actually hold once you push it through the ugly cases?", "what should this feel like?" A paper state table always looks fine. Driving it by hand for ninety seconds is where it falls over.
**All three gates must open before you write a line of code:**
1. The paper sketch was tried and did not settle it. Not skipped — tried. Say what the paper sketch failed to resolve.
2. There is an obvious way to run it in this project — an existing runtime and task runner. Do not add a package manager, language, or framework for a sketch.
3. The user says go. Ask explicitly: *"Paper didn't settle row 5. I can build a throwaway terminal app under `specs/audit-export/pathfinder/sketch-01/` that lets you drive the state machine by hand — about 60 lines, one command, deleted after. Go?"*
Any gate that stays shut: stay on paper, or convert the question to a `grill`.
#### Rules for a runnable sketch
1. **Throwaway from day one, and clearly marked.** Its README's first line is the banner, and its second says what question it exists to answer.
2. **It lives ONLY at `specs/<idea>/pathfinder/sketch-NN/`** — never in the project's own source tree, never beside the module it is sketching for. This is where pathfinder deliberately departs from upstream: upstream co-locates prototypes with the real code; pathfinder quarantines them, because `specs/` is gitignored scratch and the project tree is not.
3. **One command to run.** Print the exact command to the user. They must not have to remember a path or a flag. If the project has a task runner, use the runner's own idiom, but keep the entry point inside `sketch-NN/`.
4. **No persistence.** State lives in memory. Persistence is what the sketch is checking, not something it leans on. If the question is specifically about storage, use a local file named so its disposability is obvious.
5. **Skip all polish.** No tests, no error handling beyond what makes it run, no abstractions, no "we might want X later."
6. **Surface the full relevant state after every action** (logic) **or on every variant switch** (UI). The user must see the whole picture change, not a delta.
7. **Never merged.** The sketch is not lifted into the project. Only the validated decision it produced survives, in the `## Answer`. Reference the sketch directory from `## Evidence` so a later reader can re-run it, but the code is scaffolding, not output.
#### Pick the branch: logic or UI
| Question shape | Branch | Artifact |
|---|---|---|
| "Does this state model / data model / rule hold?" | **Logic** | One tiny interactive terminal app |
| "What should this look like?" | **UI** | Several radically different variations, switchable |
Getting this wrong wastes the entire sketch. If the question is genuinely ambiguous and the user is unreachable, default by what the question touches — a backend module or a rules engine points to logic, a page or component points to UI — and **state the assumption in the first lines of the sketch's README**, so the human can reject the framing before reading the code.
**Logic branch.** Build the smallest interactive terminal app that pushes the machine through the cases that are hard to reason about on paper. Keep the logic itself pure — a reducer, a state machine, or a small set of pure functions over a plain data type — with the terminal shell as a thin wrapper that imports it and never the reverse. Each frame: clear the screen, print the whole current state one field per line, then print the key legend, e.g. `[f] flag [c] clear [e] escalate [h] hold [t] advance clock 1d [q] quit`. Re-render the entire frame after every keystroke; never append to scrollback. The whole frame fits on one screen. The interesting moment is the user saying "wait, that shouldn't have been possible" — that is a bug in the *idea*, which is the entire point. Add actions on request; sketches evolve.
**UI branch.** Generate **several radically different variations side by side, switchable** — not one polished take. Default to 3, cap at 5. They must disagree about structure: different layout, different information hierarchy, different primary affordance. Three tweaked card grids is wallpaper, not a sketch. If two drafts come out similar, redo one with an explicit constraint against the shape they share. Switch by a URL search param plus a small floating bar (previous / current variant name / next), following whatever routing convention the project already uses — but with the files under `sketch-NN/`. Wire variants to stubbed data, never to real mutations; the question is what it should look like, not whether the backend works. The most valuable feedback is usually "I want the header from B with the list from C" — that hybrid IS the answer, and it goes in the `## Answer`.
#### After a runnable sketch
Record the verdict and the question it settled in `## Answer`. Record the sketch path, the run command, and what the user actually said while driving it in `## Evidence`. Leave the directory in place — it is gitignored scratch, it costs nothing, and the next session may want to re-run it. Never copy any of it into the project.
---
## `legwork · HITL` or `legwork · AFK`
The one type that DOES rather than decides. There is nothing here to research, sketch, or grill — a decision is simply blocked until some manual work happens.
Typical: provisioning access to a system, signing up for a service so its API can actually be judged, moving a data sample somewhere it can be looked at, requesting a sandbox tenant, reading the codebase (`questions/00-codebase-context.md` is always this type).
**It earns its place only by unblocking a decision, never by delivering the destination.**
### AFK or HITL
| Mode | When | How it resolves |
|---|---|---|
| `legwork · AFK` | The agent can do it with the tools it has — read the code, run a query, count rows, inspect a config | Do it, record the facts, resolve |
| `legwork · HITL` | It needs a human's hands, credentials, card, or signature | Hand over a precise numbered checklist and WAIT |
Drive it alone wherever you can. Do not hand a human a checklist for work you could have done yourself.
### The HITL checklist
Numbered, specific, and verifiable — every line names the exact place to click, the exact value to use, and what the human should see when it worked. Plain English throughout: exact names and values where they carry the work, no Pathfinder vocabulary anywhere (see *Say it in plain English* in the grilling playbook). No `- [ ]` checkboxes; question files never carry them.
```markdown
1. Go to https://console.vendor.example/settings/api and sign in with the
shared ops account (credentials in 1Password, item "Vendor Ops").
2. Create an API key named `pathfinder-eval-2026-08`. Scope it to
read-only — untick "Write" and "Admin".
3. Copy the key into 1Password as a NEW item named "Vendor Eval Key".
Do not paste it into this chat or into any file under specs/.
4. On the same page, note the "Rate limit" value shown for the key
and tell me the number.
5. Under Settings > Data, note whether "Historical backfill" is listed
as included or as a paid add-on, and tell me which.
Tell me when 1-5 are done, plus the two values from steps 4 and 5.
```
Immediately after the checklist, invoke the structured question tool: `Done` · `Blocked` · `Need help` · `Defer`; the question text names every value the human must include, and `Other` carries those values/details. Then stop and wait. Do not guess, proceed, or mark it resolved on the assumption it went fine.
Handing over a checklist is a **Form B turn** in `trail.md` — close with `WAITING ON YOU` naming the checklist and the values you asked for, and no resume command. The human may be gone for hours, but the session is still theirs to come back to; only park it as a session end (Form A) once you are actually stopping.
### What its `## Answer` records
Two parts: **what was done**, and **the resulting facts later questions depend on**. Credentials locations (never the credentials), new URLs, row counts, version numbers, quota limits, table shapes, file paths.
```markdown
## Answer
**Done.** Read-only API key provisioned against the shared ops account and
stored in 1Password as "Vendor Eval Key". No key material is stored under specs/.
**Facts other questions depend on**
- Key location: 1Password item "Vendor Eval Key" (ops vault).
- Rate limit: 600 requests/minute per key, burst 1000.
- Historical backfill beyond 90 days is a paid add-on, not included in the
eval tier — so any evaluation against real 2024 traffic needs a purchase.
- Base URL for the eval tenant: https://eval-3f2.vendor.example/api/v2
(differs from the production host in their docs).
**Consequences** — the 90-day eval ceiling means the volume question cannot be
answered against real historical data on this tier; it has to be extrapolated
or the add-on has to be bought. That is a fresh decision, not one to make here.
**Gist:** Read-only eval key in 1Password; 600 rpm; history capped at 90 days
without a paid add-on.
```
### The guard
If the legwork turns out to BE the deliverable rather than an unblocker — you are migrating the data, not sampling it; you are building the integration, not evaluating it — **it is out of scope for pathfinder.** Stop. Say so plainly:
> "This has stopped being legwork that unblocks a decision and become the work itself. Pathfinder plans; it doesn't build. I'm ruling this out of scope and it belongs in planning."
Rule the question out with `rule-out <NN> --reason "<what it turned into>"` (it marks the row `[-]` and adds the `## Out of scope` line), and hand off to `/plan2code-1-plan` for that piece. Never let pathfinder quietly become the implementation.
---
## `grill · HITL`
The default type: a decision only the human can make. Route to **the grilling playbook** — it owns the interrogation technique, structured-question-tool-first delivery, batching rules (up to three independent probes per turn), prose fallback when the tool is unavailable, and the recommend-then-ask pattern.
Three things this playbook adds on top:
- **Zoom before you grill.** Work Step 5 already had you read the claimed question plus anything it references. Bring the resolved neighbors' gists into the first message so the human is not re-litigating settled ground.
- **Batch probes, not question files.** One question file at a time is unchanged. A batch of three probes resolves ONE `questions/NN-*.md`; the next file starts only after this one's menu turn (§Cadence).
- **The human's own words.** A `grill` resolves only through live exchange. Never write the `## Answer` from what you inferred they would probably say — and a probe they skipped twice is unanswered, not decided.
A good grill `## Answer` contains four things:
1. **The decision** — stated flatly, in the human's terms, not hedged.
2. **What was rejected and why** — the alternatives that were live during the conversation, each with the reason it lost. This is the part that stops the decision from being reopened in three weeks.
3. **The consequences for other questions** — which open questions this constrains, which fog patches it just made sharp, which resolved answers it complicates. Name them; never number them in prose.
4. **A one-line bold Gist.**
---
## Writing the `## Answer`
Same anatomy for every type. Append it at Work Step 7; never edit `## Question` to match the answer. Then run `node "<S>/pathfinder.mjs" resolve specs/<idea>/pathfinder <NN>`: it sets `State: resolved` **and** `Resolved:` to today (from the clock; the date is what lets a brief report "decided on <day>"), and writes the map row from your `**Gist:**`. It refuses an Answer with no Gist line.
| Part | Required | Content |
|---|---|---|
| The decision (or, for `research`, the facts found) | Always | What was settled, stated flatly |
| Rejected alternatives, with reasons | When alternatives existed | Each option that lost, and why |
| Consequences | Always | Effects on other questions, named not numbered |
| `**Gist:**` | Always | One line, last |
| `## Evidence` | When there is any | Sources, sketch paths, transcript quotes, commands run |
Worked example — `questions/03-export-format.md`:
```markdown
## Answer
**Decision.** Exports are written as one `.eml` file per message inside a ZIP,
with a top-level `manifest.csv` giving message id, channel, participants,
timestamp, SHA-256, and relative path. One ZIP per 2 GB, numbered `part-001`.
**Rejected**
- **Single NDJSON file.** Compact and trivially streamable, but the review
vendors named in Codebase context both ingest `.eml` natively and neither
parses NDJSON. Rejected because it moves the conversion cost onto the
customer's e-discovery team.
- **PST.** What the legal team asked for by name, but PST is a single-writer
format with a practical 50 GB ceiling and no first-party writer outside
Outlook. Rejected on the ceiling alone — the 2025 trading-desk export is
~12 GB and growing 40% year over year, so the ceiling is 3 years out.
- **One ZIP, no parts.** Rejected because S3 presigned downloads over 5 GB
fail on several corporate proxies the support team has already seen.
**Consequences**
- Makes [Export job API](./questions/09-export-job-api.md) sharper: the
response must return an ARRAY of download URLs, not one.
- Constrains [Integrity attestation](./questions/12-integrity-attestation.md) —
a per-message SHA-256 already exists in the manifest, so attestation can hang
off the manifest rather than needing a separate hash pass.
- Kills the "streaming export" fog bullet: parts and streaming are exclusive.
Removed from `## Not yet specified`.
**Gist:** One `.eml` per message in 2 GB ZIP parts, with a manifest.csv
carrying per-message SHA-256.
```
### The gist
The gist is what gets copied into the map row. It is not a summary of the answer — it is the one line that lets a future session decide, at a glance, whether to open the file.
- One line. Fits in a table row without wrapping twice.
- Says what was DECIDED, not what was discussed. "Chose ZIP parts" is weak; "One `.eml` per message in 2 GB ZIP parts" is judgeable.
- Carries the number or name that matters, if there is one.
- Never the full answer. If it needs a semicolon and a subordinate clause, cut it.
The map row it produces — gist, then the `Resolved:` date in italics:
```markdown
- [x] [Export format](./questions/03-export-format.md) — one `.eml` per message in 2 GB ZIP parts, manifest.csv carries SHA-256 *(2026-08-03)*
```
---
## Graduating the fog (Work Step 8)
`## Not yet specified` is the fog: in-scope questions you can *see* coming but could not phrase sharply when you wrote the map. Resolving a question clears the fog immediately ahead of it. Step 8 is where you collect what just became visible.
**The test is whether you can state the question precisely NOW — not whether you can answer it.** A question you cannot act on for weeks still gets a file, with `Blocked by:` filled in. A question you could answer this minute but cannot phrase without hand-waving stays fog.
### Procedure
1. **Re-read `## Not yet specified` in full.** Every bullet, every session, after every resolution. Not the ones you remember — you are assuming no memory of prior sessions, and the bullet that graduates is usually the one you forgot was there.
2. **Ask of each bullet: did the answer just make this sharp?** Can you now write a `## Question` paragraph a stranger could act on, without "we'll need to figure out" anywhere in it?
3. **If yes, write the question file NOW** — in this same session, before Work Step 9. Its `NN` is `frontier`'s `nextNN` (max existing + 1, from the directory, never reused). Fill all six schema lines, with `Blocked by:` wired in the same pass. `reconcile` then adds its `[ ]` or `[!]` row to `## Question Checklist`.
4. **DELETE the bullet from `## Not yet specified`.** Immediately, in the same edit as writing the file.
5. **If no, leave the bullet alone** — untouched, not reworded into something that merely sounds sharper.
6. **Re-check the counts.** One fog patch may graduate into three questions, or into none. Both are normal. A patch that graduates into three was written at the right coarseness; a patch that graduates into exactly one every time was probably a question all along.
### The bullet you left behind
**A fog bullet still sitting in `## Not yet specified` after its question file exists is the single most common drift in this skill.** It is quiet — nothing errors, the map still renders — and it is corrosive:
- The Clearing Gate requires `## Not yet specified` to be EMPTY. A stale bullet blocks the gate forever, so the map never clears even when every question is resolved.
- A later session reads the bullet, does not recognize the question file as the same thing under a different phrasing, and writes a duplicate. Now two files hold half a decision each.
- It violates the rule that detail lives in exactly one place.
Detection is cheap: after writing any graduated question file, re-read `## Not yet specified` top to bottom and confirm the bullet is gone. If a bullet reads like a question you have already written a file for, delete the bullet — the file always wins.
### Ruling a question out of scope mid-work
The destination fixes the scope. When a resolution reveals that a question — the one you just claimed, or another on the map — sits past the destination:
1. Decide the one-line reason. Do NOT write a `## Answer`; there is no decision, only a scope boundary.
2. Run `node "<S>/pathfinder.mjs" rule-out specs/<idea>/pathfinder <NN> --reason "<why>"`. It sets `State: out-of-scope`, adds the reason under `## Question`, marks the row `[-]` and adds the linked line to `## Out of scope`.
3. Handle its `stranded` list: questions whose `Blocked by:` names it. A blocker that is `out-of-scope` will never be `resolved`, so the dependent is permanently blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
Out-of-scope work never graduates back. The frontier stops at the destination. It returns only if the destination is redrawn, and then as a fresh effort with a fresh map.
```markdown
## Out of scope
- [Slack connector](./questions/08-slack-connector.md) — the destination names
MS Teams only; Slack is a separate effort with its own compliance posture.
```
### Re-framing or deleting a question the answer invalidated
An answer can also break questions that already exist. Three cases:
| What happened | Do this |
|---|---|
| The question still matters but is asked wrong | **Re-frame.** Rewrite `## Question` in place. Keep `NN`, keep the file, keep the links. Add one line noting which answer forced the re-frame. |
| The question no longer exists — the answer subsumed it | **Delete the file, then run `reconcile`** (it drops the map row). Add one line to the answering question's `## Answer` consequences saying what it absorbed. Do not renumber anything. |
| The question is now two questions | **Re-frame the original to the narrower half; write a new file at max+1 for the other.** Wire `Blocked by:` between them if one gates the other. |
Never leave a question standing that you know is wrong on the theory that a later session will notice. It will not — it assumes no memory, and a well-formed `## Question` reads as intentional.
Two hard constraints on all three cases: **`NN` is never reused and never renumbered** — links and `Blocked by:` lines would rot silently. And run `reconcile` straight after any re-frame or deletion, so the index never disagrees with the files (it drops the row of a deleted file and adds one for a new file).
@@ -1,86 +0,0 @@
# Trail Footer
> Loaded at the top of the skill. Read once; it applies to EVERY response in both modes. Defines the map visual and the pathed resume command that close each turn.
>
> **Backend note.** The glyphs, the two forms, and the discipline are identical either way. On `**Backend:** github` the inputs come from the sub-issue query rather than the checklist, and Form A's command is the map issue URL — see `github-issues.md`. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
The trail is how a human with no memory of the last session sees, at a glance, how far the map has come and what is left — and copies the exact command to resume without hunting for a path that lives in gitignored `specs/`. It closes every response once a map exists.
It is **presentation only**, rebuilt fresh from the files every response and never written to disk. The script draws it; you choose its form.
```
node "<S>/pathfinder.mjs" trail specs/<idea>/pathfinder --form A|B|C [--item "<probe>" ...] --text
```
`--text` prints the footer itself: paste it verbatim as the last thing in the response. Use it for Forms A and B. For Form C leave `--text` off: the JSON carries the same `text` plus the `menu` the question tool needs. Run `reconcile` first in a session (Work Step 2) so the files it reads are settled.
---
## When it renders, and which form
The **turn type** picks the form, never the map's status. This is the one decision the script cannot make for you.
| Situation | Footer |
|---|---|
| `map.md` exists and the turn **ends the session** — Session End, a cleared map, a fully blocked frontier, a parked grill | **Form A**: the trail, then the resume command |
| `map.md` exists and the turn **asks the human something** — a probe batch, a sketch put up for reaction, a `legwork · HITL` checklist, the Chart Step 2 destination grill, the Chart Step 4 frontier grill | **Form B**: the trail, then the waiting notice. Never a resume command |
| `map.md` exists and the turn **offers the menu after a recorded decision** — the continue-or-stop fork of the Work cadence | **Form C**: the trail, the `OR START FRESH` command, then the question tool |
| Intent Gate (Step 0), the no-fog off-ramp, or any route-and-stop before Step 5 | **None** — no map on disk yet, and no path to resume |
One idea per session, so there is only ever one trail.
### What the script draws (so you can read it, not build it)
```
🧭 audit-log-export · Working · 2/6 cleared
START ●━●━◉··○··○··⊘··⊝ ····⚑
● done · ◉ here · ○ open · ⊘ blocked · ⊝ out of scope · ⚑ destination · ~4 fog
1 Codebase context ✔ · 2 Export format ✔ · 3 Row-count ceiling ◀ here · 4 Export authorization
5 Testing posture · 6 Delivery channel (blocked:3) · 7 SIEM push (out of scope)
Confidence: solid, but Risk is borderline.
WAITING ON YOU · answer here, in this conversation:
Q2 Ceiling behaviour past the cap (re-ask) · Q3 Who sees the truncation warning
```
- The heading counts resolved questions over every question except out-of-scope ones.
- One glyph per question in `NN` order: `●` resolved, `◉` claimed, `○` open, `⊘` blocked, `⊝` out of scope. A solid `━` leads into a walked stop (`●`, `◉`); `··` leads into one still ahead. `····⚑` stands for the fog; with no fog the path ends `━⚑` once every stop is walked (or ruled out) and `··⚑` while any is still ahead. A cleared map ends `━⚑ arrived` and drops both legend lines.
- The named legend numbers stops by position, and `(blocked:3)` points at stop 3.
- The confidence line is the map's four internal scores reduced to plain English: `solid` (all ≥ 20), `solid, but <Dimension> is borderline` (all ≥ 18, some at 18-19), `not yet — <Dimension(s)> still need work` (any < 18). The raw numbers never reach the human. No `**Confidence:**` line on the map, no confidence line in the trail.
---
## Form A — the turn ends the session
The command follows the map's status: `/plan2code-0-pathfinder specs/<idea>/pathfinder --web` while `Charting` / `Working`; `/plan2code-1-plan --web` once `Cleared`; and `/plan2code-init` first when `## Ground rules` records `AGENTS.md` absent and it still is. The path is the exact argument Auto-Discovery resolves an idea from, so the human pastes it back with zero edits.
## Form B — the turn asks the human something
Pass every outstanding item as `--item`, at its stable number (`--item "Q1 Duration model"`), so a partial reply is cheap and a dropped probe is visible to both of you. The script refuses more than three: the three-probe cap.
**Emit no resume command on a Form B turn.** There is nothing to resume — the session is alive and holding a claim. A resume command here reads as *we're done*, and the human either walks away mid-decision or burns the next turn asking what you meant. This is the single most common way the footer misfires, and it costs the batch the round trips batching was introduced to save.
One exception: `grilling.md`'s unreachable-human procedure. Parking a mid-grill question and stopping IS a session end — use Form A, and say in the body that the question is parked mid-grill with its batch outstanding.
## Form C — the menu after a recorded decision
Used ONLY on the Work cadence's fork-menu turn (resolve.md §Cadence), immediately after `resolve` recorded an `## Answer`. The script refuses it while a question is claimed or once the map is `Cleared`. Pass `--resolved-this-session <N>`, and `--heavy` when the decision just recorded was heavy, contested, or `Locked: yes`.
It prints the stop branch, labeled `OR START FRESH · new conversation, paste:`, and returns `menu`: the header, the question text, up to three takeable questions plus `Start fresh`, and which option to mark `RECOMMENDED` (a question early in the session; `Start fresh` after ~3 resolved or a heavy decision, with the reason in the question text, "to keep me sharp").
Then invoke the structured question tool with that menu. Put each question's gist or newly-unblocked note (from `resolve`'s `unblocked`) in its description. The automatic `Other` path lets the human name a frontier question not shown (`menu.more`).
Rules for Form C:
- **The command label is mandatory and exact.** It makes the command the stop branch, not a farewell. Never render a bare command on a menu turn.
- **The choice itself always uses the structured tool.** Never print `NEXT UP` as a prose menu when the tool exists.
- **Form C never replaces Form B.** A turn that asks probes, shows a sketch, or hands over a checklist is Form B, no command. Form C fires only between decisions, when nothing is claimed.
- If the human walks away mid-menu, nothing is stranded: no claim is open, and the command to come back is already on screen.
---
## Discipline
- **Never print a bare resume command on a turn that asks a question.** Before you choose the form, ask whether the response above it ends with something for them to answer: mid-question (probes, sketch, checklist) → Form B, no exceptions but the parked-grill one; between decisions at the fork-menu → Form C.
- **Draw it, never type it.** A hand-built trail drifts from the files; the script reads them every time. If the trail disagrees with the checklist above it, run `reconcile`, but only at session start or while nothing is claimed: `reconcile` resets a claim with no answer to `open`, so mid-question it would drop your own live claim. With a claim open, finish that question instead; `resolve` rebuilds the checklist, and the next trail is drawn from it. On `github` (the script cannot read the tracker), build it by hand from the sub-issue query, following "What the script draws" exactly.
- **One trail.** Never render two ideas' trails, and never invent a stop the map does not list.
@@ -1,498 +0,0 @@
# Build Sessions on the Web Console
For `/plan2code-3-implement`, `/plan2code-3-implement-review` and
`/plan2code-quick-task`. Read `console.md` first: everything there still
applies (the wait loop, one post per send, `finish` before `stop`, the house
rules). This file adds what a build needs, because a build is mostly you
working, and the page has to be told so.
**The console changes where you ask, not what you build.** Every rule of the
workflow stands: the same specs, the same checkbox writes to disk after every
task, the same sign-off wording, the same "no git commands". The files under
`specs/` and the code are the record. The page is a window onto them.
---
## Opening
Open first, before reading the spec — the page shows a starting screen while
you work out the phase:
```
node "<CONSOLE>" open --workflow implement
```
| Workflow you are running | `--workflow` | `--spec` |
| --- | --- | --- |
| `/plan2code-3-implement` | `implement` | `specs/<feature>` |
| `/plan2code-3-implement-review` | `implement-review` | `specs/<feature>` |
| `/plan2code-quick-task` | `quick-task` | leave it out |
`--spec` is what the page builds a resume command from if you ever cannot
answer a stop yourself. Pass it to `open` when you already know the spec;
otherwise post `"specDir": "specs/<feature>"` and a real `title` ("<feature>:
Phase 3") in your first update, once the phase is chosen, or with the phase
question as its first item if there is one to ask. `--file` works on `open`
too, but opening bare and posting the task list as your first update gets
them the page while you are still composing.
**Launched from the dashboard?** Then the session is already open and the
person is watching it — `open --resume <sid> --no-open --workflow <yours>`
(plus `--spec` once known) instead of a fresh `open`, exactly as console.md →
Launches says. Everything below is unchanged; the only difference is whose
session it was a minute ago.
The first payload for a phase you are about to build:
```jsonc
{
"headline": { "stage": "Phase 3: API layer", "cleared": 0, "total": 9 },
"docs": [
{ "id": "phase", "title": "Phase 3 tasks", "version": 1, "blocks": [
{ "id": "tasks", "state": "settled", "md": "- [ ] **Task 3.1:** ...\n- [ ] **Task 3.2:** ..." }
]},
{ "id": "phasefile", "title": "phase-3.md", "version": 1, "blocks": [
{ "id": "body", "state": "settled", "md": "...the whole phase-3.md file, verbatim..." }
]}
],
"agent": { "status": "working", "activity": "Checking the prerequisites", "quietMinutes": 15 }
}
```
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
progress bar is the first thing someone watching a build looks at. The session
meter counts the build's tasks from `cleared` as it rises, so keep it current,
and start every phase (a second one in the same run too) at `"cleared": 0`.
`"version": 1` is for the first phase of a session only. A doc's version
never goes back (console.md → House rules, rule 9), so a later phase in the
same session reposts `phase` and `phasefile` at one more than the version the
page holds, with the new phase's title and content. The same goes for
`report` at sign-off and `review` in a mid-session review: version 1 the
first time, then up from wherever the page has it.
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
the person can read the prerequisites and task specs while you build. Re-post
it whenever the file changes, which is every task: the checkbox write that
ticks the list above ticks the file too, and the Phase Completion Summary
lands in it at the end. It renders as markdown, so the file's checkboxes show
as ticks exactly as they stand on disk.
---
## While you build
Post after every task, in the same breath as writing its checkbox to disk.
Write the patch file into the session's own folder (the `session` path `open`
printed), never into the project or into `~/.plan2code/console/` directly:
```jsonc
{
"headline": { "cleared": 4 },
"docs": [
{ "id": "phase", "version": 5, "blocks": [ { "id": "tasks", "state": "settled", "md": "...the whole list, 4 ticked..." } ] },
{ "id": "phasefile", "version": 5, "blocks": [ { "id": "body", "state": "settled", "md": "...phase-3.md as it now stands on disk..." } ] }
],
"agent": { "activity": "Task 5 of 9: the rate limiter" }
}
```
- **`activity`** is one plain sentence saying what you are doing now. The page
shows it beside Planny and in place of "questions coming". No internal
vocabulary, no loop completion markers. Number tasks by their position in
the phase, of the phase's task count (`Task 5 of 9`), not by the file's
`5.5`-style labels: the phase is already in the headline. The page rewrites
the old form as a safety net.
- **`quietMinutes`** is how long you might go without posting (1 to 60). The
page calls a working agent stuck after two minutes of silence unless you say
otherwise, and a build task can honestly take twenty. Set it to the longest
gap you expect, usually 10 to 30. Every post is also a heartbeat. **Clear it
(`"quietMinutes": null`) whenever you go back to waiting**: it only counts
while you are `working`, but leaving it set invites a stale value later.
- `blocks` inside a doc are replaced whole, so post the whole task list each
time. It is small. The same goes for `phasefile`: re-read `phase-X.md` and
post it fresh, because the checkbox write just changed it.
- If the task list grows mid-build, raise `headline.total` in the same post;
the page never shows more done than the total, but the bar reads truer when
you keep it current.
- Do not call `wait` while building. There is nothing to collect, and the page
holds anything the person sends until you next look.
A build may receive a `Subagents:` standing instruction, on `open` output or a
`chat` check between tasks. Follow console.md → Standing instructions for
handing independent tasks to helpers and reporting them as `helpers`. Keep the
per-task progress posts, the checkbox writes, the chat checks and the sign-off
with you.
### Quick questions between tasks
The person can ask a Quick question on the Ask tab at any point in a build
(console.md → Quick questions). After each task's progress post, check for
one before starting the next task:
```
node "<CONSOLE>" chat --session <sid>
```
| Exit | What you do |
| --- | --- |
| `0` | Answer everything waiting, under console.md → Quick questions, in one post, then start the next task. A `workspace` list in the output is a change to the session's folders (console.md → Workspace): take it into account from the next task on; it needs no reply. |
| `10` | Nothing waiting. Carry on. |
| `20` | The server is gone: `open --resume <sid>` as usual, then carry on. |
This is an instant check, not a wait: it never sleeps and never touches card
sends. It does not replace `wait` at a gate, and no build calls `wait`
mid-build for cards. An approved chat edit is made here, between tasks, never
in the middle of one.
A blocker (`[!]`), a `SPEC NOTE` and a verified or assumed prerequisite are
not questions. Put them in the phase doc as they happen, and in the report.
### When the workflow asks something
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }` in
the SAME post, and go into the wait loop. When the answer lands, set `working`
again and carry on.
A question stops the build. Never leave yourself `working` with a question
open, and never "carry on while you decide": the page reads `working` as "not
your turn", and the person is left looking at a question they cannot answer.
If there is other work the answer does not touch, finish it before you ask,
then ask and wait.
| Moment | `kind` | Notes |
| --- | --- | --- |
| Several phases can be picked | `choice` | One option per phase, `detail` = status and task count, `token` = the phase number. Put the "run another agent on a different phase" tip in `body`. |
| A phase is already in progress | `confirm` | "Resume Phase 3?" `yes` / `no`. |
| `SPEC CONFLICT` | `choice` or `text` | The conflict in `body`, the readings as options where there are clear ones. Never guess on architecture. |
| Test failures | `choice` | `1` Fix now, `2` Document and proceed, `3` Investigate first. |
| A small phase, continue with the next? | `confirm` | |
| A spec gap only they can close | `text` | |
| Something learned for AGENTS.md | `confirm` | The proposed lines in `consequences`. |
Titles stay plain: "Which phase next", "Tests are failing", "Keep going?".
---
## Sign-off
Put the Completion Report on the page as a doc, then ask for approval as a
`review` item pointing at it. The review offer rides on this card, as a verdict
ahead of the approval buttons — not on the finish after it, where it could
only ever be offered once nothing could come of it:
```jsonc
{
"docs": [{ "id": "report", "title": "Completion report", "version": 1, "blocks": [
{ "id": "summary", "state": "settled", "md": "## Summary\n\n..." },
{ "id": "files", "state": "settled", "md": "## Files\n\n..." },
{ "id": "verify", "state": "settled", "md": "## How to check it\n\n..." }
]}],
"items": [{
"id": "signoff", "kind": "review", "title": "Approve this phase", "doc": "report",
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, or say what to change.",
"verdicts": [
{ "id": "review", "label": "Review the code first" },
{ "id": "approve", "label": "Approve this phase" },
{ "id": "changes", "label": "I want changes" }
],
"token": { "review": "review", "approve": "approved", "changes": "needs changes" },
"nothingYet": "Nothing is marked complete until you approve.",
"gate": { "id": "signoff", "authoritative": true },
"fallbackText": "Reply \"approved\" to mark this phase complete, \"review\" to run the code review first, or describe any issues."
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
`reply` carries `Approve this phase: approved`, which is the terminal's
`approved`. If the note that came with an approval asks for a change, treat it
as "describe any issues": do the change first and ask again. `changes` means
exactly what it says: address it, bump the report's version (a later phase's
report starts above the last one's, too), and reopen the
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
person asking for the code review before they approve anything — see "The
review, mid-session" below.
`gate` marks the one approval that counts. The server refuses a second open
authoritative gate, which is what keeps a composed workflow from asking for
sign-off twice.
---
## After approval: the finish
Do everything the workflow does on approval (the checkboxes, the summary, the
upcoming phases, the commit command) and print it in the terminal as usual.
Then post the finish, wait for the dashboard button as console.md → Finishing
says, and `stop`:
```jsonc
{
"items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "approve" } }],
"run": { "event": "implement-phase", "id": "phase-3", "tasks": 9 },
"finish": {
"headline": "Phase 3 is done",
"body": "9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```",
"command": "/plan2code-3-implement specs/lunch-vote/overview.md",
"doc": "report",
"dashboard": true
},
"agent": { "status": "waiting" }
}
```
`finish.command` is the next pipeline step, the same one the terminal names:
the next `/plan2code-3-implement`, or `/plan2code-4-finalize` after the last
phase. An `implement` finish never carries `review`: the offer was on the
sign-off card, and approving past it was the answer. `implement-review` ends
the same way; that phase was reviewed already. Only a finished `quick-task`
still offers the review on its finish — see below.
`run` gives the approved phase its final score on the session meter (console.md →
Posting an update → Session meter), in the same post that records the approval;
it takes over what the build already counted from `cleared`, never adds to it:
`implement-phase` for Implement, `implement-review-phase` for Implement +
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
twelve-task phase weighs four times a three-task one; leave `tasks` out and
every phase weighs the same. Quick task and a standalone Review are counted when
their session opens, so they post no `run` for that; a review run on the page
after a build reports its own (below).
---
## The review, mid-session
The same focused review runs from either of two doors:
- **`implement`:** the `review` verdict on the sign-off card, before anything
is approved. A note sent with it is theirs — read it as focus for the
review. Settle the card with it in the same post that goes back to work:
```jsonc
{
"items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "review" } }],
"headline": { "stage": "Reviewing Phase 3", "cleared": 0, "total": 0 },
"run": { "event": "review", "id": "review" },
"agent": { "status": "working", "activity": "Reviewing the 7 files this phase changed", "quietMinutes": 15 }
}
```
- **`quick-task`:** the **Review it now** button on the finished screen, which
`finish.review` puts there. It arrives through the wait loop as an action
`{ "i": "__review", "type": "review" }`, like any send. Take it up with the
same post minus the `items` line, plus `"finish": null` — that takes the
session off its ending and back to work.
Either way, the post that takes the review up carries `"run": { "event":
"review", "id": "review" }`: the review runs inside this skill's session, so no
launch scores it on the session meter. Never resume the session under
`--workflow review` for it as well, or it counts twice.
A finish carrying `review` keeps the session alive for the answer, so a
`quick-task` that just posted one keeps waiting, for up to about ten minutes.
A quick-task finish carries both `review` and `"dashboard": true` and waits
for whichever comes first:
| What arrives | What you do |
| --- | --- |
| An action `{ "i": "__review", "type": "review" }` | Take the review up (below). |
| An action `{ "i": "__dashboard", "type": "dashboard" }` | Take the session back as the dashboard (console.md → Finishing). |
| An action `{ "i": "__done", "type": "done" }` | `stop` the server. The session is over. |
| `wait` exit `20` | The server is gone, not necessarily the tab. Resume it (`open --resume <sid> --no-open --workflow <yours>`) and keep waiting. |
| Nothing after about ten minutes | `stop` the server. The page then shows the terminal command for a review instead of a button that would go nowhere. |
**Read references/review.md** and run Review Mode with these overrides:
- **Scope is Focused, and already decided:** the exact change set of this
session (files created or modified by the phase or the quick task, plus the
tests and docs changed for it). Do not ask about scope. Use overview.md and
the phase file for spec compliance; they do not widen the scope.
- **No commit instructions and no next-conversation routing** mid-review. The
way back out carries both.
- The page takes the whole report, so the "top 10 of 15+" rule does not apply,
and tables go in the doc.
### The findings
The full Review Mode report as a doc, and the fix choice as one `multi` item:
```jsonc
{
"docs": [{ "id": "review", "title": "Review findings", "version": 1, "blocks": [
{ "id": "report", "state": "settled", "md": "## Overview\n\n...\n\n## Findings\n\n| # | Severity | Issue | File |\n..." }
]}],
"items": [{
"id": "fixes", "kind": "multi", "title": "Which to fix", "required": false, "doc": "review",
"body": "Tick what should be fixed now. Anything left unticked is written up as still open. Nothing changes until you send.",
"options": [
{ "k": "1", "text": "Critical: token is logged in plain text", "detail": "src/auth.ts:42. Fix: redact before logging." },
{ "k": "2", "text": "Warning: missing null check on the user lookup", "detail": "src/users.ts:88. Fix: ..." },
{ "k": "3", "text": "Suggestion: repeated query could be batched", "detail": "src/report.ts:17. Fix: ..." }
],
"presets": [
{ "label": "Critical and warnings", "ks": ["1", "2"] },
{ "label": "All of them", "ks": ["1", "2", "3"] }
],
"token": { "1": "1", "2": "2", "3": "3" },
"fallbackText": "Reply H to fix Critical + Warning findings, A to fix all findings, or S 1,3,5 to fix specific findings."
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
`"doc": "review"` puts a **Read "Review findings" in full** button on the
card, so the report is one click from the list rather than behind a tab
nobody notices. Always carry it.
Read the reply as Review Mode's fix choice: `Which to fix: 1, 2` is `S 1,2`,
every finding ticked is `A`, and `skip` (or nothing ticked) is "fix none,
keep them as unresolved". Leave out `presets` a set would not change (no
warnings, one finding). With **zero findings** there is no item: say so in the
doc and go straight to the way back out.
### Fixing
Settle the `fixes` item in the same post that goes back to work —
`"status": "answered"` with the `answer` they sent (`{ "ks": ["1", "2"] }`,
or `{ "ks": [] }` when nothing was ticked). The server records their send on
the item, but only you decide it is settled; left open it stays on the page
as an outstanding question, beside the card you ask next. Then follow Review
Mode's Post-Fix Flow, posting `activity` per fix ("Fix 2 of 3: the null
check") and `quietMinutes` as in a build.
### The way back out
**`implement` — back to the sign-off.** The review was the preamble to an
approval that has not happened yet, so this is where it lands. Fold the review
results and any still-open findings into the report doc and bump it, then
reopen the sign-off **without the review verdict** — re-offering a review that
just ran reads as though nothing happened:
```jsonc
{
"items": [{ "id": "signoff", "status": "reopened",
"body": "Reviewed and ready for sign-off. The review found 3 issues: 2 fixed, 1 still open in the Review findings tab. The report is updated.",
"verdicts": [
{ "id": "approve", "label": "Approve this phase" },
{ "id": "changes", "label": "I want changes" }
],
"thread": [{ "who": "agent", "text": "Review done: 2 of 3 findings fixed; the rest is written up in the findings tab." }]
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
Review Mode's own closing gate ("Reply approved to commit") is this card:
approving the phase now covers the fixes too, so there is no separate "Check
the fixes" step. On approval, continue at "After approval: the finish".
**`quick-task` — the closing gate, then the finish.** Review Mode's closing
gate ("Reply approved to commit, or request changes") becomes a `review` item
titled "Check the fixes", `doc: "review"`, verdicts `approve` ("The fixes look
right") and `changes`, token `approved` / `needs changes`. When it clears,
settle it in the same post as the new finish — `"status": "answered"` plus
`"answer": { "verdict": "approve" }` (or `"changes"`) — post the finish
**without** `review`, then `stop`. An item left open survives on the page as
a question still owed, above the ending itself:
- `headline`: "The review is done"
- `body`: findings by severity, what was fixed, what is still open, and the
commit command for the fixes, in the project's commit format.
- `command`: the same next step as the finish before it.
- `doc`: `"review"`.
---
## Implement + Review (`implement-review`)
The same build, then Stage 2 publishes the findings exactly as above (the
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
item: Stage 4 is the only gate. The post that starts Stage 2's review carries
`"run": { "event": "review", "id": "review" }`, as above: in this workflow it
scores the review stage's 1 point on the meter as it begins, and the phase's
final `run` leaves that point out. Stage 4 is the sign-off above **without the
review verdict** — the phase was already reviewed — with the review results
and unresolved findings in the report doc, header "Reviewed and ready for
sign-off" in the item's `body`. The finish never carries `review`, and its
post carries `"run": { "event": "implement-review-phase", "id": "phase-N", "tasks": N }`
with the count of completed tasks.
---
## Quick task (`quick-task`)
- Open with the first clarifying question. Clarifying questions go out as
`text` or `choice`, at most three at a time.
- Post `"stopWarning": "A quick task saves nothing until it is built, so stopping now loses what we have worked out."`
at the start, and `"stopWarning": ""` once the build is under way.
- **Scope check:** a `choice`, "Too big for a quick task?", options
`1` Continue (lightweight format) and `2` Escalate to a full plan, with the
measured counts against the thresholds in `body`.
- **Feature name** (escalating): `text` with
`"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"` and a kebab-case placeholder.
- **The plan:** a `plan` doc (Summary, Files to change, Steps, Verify) and a
`review` item "Build this plan?" with verdicts `yes` ("Build it"), `modify`
("Change the plan"), `escalate` ("Plan it properly instead") and `abort`
("Stop here", `"danger": true`), token equal to the ids.
- **Building** after `yes`: settle the verdict (`"status": "answered"` plus
`"answer": { "verdict": "yes" }`) in the post that starts the build, and
open a **Build progress** tab in that same post, the way an Implement phase
gets its tasks tab. The plan's steps are the task list and `total` is their
number:
```jsonc
{
"stopWarning": "",
"items": [{ "id": "<the Build this plan? item's id>", "status": "answered", "answer": { "verdict": "yes" } }],
"headline": { "stage": "Building", "cleared": 0, "total": 4 },
"docs": [{ "id": "tasks", "title": "Build progress", "version": 1, "blocks": [
{ "id": "tasks", "state": "settled", "md": "- [ ] Step one\n- [ ] Step two\n- [ ] Step three\n- [ ] Step four" }
]}],
"agent": { "status": "working", "activity": "Step 1 of 4: step one", "quietMinutes": 10 }
}
```
Then post after every step, exactly as "While you build": bump the doc's
`version` and repost the whole list with that step ticked, raise
`headline.cleared`, and set `agent.activity` to the next step ("Step 2 of 4:
step two"). Never go silent for the whole build: a quick task with many steps
is the case this tab is for. Check for a Quick question between steps, and do
not call `wait` until the build is done.
- **The finish after the build:** `command` is the commit command, filled in,
in the project's commit format (AGENTS.md), with
`"where": "When you are happy with it, commit it from your terminal:"`, and
`review` on offer — the **Review it now** button, since a quick task has no
sign-off card to put it on — and `"dashboard": true`, so the finished screen
also offers **Back to the dashboard**. Both are required: a finish without
`dashboard` leaves the person on a dead end. Keep waiting for whichever
button is pressed, and everything after that is "The review, mid-session"
above.
- **Escalated / aborted:** settle the verdict the same way in the finish post —
finish with `"command": "/plan2code-1-plan"` and the
PLAN-DRAFT's path in `body`, no review; or `"command": "/plan2code-quick-task"`.
Both set `"dashboard": true`: an abort of a quick task saves nothing to
resume, so it is not a pause.
---
## Stop requests during a build
The Stop button only works on the person's turn, so it never lands mid-task.
When `__stop` arrives:
- **implement / implement-review:** Implementation Mode's abort, without the
"are you sure" (the page asked): the phase stays `[/]`, list completed and
remaining tasks, post `finish` with the resume command
(`/plan2code-3-implement specs/<feature>/overview.md`), then `stop`. An
implement abort is a pause: a headline starting "Paused", no `dashboard`,
`stop` at once.
- **quick-task:** say in `finish.body` what was worked out, and that nothing was
saved unless it was built; `"command": "/plan2code-quick-task"`.
A mid-build `__dashboard` (the top bar's triangle, console.md → Stop requests →
"Back to the dashboard, mid-workflow") lands the same way, only on the person's
turn. Save exactly as for `__stop` above (an implement phase stays `[/]`), but
post no finish and do not `stop`: resume as the dashboard instead, with one
terminal line naming what was saved and the resume command.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,265 +0,0 @@
// Plan2Code Web Console - the native folder picker behind Workspace's Browse…
//
// A port of the launcher's picker (src/launcher/plan2code.js). The launcher
// is self-contained CommonJS copied alone to ~/.plan2code/bin/, and this
// console is ESM bundled into every skill, so the two cannot share a module:
// this is a copy, and a drift test in scripts/test-web-console.mjs fails the
// moment the launcher's picker changes without it. The prompt is a parameter
// here rather than the launcher's constant.
//
// Always spawned asynchronously: spawnSync would freeze the server's polling,
// chat and wait for as long as the dialog stayed open.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
const IS_WINDOWS = process.platform === "win32";
const IS_MAC = process.platform === "darwin";
export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace";
// Copied verbatim from src/launcher/plan2code.js; see the drift test.
export const WINDOWS_PICKER_SOURCE = `
using System;
using System.Runtime.InteropServices;
using System.Threading;
public static class Plan2CodeFolderPicker {
[ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
private class FileOpenDialog {}
[ComImport, Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IFileOpenDialog {
[PreserveSig] int Show(IntPtr owner);
void SetFileTypes(uint count, IntPtr specs);
void SetFileTypeIndex(uint index);
void GetFileTypeIndex(out uint index);
void Advise(IntPtr events, out uint cookie);
void Unadvise(uint cookie);
void SetOptions(uint options);
void GetOptions(out uint options);
void SetDefaultFolder(IShellItem item);
void SetFolder(IShellItem item);
void GetFolder(out IShellItem item);
void GetCurrentSelection(out IShellItem item);
void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
void GetResult(out IShellItem item);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem {
void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
void GetParent(out IShellItem parent);
void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name);
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
private static extern void SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid iid, out IShellItem item);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string className, string title);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int w, int h, uint flags);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int index);
private const uint FOS_PICKFOLDERS = 0x20;
private const uint FOS_FORCEFILESYSTEM = 0x40;
private const uint FOS_PATHMUSTEXIST = 0x800;
private const uint SIGDN_FILESYSPATH = 0x80058000;
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
private static void Raise(string title) {
for (int i = 0; i < 100; i++) {
IntPtr hwnd = FindWindow(null, title);
if (hwnd != IntPtr.Zero) {
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
int h = Math.Min(750, GetSystemMetrics(1) - 80);
int x = (GetSystemMetrics(0) - w) / 2 + 40;
int y = (GetSystemMetrics(1) - h) / 2 + 40;
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
SetForegroundWindow(hwnd);
return;
}
Thread.Sleep(50);
}
}
public static string Pick(IntPtr owner, string title, string start) {
IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
try {
uint options;
dialog.GetOptions(out options);
dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
dialog.SetTitle(title);
if (!string.IsNullOrEmpty(start)) {
try {
Guid iid = typeof(IShellItem).GUID;
IShellItem folder;
SHCreateItemFromParsingName(start, IntPtr.Zero, ref iid, out folder);
dialog.SetFolder(folder);
} catch (Exception) {}
}
Thread raiser = new Thread(delegate() { Raise(title); });
raiser.IsBackground = true;
raiser.Start();
int hr = dialog.Show(owner);
if (hr == ERROR_CANCELLED) return null;
Marshal.ThrowExceptionForHR(hr);
IShellItem result;
dialog.GetResult(out result);
string path;
result.GetDisplayName(SIGDN_FILESYSPATH, out path);
return path;
} finally {
Marshal.ReleaseComObject(dialog);
}
}
}
`;
// Resolve a command on PATH the way the shell would, including PATHEXT on Windows.
function findOnPath(command) {
const dirs = (process.env.PATH || "").split(path.delimiter).filter(Boolean);
const extensions = IS_WINDOWS ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [""];
for (const dir of dirs) {
for (const ext of extensions) {
const candidate = path.join(dir.replace(/^"|"$/g, ""), command + ext);
try {
if (fs.statSync(candidate).isFile()) return candidate;
} catch {}
}
}
return null;
}
/**
* The native folder picker for this OS, as a command to run: it prints the
* chosen folder, or nothing when the person cancels. Null when this OS has no
* picker we can drive.
*/
export function pickerCommand(start, prompt) {
if (IS_WINDOWS) {
const script = [
"$ErrorActionPreference = 'Stop'",
"try {",
" [Console]::OutputEncoding = [Text.Encoding]::UTF8",
" Add-Type -AssemblyName System.Windows.Forms",
" [System.Windows.Forms.Application]::EnableVisualStyles()",
// A TopMost owner keeps the dialog in front of the console window that launched it.
" $owner = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true; ShowInTaskbar = $false }",
" try {",
" Add-Type -TypeDefinition $env:PLAN2CODE_PICKER_SOURCE",
" $picked = [Plan2CodeFolderPicker]::Pick($owner.Handle, $env:PLAN2CODE_PICKER_PROMPT, $env:PLAN2CODE_PICKER_START)",
" } catch {",
// Add-Type is blocked under Constrained Language Mode and some AppLocker policies; the
// old tree dialog still works there.
" $dialog = New-Object System.Windows.Forms.FolderBrowserDialog",
" $dialog.Description = $env:PLAN2CODE_PICKER_PROMPT",
" $dialog.SelectedPath = $env:PLAN2CODE_PICKER_START",
" $picked = if ($dialog.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { $dialog.SelectedPath } else { $null }",
" }",
" if ($picked) { $picked }",
"} catch { exit 3 }",
].join("\n");
return {
command: "powershell.exe",
args: [
"-NoProfile",
"-NonInteractive",
"-STA",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
Buffer.from(script, "utf16le").toString("base64"),
],
env: {
PLAN2CODE_PICKER_PROMPT: prompt,
PLAN2CODE_PICKER_START: start,
PLAN2CODE_PICKER_SOURCE: WINDOWS_PICKER_SOURCE,
},
};
}
if (IS_MAC) {
return {
command: "osascript",
args: [
"-e",
"on run argv",
"-e",
`POSIX path of (choose folder with prompt "${prompt}" default location (POSIX file (item 1 of argv)))`,
"-e",
"end run",
start,
],
};
}
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return null;
if (findOnPath("zenity")) {
return {
command: "zenity",
args: ["--file-selection", "--directory", `--title=${prompt}`, `--filename=${start}${path.sep}`],
};
}
if (findOnPath("kdialog")) {
return { command: "kdialog", args: ["--title", prompt, "--getexistingdirectory", start] };
}
return null;
}
/**
* Show the picker and settle on what the person did: `{ path }` for a pick,
* `{ cancelled: true }` when they closed it, `{ error }` when the picker
* itself failed or this OS has none. Pickers exit 0 or 1 with nothing printed
* when cancelled.
*/
export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
const picker = pickerCommand(start, prompt);
if (!picker) return Promise.resolve({ error: "picker-failed" });
return new Promise((resolve) => {
let settled = false;
const settle = (result) => {
if (settled) return;
settled = true;
resolve(result);
};
let child;
try {
child = spawnImpl(picker.command, picker.args, {
env: { ...process.env, ...(picker.env || {}) },
// stderr is ignored, not piped: a pipe nobody reads fills up and
// blocks a chatty picker (GTK warnings) before it can exit.
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
});
} catch {
return settle({ error: "picker-failed" });
}
let stdout = "";
if (child.stdout) {
child.stdout.setEncoding?.("utf8");
child.stdout.on("data", (chunk) => (stdout += chunk));
}
child.on("error", () => settle({ error: "picker-failed" }));
child.on("close", (code) => {
const folder = stdout.trim();
if (code === 0 && folder) return settle({ path: path.resolve(folder) });
if (!folder && (code === 0 || code === 1)) return settle({ cancelled: true });
settle({ error: "picker-failed" });
});
});
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,138 +0,0 @@
// Planny's wake-up on a freshly opened dashboard: he sits powered down centre
// stage until the first click or key, gets nudged awake (he rocks side to side
// for one snore), then about five seconds of him powering on, then a glide
// into the rail as the menu comes in.
//
// The beats before the glide are pure CSS (keyframes on delays under
// `.wake.booting`, see app.css). The glide is the one part CSS cannot know on
// its own, because it ends wherever the rail's Planny sits right now, so this
// measures it once and hands CSS a single transform through --wake-glide.
//
// No DOM access at module scope, so `node --test` can import it.
// When the glide starts, and when the run is over at the latest. The CSS
// delays are the beats before GLIDE_AT_MS; the glide itself is 0.6 s.
export const GLIDE_AT_MS = 4300;
export const DONE_AT_MS = 5000;
// Plays the wake-up and resolves `{ skipped }` once the dashboard is fully
// awake. He waits powered down until the first click or key anywhere, which
// nudges him (`.stirring`) and calls `stir()` -- the page's cue to play one
// full snore, since a browser only lets a page make noise after a real click
// or keypress. The boot starts once the promise `stir()` returns settles (at
// once without one), and calls `onStart()`, the page's cue for the boot-up
// sound. `onGlide({ instant })` is the page's cue to bring the menu in: called
// at the glide, or with `instant: true` if the run ends before one (a skip).
// From the nudge on, clicks and keys are swallowed, so the run always plays
// out to the end with its sound; only `skipEl` (the muted Skip button, or the
// Escape key, for anyone without a mouse) and `signal` aborting (the page
// leaving the dashboard, dormant or mid-run) cut it short, as a skip.
// `onSkip` is the page's cue to silence the intro sounds
// once a skip lands. Under reduced motion nothing is shown and it resolves at
// once.
export function playWake({ stage, bot, target, skipEl, stir, onStart, onGlide, onSkip, signal }) {
return new Promise((resolve) => {
if (matchMedia("(prefers-reduced-motion: reduce)").matches || signal?.aborted) {
resolve({ skipped: false });
return;
}
const timers = [];
let glided = false;
let over = false;
const onGlideEnd = (e) => {
if (e.target === bot && e.propertyName === "transform") end(false);
};
const skip = () => end(true);
// The Skip button's events must reach it: the document handlers below run
// in the capture phase, ahead of the button's own click.
const hitsSkip = (e) => Boolean(skipEl && e.target instanceof Node && skipEl.contains(e.target));
const onSkipClick = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through;
// Escape skips, so the run can be left by keyboard too.
const swallow = (e) => {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
if (e.ctrlKey || e.metaKey || e.altKey) return;
e.preventDefault();
e.stopPropagation();
};
function glide() {
glided = true;
// Measured untransformed, as the sketch's glideToSlot() does: the
// transform-origin is the drawing's top-left, so the move is the gap
// between the two top-left corners and the scale is the width ratio.
// The target's own box, not its bounding rect: the rail's Planny is
// usually tilted mid-flight, and a tilted box measures wider than he
// is. Centred on the rect, which the tilt barely moves.
const from = bot.getBoundingClientRect();
const rect = target.getBoundingClientRect();
const w = target.clientWidth || rect.width;
const h = target.clientHeight || rect.height;
const left = rect.left + (rect.width - w) / 2;
const top = rect.top + (rect.height - h) / 2;
const scale = from.width ? w / from.width : 1;
bot.style.setProperty("--wake-glide", `translate(${left - from.left}px, ${top - from.top}px) scale(${scale})`);
bot.addEventListener("transitionend", onGlideEnd);
stage.classList.add("gliding");
onGlide({ instant: false });
}
function end(skipped) {
if (over) return;
over = true;
for (const t of timers) clearTimeout(t);
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
document.removeEventListener("pointerdown", swallow, true);
document.removeEventListener("keydown", swallow, true);
bot.removeEventListener("transitionend", onGlideEnd);
signal?.removeEventListener("abort", skip);
skipEl?.removeEventListener("click", onSkipClick);
if (skipped) onSkip?.();
stage.hidden = true;
stage.classList.remove("dormant", "stirring", "booting", "gliding");
bot.style.removeProperty("--wake-glide");
if (!glided) onGlide({ instant: true });
resolve({ skipped });
}
// The waking click is the only input the run takes: from here on every
// click and key is swallowed until it ends.
function start(e) {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
e.preventDefault();
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
stage.classList.replace("dormant", "stirring");
document.addEventListener("pointerdown", swallow, true);
document.addEventListener("keydown", swallow, true);
Promise.resolve(stir?.()).then(boot);
}
function boot() {
if (over) return;
stage.classList.replace("stirring", "booting");
onStart?.();
timers.push(setTimeout(glide, GLIDE_AT_MS));
// The glide's transitionend normally ends the run a touch earlier; this
// is the fallback for a transition that never fires (a hidden tab).
timers.push(setTimeout(() => end(false), DONE_AT_MS));
}
document.addEventListener("pointerdown", start, true);
document.addEventListener("keydown", start, true);
skipEl?.addEventListener("click", onSkipClick);
signal?.addEventListener("abort", skip);
stage.hidden = false;
stage.classList.add("dormant");
});
}
@@ -1,226 +0,0 @@
// Plan2Code Web Console - the Quick question chat's shared rules.
//
// Imported by the server (its guards) and by the page (its composer), so the
// two can never disagree about a limit. No DOM access at module scope, and no
// imports but answers.js: the server and `node --test` import this file too.
import { MAX_ATTACHMENTS, STALE_MS, quietLimitMs } from "./answers.js";
// Typed messages per conversation. Approve / Decline and resets never count.
export const CHAT_LIMIT = 10;
export const CHAT_MAX_CHARS = 4000;
// Images and documents together. The old name stays for existing imports.
export const CHAT_MAX_ATTACHMENTS = MAX_ATTACHMENTS;
export const CHAT_MAX_IMAGES = CHAT_MAX_ATTACHMENTS;
export const CHAT_LIMIT_TEXT = "That's 10 questions in this conversation — start a new one to keep going.";
export const CHAT_OFFLINE_TEXT = "No agent available — wait for one to become available (your terminal might be working on a task or waiting a permission approval)";
export const CHAT_LAST_WAIT_TEXT = "That was the last question in this conversation — its answer will land here.";
export const CHAT_WAITING_TEXT = "Plan2Code will answer at its next check-in";
export const CHAT_WORKING_TEXT = "Plan2Code is working on the answer…";
const EMPTY_CHAT = { conversation: 0, messages: [], typed: 0, limit: CHAT_LIMIT, offline: false, pickedUp: 0 };
const chatOf = (frameChat) => ({ ...EMPTY_CHAT, ...(frameChat || {}) });
// Person messages in the frame, each marked with whether an agent reply comes
// after it. The server puts a reply straight after the entry it answers, so a
// reply further down also covers the follow-ups sent before it.
function answeredFlags(messages) {
const flags = new Map();
let replyLater = false;
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m.from === "agent") replyLater = true;
else if (m.kind === "message") flags.set(m.seq, replyLater);
}
return flags;
}
/**
* What the Ask pane draws, in order: the conversation from the frame, then
* any send of this page's the server has not echoed yet.
*/
export function chatView(frameChat, ui = {}) {
const chat = chatOf(frameChat);
const messages = Array.isArray(chat.messages) ? chat.messages : [];
const answered = answeredFlags(messages);
const decisions = new Map(
messages.filter((m) => m.from === "person" && m.kind === "decision").map((m) => [m.re, m.decision])
);
const activity = typeof ui.agentActivity === "string" ? ui.agentActivity.trim() : "";
// The last seq the agent collected: an unanswered message at or below it is
// in the agent's hands, not still waiting for a check-in.
const pickedUp = Number.isInteger(chat.pickedUp) ? chat.pickedUp : 0;
const rows = [];
for (const m of messages) {
if (m.from === "agent") {
rows.push({
kind: "agent",
id: m.id,
md: m.md,
proposal: m.proposal || null,
changed: m.changed || null,
decided: decisions.get(m.id) || null,
});
} else if (m.kind === "decision") {
rows.push({ kind: "decision", decision: m.decision, text: m.text || "", re: m.re });
} else if (m.kind === "message") {
const row = {
kind: "person",
seq: m.seq,
text: m.text,
about: m.about || null,
images: m.images || [],
files: m.files || [],
};
if (!answered.get(m.seq)) {
row.waiting = true;
row.working = m.seq <= pickedUp;
row.waitingText = row.working ? CHAT_WORKING_TEXT : CHAT_WAITING_TEXT;
if (activity) row.activity = activity;
}
rows.push(row);
}
}
// A pending send is echoed once the server has it: by the seq its POST came
// back with, or, while that response is still on its way, by its text
// against a server message no other pending send has claimed.
const serverPerson = messages.filter((m) => m.from === "person" && m.kind === "message");
const serverSeqs = new Set(serverPerson.map((m) => m.seq));
const claimed = new Set((ui.pendingSends || []).filter((p) => p.seq).map((p) => p.seq));
for (const p of ui.pendingSends || []) {
if (p.seq) {
if (serverSeqs.has(p.seq)) continue;
} else {
const echo = serverPerson.find((m) => m.text === p.text && !claimed.has(m.seq));
if (echo) {
claimed.add(echo.seq);
continue;
}
}
rows.push({
kind: "person",
pending: true,
tempId: p.tempId,
text: p.text,
about: p.about || null,
images: p.images || [],
files: p.files || [],
failed: Boolean(p.failed),
});
}
return {
conversation: chat.conversation,
rows,
counterText: `${chat.typed} of ${chat.limit}`,
typed: chat.typed,
limit: chat.limit,
};
}
/**
* Whether the composer can take a message, and what to say when it cannot.
* Offline first, so a finished page never talks about the limit. The limit
* lands once the 10th question is answered; until then the 10th is simply
* waiting, and nothing more can be typed.
*/
export function sendState({ frameChat, gone, pendingSendCount = 0 }) {
const chat = chatOf(frameChat);
if (chat.offline || gone) return { state: "offline", text: CHAT_OFFLINE_TEXT, canType: false };
if (chat.typed + pendingSendCount >= chat.limit) {
const allAnswered = pendingSendCount === 0 && [...answeredFlags(chat.messages || []).values()].every(Boolean);
if (allAnswered) return { state: "limit", text: CHAT_LIMIT_TEXT, canType: false };
return { state: "ok", text: CHAT_LAST_WAIT_TEXT, canType: false };
}
return { state: "ok", text: "", canType: true };
}
const ABOUT_HISTORY = 3;
/**
* What a message is about, attached on purpose. Visiting a question card, doc
* section or spec only records it in `history` (the last 3 places, newest
* first, one entry per place); `about` is set only when the person picks one
* from + Add context, and × or a send clears it.
*
* The tracker is `{ history, about }`; each entry and `about` are
* `{ kind, id, label }` (`about` may be null), in the exact shape POST /chat
* takes. An old `{ about, frozen, dropped }` tracker normalises to an empty
* history.
*/
export function nextAbout(prev, event) {
const p = prev || {};
const state = { history: Array.isArray(p.history) ? [...p.history] : [], about: p.about ?? null };
const visit = (entry) => ({
...state,
history: [entry, ...state.history.filter((h) => h.kind !== entry.kind || h.id !== entry.id)].slice(0, ABOUT_HISTORY),
});
switch (event && event.type) {
case "card":
return visit({ kind: "card", id: String(event.id), label: String(event.label || "") });
case "section":
return visit({ kind: "section", id: `${event.docId}#${event.blockId}`, label: String(event.label || "") });
case "spec":
return visit({ kind: "spec", id: String(event.dir), label: String(event.label || "") });
case "pick":
return event.about ? { ...state, about: event.about } : state;
case "drop":
case "sent":
return { ...state, about: null };
default:
return state;
}
}
// What + Add context lists: the recent places, then "This spec" unless it is
// already one of them.
export function contextOptions(state, spec) {
const options = [...((state && state.history) || [])];
if (spec && spec.dir && !options.some((o) => o.kind === "spec" && o.id === spec.dir)) {
options.push({ kind: "spec", id: spec.dir, label: "This spec" });
}
return options;
}
const newestReply = (frameChat) => {
const messages = chatOf(frameChat).messages || [];
for (let i = messages.length - 1; i >= 0; i--) if (messages[i].from === "agent") return messages[i];
return null;
};
// The Ask tab's dot: a reply landed that the person has not seen.
export function unreadDot({ lastSeenReplyId, frameChat, viewIsAsk }) {
if (viewIsAsk) return false;
const reply = newestReply(frameChat);
return Boolean(reply) && reply.id !== lastSeenReplyId;
}
export function newestReplyId(frameChat) {
const reply = newestReply(frameChat);
return reply ? reply.id : null;
}
// One chime per reply: only the moment the dot appears.
export function shouldChime(prevDot, nextDot) {
return !prevDot && Boolean(nextDot);
}
// The page's own "has drifted away" threshold for an agent that is waiting.
const ADRIFT_MS = 3 * 60 * 1000;
/**
* Whether nobody is there to answer a chat message. A finished session's agent
* is often still listening through its last wait (the review and dashboard
* buttons on the hand-off card live as long as it does), so finish alone does
* not end the chat — going quiet does. Offline once the agent has been silent
* longer than the page would tolerate before calling it stuck (working) or
* adrift (anything else), which is also the only signal left once the server
* is gone.
*/
export function chatOffline({ finish, agent, agentLastSeenMs, now }) {
const silent = now - agentLastSeenMs;
if (agent && agent.status === "working") return silent > quietLimitMs(agent, STALE_MS);
return silent > quietLimitMs(agent, ADRIFT_MS);
}
@@ -1,90 +0,0 @@
// Plan2Code Web Console - the tab icon's status bar.
//
// The favicon follows the status line with a bar along its bottom edge: dashed
// amber while Plan2Code is busy, solid green when it is the person's move,
// solid red when it needs attention, and none (the plain Planny) once the
// session is finished. It reads from the same calls
// renderStatus() already makes for Planny's mood, so the icon and the line
// beside him can never disagree. No DOM access at module scope: `node --test`
// imports this file.
// Planny exactly as public/favicon.svg draws him (a test keeps the two in
// step), minus the <svg> wrapper so the bar can be layered on top.
export const FAVICON_BODY = `<rect x="4" y="4.6" width="24" height="30" rx="5" fill="#fff4ef" stroke="#3b332c" stroke-width="2.2" />
<path d="M16 9.8 L17.41 13.26 L21.14 13.53 L18.28 15.94 L19.17 19.57 L16 17.6 L12.83 19.57 L13.72 15.94 L10.86 13.53 L14.59 13.26 Z" fill="#ae4f2b" />
<path d="M11.6 22.2 Q16 26.4 20.4 22.2" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />`;
// The bar's color per state. `plain` has none.
export const FAVICON_COLORS = Object.freeze({
busy: "#f5a524",
ready: "#22c55e",
attention: "#e5484d",
});
/**
* Which icon a status line calls for. `mood` and `spin` are what renderStatus()
* handed to say(): `spin` marks something really happening at the other end
* right now, so that is busy. A working mood without the spin is the stale
* line ("has not checked in for a few minutes"), which, like adrift and gone,
* needs attention. `point` is the person's move. A finished session is plain
* unless it is visibly busy again (opening the dashboard, starting a review).
*/
export function faviconState({ mood, spin = false, finished = false } = {}) {
if (spin) return "busy";
if (finished) return "plain";
if (mood === "adrift" || mood === "gone" || mood === "work") return "attention";
if (mood === "point") return "ready";
return "plain";
}
/**
* The whole SVG for a state: Planny, plus a bar across the bottom edge, where
* he is cropped anyway. Busy's bar is dashed on a white strip (a progress bar
* mid-run) and the others solid, so busy differs by pattern as well as color:
* amber and green are close to one color for red-green color-blind eyes.
*/
export function faviconSvg(state) {
const color = FAVICON_COLORS[state];
let badge = "";
if (state === "busy") {
badge = `\n <rect x="0" y="27" width="32" height="5" fill="#ffffff" />\n <path d="M1.5 29.5 L30.5 29.5" stroke="${color}" stroke-width="4" stroke-dasharray="4 2.5" />`;
} else if (color) {
badge = `\n <rect x="0" y="27" width="32" height="5" rx="1" fill="${color}" />`;
}
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">\n ${FAVICON_BODY}${badge}\n</svg>\n`;
}
let shown = "plain";
/**
* Point the page's two icon links at `state`'s icon, only when it changed. The
* SVG link takes the variant as a data URL; the PNG link, for browsers that
* pick the bitmap, gets the same variant drawn through a canvas. Plain goes
* back to the served files.
*/
export function setFavicon(state) {
if (state === shown || typeof document === "undefined") return;
shown = state;
const svgLink = document.querySelector('link[rel="icon"][type="image/svg+xml"]');
const pngLink = document.querySelector('link[rel="icon"][type="image/png"]');
if (state === "plain") {
if (svgLink) svgLink.href = "/favicon.svg";
if (pngLink) pngLink.href = "/favicon.png";
return;
}
const url = "data:image/svg+xml," + encodeURIComponent(faviconSvg(state));
if (svgLink) svgLink.href = url;
if (!pngLink) return;
const img = new Image();
img.onload = () => {
// A newer state won the race while this one was loading.
if (shown !== state) return;
try {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 64;
canvas.getContext("2d").drawImage(img, 0, 0, 64, 64);
pngLink.href = canvas.toDataURL("image/png");
} catch {}
};
img.src = url;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

@@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<rect x="4" y="4.6" width="24" height="30" rx="5" fill="#fff4ef" stroke="#3b332c" stroke-width="2.2" />
<path d="M16 9.8 L17.41 13.26 L21.14 13.53 L18.28 15.94 L19.17 19.57 L16 17.6 L12.83 19.57 L13.72 15.94 L10.86 13.53 L14.59 13.26 Z" fill="#ae4f2b" />
<path d="M11.6 22.2 Q16 26.4 20.4 22.2" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />
</svg>

Before

Width:  |  Height:  |  Size: 443 B

@@ -1,67 +0,0 @@
// Plan2Code Web Console - the Help dialog's tab list and rules.
//
// The source of truth for which tabs Help has, in what order, and which one
// opens. The content itself is HTML in <template id="help-content">
// in index.html. No DOM access at module scope and no imports: the page and
// `node --test` both import this file.
const tab = (id, label, diagram) => Object.freeze({ id, label, diagram });
export const HELP_TABS = Object.freeze([
tab("about", "What this page is", true),
tab("around", "Finding your way around", true),
tab("workspace", "Your workspace", false),
tab("planny", "Reading Planny", true),
tab("answering", "Answering questions", false),
tab("sending", "Sending and what happens next", true),
tab("notes", "Notes and attachments", false),
tab("docs", "Documents and printing", false),
tab("dashboard", "The dashboard", true),
tab("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
tab("finishing", "Stopping and finishing", false),
tab("stuck", "When something looks stuck", true),
tab("prefs", "Keyboard and preferences", false),
tab("privacy", "Privacy and where things are saved", false),
]);
// Not labels.js's BUILD_WORKFLOWS: that one leaves out quick-task, which is a
// build as far as the person watching it is concerned.
const HELP_BUILD_WORKFLOWS = new Set(["implement", "implement-review", "quick-task"]);
// Which tab Help opens on, from where the person is. First match wins.
export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow, workspace, meterRed } = {}) {
const v = view || "";
// Finished comes first: a finished session's server is stopped on purpose,
// which also sets `gone`, and that is not something being stuck.
if (finished || v === "end") return "finishing";
if (gone || adrift) return "stuck";
if (workspace) return "workspace";
if (v === "ask") return "ask";
if (v === "subagents") return "subagents";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v.startsWith("doc:")) return "docs";
if (HELP_BUILD_WORKFLOWS.has(workflow)) return "build";
return "about";
}
// The tab index a key moves to, or -1 when the key is not a tab key.
export function helpKeyTarget(key, index, count) {
switch (key) {
case "ArrowDown":
case "ArrowRight":
return (index + 1) % count;
case "ArrowUp":
case "ArrowLeft":
return (index - 1 + count) % count;
case "Home":
return 0;
case "End":
return count - 1;
default:
return -1;
}
}
File diff suppressed because it is too large. Load diff
@@ -1,31 +0,0 @@
// Activity-line wording the page corrects on the way in. Kept out of app.js so
// `node --test` can import it: no DOM access at module scope.
//
// A build numbers its tasks "Task 4.2" after the phase, but a person watching
// the page counts within the phase, so "Task 4.2 of 6" reads as nonsense
// beside a progress bar that says 2 of 6.
// The only workflows whose activity lines get rewritten.
export const BUILD_WORKFLOWS = new Set(["implement", "implement-review"]);
const PHASE_TASK = /^Task (\d+)\.(\d+) of (\d+)/;
export function taskLabel(text) {
if (typeof text !== "string" || !PHASE_TASK.test(text)) return text;
return text.replace(PHASE_TASK, (_, _phase, n, total) => `Task ${n} of ${total}`);
}
// An activity line as the page shows it: rewritten in a build, as sent
// everywhere else (a plan's "Task 2.1" is a real section number).
export function activityLabel(text, workflow) {
return BUILD_WORKFLOWS.has(workflow) ? taskLabel(text) : text;
}
// What a working agent is doing, for a page with nothing asked yet: its
// activity line, or the headline note it posted instead. Either one means the
// skill has started, so the page leaves its starting screen.
export function workingLine(agent, headline, workflow) {
if (!agent || agent.status !== "working") return "";
if (typeof agent.activity === "string" && agent.activity.trim()) return activityLabel(agent.activity.trim(), workflow);
return typeof headline?.note === "string" ? headline.note.trim() : "";
}
@@ -1,46 +0,0 @@
// Plan2Code Web Console - `@name` suggestions in a text box.
//
// Finds the `@partial` the caret sits in, filters the workspace's folder
// names against it, and splices a pick back into the text. The page owns the
// popover; this file owns the rules. No DOM access at module scope and no
// imports: the page and `node --test` both import this file.
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
// by the workspace rules, and a query typed with a capital otherwise matches
// nothing and opens no suggestions at all.
const NAME_CHAR = /[a-z0-9-]/i;
const MAX_MATCHES = 6;
/**
* The mention the caret is in: `{ start, query }`, where `start` is the index
* of the `@`, or null. The `@` must open the text or follow whitespace or
* `(`, so an email address never offers suggestions.
*/
export function mentionAt(text, caret) {
let i = caret;
while (i > 0 && NAME_CHAR.test(text[i - 1])) i--;
const at = i - 1;
if (at < 0 || text[at] !== "@") return null;
if (at > 0 && !/[\s(]/.test(text[at - 1])) return null;
return { start: at, query: text.slice(i, caret) };
}
// Names starting with the query first, then names containing it, in the
// order given, at most six. Case-folded: folder names are lowercase by rule,
// and "@Repo" should still find @repo rather than claim nothing matches.
export function matchNames(names, query) {
const q = String(query || "").toLowerCase();
const fold = (n) => String(n).toLowerCase();
const prefix = names.filter((n) => fold(n).startsWith(q));
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
return [...prefix, ...inside].slice(0, MAX_MATCHES);
}
// The text with `@partial` replaced by `@name `, and the caret after the space.
export function applyMention(text, caret, mention, name) {
const insert = `@${name} `;
return {
text: text.slice(0, mention.start) + insert + text.slice(caret),
caret: mention.start + insert.length,
};
}
@@ -1,306 +0,0 @@
// Plan2Code Web Console - the session meter's weights, count and wording.
//
// The source of truth for how much each piece of work weighs, how the count
// is folded out of ledger.ndjson, and what the pill says at each level. The
// count is never stored: it is always pointsFrom() over the ledger. No DOM
// access at module scope and no imports: the server, console.mjs, the page
// and `node --test` all import this file.
// The one place the weights live (FR-12). Tune here.
export const WEIGHTS = Object.freeze({
"pathfinder-chart": 2,
// Scores 0: a Pathfinder question now counts through its answers (below).
"pathfinder-question": 0,
// Research reads sources and hands its findings back into the context, with
// nobody answering anything, so each research question scores on its own.
"pathfinder-research": 1,
plan: 2,
"revise-plan": 1,
document: 2,
"implement-phase": 2,
"implement-review-phase": 3,
review: 2,
"quick-task": 1,
init: 2,
"init-update": 2,
finalize: 1,
handoff: 0,
});
// Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder,
// implement and implement-review score only through the agent's `run`
// reports; dashboard and handoff never score.
export const LAUNCH_COUNTED = Object.freeze(
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize"])
);
const weightOf = (key) => (Object.prototype.hasOwnProperty.call(WEIGHTS, key) ? WEIGHTS[key] : 0);
// The event names an agent may report in `run`.
export const RUN_EVENTS = new Set(Object.keys(WEIGHTS));
// Built phases weigh what they did: a `run` for one of these may carry
// `tasks`, the tasks the phase completed, and then scores one point per
// TASKS_PER_POINT tasks (rounded up, at least 1), plus the event's
// TASK_BONUS for work every phase does whatever its size (the review). A
// run without `tasks` falls back to WEIGHTS. Tune here.
export const TASKS_PER_POINT = 3;
export const TASK_BONUS = Object.freeze({
"implement-phase": 0,
"implement-review-phase": 1,
});
export const TASK_EVENTS = Object.freeze(new Set(Object.keys(TASK_BONUS)));
// The most tasks one run may report: past this it is a typo, not a phase.
export const MAX_TASKS = 999;
// A build scores while it runs, not only once it is approved: console.mjs
// writes a `progress` ledger entry whenever a build's `headline.cleared`
// rises, and the build's row scores those tasks at TASKS_PER_POINT with no
// bonus. The phase's `run` then takes the row over with its final score, so
// the total only ever climbs. Workflows whose headline counts tasks:
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(["implement", "implement-review"]));
// Implement + Review reviews every phase as a stage of the build. A `review`
// run inside it is that stage, so it scores the phase's TASK_BONUS when it
// starts, and the phase's own run leaves the bonus out after it.
const BUILT_IN_REVIEW = Object.freeze({ "implement-review": "implement-review-phase" });
/**
* The ledger entry a build's progress post stands for, or null when it adds
* nothing: not a task-counting workflow, no whole `cleared`, or no more tasks
* than this build already has. `seg` is how many phases this skill run has
* finished, so a second phase in the same run starts its own count, but only
* once its headline is back at 0: until then a `cleared` is the finished
* phase's, posted again, and opening a build on it would count it twice.
*/
export function progressEntry(entries, launch, workflow, cleared) {
if (!PROGRESS_WORKFLOWS.has(workflow)) return null;
if (cleared !== 0 && !isTaskCount(cleared)) return null;
const list = Array.isArray(entries) ? entries : [];
const seg = list.filter((e) => e && e.kind === "run" && TASK_EVENTS.has(e.event) && launchOf(e.id) === launch).length;
const build = `${launch}:b${seg}`;
const mine = list.filter((e) => e && e.kind === "progress" && e.build === build);
const entry = (tasks) => ({ kind: "progress", id: `${build}:${tasks}`, build, workflow, tasks });
if (cleared === 0) return seg > 0 && !mine.length ? entry(0) : null;
if (seg > 0 && !mine.length) return null;
const most = mine.reduce((n, e) => Math.max(n, e.tasks), 0);
return cleared > most ? entry(cleared) : null;
}
/** A valid `run.tasks`: a whole number from 1 to MAX_TASKS. */
export function isTaskCount(tasks) {
return Number.isInteger(tasks) && tasks >= 1 && tasks <= MAX_TASKS;
}
/**
* What one `run` scores, from its event and (for a built phase) its tasks.
* `bonus: false` leaves the review bonus out, for a phase whose review
* already scored.
*/
export function runPoints(event, tasks, { bonus = true } = {}) {
if (TASK_EVENTS.has(event) && isTaskCount(tasks)) {
return Math.ceil(tasks / TASKS_PER_POINT) + (bonus ? TASK_BONUS[event] : 0);
}
if (TASK_EVENTS.has(event) && !bonus) return weightOf(event) - TASK_BONUS[event];
return weightOf(event);
}
// Back-and-forth weighs what it took: every answer the person sends from a
// card is an `answer` ledger entry (console.mjs writes one per answered item
// when the agent collects a send), and each skill run scores one point per
// ANSWERS_PER_POINT answers, rounded down. Tune here.
export const ANSWERS_PER_POINT = 2;
// The skill names the answers row uses ("7 answers in Plan").
const WORKFLOW_NAMES = Object.freeze({
dashboard: "the dashboard",
pathfinder: "Pathfinder",
plan: "Plan",
"revise-plan": "Revise plan",
document: "Document",
implement: "Implement",
"implement-review": "Implement + Review",
review: "Review",
"quick-task": "Quick task",
init: "Init",
"init-update": "Init update",
finalize: "Finalize",
handoff: "Handoff",
});
// The skill run an entry belongs to, from its ledger id ("L3:..." -> "L3").
const launchOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(0, id.indexOf(":")) : "L0");
// What each scoring event is called in the meter's list of contributions.
const LAUNCH_LABELS = Object.freeze({
plan: "Plan started",
"revise-plan": "Revise plan started",
document: "Document started",
review: "Review started",
"quick-task": "Quick task started",
init: "Init started",
"init-update": "Init update started",
finalize: "Finalize started",
});
const RUN_LABELS = Object.freeze({
"pathfinder-chart": "Pathfinder map written",
"pathfinder-question": "Pathfinder question settled",
"pathfinder-research": "Pathfinder research done",
plan: "Plan drafted",
"revise-plan": "Plan revised",
document: "Spec documented",
"implement-phase": "Implement phase built",
"implement-review-phase": "Implement + Review phase built",
review: "Code review run",
"quick-task": "Quick task built",
init: "Init run",
"init-update": "Init update run",
finalize: "Finalize run",
handoff: "Handoff written",
});
// The unit a run names, from its ledger id ("L3:phase-2" -> "phase-2").
const unitOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(id.indexOf(":") + 1) : "");
/**
* What the count is made of: one { label, points } per ledger entry that
* scored, in order, and one row per skill run for its answers, where its
* first answer came. An id seen before is skipped, so a repeated `post` never
* counts twice. Entries that weigh nothing are left out.
*/
export function breakdownFrom(entries) {
const seen = new Set();
const rows = [];
const answers = new Map(); // launch id -> { row, count, workflow }
const builds = new Map(); // launch id -> the row of the build in progress
const reviewed = new Set(); // launch ids whose built-in review has scored
for (const entry of Array.isArray(entries) ? entries : []) {
if (!entry || typeof entry !== "object") continue;
if (entry.id !== undefined) {
if (seen.has(entry.id)) continue;
seen.add(entry.id);
}
if (entry.kind === "answer") {
const launch = launchOf(entry.id);
let tally = answers.get(launch);
if (!tally) {
tally = { row: { label: "", points: 0 }, count: 0, workflow: entry.workflow };
answers.set(launch, tally);
rows.push(tally.row);
}
tally.count += 1;
continue;
}
if (entry.kind === "progress") {
if (!isTaskCount(entry.tasks)) continue;
const launch = launchOf(entry.id);
let row = builds.get(launch);
if (!row || row.build !== entry.build) {
row = { label: "", points: 0, build: entry.build, tasks: 0 };
builds.set(launch, row);
rows.push(row);
}
if (entry.tasks > row.tasks) {
row.tasks = entry.tasks;
row.points = Math.ceil(entry.tasks / TASKS_PER_POINT);
const where = WORKFLOW_NAMES[entry.workflow] || "Build";
row.label = `${where}: ${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"} built so far`;
}
continue;
}
let points = 0;
let label = "";
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
points = weightOf(entry.workflow);
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
} else if (entry.kind === "run") {
const launch = launchOf(entry.id);
const builtIn = BUILT_IN_REVIEW[entry.workflow];
if (entry.event === "review" && builtIn) {
// The review stage of Implement + Review: it scores the bonus its
// phase would otherwise carry, once per skill run.
if (reviewed.has(launch)) continue;
reviewed.add(launch);
points = TASK_BONUS[builtIn];
label = `${WORKFLOW_NAMES[entry.workflow]}: code review run`;
} else {
const bonus = !(TASK_EVENTS.has(entry.event) && reviewed.has(launch));
points = runPoints(entry.event, entry.tasks, { bonus });
const unit = unitOf(entry.id);
const counted = TASK_EVENTS.has(entry.event) && isTaskCount(entry.tasks);
const size = counted ? ` (${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"})` : "";
label = (RUN_LABELS[entry.event] || entry.event) + (unit && unit !== entry.event ? `: ${unit}` : "") + size;
}
// A finished phase takes over its build's progress row, in place.
if (TASK_EVENTS.has(entry.event) && builds.has(launch)) {
const row = builds.get(launch);
builds.delete(launch);
row.label = label;
row.points = Math.max(points, row.points);
continue;
}
}
if (points > 0) rows.push({ label, points });
}
for (const { row, count, workflow } of answers.values()) {
row.points = Math.floor(count / ANSWERS_PER_POINT);
const where = WORKFLOW_NAMES[workflow] ? ` in ${WORKFLOW_NAMES[workflow]}` : "";
row.label = `${count} ${count === 1 ? "answer" : "answers"}${where}`;
}
return rows.filter((row) => row.points > 0).map(({ label, points }) => ({ label, points }));
}
/** The session's points, folded from ledger entries in order. */
export function pointsFrom(entries) {
return breakdownFrom(entries).reduce((sum, row) => sum + row.points, 0);
}
export const YELLOW_AT = 5;
export const RED_AT = 10;
export const RING_FULL = 15;
export function levelFor(points) {
if (points < YELLOW_AT) return "green";
if (points < RED_AT) return "yellow";
return "red";
}
// How much of the ring is filled: full at RING_FULL, never below empty.
export function ringFraction(points) {
return Math.max(0, Math.min(points, RING_FULL)) / RING_FULL;
}
export const WORDS = Object.freeze({
green: "Session: fresh",
yellow: "Session: getting long",
red: "Session: time for a fresh start",
});
export function tooltipFor(points) {
const count = `${points} ${points === 1 ? "point" : "points"}`;
switch (levelFor(points)) {
case "green":
return `This session is fresh (${count}).`;
case "yellow":
return `This session is getting long (${count}). A fresh one will soon be sharper.`;
default:
return `This session has done a lot (${count}). The agent may start missing things.`;
}
}
export const RED_BANNER =
"This console session has done a lot. Starting a new console session will keep the agent sharp.";
// Everything the pill draws, from the ledger alone.
export function meterView(entries) {
const points = pointsFrom(entries);
const level = levelFor(points);
return {
points,
level,
fraction: ringFraction(points),
words: WORDS[level],
tooltip: tooltipFor(points),
items: breakdownFrom(entries),
};
}
@@ -1,3 +0,0 @@
{
"type": "module"
}
@@ -1,238 +0,0 @@
// The highlight colors, as data. Kept out of app.js for one reason: app.js
// cannot be imported outside a browser, and thirty-two colors each with four
// shades in two themes is far too many to trust to eyeballing. The test suite
// imports this and checks every one.
//
// The palette has three colors that MEAN something -- green settled, amber
// waiting, red careful. The reds, golds and greens here are offered anyway,
// because people asked for them; the help text in the dialog says what they
// share a hue with, and the choice is theirs.
//
// Each accent is four values, not one, because one color cannot do four jobs:
// fill the highlight itself: filled buttons, the marker on the open step
// soft a tint faint enough to sit behind body text
// ink what is legible ON the fill. Dark mode's accents are light shades,
// where a white label falls to about 2:1; they take a near-black.
// line the secondary: borders, badge edges, the dashed drop target.
//
// Every pair clears 4.5:1 for ink on fill and for fill on soft (the fill is
// also badge text on the soft tint). Everything after the first five was
// found by stepping lightness until both held, not picked by eye.
//
// Order is the order of the picker: round the wheel, then the greys. Sixteen
// a row, so the warm half and the greens sit on the first, the blues, purples,
// pinks and greys on the second.
export const ACCENTS = {
// name fill soft ink line
crimson: {
name: "Crimson",
light: ["#cd1d41", "#fbe9ed", "#ffffff", "#dcaab4"],
dark: ["#e75874", "#321b1f", "#140b0d", "#743e49"],
},
scarlet: {
name: "Scarlet",
light: ["#cf2317", "#fbebe9", "#ffffff", "#ddaaa7"],
dark: ["#eb594e", "#321c1b", "#140b0b", "#74403c"],
},
coral: {
name: "Coral",
light: ["#c83510", "#fbede9", "#ffffff", "#dcaca0"],
dark: ["#ef5b37", "#321f1b", "#140d0b", "#6f4237"],
},
rust: {
name: "Rust",
light: ["#ae4f2b", "#fbeee7", "#ffffff", "#dd9b7e"],
dark: ["#e8825a", "#34211a", "#1a120e", "#8a4f36"],
},
tangerine: {
name: "Tangerine",
light: ["#b15209", "#fbf1e9", "#ffffff", "#d9af8f"],
dark: ["#f2700d", "#32251b", "#140f0b", "#664830"],
},
copper: {
name: "Copper",
light: ["#a2592f", "#f9f0eb", "#ffffff", "#cdb2a2"],
dark: ["#cb7a4b", "#32231b", "#140e0b", "#5f493d"],
},
clay: {
name: "Clay",
light: ["#8d644c", "#f5f2f0", "#ffffff", "#bfafa6"],
dark: ["#ba957f", "#2b2521", "#17100c", "#62544b"],
},
marigold: {
name: "Marigold",
light: ["#9a6406", "#fbf5e9", "#ffffff", "#d3b279"],
dark: ["#f59f0a", "#32291b", "#14110b", "#5e4c2c"],
},
gold: {
name: "Gold",
light: ["#896b09", "#fbf7e9", "#ffffff", "#ccb66d"],
dark: ["#f0bb0f", "#322c1b", "#14120b", "#584d2a"],
},
mustard: {
name: "Mustard",
light: ["#806f1b", "#fbf8ea", "#ffffff", "#c3b881"],
dark: ["#d2b72d", "#322e1b", "#14120b", "#544e31"],
},
olive: {
name: "Olive",
light: ["#72742c", "#f8f8ed", "#ffffff", "#b8ba8c"],
dark: ["#b5b946", "#31321b", "#14140b", "#4f5037"],
},
lime: {
name: "Lime",
light: ["#577a1a", "#f4fbea", "#ffffff", "#a6c07a"],
dark: ["#96d22d", "#29321b", "#11140b", "#465230"],
},
moss: {
name: "Moss",
light: ["#577740", "#f2f6ee", "#ffffff", "#acbca1"],
dark: ["#79a659", "#24321b", "#0f140b", "#475140"],
},
emerald: {
name: "Emerald",
light: ["#207e47", "#ebfaf1", "#ffffff", "#8ac4a2"],
dark: ["#33cc73", "#1b3224", "#0b140f", "#345542"],
},
jade: {
name: "Jade",
light: ["#297c61", "#ecf9f4", "#ffffff", "#92c1b1"],
dark: ["#40bf95", "#1b322a", "#0b1411", "#38544b"],
},
teal: {
name: "Teal",
light: ["#0f766e", "#e2f1ef", "#ffffff", "#6fb3aa"],
dark: ["#5ecfc0", "#14302c", "#0b1a18", "#3a7d74"],
},
cyan: {
name: "Cyan",
light: ["#0f798a", "#ebf7f9", "#ffffff", "#75bec9"],
dark: ["#19cae6", "#183034", "#0c1617", "#305f66"],
},
sky: {
name: "Sky",
light: ["#0e74a7", "#ebf5fa", "#ffffff", "#85b9d3"],
dark: ["#21a9ed", "#182b35", "#0c1417", "#325c71"],
},
ocean: {
name: "Ocean",
light: ["#206cc3", "#ecf2f9", "#ffffff", "#9ab4d3"],
dark: ["#619fe5", "#1a2533", "#0c1117", "#3d5978"],
},
navy: {
name: "Navy",
light: ["#24396b", "#eef0f7", "#ffffff", "#a7b3cd"],
dark: ["#819ad5", "#1e232f", "#0c1017", "#4a5775"],
},
cobalt: {
name: "Cobalt",
light: ["#405ce7", "#ebeef9", "#ffffff", "#a8b0dc"],
dark: ["#7b8fef", "#191d34", "#0c0e17", "#465392"],
},
indigo: {
name: "Indigo",
light: ["#4f46e5", "#ecebfb", "#ffffff", "#9b95ef"],
dark: ["#a5a0ff", "#1e1d3a", "#121129", "#5f5ba8"],
},
violet: {
name: "Violet",
light: ["#7f4dd5", "#f1edf8", "#ffffff", "#bbabd6"],
dark: ["#a785e2", "#231c31", "#100c17", "#624c87"],
},
lilac: {
name: "Lilac",
light: ["#8b51b8", "#f3eff6", "#ffffff", "#beaccb"],
dark: ["#b189cf", "#271f2d", "#130c17", "#634f73"],
},
orchid: {
name: "Orchid",
light: ["#a141b9", "#f5eef7", "#ffffff", "#c5a8cc"],
dark: ["#c281d3", "#2b1e2f", "#150c17", "#6c4b74"],
},
magenta: {
name: "Magenta",
light: ["#b82eaa", "#f8edf7", "#ffffff", "#d1a3cc"],
dark: ["#dc72d1", "#311c2f", "#170c16", "#784573"],
},
plum: {
name: "Plum",
light: ["#8a3b6b", "#f8eaf2", "#ffffff", "#c88cb0"],
dark: ["#e08ab8", "#331a29", "#1d1017", "#8a5570"],
},
rose: {
name: "Rose",
light: ["#c42e6a", "#f8edf1", "#ffffff", "#d3a6b8"],
dark: ["#df77a0", "#311c24", "#170c11", "#7c465b"],
},
steel: {
name: "Steel",
light: ["#50737c", "#f0f3f4", "#ffffff", "#a5b5b8"],
dark: ["#7fa4ad", "#22292a", "#0c1517", "#4c595c"],
},
slate: {
name: "Slate",
light: ["#5b6e88", "#f0f2f4", "#ffffff", "#acb3bc"],
dark: ["#8e9eb4", "#23262a", "#0c1117", "#515861"],
},
mauve: {
name: "Mauve",
light: ["#816281", "#f4f1f4", "#ffffff", "#bbafbb"],
dark: ["#ae93ae", "#292329", "#170c17", "#5f545f"],
},
graphite: {
name: "Graphite",
light: ["#4a4640", "#eeedea", "#ffffff", "#a8a196"],
dark: ["#cfc7bb", "#2b2a28", "#161513", "#7a7369"],
},
};
export const DEFAULT_ACCENT = "ocean";
// The card-width presets. Here for the same reason the accents are: the page
// validates a saved `looks.width` with cardWidth(), and the server uses it to
// paint the first-load `data-width` attribute before app.js runs. One list,
// two readers, no drift.
export const CARD_WIDTHS = {
narrow: { label: "Narrow", px: 720 },
comfortable: { label: "Comfortable", px: 880 },
wide: { label: "Wide", px: 1080 },
};
export const DEFAULT_CARD_WIDTH = "comfortable";
export function cardWidth(value) {
return typeof value === "string" && Object.hasOwn(CARD_WIDTHS, value) ? value : DEFAULT_CARD_WIDTH;
}
// Every moment the page makes a noise, each switchable on its own in User
// Preferences (the `data-sound` boxes in index.html). Several share a file;
// the event, not the file, is what a person turns off. `rank` settles which
// wins when two ask at once (see the sounds section in app.js). Stored flat as
// `soundQuestion` and so on, because looks.json only holds flat values.
export const SOUND_EVENTS = {
startSkill: { file: "start-skill", rank: 5 },
bootup: { file: "bootup", rank: 4 },
sessionStart: { file: "start-stop", rank: 3 },
sessionEnd: { file: "start-stop", rank: 3 },
question: { file: "next", rank: 2 },
skillReady: { file: "next", rank: 2 },
chatReply: { file: "next", rank: 2 },
newTab: { file: "insert", rank: 1 },
snore: { file: "sleeping", rank: 0 },
};
export const soundKey = (event) => "sound" + event[0].toUpperCase() + event.slice(1);
// The per-event switches out of a saved looks object: each one as saved when
// it is a boolean, on otherwise. A looks.json from before the switches has
// none of these keys, so it keeps every sound.
export function soundPrefs(saved) {
const source = saved && typeof saved === "object" ? saved : {};
return Object.fromEntries(
Object.keys(SOUND_EVENTS).map((event) => {
const value = source[soundKey(event)];
return [soundKey(event), typeof value === "boolean" ? value : true];
})
);
}
@@ -1,308 +0,0 @@
// Markdown to DOM, safely.
//
// The rule this file exists to enforce: NO HTML STRING IS EVER PRODUCED.
// We take marked's token tree and build nodes with createElement/textContent.
//
// Why that matters more than it looks: this page is same-origin with a server
// that reads and writes the user's files and holds the session cookie. Script
// running here could post arbitrary answers back to the agent, which would then
// act 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 hostile.
//
// Building nodes rather than parsing a string makes injection structurally
// impossible instead of filtered, so there is nothing for a sanitiser bypass to
// bypass. `html` tokens render as visible text, on purpose.
import { marked } from "./vendor/marked.esm.js";
// A bare `/` path stays on this origin; `//host` (and `/\host`, which browsers
// read the same way) is protocol-relative and would not, so it is refused.
const SAFE_PROTOCOL = /^(https?:|mailto:|#|\/(?![/\\]))/i;
function safeHref(href) {
if (!href) return null;
const trimmed = String(href).trim();
// Blocks javascript: and data: hrefs before they can reach the DOM, and a
// protocol-relative `//host` (or `/\host`), which leaves the page for another site.
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
}
function el(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text != null) node.textContent = text;
return node;
}
function inlineInto(parent, tokens) {
for (const t of tokens || []) {
switch (t.type) {
case "text":
// Nested inline tokens (a link inside emphasis, say) arrive here.
if (t.tokens && t.tokens.length) inlineInto(parent, t.tokens);
else parent.appendChild(document.createTextNode(t.text ?? t.raw ?? ""));
break;
case "escape":
parent.appendChild(document.createTextNode(t.text));
break;
case "strong": {
const n = el("strong");
inlineInto(n, t.tokens);
parent.appendChild(n);
break;
}
case "em": {
const n = el("em");
inlineInto(n, t.tokens);
parent.appendChild(n);
break;
}
case "del": {
const n = el("s");
inlineInto(n, t.tokens);
parent.appendChild(n);
break;
}
case "codespan":
parent.appendChild(el("code", "md-code", t.text));
break;
case "br":
parent.appendChild(document.createElement("br"));
break;
case "link": {
const href = safeHref(t.href);
if (!href) {
inlineInto(parent, t.tokens);
break;
}
const a = el("a");
a.href = href;
a.rel = "noopener noreferrer";
if (/^https?:/i.test(href)) a.target = "_blank";
if (t.title) a.title = t.title;
inlineInto(a, t.tokens);
parent.appendChild(a);
break;
}
case "image": {
const src = safeHref(t.href);
if (!src) {
parent.appendChild(document.createTextNode(t.text || ""));
break;
}
const img = el("img", "md-img");
img.src = src;
img.alt = t.text || "";
parent.appendChild(img);
break;
}
default:
// Includes `html`: rendered as literal text, never parsed.
parent.appendChild(document.createTextNode(t.raw ?? t.text ?? ""));
}
}
}
// What a fenced code block offers beside Copy, from its first non-empty line:
// `'run'` gets a Run it button (git commands — the one kind a person keeps
// copying into Ask by hand), `'hint'` a muted note that pasting it into Ask
// may get the agent to run it, and `null` nothing extra. A leading `/` is a
// skill command for a new conversation, never a terminal command, so it gets
// neither.
const COMMAND_WORDS =
/^(git|node|npm|npx|pnpm|yarn|bun|deno|python3?|pip3?|brew|curl|wget|docker|kubectl|terraform|make|cmake|cargo|go|java|mvn|gradle|gh|aws|az|gcloud|jq|ssh|scp|rsync|chmod|chown|mkdir|cp|mv|rm|ls|cd|cat|echo|export|source|bash|sh|zsh|fish|pwsh|powershell|cmd|systemctl|service|apt|apt-get|dnf|yum|pacman|tar|unzip|zip)\b/i;
export function runHint(text) {
const firstLine = (text || "")
.split("\n")
.map((line) => line.trim())
.find((line) => line.length > 0);
if (!firstLine || firstLine.startsWith("/")) return null;
if (/^git(\s|$)/.test(firstLine)) return "run";
if (firstLine.startsWith("#!")) return "hint";
return COMMAND_WORDS.test(firstLine) ? "hint" : null;
}
function blockInto(parent, tokens) {
for (const t of tokens || []) {
switch (t.type) {
case "space":
break;
case "heading": {
const level = Math.min(6, Math.max(2, (t.depth || 1) + 1)); // never an h1: the page owns that
const h = el("h" + level, "md-h");
inlineInto(h, t.tokens);
parent.appendChild(h);
break;
}
case "paragraph": {
const p = el("p", "md-p");
inlineInto(p, t.tokens);
parent.appendChild(p);
break;
}
case "text": {
const p = el("p", "md-p");
if (t.tokens) inlineInto(p, t.tokens);
else p.textContent = t.text || "";
parent.appendChild(p);
break;
}
case "blockquote": {
const q = el("blockquote", "md-quote");
blockInto(q, t.tokens);
parent.appendChild(q);
break;
}
case "code": {
const wrap = el("div", "md-pre-wrap");
const pre = el("pre", "md-pre");
// textContent, so a fenced block containing markup is inert.
pre.appendChild(el("code", null, t.text));
wrap.appendChild(copyButton(t.text, "md-copy"));
const hint = runHint(t.text);
if (hint === "run") {
const run = el("button", "md-run", "Run it");
run.type = "button";
wrap.appendChild(run);
}
wrap.appendChild(pre);
if (hint === "hint") {
wrap.appendChild(el("p", "md-run-hint", "The agent may be able to run this — paste it into the Ask tab"));
}
parent.appendChild(wrap);
break;
}
case "hr":
parent.appendChild(el("hr", "md-hr"));
break;
case "list": {
const list = el(t.ordered ? "ol" : "ul", "md-list");
if (t.ordered && typeof t.start === "number" && t.start !== 1) list.start = t.start;
for (const item of t.items || []) {
const li = el("li", "md-li" + (item.task ? " is-task" : ""));
if (item.task) {
const box = el("span", "md-task" + (item.checked ? " is-done" : ""));
box.textContent = item.checked ? "✓" : "·";
box.setAttribute("aria-label", item.checked ? "done" : "not done");
li.appendChild(box);
}
blockInto(li, item.tokens);
list.appendChild(li);
}
parent.appendChild(list);
break;
}
case "table": {
const scroll = el("div", "md-table-wrap");
const table = el("table", "md-table");
const thead = el("thead");
const hr = el("tr");
(t.header || []).forEach((cell, i) => {
const th = el("th");
if (t.align && t.align[i]) th.style.textAlign = t.align[i];
inlineInto(th, cell.tokens);
hr.appendChild(th);
});
thead.appendChild(hr);
table.appendChild(thead);
const tbody = el("tbody");
for (const row of t.rows || []) {
const tr = el("tr");
row.forEach((cell, i) => {
const td = el("td");
if (t.align && t.align[i]) td.style.textAlign = t.align[i];
inlineInto(td, cell.tokens);
tr.appendChild(td);
});
tbody.appendChild(tr);
}
table.appendChild(tbody);
scroll.appendChild(table);
parent.appendChild(scroll);
break;
}
default: {
// Unknown or raw html block: show the source, do not interpret it.
const p = el("p", "md-p");
p.textContent = t.raw ?? t.text ?? "";
parent.appendChild(p);
}
}
}
}
/** Render markdown into a fresh element. Returns the element. */
export function md(source, className = "md") {
const host = el("div", className);
if (!source) return host;
let tokens;
try {
tokens = marked.lexer(String(source));
} catch {
host.appendChild(el("p", "md-p", String(source)));
return host;
}
blockInto(host, tokens);
return host;
}
/** Render markdown into an existing element, replacing its contents. */
export function mdInto(node, source) {
node.replaceChildren();
const rendered = md(source);
while (rendered.firstChild) node.appendChild(rendered.firstChild);
return node;
}
// The page's only clipboard action, in one place. writeText can be refused --
// a browser that has not granted the permission, a page that was not focused
// when the click landed -- and a button that silently does nothing is worse
// than one that says what to press instead.
//
// It lives here rather than in app.js because app.js imports this file and not
// the other way round, and a fenced code block needed it first.
//
// copyText() is the action itself: `button` reads "Copied" for a moment, then
// `label` again. `label` may be a function, read when the moment is up, for a
// button whose text can change in the meantime. `onRefused` is what the caller
// offers instead when the browser says no -- usually a selection to press
// Ctrl+C on.
async function copyText(text, button, label, onRefused) {
try {
await navigator.clipboard.writeText(text);
button.textContent = "Copied";
setTimeout(() => (button.textContent = typeof label === "function" ? label() : label), 1400);
} catch {
onRefused();
}
}
function selectContents(node) {
try {
const range = document.createRange();
range.selectNodeContents(node);
const sel = getSelection();
sel.removeAllRanges();
sel.addRange(range);
} catch {}
}
function copyButton(text, className, source) {
const b = el("button", className || "btn small", "Copy");
b.type = "button";
b.addEventListener("click", () =>
copyText(text, b, "Copy", () => {
// "Press Ctrl+C" on its own asks them to copy a selection that does not
// exist. Select the text for them, so the instruction is one they can
// actually follow.
const node = source || b.parentNode.querySelector("pre, code");
if (node) selectContents(node);
b.textContent = "Press Ctrl+C";
})
);
return b;
}
export { el, copyButton, copyText, selectContents };
@@ -1,440 +0,0 @@
// Plan2Code Web Console - roles, starter templates and Ask starter questions.
//
// The source of truth for the Role list in User Preferences, the starter
// templates on the first "What's the idea?" card of Pathfinder, Plan and Quick
// Task, the order each role sees them in, and the starter questions an empty
// Ask conversation offers. No DOM access at module scope and no imports: the
// page and `node --test` both import this file.
const role = (id, label) => Object.freeze({ id, label });
export const ROLES = Object.freeze([
role("engineer", "Engineer"),
role("pm", "Product lead / PM"),
role("architect", "Architect / tech lead"),
role("designer", "Designer (UX)"),
role("qa", "QA / test engineer"),
role("em", "Engineering manager"),
]);
export const ROLE_NOT_SET = "none";
export const ROLE_NOT_SET_LABEL = "Not set / none of these";
export const TEMPLATE_WORKFLOWS = Object.freeze(["pathfinder", "plan", "quick-task"]);
const ROLE_IDS = new Set(ROLES.map((r) => r.id));
// A known role id, or "none" for anything else (missing, unknown, not a string).
export function normalizeRole(value) {
return ROLE_IDS.has(value) ? value : ROLE_NOT_SET;
}
// The dashboard nudge shows until looks.json carries a role of any value:
// choosing Not set, or pressing Not now, ends it just as a real role does.
export function needsRoleNudge(looks) {
if (!looks || typeof looks !== "object") return true;
return !Object.hasOwn(looks, "role");
}
// The wording was revised in v2.5.1 (Markdown sections); a change is a page change.
const template = (id, label, lines) => Object.freeze({ id, label, text: lines.join("\n") });
export const TEMPLATES = Object.freeze({
"engineering-spec": template("engineering-spec", "Engineering spec", [
"## Engineering spec",
"[the feature or change, in a sentence]",
"",
"## Who reads it",
"The engineers who will build and review it.",
"",
"## What it should pin down",
"The behaviour, the parts of the code it touches, the interfaces between them, the simpler options we're turning down, and how we'll know it works.",
"",
"## Out of scope",
"[what this deliberately won't do]",
"",
"## What I already know",
"[constraints, links, earlier attempts]",
]),
"product-requirements": template("product-requirements", "Product requirements", [
"## Product requirements",
"[the feature, in a sentence]",
"",
"## Who it's for",
"[the users], and the product, design and engineering people deciding on it.",
"",
"## What it should pin down",
"The problem, who has it, the evidence it's real, and how we'll measure success.",
"",
"## Not doing",
"[what this release leaves out]",
"",
"## What I already know",
"[customer asks, data, deadlines]",
]),
"design-decision": template("design-decision", "Design decision", [
"## Design decision",
"[the choice we're facing, in a sentence]",
"",
"## Who it's for",
"The engineers and architects who will live with it.",
"",
"## What it should pin down",
"The options, the trade-offs of each, the one we pick and why, and what it costs us later.",
"",
"## Constraints",
"[performance, compatibility, deadlines, team skills]",
]),
"test-strategy": template("test-strategy", "Test strategy", [
"## Test strategy",
"[the feature or area]",
"",
"## Who reads it",
"QA and the engineers writing the tests.",
"",
"## What it should pin down",
'What\'s riskiest, meaning what costs most if it breaks, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
"",
"## What exists today",
"[current tests, known gaps]",
]),
"scoping-rollout": template("scoping-rollout", "Scoping & rollout", [
"## Scoping and rollout",
"[the feature or project]",
"",
"## Who reads it",
"The engineering manager, the product lead and the team.",
"",
"## What it should pin down",
"What's in the first release and what waits, the build order, risks to the timeline, how it reaches users (flags, stages, who sees it first), and how we roll it back.",
"",
"## Constraints",
"[dates, people, dependencies]",
]),
"brainstorm-notes": template("brainstorm-notes", "Brainstorm → curated notes", [
"## Brainstorm to curated notes",
"[the topic or rough idea]",
"",
"## Who reads the notes",
"[the team or people this goes to]",
"",
"## What I want out of it",
"The ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
"",
"## Starting thoughts",
"[anything already on your mind]",
]),
"bug-investigation": template("bug-investigation", "Bug investigation", [
"## Bug investigation",
"[what's going wrong, in a sentence]",
"",
"## Steps to reproduce",
"1. [first step]",
"2. [next step]",
"",
"## Expected",
"[what should happen]",
"",
"## Actual",
"[what happens instead]",
"",
"## How often",
"[every time, sometimes, once]",
"",
"## Error or logs",
"[paste the exact text]",
"",
"## Where and since when",
"[environment, version, first seen]",
]),
"small-change": template("small-change", "Small change", [
"## Small change",
"[what to change, in a sentence]",
"",
"## Where",
"[the file, screen or command, if you know it]",
"",
"## Leave alone",
"[anything that must not change]",
"",
"## Done when",
"[the command to run or the thing to check]",
]),
"copy-tweak": template("copy-tweak", "Copy / content tweak", [
"## Copy or content tweak",
"[the screen, message, email or doc]",
"",
"## Current text",
"[paste it]",
"",
"## New text",
"[paste it, or describe the tone you want]",
"",
"## Who reads it",
"[the people who see it]",
]),
"ui-polish": template("ui-polish", "UI polish", [
"## UI polish",
"[the screen or component]",
"",
"## What looks or feels off",
"[spacing, alignment, colour, states, small screens]",
"",
"## What good looks like",
"[a reference, screenshot or description]",
"",
"## Leave alone",
"[anything that must not move]",
]),
"visual-prototype": template("visual-prototype", "Visual prototype", [
"## Visual prototype",
"[the screen or component to mock up]",
"",
"## What to show",
"[the states or flows to click through]",
"",
"## What I want to learn",
"[the question it should answer]",
"",
"## Where it lives",
"A prototypes/ folder [or its own branch], never wired into the real code.",
]),
"add-a-test": template("add-a-test", "Add a test", [
"## Add a test",
"[the function, behaviour or bug]",
"",
"## Cases to cover",
"- [the normal case]",
"- [the edge cases]",
"- [the failure or bug it guards against]",
"",
"## Where tests live",
"[the test file or folder, if you know it]",
]),
"record-decision": template("record-decision", "Record a decision", [
"## Record a decision",
"[the decision we've already made, in a sentence]",
"",
"## Why",
"[what forced the choice, and the options we turned down]",
"",
"## What it commits us to",
"[the consequences]",
"",
"## Save it in",
"docs/adr/ [or wherever this repo keeps them]",
]),
refactor: template("refactor", "Refactor", [
"## Refactor",
"[what to restructure, in a sentence]",
"",
"## Why now",
"[what the current shape makes hard]",
"",
"## Behaviour that must not change",
"[the public API, outputs or tests that must stay the same]",
"",
"## Done when",
"[the tests that must still pass, and the shape it ends in]",
]),
"performance-problem": template("performance-problem", "Performance problem", [
"## Performance problem",
"[what's slow, in a sentence]",
"",
"## How it's measured today",
"[the number, and how you got it]",
"",
"## Target",
"[the number that counts as fixed]",
"",
"## Where",
"[the endpoint, page, query or job]",
]),
"dependency-upgrade": template("dependency-upgrade", "Dependency upgrade", [
"## Dependency upgrade",
"[the package, from version to version]",
"",
"## Why",
"[security fix, a feature we need, end of support]",
"",
"## Known breaking changes",
'[release notes link, or "not checked yet"]',
"",
"## Done when",
"[the build, tests or checks that must pass]",
]),
spike: template("spike", "Spike", [
"## Spike",
"[the question to answer, in a sentence]",
"",
"## Why it matters",
"[the decision waiting on the answer]",
"",
"## Time box",
"[how long before we stop and decide anyway]",
"",
"## Answered when",
"[the evidence that would settle it]",
]),
integration: template("integration", "Integration", [
"## Integration",
"[the system we're connecting to, and why]",
"",
"## What flows",
"[the data or events, and in which direction]",
"",
"## Their side",
"[API docs, auth method, rate limits, test sandbox]",
"",
"## When it fails",
"[what should happen if they're down or slow]",
]),
"data-migration": template("data-migration", "Data migration", [
"## Data migration",
"[what moves or changes shape]",
"",
"## Size and downtime",
"[row counts, and whether users can stay on while it runs]",
"",
"## Rollback",
"[how we undo it if it goes wrong]",
"",
"## Done when",
"[the checks that prove nothing was lost]",
]),
});
const orders = (byRole) => Object.freeze(Object.fromEntries(Object.entries(byRole).map(([r, ids]) => [r, Object.freeze(ids)])));
// One full order per role per skill. No "none" row: Not set reads Engineer's.
export const TEMPLATE_ORDERS = Object.freeze({
pathfinder: orders({
engineer: ["engineering-spec", "design-decision", "spike", "integration", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "spike", "engineering-spec", "design-decision", "integration", "test-strategy"],
architect: ["design-decision", "engineering-spec", "integration", "spike", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
designer: ["brainstorm-notes", "product-requirements", "design-decision", "spike", "engineering-spec", "scoping-rollout", "integration", "test-strategy"],
qa: ["test-strategy", "engineering-spec", "spike", "product-requirements", "integration", "scoping-rollout", "design-decision", "brainstorm-notes"],
em: ["scoping-rollout", "engineering-spec", "product-requirements", "spike", "test-strategy", "design-decision", "integration", "brainstorm-notes"],
}),
plan: orders({
engineer: ["engineering-spec", "bug-investigation", "refactor", "performance-problem", "integration", "data-migration", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "integration", "test-strategy", "design-decision", "performance-problem", "bug-investigation", "data-migration", "refactor"],
architect: ["design-decision", "engineering-spec", "data-migration", "integration", "refactor", "scoping-rollout", "performance-problem", "test-strategy", "product-requirements", "bug-investigation"],
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "performance-problem", "test-strategy", "bug-investigation", "integration", "refactor", "data-migration"],
qa: ["test-strategy", "bug-investigation", "performance-problem", "engineering-spec", "data-migration", "integration", "product-requirements", "scoping-rollout", "refactor", "design-decision"],
em: ["scoping-rollout", "engineering-spec", "data-migration", "product-requirements", "test-strategy", "integration", "bug-investigation", "performance-problem", "refactor", "design-decision"],
}),
"quick-task": orders({
engineer: ["small-change", "bug-investigation", "refactor", "add-a-test", "dependency-upgrade", "performance-problem", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "performance-problem", "add-a-test", "record-decision", "dependency-upgrade", "refactor"],
architect: ["record-decision", "refactor", "small-change", "dependency-upgrade", "performance-problem", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "performance-problem", "add-a-test", "refactor", "dependency-upgrade", "record-decision"],
qa: ["add-a-test", "bug-investigation", "performance-problem", "small-change", "dependency-upgrade", "ui-polish", "refactor", "copy-tweak", "visual-prototype", "record-decision"],
em: ["small-change", "record-decision", "dependency-upgrade", "add-a-test", "bug-investigation", "performance-problem", "refactor", "copy-tweak", "ui-polish", "visual-prototype"],
}),
});
const roleRow = (role) => {
const r = normalizeRole(role);
return r === ROLE_NOT_SET ? "engineer" : r;
};
/**
* The idea card's template row for a skill: Blank first, then the skill's
* templates in the role's order. The first template carries `forYou` only for
* a chosen role, never for Not set. `[]` for a skill with no templates.
*/
export function templatesFor(workflow, role) {
if (!TEMPLATE_WORKFLOWS.includes(workflow)) return [];
const chosen = normalizeRole(role) !== ROLE_NOT_SET;
const ordered = TEMPLATE_ORDERS[workflow][roleRow(role)].map((id, i) => {
const { label, text } = TEMPLATES[id];
return { id, label, text, forYou: chosen && i === 0 };
});
return [{ id: "blank", label: "Blank", text: "" }, ...ordered];
}
// Swapping templates: an empty box, or one untouched since the last pick,
// swaps silently; anything the person typed asks first.
export function templateSwap({ selectedText, boxText, nextText } = {}) {
const box = typeof boxText === "string" ? boxText : "";
const selected = typeof selectedText === "string" ? selectedText : "";
return { text: typeof nextText === "string" ? nextText : "", confirm: box.trim() !== "" && box !== selected };
}
// Ask starter questions (PLAN-DRAFT Appendix B, approved). `lead` names the
// roles that see a starter first; `needsContext` starters wait for
// + Add context.
const starter = (id, text, lead, needsContext = false) =>
Object.freeze({ id, text, lead: Object.freeze(lead), needsContext });
export const STARTER_SETS = Object.freeze({
pathfinder: Object.freeze([
starter("pathfinder-files", "Which files or parts of the code does this decision touch?", ["engineer", "architect"], true),
starter("pathfinder-prior-art", "Has anything like this been done elsewhere in the repo?", ["engineer", "architect"]),
starter("pathfinder-decided", "What have we already decided, and what's still open?", ["pm", "em", "architect"]),
starter("pathfinder-plain", "What does this question mean, in plain words?", ["pm", "designer", "em"], true),
]),
plan: Object.freeze([
starter("plan-files", "Which existing files would this plan change?", ["engineer", "architect"]),
starter("plan-test", "How would we test this?", ["qa", "engineer"], true),
starter("plan-risks", "What are the biggest risks or unknowns in this plan?", ["architect", "em", "qa"]),
starter("plan-plain", "Explain this section as if I'm not an engineer.", ["pm", "designer", "em"], true),
]),
document: Object.freeze([
starter("document-touch", "Where does this phase touch existing code?", ["engineer"], true),
starter("document-guesses", "Which parts of this phase are still guesses?", ["architect", "engineer"], true),
starter("document-users", "What will users notice once every phase ships?", ["designer", "pm", "qa"]),
starter("document-summary", "Summarize the phases written so far in three bullets.", ["pm", "em"]),
]),
build: Object.freeze([
starter("build-last-task", "What changed in the last task, and why?", ["engineer", "em", "qa"]),
starter("build-finding", "Where exactly is this finding in the code?", ["engineer", "qa"], true),
starter("build-progress", "How far along are we, and what's next?", ["em", "pm"]),
starter("build-check", "What should I check by hand after this phase?", ["qa", "designer"]),
]),
"quick-task": Object.freeze([
starter("quick-task-files", "Which files will this touch?", ["engineer"]),
starter("quick-task-pattern", "Is there a similar pattern in the code I should follow?", ["engineer", "architect"]),
starter("quick-task-size", "Is this bigger than a quick task?", ["em", "architect"]),
starter("quick-task-try", "How do I try this out once it's done?", ["qa", "designer", "pm"]),
]),
dashboard: Object.freeze([
starter("dashboard-project", "What does this project do, in a paragraph?", ["pm", "designer", "em"]),
starter("dashboard-which-skill", "Which skill should I use for my idea?", ["pm", "designer", "em"]),
starter("dashboard-difference", "What's the difference between Pathfinder, Plan and Quick Task?", []),
starter("dashboard-spec", "Where does this spec stand?", ["pm", "em"], true),
]),
general: Object.freeze([
starter("general-step", "What is this step going to do, and what will it change?", []),
starter("general-summary", "Summarize this session so far.", ["em", "pm"]),
starter("general-left", "What's left to do after this?", ["em", "pm"]),
]),
});
// Workflows missing here (init, init-update, revise-plan, finalize, handoff,
// anything unknown) use the general set.
export const STARTER_SET_FOR = Object.freeze({
pathfinder: "pathfinder",
plan: "plan",
document: "document",
implement: "build",
"implement-review": "build",
review: "build",
"quick-task": "quick-task",
dashboard: "dashboard",
});
/**
* The starters an empty Ask conversation offers: the workflow's set, minus
* those that need context until some is attached, with the role's leads
* first and written order kept inside each group. Not set leads as Engineer.
*/
export function startersFor(workflow, role, { hasContext } = {}) {
const setId = Object.hasOwn(STARTER_SET_FOR, workflow) ? STARTER_SET_FOR[workflow] : "general";
const lead = roleRow(role);
const shown = STARTER_SETS[setId].filter((s) => hasContext || !s.needsContext);
const first = shown.filter((s) => s.lead.includes(lead));
const rest = shown.filter((s) => !s.lead.includes(lead));
return [...first, ...rest].map(({ id, text }) => ({ id, text }));
}
@@ -1,226 +0,0 @@
// Plan2Code Web Console - the Subagents switch's opt-in table, wording and checks.
//
// The source of truth for which workflows offer the switch, the instruction
// each one ships with, the fixed frame every "on" block carries, the exact
// lines the agent reads at a pickup (blockFor()), and the house rules for the
// helpers an agent reports back (checkHelper()). No DOM access at module scope
// and no imports: the server, console.mjs, the page and `node --test` all
// import this file.
// The one place a skill opts in (FR-1). Wording is behaviour-level and names
// no harness tool, so any agent can follow it or harmlessly ignore it.
export const SUBAGENT_WORKFLOWS = Object.freeze({
implement: Object.freeze({
instruction:
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
}),
"implement-review": Object.freeze({
instruction:
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
}),
"quick-task": Object.freeze({
instruction:
"Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
}),
review: Object.freeze({
instruction:
"Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.",
}),
pathfinder: Object.freeze({
instruction:
"Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
}),
});
export function offered(workflow) {
return typeof workflow === "string" && Object.prototype.hasOwnProperty.call(SUBAGENT_WORKFLOWS, workflow);
}
export const MAX_MIN = 1;
export const MAX_MAX = 20;
export const DEFAULT_MAX = 3;
export const INSTRUCTION_MAX_CHARS = 2000;
export const HELPER_TITLE_MAX = 80;
export const HELPER_ASK_MAX = 400;
export const HELPER_RESULT_MAX = 200;
export const HELPER_STATES = Object.freeze(["running", "done", "failed"]);
/* ------------------------------------------------------------- settings */
export function defaultInstruction(workflow) {
return offered(workflow) ? SUBAGENT_WORKFLOWS[workflow].instruction : "";
}
// The person's own text when they wrote some, else the workflow's default.
export function effectiveInstruction(setting) {
const own = setting && typeof setting.instruction === "string" ? setting.instruction.trim() : "";
return own || defaultInstruction(setting && setting.workflow);
}
export function defaultSetting(workflow) {
return { workflow, on: false, instruction: null, max: DEFAULT_MAX };
}
/**
* `{ on, instruction, max }` from untrusted input, or `{ error }` naming the
* field that failed: "bad" (wrong type), "too-long" (instruction) or "max".
* Returns an error object rather than throwing, so the route and the store
* reader share one validator. An empty instruction means the default: null.
*/
export function cleanSetting(input) {
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "bad" };
if (typeof input.on !== "boolean") return { error: "bad" };
let instruction = null;
if (input.instruction !== null && input.instruction !== undefined) {
if (typeof input.instruction !== "string") return { error: "bad" };
const trimmed = input.instruction.trim();
if (trimmed.length > INSTRUCTION_MAX_CHARS) return { error: "too-long" };
instruction = trimmed || null;
}
const max = input.max;
if (!Number.isInteger(max) || max < MAX_MIN || max > MAX_MAX) return { error: "max" };
return { on: input.on, instruction, max };
}
/* ------------------------------------------------------------ the lines */
// The non-editable part of every "on" block (FR-8).
export const FRAME_LINES = Object.freeze([
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
"Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.",
'If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.',
]);
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
// Only the first line of a block starts at column 0, so no line inside it can
// be read as an entry of its own (NFR-5).
export function onLines({ revision, replaces, max, instruction }) {
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
const own = String(instruction || "")
.split("\n")
.map((line) => line.trimEnd())
.filter((line) => line.trim());
return [
`Subagents: on (${label}) — a console setting, not typed by the person.`,
...[...FRAME_LINES, ...own, `At most ${max} helpers at once.`].map((line) => " " + line),
];
}
export function offLine(revision) {
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
}
/**
* What the agent is owed at a pickup, given the session setting and the
* cursor of what it was last told: `null`, or `{ field, lines, cursor }`
* where `cursor` is what to write once the lines are printed. Never says
* "off" to an agent that was not told "on" (FR-6). Pure: no clock, no I/O.
*/
export function blockFor(setting, told) {
const last = told || { revision: 0, state: "none" };
if (!setting || !offered(setting.workflow) || !(setting.revision > last.revision)) return null;
const { revision, max } = setting;
const instruction = effectiveInstruction(setting);
if (setting.on) {
const replaces = last.state === "on" ? last.revision : undefined;
return {
field: { state: "on", revision, max, instruction },
lines: onLines({ revision, replaces, max, instruction }),
cursor: { revision, state: "on" },
};
}
if (last.state !== "on") return null;
return {
field: { state: "off", revision, max, instruction },
lines: [offLine(revision)],
cursor: { revision, state: "off" },
};
}
/* ------------------------------------------------------------ helpers */
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
const nonEmpty = (v) => typeof v === "string" && v.trim() !== "";
// The problems with one reported helper, [] when it is fine.
export function checkHelper(entry) {
if (!isPlainObject(entry)) return ["helper: each entry must be an object"];
if (!nonEmpty(entry.id)) return ["helper: id must be a non-empty string"];
const who = `helper "${entry.id}"`;
if (entry.alone === true) return entry.id === "alone" ? [] : [`${who}: the working-alone entry must have id "alone"`];
const problems = [];
if (!nonEmpty(entry.title)) problems.push(`${who}: title must be a non-empty string`);
else if (entry.title.length > HELPER_TITLE_MAX) problems.push(`${who}: title must be at most ${HELPER_TITLE_MAX} characters`);
if (!nonEmpty(entry.ask)) problems.push(`${who}: ask must be a non-empty string`);
else if (entry.ask.length > HELPER_ASK_MAX) problems.push(`${who}: ask must be at most ${HELPER_ASK_MAX} characters`);
if (!HELPER_STATES.includes(entry.state)) problems.push(`${who}: state must be running, done or failed`);
if (entry.result !== undefined) {
if (typeof entry.result !== "string") problems.push(`${who}: result must be a string`);
else if (entry.result.length > HELPER_RESULT_MAX) problems.push(`${who}: result must be at most ${HELPER_RESULT_MAX} characters`);
}
return problems;
}
// The problems with a whole merged list.
export function checkHelpers(list) {
if (!Array.isArray(list)) return ["helpers must be an array"];
const problems = [];
const seen = new Set();
let alone = 0;
for (const entry of list) {
if (isPlainObject(entry) && nonEmpty(entry.id)) {
if (seen.has(entry.id)) problems.push(`helper "${entry.id}": duplicate id`);
seen.add(entry.id);
if (entry.alone === true && ++alone === 2) problems.push(`helper "${entry.id}": only one working-alone entry is allowed`);
}
problems.push(...checkHelper(entry));
}
return problems;
}
/* ------------------------------------------------------------ the page */
// The page's rules for the button, the modal and the tab, kept here so they
// are tested without a browser. `frame` is the state frame's `subagents`
// block; app.js only renders what these say.
export const CHECKIN_LINE = "Helpers report through Plan2Code, so their progress shows here at its check-ins, not live.";
const STATE_LABELS = Object.freeze({ running: "Running", done: "Done", failed: "Failed" });
// The switch shows only where the skill opts in AND the agent's console copy
// said it can deliver it (FR-3).
export function showSwitch(frame) {
return Boolean(frame && frame.offered && frame.supported);
}
// The button's tooltip and accessible name (FR-2).
export function switchLabel(frame) {
return frame && frame.on ? "Subagents: on" : "Subagents: off";
}
// What the Subagents tab draws: the working-alone note, or one row per helper
// in the order the agent reported them. A real helper supersedes the
// working-alone marker, so the note only draws when no helper was ever
// reported. A result shows once the helper ended.
export function helperRows(helpers) {
const list = Array.isArray(helpers) ? helpers.filter(isPlainObject) : [];
const real = list.filter((h) => h.alone !== true);
if (!real.length) return { alone: list.some((h) => h.alone === true), rows: [] };
const rows = real.map(({ id, title, ask, state, result }) => ({
id,
title,
ask,
state,
stateLabel: STATE_LABELS[state] || STATE_LABELS.running,
...((state === "done" || state === "failed") && typeof result === "string" && result ? { result } : {}),
}));
return { alone: false, rows };
}
// Never an empty tab. Independent of on / off, so Pathfinder's research
// helpers show even with the switch off (FR-11, FR-12).
export function showTab(frame, helpers) {
return showSwitch(frame) && Array.isArray(helpers) && helpers.length > 0;
}
File diff suppressed because it is too large. Load diff
@@ -1,92 +0,0 @@
// Plan2Code Web Console - the Workspace's naming and wording rules.
//
// The source of truth for what a folder may be called, the name a new folder
// gets by default, and the suggestion offered when a name is taken. Imported
// by the server (its guards), lib.mjs and the page, so they can never disagree.
// No DOM access at module scope and no imports: the page and `node --test`
// both import this file.
export const NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
export const NAME_MAX = 40;
const trimDashes = (s) => s.replace(/^-+|-+$/g, "");
/**
* The name a folder gets before anyone renames it: its last path segment,
* lowercased, with every run of other characters turned into one `-`.
*/
export function defaultName(folderPath) {
const segments = String(folderPath || "")
.split(/[\\/]/)
.filter(Boolean);
const last = segments.length ? segments[segments.length - 1] : "";
const name = trimDashes(trimDashes(last.toLowerCase().replace(/[^a-z0-9]+/g, "-")).slice(0, NAME_MAX));
return name || "folder";
}
// null when the name can be used, "bad-name" when it cannot.
export function nameProblem(name) {
if (typeof name !== "string" || !name || name.length > NAME_MAX || !NAME_PATTERN.test(name)) return "bad-name";
return null;
}
/**
* `base` when nobody has it, else the first free `base-2`, `base-3`, ...
* `base` is shortened first so the suffixed name still fits NAME_MAX.
*/
export function freeName(base, taken) {
if (!taken.has(base)) return base;
for (let n = 2; ; n++) {
const suffix = `-${n}`;
const candidate = trimDashes(base.slice(0, NAME_MAX - suffix.length)) + suffix;
if (!taken.has(candidate)) return candidate;
}
}
// How many footer label tiers there are: the page tries 0..FOOTER_TIERS-1,
// widest first, until the text fits.
export const FOOTER_TIERS = 4;
/**
* The footer's workspace label. `folders[0]` is the original folder.
* 0 plan2code + 2 folders · main
* 1 plan2code + 2 folders
* 2 plan2code +2
* 3 plan2code
*/
export function footerLabel({ folders, branch }, tier = 0) {
const list = Array.isArray(folders) ? folders : [];
const name = list.length ? list[0].name : "";
const n = Math.max(0, list.length - 1);
if (tier >= 3) return name;
let label = name;
if (n > 0) label += tier === 2 ? ` +${n}` : ` + ${n} ${n === 1 ? "folder" : "folders"}`;
if (tier === 0 && branch) label += ` · ${branch}`;
return label;
}
/**
* The reply line an agent is handed for one workspace.json change entry
* (`{ kind, name, path, description?, from? }`).
*/
export function changeLine(change) {
const { kind, name, path, description, from } = change || {};
switch (kind) {
case "added":
return `Workspace: added @${name} — ${path}` + (description ? ` (${description})` : "");
case "renamed":
return `Workspace: renamed @${from} to @${name} — ${path}`;
case "described":
return description
? `Workspace: @${name} is now described as "${description}"`
: `Workspace: @${name} description cleared`;
case "removed":
return `Workspace: removed @${name} — ${path}`;
case "missing":
return `Workspace: @${name} is missing — ${path} no longer exists`;
case "found":
return `Workspace: @${name} is back — ${path}`;
default:
return `Workspace: @${name} changed — ${path}`;
}
}
File diff suppressed because it is too large. Load diff
@@ -1,138 +0,0 @@
// Plan2Code Web Console - is a newer Plan2Code release out?
//
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
// release tag is "latest". The server
// starts this at boot and never waits on it; the answer, failures included, is
// cached for an hour so a burst of sessions asks GitHub once.
//
// Nothing here reads, stores or sends a credential: git authenticates itself,
// with every prompt turned off so a missing login fails fast instead of
// opening a window nobody asked for.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
export const CACHE_MS = 60 * 60 * 1000;
const SEMVER = /^\d+\.\d+\.\d+$/;
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
export function compareVersions(a, b) {
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
const x = a.split(".").map(Number);
const y = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
}
return 0;
}
/**
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
* pre-releases or other tag names are ignored. Null when nothing matches.
*/
export function latestTag(text) {
if (typeof text !== "string") return null;
let best = null;
for (const line of text.split(/\r?\n/)) {
const m = TAG_REF.exec(line.trim());
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
}
return best;
}
function readCache(cacheFile, now) {
try {
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
return typeof cached.latest === "string" ? cached.latest : null;
} catch {
return undefined;
}
}
function writeCache(cacheFile, data) {
const tmp = cacheFile + "." + process.pid + ".tmp";
try {
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
fs.renameSync(tmp, cacheFile);
} catch {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
}
/**
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
* window, no prompt.
*/
export function runLsRemote({ timeoutMs = 10000 } = {}) {
return new Promise((resolve) => {
let settled = false;
const done = (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
let child;
try {
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
shell: false,
windowsHide: true,
stdio: ["ignore", "pipe", "ignore"],
env,
});
} catch {
return resolve(null);
}
const timer = setTimeout(() => {
try {
child.kill();
} catch {}
done(null);
}, timeoutMs);
timer.unref?.();
let out = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
out += chunk;
});
child.on("error", () => done(null));
child.on("close", (code) => done(code === 0 ? out : null));
});
}
/**
* Whether `installed` is behind the newest release: `{ installed, latest,
* updateAvailable }`, or null when either version is unknown. Reuses a cache
* under an hour old, and caches a failed lookup as `latest: null` so it is
* not retried until the hour is up. Never throws.
*/
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
try {
let latest = readCache(cacheFile, now);
if (latest === undefined) {
latest = latestTag(await run());
writeCache(cacheFile, { checkedAt: now, latest });
}
const order = compareVersions(installed, latest);
if (latest === null || order === null) return null;
return { installed, latest, updateAvailable: order < 0 };
} catch {
return null;
}
}
@@ -1,22 +0,0 @@
{
"name": "Plan2Code",
"version": "2.5.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-07",
"mode": "utility"
}
@@ -1,247 +0,0 @@
// Plan2Code skill scripts: shared plumbing.
//
// Every script in a skill's scripts/ directory imports this file. It owns the
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
//
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
// on a handled failure.
// stderr a one-line human diagnostic on failure (the same message + next).
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
// 4 invalid input or a check that failed · 5 refused (would clobber
// or break a rule).
//
// Node 18+ built-ins only, no build step: this ships inside every skill.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
export class CliError extends Error {
constructor(exit, error, message, next) {
super(message);
this.exit = exit;
this.error = error;
this.next = next;
}
}
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
export function fail(exit, error, message, next) {
throw new CliError(exit, error, message, next);
}
export function out(obj) {
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
}
/**
* Parse argv into { _: positionals, <flag>: value }.
* `booleans` names flags that take no value; every other `--flag` takes the
* next argument, and repeats of a flag listed in `lists` collect into an array.
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
* silently changes behavior.
*/
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
const known = new Set([...booleans, ...values, ...lists, "help"]);
const args = { _: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) {
args._.push(a);
continue;
}
let name = a.slice(2);
let value;
const eq = name.indexOf("=");
if (eq !== -1) {
value = name.slice(eq + 1);
name = name.slice(0, eq);
}
if (!known.has(name)) {
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
}
if (name === "help" || booleans.includes(name)) {
args[name] = true;
continue;
}
if (value === undefined) {
if (i + 1 >= argv.length) {
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
}
value = argv[++i];
}
if (lists.includes(name)) (args[name] ||= []).push(value);
else args[name] = value;
}
return args;
}
/**
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
* failure shape plus an exit code, and anything else into exit 1 with the stack
* on stderr. Sets process.exitCode rather than calling process.exit(), so
* stdout is never cut off mid-write.
*/
export async function run(usage, main) {
try {
const argv = process.argv.slice(2);
if (argv.includes("--help") || argv.includes("-h")) {
process.stdout.write(usage.trim() + "\n");
return;
}
await main(argv);
} catch (err) {
if (err instanceof CliError) {
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
process.exitCode = err.exit;
return;
}
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
process.exitCode = EXIT.CRASH;
}
}
/* ------------------------------------------------------------------ time */
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
// is what "today" means to the person reading the date in their files.
export function now() {
const pinned = process.env.PLAN2CODE_NOW;
if (pinned) {
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
const d = new Date(pinned);
if (!Number.isNaN(d.getTime())) return d;
}
return new Date();
}
const pad = (n) => String(n).padStart(2, "0");
/** YYYY-MM-DD */
export function isoDate(d = now()) {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
/** YYYYMMDD */
export function compactDate(d = now()) {
return isoDate(d).replace(/-/g, "");
}
/** YYYY-MM-DD HH:mm */
export function stamp(d = now()) {
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** HHMMSS */
export function clock(d = now()) {
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
}
/* ----------------------------------------------------------------- files */
export function readText(file) {
try {
return fs.readFileSync(file, "utf8");
} catch {
return null;
}
}
export function isDir(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
/** Write a file only when its content changes. Returns true when it wrote. */
export function writeIfChanged(file, content) {
const current = readText(file);
if (current === content) return false;
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
return true;
}
/** Normalise line endings for parsing; keep the original for writing back. */
export function eol(text) {
return text.includes("\r\n") ? "\r\n" : "\n";
}
/**
* phase-N.md per phase number. An exact phase-N.md always wins over a sibling
* such as phase-1-old.md; more than one candidate is reported, never guessed.
* Shared so every script that counts a spec's tasks reads the same files.
*/
export function phaseFiles(dir) {
const files = new Map();
const extra = new Map();
for (const name of fs.readdirSync(dir).sort()) {
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
if (!m) continue;
const n = Number(m[1]);
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
if (!files.has(n)) files.set(n, name);
else if (exact) {
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
files.set(n, name);
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
}
files.extra = extra;
return files;
}
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
export function rel(root, p) {
return path.relative(root, p).split(path.sep).join("/") || ".";
}
/* --------------------------------------------------------- the web console */
// The web console ships beside these scripts in every installed skill
// (references/web-console/), and in this repo it sits at src/web-console/. Its
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
// metrics-bait scan, so the scripts import it rather than keep a second copy.
const CONSOLE_LIB_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
];
let consoleLibPromise;
export function consoleLib() {
consoleLibPromise ||= (async () => {
for (const candidate of CONSOLE_LIB_CANDIDATES) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-lib-missing",
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
);
})();
return consoleLibPromise;
}
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
export function version() {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const text = readText(file);
if (!text) continue;
try {
const v = JSON.parse(text).version;
if (typeof v === "string") return v;
} catch {}
}
return null;
}
File diff suppressed because it is too large. Load diff
@@ -1,22 +0,0 @@
{
"name": "Plan2Code",
"version": "2.5.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-07",
"mode": "utility"
}
-305
View File
@@ -1,305 +0,0 @@
---
name: plan2code-1-plan
description: "Plan2Code Step 1: Planning Mode - user-initiated workflow step. Do not invoke autonomously."
disable-model-invocation: true
---
# 🤔 PLANNING MODE
Start all PLANNING MODE responses with '🤔 [PLANNING PHASE X: Phase Name]'
## Role
Senior software architect and technical PM. Analyze requirements critically, ask questions, design robust, testable solutions. Output: SOW and Implementation Plan. Do NOT write code - plan and architect only.
## Interface
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before looking for a draft: ask **web console** (suggested — far easier for sign-offs with a non-engineer) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow plan` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then <D>/console.md → Planning notes. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console.md → Launches), then the AGENTS.md check.
## Project Context (BLOCKING)
Check if `./AGENTS.md` exists:
1. **Exists:** Read and use for project context/conventions
2. **Missing:** STOP and respond:
> ```
> ⋅
> ╭───╮ ?
> │ ★ │╱
> ╱│ ~ │ Hmm, I don't see an AGENTS.md...
> ╰┬─┬╯
> ```
>
> "No `AGENTS.md` found. This file provides project context (conventions, architecture, tech stack).
>
> **To create it:** `plan2code-init`
>
> Let me know when ready to continue."
Do not proceed until user confirms continuing without `AGENTS.md`.
## Rules
- Complete ONE phase at a time, then STOP and wait for input
- Reach 90% confidence before finalizing — investigate to close gaps; score honestly against evidence, never inflate
- Resolve ambiguities through questions - do NOT assume
- Document unavoidable assumptions clearly
- Present/confirm technology decisions with user
- NEVER write implementation code
- Keep responses conceptual - detailed specs belong in final PLAN-DRAFT only
- If no file access, output content in code blocks with file path headers
---
### Check for Existing Progress
Before Phase 1, run `node "<S>/specs.mjs" list` from the project root (`<S>`: `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-1-plan/scripts/` globally). It reads gitignored `specs/` (Glob silently finds nothing there) and gives each spec's `planDrafts` with its **Status:** line (`-prev` copies are `archived`; ignore them). Route on that status:
- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4
- Status "Escalated from Quick Task - Resume at Phase 2": Acknowledge, verify requirements, skip to Phase 2
- Status "Draft" or "Complete": Ask user how to proceed
- No PLAN-DRAFT: Begin at Phase 1. Console: its idea card carries `"templates": "idea"` (console.md → Starter templates)
---
### Clarification Protocol
1. Wait for response
2. Clear response -> proceed; New ambiguity -> ONE follow-up
3. Maximum 3 rounds per phase, then summarize and proceed
When assumptions made, end with:
**Assumptions this phase:** [Assumption] - [impact if wrong]
User MUST confirm before next phase.
### Confidence Calculation
Four dimensions (0-25% each):
| Dimension | Measures |
|-----------|----------|
| **Requirements Clarity** | All requirements unambiguous? |
| **Technical Feasibility** | Know HOW to build each component? |
| **Integration Points** | All external dependencies identified? |
| **Risk Assessment** | Blockers documented with mitigations? |
Report each sub-score with overall percentage.
## Process
### PHASE 1: Requirements Analysis
**Initial Context Check:** Ask user:
1. Additional files/folders to examine?
2. Reference materials? (designs, mockups, API specs)
3. External systems/APIs to integrate?
After confirmation, proceed with analysis:
1. Read all provided information; research the domain for standards and unstated needs
2. Extract explicit functional requirements
3. Identify implied requirements, edge cases, and failure modes
4. Determine non-functional requirements: Performance, Security, Scalability, Maintenance
5. Ask clarifying questions
6. **Testing Preferences (Optional):**
> "Include testing?
> 1. **Types**: Unit, Integration, E2E, or None
> 2. **Phase testing**: Run after each phase?
> 3. **Coverage**: Critical paths / Moderate (~60-80%) / Comprehensive (>80%)
>
> Say 'skip testing' to omit."
Default: No testing.
7. Report confidence score
8. **Requirements Sign-Off:**
> **Requirements Summary:**
> **Functional:**
> FR-1: [req]
> FR-2: [req]
> ...
> **Non-Functional:**
> NFR-1: [req]
> ...
> **Testing:** [approach or None]
>
> **Confirm:** Complete and accurate? (approved / needs changes)
Do NOT proceed to Phase 2 until user approves.
### PHASE 2: System Context Examination
**Existing projects:**
1. Examine directory structure
2. Review key files/components — verify behavior against actual code, not assumptions
3. Identify patterns, conventions, code style
4. Identify integration points
5. Note technical debt
6. Define system boundaries
**Greenfield projects:**
1. State: "Greenfield project - no existing codebase"
2. Focus on external systems
3. Define boundaries
4. Consider project structure
Both: Create system context diagram if beneficial. Update confidence.
### PHASE 3: Scope Assessment
| Scope | Indicators | Adjustment |
|-------|------------|------------|
| **Small** | 1-2 phases, <10 reqs, ≤3 components, ≤1 integration | Combine phases |
| **Medium** | 3-5 phases, 10-15 reqs, 4-6 components, 2-3 integrations | Standard workflow |
| **Large** | 6+ phases OR 15+ reqs OR 7+ components OR 4+ integrations | Multi-conversation checkpoint |
Large if ANY threshold met. When in doubt, ask.
State assessment and ask user to confirm.
**Small/Medium:** Continue to Phase 4.
**Large - Context Checkpoint:**
1. Ask for feature name (kebab-case)
2. Create `specs/<feature-name>/`
3. Create `specs/<feature-name>/PLAN-DRAFT-<YYYYMMDD>.md` with Phases 1-3
4. Set status: `Phase 3 Complete - Resume at Phase 4`
5. Include: Executive Summary, Requirements, System Context, Scope, Confidence
6. Instruct: "Large project. Progress saved. Start NEW conversation with `/plan2code-1-plan --web` to resume at Phase 4." On the web console, post `finish` with that command first, then `stop`.
7. STOP
### PHASE 4: Tech Stack
1. List user-specified technologies (confirmed)
2. Research current options; recommend unspecified decisions with evidence-based justification:
- Languages, Frameworks, Libraries, Databases, External services, Dev tools
| Category | Recommendation | Alternatives | Justification |
|----------|----------------|--------------|---------------|
3. User MUST approve tech stack before Phase 5
### PHASE 5: Architecture Design
**Devil's Advocate:** State one alternative approach and why you rejected it.
1. Propose 2-3 architecture patterns
2. For each: appropriateness, advantages, drawbacks
3. Recommend optimal pattern with justification
4. Define core components: name, responsibility, inputs/outputs, dependencies
5. Design component interfaces
6. Database schema (if applicable): entities, relationships, key fields, indexing
7. Cross-cutting concerns: Auth, Error handling, Logging, Security, Performance, Scalability
8. Update confidence
### PHASE 6: Technical Specification
1. Break into implementation phases with dependencies
2. Technical risks:
| Risk | Likelihood | Impact | Mitigation |
|------|------------|--------|------------|
3. Component specs: API contracts, data formats, validation, state management, error codes
4. Define measurable success criteria
5. Update confidence
6. **If confidence >= 90%:** "Reached [X]% confidence. Proceed to PLAN-DRAFT, or any adjustments?"
Wait for confirmation before Phase 7.
### PHASE 7: Transition Decision
1. Summarize architecture
2. Present implementation roadmap
3. State final confidence
**If >= 90%:**
1. Get feature name (kebab-case) if not determined
2. Create `specs/<feature-name>/` if needed
3. Save planning documents (format below)
**Next Step:** After PLAN-DRAFT, direct to `/plan2code-2-document` (NOT implementation). Workflow: Plan -> Document -> Implement -> Finalize.
**If < 90%:**
- List areas needing clarification (reference dimension)
- Ask targeted questions
- State: "Need clarity on [areas] to improve [dimension] confidence."
**Phase 7 Outputs:**
1. Save PLAN-CONVERSATION (see template below) — transcript + decision summary tables
2. Create PLAN-DRAFT (see template below) using same date
3. Verify: re-read conversation as source of truth, cross-reference against PLAN-DRAFT sections (Reqs→2.1/2.2, Tech→3, Architecture→4, Risks→6, Assumptions→9, Criteria→7). Add gaps with `<!-- VERIFICATION -->` comments. Output verification summary table.
4. Append `## Planning Metrics` to PLAN-DRAFT with a `<!-- METRICS_JSON {...} -->` HTML comment. The metrics pipeline parses this — use exact format:
```
## Planning Metrics
<!-- METRICS_JSON {"confidence": 95, "clarification_rounds": 0, "functional_requirements_count": 8, "non_functional_requirements_count": 6, "risk_count": 7, "phase_count": 4, "verification_gaps_found": 0, "confidence_breakdown": {"requirements": 24, "feasibility": 23, "integration": 24, "risk": 22}} -->
```
Replace values with actuals. Optionally add plain `key: value` lines below for readability (no bold/markdown).
## Templates
### PLAN-DRAFT Format
File: `specs/<feature-name>/PLAN-DRAFT-<YYYYMMDD>.md`
Header: Title, Created date, Status (Draft | Phase 3 Complete - Resume at Phase 4 | Complete), Confidence % (Reqs/Feasibility/Integration/Risk each /25), link to PLAN-CONVERSATION.
Sections:
1. **Executive Summary** — 2-3 sentences
2. **Requirements** — 2.1 Functional (FR-N checklist), 2.2 Non-Functional (NFR-N checklist), 2.3 Out of Scope, 2.4 Testing Strategy table (Types, Phase Testing, Coverage)
3. **Tech Stack** — table: Category / Technology / Version / Justification
4. **Architecture** — 4.1 Pattern (name + rationale), 4.2 System Context Diagram, 4.3 Components table, 4.4 Data Model, 4.5 API Design
5. **Implementation Phases** — Per phase: Name, Goal, Dependencies, Task checklist (Task N.N)
6. **Risks and Mitigations** — table: Risk / Likelihood / Impact / Mitigation
7. **Success Criteria** — checklist
8. **Open Questions** — remove if none
9. **Assumptions** — list
### Response Format
1. **Phase indicator:** `🤔 [PLANNING PHASE X: Name]`
2. **Deliverables:** Findings/analysis
3. **Confidence:** Percentage with breakdown
4. **Questions:** Ambiguity resolution (if any)
5. **Next steps**
## Session End
**Workflow: Plan -> Document -> Implement -> Finalize**
When complete (PLAN-DRAFT created), tell user:
1. What was accomplished
2. **Next: `/plan2code-2-document`** (NOT implementation)
3. Documentation auto-discovers planning files
**On the web console:** at every session end, and on a `__stop`, post `finish` BEFORE `stop`, per console.md → Planning.
**Closing example:**
> "Planning complete. Created in `specs/<feature-name>/`:
> - **Conversation Log:** `PLAN-CONVERSATION-<date>.md`
> - **Implementation Plan:** `PLAN-DRAFT-<date>.md`
>
> ```
> ⋅
> ╭───╮
> ╲│ ★ │╱
> │ ◡ │ Planning done! Ready for documentation!
> ╰┬─┬╯
> =============================================
> NEXT STEP: Start a NEW conversation then run:
> `/plan2code-2-document --web`
> ```"
## Abort / Recovery
- **Abort:** Confirm with user, list files needing cleanup, stop workflow
- **Lost context:** Attach PLAN-DRAFT, state phase
- **Confidence stuck <90%:** List blockers, ask targeted questions
## Reminders
- Final phase: PLANNING PHASE 7: Transition Decision
- Do NOT implement - design and present plan only
@@ -1,498 +0,0 @@
# Build Sessions on the Web Console
For `/plan2code-3-implement`, `/plan2code-3-implement-review` and
`/plan2code-quick-task`. Read `console.md` first: everything there still
applies (the wait loop, one post per send, `finish` before `stop`, the house
rules). This file adds what a build needs, because a build is mostly you
working, and the page has to be told so.
**The console changes where you ask, not what you build.** Every rule of the
workflow stands: the same specs, the same checkbox writes to disk after every
task, the same sign-off wording, the same "no git commands". The files under
`specs/` and the code are the record. The page is a window onto them.
---
## Opening
Open first, before reading the spec — the page shows a starting screen while
you work out the phase:
```
node "<CONSOLE>" open --workflow implement
```
| Workflow you are running | `--workflow` | `--spec` |
| --- | --- | --- |
| `/plan2code-3-implement` | `implement` | `specs/<feature>` |
| `/plan2code-3-implement-review` | `implement-review` | `specs/<feature>` |
| `/plan2code-quick-task` | `quick-task` | leave it out |
`--spec` is what the page builds a resume command from if you ever cannot
answer a stop yourself. Pass it to `open` when you already know the spec;
otherwise post `"specDir": "specs/<feature>"` and a real `title` ("<feature>:
Phase 3") in your first update, once the phase is chosen, or with the phase
question as its first item if there is one to ask. `--file` works on `open`
too, but opening bare and posting the task list as your first update gets
them the page while you are still composing.
**Launched from the dashboard?** Then the session is already open and the
person is watching it — `open --resume <sid> --no-open --workflow <yours>`
(plus `--spec` once known) instead of a fresh `open`, exactly as console.md →
Launches says. Everything below is unchanged; the only difference is whose
session it was a minute ago.
The first payload for a phase you are about to build:
```jsonc
{
"headline": { "stage": "Phase 3: API layer", "cleared": 0, "total": 9 },
"docs": [
{ "id": "phase", "title": "Phase 3 tasks", "version": 1, "blocks": [
{ "id": "tasks", "state": "settled", "md": "- [ ] **Task 3.1:** ...\n- [ ] **Task 3.2:** ..." }
]},
{ "id": "phasefile", "title": "phase-3.md", "version": 1, "blocks": [
{ "id": "body", "state": "settled", "md": "...the whole phase-3.md file, verbatim..." }
]}
],
"agent": { "status": "working", "activity": "Checking the prerequisites", "quietMinutes": 15 }
}
```
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
progress bar is the first thing someone watching a build looks at. The session
meter counts the build's tasks from `cleared` as it rises, so keep it current,
and start every phase (a second one in the same run too) at `"cleared": 0`.
`"version": 1` is for the first phase of a session only. A doc's version
never goes back (console.md → House rules, rule 9), so a later phase in the
same session reposts `phase` and `phasefile` at one more than the version the
page holds, with the new phase's title and content. The same goes for
`report` at sign-off and `review` in a mid-session review: version 1 the
first time, then up from wherever the page has it.
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
the person can read the prerequisites and task specs while you build. Re-post
it whenever the file changes, which is every task: the checkbox write that
ticks the list above ticks the file too, and the Phase Completion Summary
lands in it at the end. It renders as markdown, so the file's checkboxes show
as ticks exactly as they stand on disk.
---
## While you build
Post after every task, in the same breath as writing its checkbox to disk.
Write the patch file into the session's own folder (the `session` path `open`
printed), never into the project or into `~/.plan2code/console/` directly:
```jsonc
{
"headline": { "cleared": 4 },
"docs": [
{ "id": "phase", "version": 5, "blocks": [ { "id": "tasks", "state": "settled", "md": "...the whole list, 4 ticked..." } ] },
{ "id": "phasefile", "version": 5, "blocks": [ { "id": "body", "state": "settled", "md": "...phase-3.md as it now stands on disk..." } ] }
],
"agent": { "activity": "Task 5 of 9: the rate limiter" }
}
```
- **`activity`** is one plain sentence saying what you are doing now. The page
shows it beside Planny and in place of "questions coming". No internal
vocabulary, no loop completion markers. Number tasks by their position in
the phase, of the phase's task count (`Task 5 of 9`), not by the file's
`5.5`-style labels: the phase is already in the headline. The page rewrites
the old form as a safety net.
- **`quietMinutes`** is how long you might go without posting (1 to 60). The
page calls a working agent stuck after two minutes of silence unless you say
otherwise, and a build task can honestly take twenty. Set it to the longest
gap you expect, usually 10 to 30. Every post is also a heartbeat. **Clear it
(`"quietMinutes": null`) whenever you go back to waiting**: it only counts
while you are `working`, but leaving it set invites a stale value later.
- `blocks` inside a doc are replaced whole, so post the whole task list each
time. It is small. The same goes for `phasefile`: re-read `phase-X.md` and
post it fresh, because the checkbox write just changed it.
- If the task list grows mid-build, raise `headline.total` in the same post;
the page never shows more done than the total, but the bar reads truer when
you keep it current.
- Do not call `wait` while building. There is nothing to collect, and the page
holds anything the person sends until you next look.
A build may receive a `Subagents:` standing instruction, on `open` output or a
`chat` check between tasks. Follow console.md → Standing instructions for
handing independent tasks to helpers and reporting them as `helpers`. Keep the
per-task progress posts, the checkbox writes, the chat checks and the sign-off
with you.
### Quick questions between tasks
The person can ask a Quick question on the Ask tab at any point in a build
(console.md → Quick questions). After each task's progress post, check for
one before starting the next task:
```
node "<CONSOLE>" chat --session <sid>
```
| Exit | What you do |
| --- | --- |
| `0` | Answer everything waiting, under console.md → Quick questions, in one post, then start the next task. A `workspace` list in the output is a change to the session's folders (console.md → Workspace): take it into account from the next task on; it needs no reply. |
| `10` | Nothing waiting. Carry on. |
| `20` | The server is gone: `open --resume <sid>` as usual, then carry on. |
This is an instant check, not a wait: it never sleeps and never touches card
sends. It does not replace `wait` at a gate, and no build calls `wait`
mid-build for cards. An approved chat edit is made here, between tasks, never
in the middle of one.
A blocker (`[!]`), a `SPEC NOTE` and a verified or assumed prerequisite are
not questions. Put them in the phase doc as they happen, and in the report.
### When the workflow asks something
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }` in
the SAME post, and go into the wait loop. When the answer lands, set `working`
again and carry on.
A question stops the build. Never leave yourself `working` with a question
open, and never "carry on while you decide": the page reads `working` as "not
your turn", and the person is left looking at a question they cannot answer.
If there is other work the answer does not touch, finish it before you ask,
then ask and wait.
| Moment | `kind` | Notes |
| --- | --- | --- |
| Several phases can be picked | `choice` | One option per phase, `detail` = status and task count, `token` = the phase number. Put the "run another agent on a different phase" tip in `body`. |
| A phase is already in progress | `confirm` | "Resume Phase 3?" `yes` / `no`. |
| `SPEC CONFLICT` | `choice` or `text` | The conflict in `body`, the readings as options where there are clear ones. Never guess on architecture. |
| Test failures | `choice` | `1` Fix now, `2` Document and proceed, `3` Investigate first. |
| A small phase, continue with the next? | `confirm` | |
| A spec gap only they can close | `text` | |
| Something learned for AGENTS.md | `confirm` | The proposed lines in `consequences`. |
Titles stay plain: "Which phase next", "Tests are failing", "Keep going?".
---
## Sign-off
Put the Completion Report on the page as a doc, then ask for approval as a
`review` item pointing at it. The review offer rides on this card, as a verdict
ahead of the approval buttons — not on the finish after it, where it could
only ever be offered once nothing could come of it:
```jsonc
{
"docs": [{ "id": "report", "title": "Completion report", "version": 1, "blocks": [
{ "id": "summary", "state": "settled", "md": "## Summary\n\n..." },
{ "id": "files", "state": "settled", "md": "## Files\n\n..." },
{ "id": "verify", "state": "settled", "md": "## How to check it\n\n..." }
]}],
"items": [{
"id": "signoff", "kind": "review", "title": "Approve this phase", "doc": "report",
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, or say what to change.",
"verdicts": [
{ "id": "review", "label": "Review the code first" },
{ "id": "approve", "label": "Approve this phase" },
{ "id": "changes", "label": "I want changes" }
],
"token": { "review": "review", "approve": "approved", "changes": "needs changes" },
"nothingYet": "Nothing is marked complete until you approve.",
"gate": { "id": "signoff", "authoritative": true },
"fallbackText": "Reply \"approved\" to mark this phase complete, \"review\" to run the code review first, or describe any issues."
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
`reply` carries `Approve this phase: approved`, which is the terminal's
`approved`. If the note that came with an approval asks for a change, treat it
as "describe any issues": do the change first and ask again. `changes` means
exactly what it says: address it, bump the report's version (a later phase's
report starts above the last one's, too), and reopen the
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
person asking for the code review before they approve anything — see "The
review, mid-session" below.
`gate` marks the one approval that counts. The server refuses a second open
authoritative gate, which is what keeps a composed workflow from asking for
sign-off twice.
---
## After approval: the finish
Do everything the workflow does on approval (the checkboxes, the summary, the
upcoming phases, the commit command) and print it in the terminal as usual.
Then post the finish, wait for the dashboard button as console.md → Finishing
says, and `stop`:
```jsonc
{
"items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "approve" } }],
"run": { "event": "implement-phase", "id": "phase-3", "tasks": 9 },
"finish": {
"headline": "Phase 3 is done",
"body": "9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```",
"command": "/plan2code-3-implement specs/lunch-vote/overview.md",
"doc": "report",
"dashboard": true
},
"agent": { "status": "waiting" }
}
```
`finish.command` is the next pipeline step, the same one the terminal names:
the next `/plan2code-3-implement`, or `/plan2code-4-finalize` after the last
phase. An `implement` finish never carries `review`: the offer was on the
sign-off card, and approving past it was the answer. `implement-review` ends
the same way; that phase was reviewed already. Only a finished `quick-task`
still offers the review on its finish — see below.
`run` gives the approved phase its final score on the session meter (console.md →
Posting an update → Session meter), in the same post that records the approval;
it takes over what the build already counted from `cleared`, never adds to it:
`implement-phase` for Implement, `implement-review-phase` for Implement +
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
twelve-task phase weighs four times a three-task one; leave `tasks` out and
every phase weighs the same. Quick task and a standalone Review are counted when
their session opens, so they post no `run` for that; a review run on the page
after a build reports its own (below).
---
## The review, mid-session
The same focused review runs from either of two doors:
- **`implement`:** the `review` verdict on the sign-off card, before anything
is approved. A note sent with it is theirs — read it as focus for the
review. Settle the card with it in the same post that goes back to work:
```jsonc
{
"items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "review" } }],
"headline": { "stage": "Reviewing Phase 3", "cleared": 0, "total": 0 },
"run": { "event": "review", "id": "review" },
"agent": { "status": "working", "activity": "Reviewing the 7 files this phase changed", "quietMinutes": 15 }
}
```
- **`quick-task`:** the **Review it now** button on the finished screen, which
`finish.review` puts there. It arrives through the wait loop as an action
`{ "i": "__review", "type": "review" }`, like any send. Take it up with the
same post minus the `items` line, plus `"finish": null` — that takes the
session off its ending and back to work.
Either way, the post that takes the review up carries `"run": { "event":
"review", "id": "review" }`: the review runs inside this skill's session, so no
launch scores it on the session meter. Never resume the session under
`--workflow review` for it as well, or it counts twice.
A finish carrying `review` keeps the session alive for the answer, so a
`quick-task` that just posted one keeps waiting, for up to about ten minutes.
A quick-task finish carries both `review` and `"dashboard": true` and waits
for whichever comes first:
| What arrives | What you do |
| --- | --- |
| An action `{ "i": "__review", "type": "review" }` | Take the review up (below). |
| An action `{ "i": "__dashboard", "type": "dashboard" }` | Take the session back as the dashboard (console.md → Finishing). |
| An action `{ "i": "__done", "type": "done" }` | `stop` the server. The session is over. |
| `wait` exit `20` | The server is gone, not necessarily the tab. Resume it (`open --resume <sid> --no-open --workflow <yours>`) and keep waiting. |
| Nothing after about ten minutes | `stop` the server. The page then shows the terminal command for a review instead of a button that would go nowhere. |
**Read references/review.md** and run Review Mode with these overrides:
- **Scope is Focused, and already decided:** the exact change set of this
session (files created or modified by the phase or the quick task, plus the
tests and docs changed for it). Do not ask about scope. Use overview.md and
the phase file for spec compliance; they do not widen the scope.
- **No commit instructions and no next-conversation routing** mid-review. The
way back out carries both.
- The page takes the whole report, so the "top 10 of 15+" rule does not apply,
and tables go in the doc.
### The findings
The full Review Mode report as a doc, and the fix choice as one `multi` item:
```jsonc
{
"docs": [{ "id": "review", "title": "Review findings", "version": 1, "blocks": [
{ "id": "report", "state": "settled", "md": "## Overview\n\n...\n\n## Findings\n\n| # | Severity | Issue | File |\n..." }
]}],
"items": [{
"id": "fixes", "kind": "multi", "title": "Which to fix", "required": false, "doc": "review",
"body": "Tick what should be fixed now. Anything left unticked is written up as still open. Nothing changes until you send.",
"options": [
{ "k": "1", "text": "Critical: token is logged in plain text", "detail": "src/auth.ts:42. Fix: redact before logging." },
{ "k": "2", "text": "Warning: missing null check on the user lookup", "detail": "src/users.ts:88. Fix: ..." },
{ "k": "3", "text": "Suggestion: repeated query could be batched", "detail": "src/report.ts:17. Fix: ..." }
],
"presets": [
{ "label": "Critical and warnings", "ks": ["1", "2"] },
{ "label": "All of them", "ks": ["1", "2", "3"] }
],
"token": { "1": "1", "2": "2", "3": "3" },
"fallbackText": "Reply H to fix Critical + Warning findings, A to fix all findings, or S 1,3,5 to fix specific findings."
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
`"doc": "review"` puts a **Read "Review findings" in full** button on the
card, so the report is one click from the list rather than behind a tab
nobody notices. Always carry it.
Read the reply as Review Mode's fix choice: `Which to fix: 1, 2` is `S 1,2`,
every finding ticked is `A`, and `skip` (or nothing ticked) is "fix none,
keep them as unresolved". Leave out `presets` a set would not change (no
warnings, one finding). With **zero findings** there is no item: say so in the
doc and go straight to the way back out.
### Fixing
Settle the `fixes` item in the same post that goes back to work —
`"status": "answered"` with the `answer` they sent (`{ "ks": ["1", "2"] }`,
or `{ "ks": [] }` when nothing was ticked). The server records their send on
the item, but only you decide it is settled; left open it stays on the page
as an outstanding question, beside the card you ask next. Then follow Review
Mode's Post-Fix Flow, posting `activity` per fix ("Fix 2 of 3: the null
check") and `quietMinutes` as in a build.
### The way back out
**`implement` — back to the sign-off.** The review was the preamble to an
approval that has not happened yet, so this is where it lands. Fold the review
results and any still-open findings into the report doc and bump it, then
reopen the sign-off **without the review verdict** — re-offering a review that
just ran reads as though nothing happened:
```jsonc
{
"items": [{ "id": "signoff", "status": "reopened",
"body": "Reviewed and ready for sign-off. The review found 3 issues: 2 fixed, 1 still open in the Review findings tab. The report is updated.",
"verdicts": [
{ "id": "approve", "label": "Approve this phase" },
{ "id": "changes", "label": "I want changes" }
],
"thread": [{ "who": "agent", "text": "Review done: 2 of 3 findings fixed; the rest is written up in the findings tab." }]
}],
"agent": { "status": "waiting", "quietMinutes": null }
}
```
Review Mode's own closing gate ("Reply approved to commit") is this card:
approving the phase now covers the fixes too, so there is no separate "Check
the fixes" step. On approval, continue at "After approval: the finish".
**`quick-task` — the closing gate, then the finish.** Review Mode's closing
gate ("Reply approved to commit, or request changes") becomes a `review` item
titled "Check the fixes", `doc: "review"`, verdicts `approve` ("The fixes look
right") and `changes`, token `approved` / `needs changes`. When it clears,
settle it in the same post as the new finish — `"status": "answered"` plus
`"answer": { "verdict": "approve" }` (or `"changes"`) — post the finish
**without** `review`, then `stop`. An item left open survives on the page as
a question still owed, above the ending itself:
- `headline`: "The review is done"
- `body`: findings by severity, what was fixed, what is still open, and the
commit command for the fixes, in the project's commit format.
- `command`: the same next step as the finish before it.
- `doc`: `"review"`.
---
## Implement + Review (`implement-review`)
The same build, then Stage 2 publishes the findings exactly as above (the
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
item: Stage 4 is the only gate. The post that starts Stage 2's review carries
`"run": { "event": "review", "id": "review" }`, as above: in this workflow it
scores the review stage's 1 point on the meter as it begins, and the phase's
final `run` leaves that point out. Stage 4 is the sign-off above **without the
review verdict** — the phase was already reviewed — with the review results
and unresolved findings in the report doc, header "Reviewed and ready for
sign-off" in the item's `body`. The finish never carries `review`, and its
post carries `"run": { "event": "implement-review-phase", "id": "phase-N", "tasks": N }`
with the count of completed tasks.
---
## Quick task (`quick-task`)
- Open with the first clarifying question. Clarifying questions go out as
`text` or `choice`, at most three at a time.
- Post `"stopWarning": "A quick task saves nothing until it is built, so stopping now loses what we have worked out."`
at the start, and `"stopWarning": ""` once the build is under way.
- **Scope check:** a `choice`, "Too big for a quick task?", options
`1` Continue (lightweight format) and `2` Escalate to a full plan, with the
measured counts against the thresholds in `body`.
- **Feature name** (escalating): `text` with
`"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"` and a kebab-case placeholder.
- **The plan:** a `plan` doc (Summary, Files to change, Steps, Verify) and a
`review` item "Build this plan?" with verdicts `yes` ("Build it"), `modify`
("Change the plan"), `escalate` ("Plan it properly instead") and `abort`
("Stop here", `"danger": true`), token equal to the ids.
- **Building** after `yes`: settle the verdict (`"status": "answered"` plus
`"answer": { "verdict": "yes" }`) in the post that starts the build, and
open a **Build progress** tab in that same post, the way an Implement phase
gets its tasks tab. The plan's steps are the task list and `total` is their
number:
```jsonc
{
"stopWarning": "",
"items": [{ "id": "<the Build this plan? item's id>", "status": "answered", "answer": { "verdict": "yes" } }],
"headline": { "stage": "Building", "cleared": 0, "total": 4 },
"docs": [{ "id": "tasks", "title": "Build progress", "version": 1, "blocks": [
{ "id": "tasks", "state": "settled", "md": "- [ ] Step one\n- [ ] Step two\n- [ ] Step three\n- [ ] Step four" }
]}],
"agent": { "status": "working", "activity": "Step 1 of 4: step one", "quietMinutes": 10 }
}
```
Then post after every step, exactly as "While you build": bump the doc's
`version` and repost the whole list with that step ticked, raise
`headline.cleared`, and set `agent.activity` to the next step ("Step 2 of 4:
step two"). Never go silent for the whole build: a quick task with many steps
is the case this tab is for. Check for a Quick question between steps, and do
not call `wait` until the build is done.
- **The finish after the build:** `command` is the commit command, filled in,
in the project's commit format (AGENTS.md), with
`"where": "When you are happy with it, commit it from your terminal:"`, and
`review` on offer — the **Review it now** button, since a quick task has no
sign-off card to put it on — and `"dashboard": true`, so the finished screen
also offers **Back to the dashboard**. Both are required: a finish without
`dashboard` leaves the person on a dead end. Keep waiting for whichever
button is pressed, and everything after that is "The review, mid-session"
above.
- **Escalated / aborted:** settle the verdict the same way in the finish post —
finish with `"command": "/plan2code-1-plan"` and the
PLAN-DRAFT's path in `body`, no review; or `"command": "/plan2code-quick-task"`.
Both set `"dashboard": true`: an abort of a quick task saves nothing to
resume, so it is not a pause.
---
## Stop requests during a build
The Stop button only works on the person's turn, so it never lands mid-task.
When `__stop` arrives:
- **implement / implement-review:** Implementation Mode's abort, without the
"are you sure" (the page asked): the phase stays `[/]`, list completed and
remaining tasks, post `finish` with the resume command
(`/plan2code-3-implement specs/<feature>/overview.md`), then `stop`. An
implement abort is a pause: a headline starting "Paused", no `dashboard`,
`stop` at once.
- **quick-task:** say in `finish.body` what was worked out, and that nothing was
saved unless it was built; `"command": "/plan2code-quick-task"`.
A mid-build `__dashboard` (the top bar's triangle, console.md → Stop requests →
"Back to the dashboard, mid-workflow") lands the same way, only on the person's
turn. Save exactly as for `__stop` above (an implement phase stays `[/]`), but
post no finish and do not `stop`: resume as the dashboard instead, with one
terminal line naming what was saved and the resume command.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,265 +0,0 @@
// Plan2Code Web Console - the native folder picker behind Workspace's Browse…
//
// A port of the launcher's picker (src/launcher/plan2code.js). The launcher
// is self-contained CommonJS copied alone to ~/.plan2code/bin/, and this
// console is ESM bundled into every skill, so the two cannot share a module:
// this is a copy, and a drift test in scripts/test-web-console.mjs fails the
// moment the launcher's picker changes without it. The prompt is a parameter
// here rather than the launcher's constant.
//
// Always spawned asynchronously: spawnSync would freeze the server's polling,
// chat and wait for as long as the dialog stayed open.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
const IS_WINDOWS = process.platform === "win32";
const IS_MAC = process.platform === "darwin";
export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace";
// Copied verbatim from src/launcher/plan2code.js; see the drift test.
export const WINDOWS_PICKER_SOURCE = `
using System;
using System.Runtime.InteropServices;
using System.Threading;
public static class Plan2CodeFolderPicker {
[ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
private class FileOpenDialog {}
[ComImport, Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IFileOpenDialog {
[PreserveSig] int Show(IntPtr owner);
void SetFileTypes(uint count, IntPtr specs);
void SetFileTypeIndex(uint index);
void GetFileTypeIndex(out uint index);
void Advise(IntPtr events, out uint cookie);
void Unadvise(uint cookie);
void SetOptions(uint options);
void GetOptions(out uint options);
void SetDefaultFolder(IShellItem item);
void SetFolder(IShellItem item);
void GetFolder(out IShellItem item);
void GetCurrentSelection(out IShellItem item);
void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
void GetResult(out IShellItem item);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem {
void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
void GetParent(out IShellItem parent);
void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name);
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
private static extern void SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid iid, out IShellItem item);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string className, string title);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int w, int h, uint flags);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int index);
private const uint FOS_PICKFOLDERS = 0x20;
private const uint FOS_FORCEFILESYSTEM = 0x40;
private const uint FOS_PATHMUSTEXIST = 0x800;
private const uint SIGDN_FILESYSPATH = 0x80058000;
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
private static void Raise(string title) {
for (int i = 0; i < 100; i++) {
IntPtr hwnd = FindWindow(null, title);
if (hwnd != IntPtr.Zero) {
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
int h = Math.Min(750, GetSystemMetrics(1) - 80);
int x = (GetSystemMetrics(0) - w) / 2 + 40;
int y = (GetSystemMetrics(1) - h) / 2 + 40;
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
SetForegroundWindow(hwnd);
return;
}
Thread.Sleep(50);
}
}
public static string Pick(IntPtr owner, string title, string start) {
IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
try {
uint options;
dialog.GetOptions(out options);
dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
dialog.SetTitle(title);
if (!string.IsNullOrEmpty(start)) {
try {
Guid iid = typeof(IShellItem).GUID;
IShellItem folder;
SHCreateItemFromParsingName(start, IntPtr.Zero, ref iid, out folder);
dialog.SetFolder(folder);
} catch (Exception) {}
}
Thread raiser = new Thread(delegate() { Raise(title); });
raiser.IsBackground = true;
raiser.Start();
int hr = dialog.Show(owner);
if (hr == ERROR_CANCELLED) return null;
Marshal.ThrowExceptionForHR(hr);
IShellItem result;
dialog.GetResult(out result);
string path;
result.GetDisplayName(SIGDN_FILESYSPATH, out path);
return path;
} finally {
Marshal.ReleaseComObject(dialog);
}
}
}
`;
// Resolve a command on PATH the way the shell would, including PATHEXT on Windows.
function findOnPath(command) {
const dirs = (process.env.PATH || "").split(path.delimiter).filter(Boolean);
const extensions = IS_WINDOWS ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [""];
for (const dir of dirs) {
for (const ext of extensions) {
const candidate = path.join(dir.replace(/^"|"$/g, ""), command + ext);
try {
if (fs.statSync(candidate).isFile()) return candidate;
} catch {}
}
}
return null;
}
/**
* The native folder picker for this OS, as a command to run: it prints the
* chosen folder, or nothing when the person cancels. Null when this OS has no
* picker we can drive.
*/
export function pickerCommand(start, prompt) {
if (IS_WINDOWS) {
const script = [
"$ErrorActionPreference = 'Stop'",
"try {",
" [Console]::OutputEncoding = [Text.Encoding]::UTF8",
" Add-Type -AssemblyName System.Windows.Forms",
" [System.Windows.Forms.Application]::EnableVisualStyles()",
// A TopMost owner keeps the dialog in front of the console window that launched it.
" $owner = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true; ShowInTaskbar = $false }",
" try {",
" Add-Type -TypeDefinition $env:PLAN2CODE_PICKER_SOURCE",
" $picked = [Plan2CodeFolderPicker]::Pick($owner.Handle, $env:PLAN2CODE_PICKER_PROMPT, $env:PLAN2CODE_PICKER_START)",
" } catch {",
// Add-Type is blocked under Constrained Language Mode and some AppLocker policies; the
// old tree dialog still works there.
" $dialog = New-Object System.Windows.Forms.FolderBrowserDialog",
" $dialog.Description = $env:PLAN2CODE_PICKER_PROMPT",
" $dialog.SelectedPath = $env:PLAN2CODE_PICKER_START",
" $picked = if ($dialog.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { $dialog.SelectedPath } else { $null }",
" }",
" if ($picked) { $picked }",
"} catch { exit 3 }",
].join("\n");
return {
command: "powershell.exe",
args: [
"-NoProfile",
"-NonInteractive",
"-STA",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
Buffer.from(script, "utf16le").toString("base64"),
],
env: {
PLAN2CODE_PICKER_PROMPT: prompt,
PLAN2CODE_PICKER_START: start,
PLAN2CODE_PICKER_SOURCE: WINDOWS_PICKER_SOURCE,
},
};
}
if (IS_MAC) {
return {
command: "osascript",
args: [
"-e",
"on run argv",
"-e",
`POSIX path of (choose folder with prompt "${prompt}" default location (POSIX file (item 1 of argv)))`,
"-e",
"end run",
start,
],
};
}
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return null;
if (findOnPath("zenity")) {
return {
command: "zenity",
args: ["--file-selection", "--directory", `--title=${prompt}`, `--filename=${start}${path.sep}`],
};
}
if (findOnPath("kdialog")) {
return { command: "kdialog", args: ["--title", prompt, "--getexistingdirectory", start] };
}
return null;
}
/**
* Show the picker and settle on what the person did: `{ path }` for a pick,
* `{ cancelled: true }` when they closed it, `{ error }` when the picker
* itself failed or this OS has none. Pickers exit 0 or 1 with nothing printed
* when cancelled.
*/
export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
const picker = pickerCommand(start, prompt);
if (!picker) return Promise.resolve({ error: "picker-failed" });
return new Promise((resolve) => {
let settled = false;
const settle = (result) => {
if (settled) return;
settled = true;
resolve(result);
};
let child;
try {
child = spawnImpl(picker.command, picker.args, {
env: { ...process.env, ...(picker.env || {}) },
// stderr is ignored, not piped: a pipe nobody reads fills up and
// blocks a chatty picker (GTK warnings) before it can exit.
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
});
} catch {
return settle({ error: "picker-failed" });
}
let stdout = "";
if (child.stdout) {
child.stdout.setEncoding?.("utf8");
child.stdout.on("data", (chunk) => (stdout += chunk));
}
child.on("error", () => settle({ error: "picker-failed" }));
child.on("close", (code) => {
const folder = stdout.trim();
if (code === 0 && folder) return settle({ path: path.resolve(folder) });
if (!folder && (code === 0 || code === 1)) return settle({ cancelled: true });
settle({ error: "picker-failed" });
});
});
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,138 +0,0 @@
// Planny's wake-up on a freshly opened dashboard: he sits powered down centre
// stage until the first click or key, gets nudged awake (he rocks side to side
// for one snore), then about five seconds of him powering on, then a glide
// into the rail as the menu comes in.
//
// The beats before the glide are pure CSS (keyframes on delays under
// `.wake.booting`, see app.css). The glide is the one part CSS cannot know on
// its own, because it ends wherever the rail's Planny sits right now, so this
// measures it once and hands CSS a single transform through --wake-glide.
//
// No DOM access at module scope, so `node --test` can import it.
// When the glide starts, and when the run is over at the latest. The CSS
// delays are the beats before GLIDE_AT_MS; the glide itself is 0.6 s.
export const GLIDE_AT_MS = 4300;
export const DONE_AT_MS = 5000;
// Plays the wake-up and resolves `{ skipped }` once the dashboard is fully
// awake. He waits powered down until the first click or key anywhere, which
// nudges him (`.stirring`) and calls `stir()` -- the page's cue to play one
// full snore, since a browser only lets a page make noise after a real click
// or keypress. The boot starts once the promise `stir()` returns settles (at
// once without one), and calls `onStart()`, the page's cue for the boot-up
// sound. `onGlide({ instant })` is the page's cue to bring the menu in: called
// at the glide, or with `instant: true` if the run ends before one (a skip).
// From the nudge on, clicks and keys are swallowed, so the run always plays
// out to the end with its sound; only `skipEl` (the muted Skip button, or the
// Escape key, for anyone without a mouse) and `signal` aborting (the page
// leaving the dashboard, dormant or mid-run) cut it short, as a skip.
// `onSkip` is the page's cue to silence the intro sounds
// once a skip lands. Under reduced motion nothing is shown and it resolves at
// once.
export function playWake({ stage, bot, target, skipEl, stir, onStart, onGlide, onSkip, signal }) {
return new Promise((resolve) => {
if (matchMedia("(prefers-reduced-motion: reduce)").matches || signal?.aborted) {
resolve({ skipped: false });
return;
}
const timers = [];
let glided = false;
let over = false;
const onGlideEnd = (e) => {
if (e.target === bot && e.propertyName === "transform") end(false);
};
const skip = () => end(true);
// The Skip button's events must reach it: the document handlers below run
// in the capture phase, ahead of the button's own click.
const hitsSkip = (e) => Boolean(skipEl && e.target instanceof Node && skipEl.contains(e.target));
const onSkipClick = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through;
// Escape skips, so the run can be left by keyboard too.
const swallow = (e) => {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
if (e.ctrlKey || e.metaKey || e.altKey) return;
e.preventDefault();
e.stopPropagation();
};
function glide() {
glided = true;
// Measured untransformed, as the sketch's glideToSlot() does: the
// transform-origin is the drawing's top-left, so the move is the gap
// between the two top-left corners and the scale is the width ratio.
// The target's own box, not its bounding rect: the rail's Planny is
// usually tilted mid-flight, and a tilted box measures wider than he
// is. Centred on the rect, which the tilt barely moves.
const from = bot.getBoundingClientRect();
const rect = target.getBoundingClientRect();
const w = target.clientWidth || rect.width;
const h = target.clientHeight || rect.height;
const left = rect.left + (rect.width - w) / 2;
const top = rect.top + (rect.height - h) / 2;
const scale = from.width ? w / from.width : 1;
bot.style.setProperty("--wake-glide", `translate(${left - from.left}px, ${top - from.top}px) scale(${scale})`);
bot.addEventListener("transitionend", onGlideEnd);
stage.classList.add("gliding");
onGlide({ instant: false });
}
function end(skipped) {
if (over) return;
over = true;
for (const t of timers) clearTimeout(t);
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
document.removeEventListener("pointerdown", swallow, true);
document.removeEventListener("keydown", swallow, true);
bot.removeEventListener("transitionend", onGlideEnd);
signal?.removeEventListener("abort", skip);
skipEl?.removeEventListener("click", onSkipClick);
if (skipped) onSkip?.();
stage.hidden = true;
stage.classList.remove("dormant", "stirring", "booting", "gliding");
bot.style.removeProperty("--wake-glide");
if (!glided) onGlide({ instant: true });
resolve({ skipped });
}
// The waking click is the only input the run takes: from here on every
// click and key is swallowed until it ends.
function start(e) {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
e.preventDefault();
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
stage.classList.replace("dormant", "stirring");
document.addEventListener("pointerdown", swallow, true);
document.addEventListener("keydown", swallow, true);
Promise.resolve(stir?.()).then(boot);
}
function boot() {
if (over) return;
stage.classList.replace("stirring", "booting");
onStart?.();
timers.push(setTimeout(glide, GLIDE_AT_MS));
// The glide's transitionend normally ends the run a touch earlier; this
// is the fallback for a transition that never fires (a hidden tab).
timers.push(setTimeout(() => end(false), DONE_AT_MS));
}
document.addEventListener("pointerdown", start, true);
document.addEventListener("keydown", start, true);
skipEl?.addEventListener("click", onSkipClick);
signal?.addEventListener("abort", skip);
stage.hidden = false;
stage.classList.add("dormant");
});
}
@@ -1,226 +0,0 @@
// Plan2Code Web Console - the Quick question chat's shared rules.
//
// Imported by the server (its guards) and by the page (its composer), so the
// two can never disagree about a limit. No DOM access at module scope, and no
// imports but answers.js: the server and `node --test` import this file too.
import { MAX_ATTACHMENTS, STALE_MS, quietLimitMs } from "./answers.js";
// Typed messages per conversation. Approve / Decline and resets never count.
export const CHAT_LIMIT = 10;
export const CHAT_MAX_CHARS = 4000;
// Images and documents together. The old name stays for existing imports.
export const CHAT_MAX_ATTACHMENTS = MAX_ATTACHMENTS;
export const CHAT_MAX_IMAGES = CHAT_MAX_ATTACHMENTS;
export const CHAT_LIMIT_TEXT = "That's 10 questions in this conversation — start a new one to keep going.";
export const CHAT_OFFLINE_TEXT = "No agent available — wait for one to become available (your terminal might be working on a task or waiting a permission approval)";
export const CHAT_LAST_WAIT_TEXT = "That was the last question in this conversation — its answer will land here.";
export const CHAT_WAITING_TEXT = "Plan2Code will answer at its next check-in";
export const CHAT_WORKING_TEXT = "Plan2Code is working on the answer…";
const EMPTY_CHAT = { conversation: 0, messages: [], typed: 0, limit: CHAT_LIMIT, offline: false, pickedUp: 0 };
const chatOf = (frameChat) => ({ ...EMPTY_CHAT, ...(frameChat || {}) });
// Person messages in the frame, each marked with whether an agent reply comes
// after it. The server puts a reply straight after the entry it answers, so a
// reply further down also covers the follow-ups sent before it.
function answeredFlags(messages) {
const flags = new Map();
let replyLater = false;
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m.from === "agent") replyLater = true;
else if (m.kind === "message") flags.set(m.seq, replyLater);
}
return flags;
}
/**
* What the Ask pane draws, in order: the conversation from the frame, then
* any send of this page's the server has not echoed yet.
*/
export function chatView(frameChat, ui = {}) {
const chat = chatOf(frameChat);
const messages = Array.isArray(chat.messages) ? chat.messages : [];
const answered = answeredFlags(messages);
const decisions = new Map(
messages.filter((m) => m.from === "person" && m.kind === "decision").map((m) => [m.re, m.decision])
);
const activity = typeof ui.agentActivity === "string" ? ui.agentActivity.trim() : "";
// The last seq the agent collected: an unanswered message at or below it is
// in the agent's hands, not still waiting for a check-in.
const pickedUp = Number.isInteger(chat.pickedUp) ? chat.pickedUp : 0;
const rows = [];
for (const m of messages) {
if (m.from === "agent") {
rows.push({
kind: "agent",
id: m.id,
md: m.md,
proposal: m.proposal || null,
changed: m.changed || null,
decided: decisions.get(m.id) || null,
});
} else if (m.kind === "decision") {
rows.push({ kind: "decision", decision: m.decision, text: m.text || "", re: m.re });
} else if (m.kind === "message") {
const row = {
kind: "person",
seq: m.seq,
text: m.text,
about: m.about || null,
images: m.images || [],
files: m.files || [],
};
if (!answered.get(m.seq)) {
row.waiting = true;
row.working = m.seq <= pickedUp;
row.waitingText = row.working ? CHAT_WORKING_TEXT : CHAT_WAITING_TEXT;
if (activity) row.activity = activity;
}
rows.push(row);
}
}
// A pending send is echoed once the server has it: by the seq its POST came
// back with, or, while that response is still on its way, by its text
// against a server message no other pending send has claimed.
const serverPerson = messages.filter((m) => m.from === "person" && m.kind === "message");
const serverSeqs = new Set(serverPerson.map((m) => m.seq));
const claimed = new Set((ui.pendingSends || []).filter((p) => p.seq).map((p) => p.seq));
for (const p of ui.pendingSends || []) {
if (p.seq) {
if (serverSeqs.has(p.seq)) continue;
} else {
const echo = serverPerson.find((m) => m.text === p.text && !claimed.has(m.seq));
if (echo) {
claimed.add(echo.seq);
continue;
}
}
rows.push({
kind: "person",
pending: true,
tempId: p.tempId,
text: p.text,
about: p.about || null,
images: p.images || [],
files: p.files || [],
failed: Boolean(p.failed),
});
}
return {
conversation: chat.conversation,
rows,
counterText: `${chat.typed} of ${chat.limit}`,
typed: chat.typed,
limit: chat.limit,
};
}
/**
* Whether the composer can take a message, and what to say when it cannot.
* Offline first, so a finished page never talks about the limit. The limit
* lands once the 10th question is answered; until then the 10th is simply
* waiting, and nothing more can be typed.
*/
export function sendState({ frameChat, gone, pendingSendCount = 0 }) {
const chat = chatOf(frameChat);
if (chat.offline || gone) return { state: "offline", text: CHAT_OFFLINE_TEXT, canType: false };
if (chat.typed + pendingSendCount >= chat.limit) {
const allAnswered = pendingSendCount === 0 && [...answeredFlags(chat.messages || []).values()].every(Boolean);
if (allAnswered) return { state: "limit", text: CHAT_LIMIT_TEXT, canType: false };
return { state: "ok", text: CHAT_LAST_WAIT_TEXT, canType: false };
}
return { state: "ok", text: "", canType: true };
}
const ABOUT_HISTORY = 3;
/**
* What a message is about, attached on purpose. Visiting a question card, doc
* section or spec only records it in `history` (the last 3 places, newest
* first, one entry per place); `about` is set only when the person picks one
* from + Add context, and × or a send clears it.
*
* The tracker is `{ history, about }`; each entry and `about` are
* `{ kind, id, label }` (`about` may be null), in the exact shape POST /chat
* takes. An old `{ about, frozen, dropped }` tracker normalises to an empty
* history.
*/
export function nextAbout(prev, event) {
const p = prev || {};
const state = { history: Array.isArray(p.history) ? [...p.history] : [], about: p.about ?? null };
const visit = (entry) => ({
...state,
history: [entry, ...state.history.filter((h) => h.kind !== entry.kind || h.id !== entry.id)].slice(0, ABOUT_HISTORY),
});
switch (event && event.type) {
case "card":
return visit({ kind: "card", id: String(event.id), label: String(event.label || "") });
case "section":
return visit({ kind: "section", id: `${event.docId}#${event.blockId}`, label: String(event.label || "") });
case "spec":
return visit({ kind: "spec", id: String(event.dir), label: String(event.label || "") });
case "pick":
return event.about ? { ...state, about: event.about } : state;
case "drop":
case "sent":
return { ...state, about: null };
default:
return state;
}
}
// What + Add context lists: the recent places, then "This spec" unless it is
// already one of them.
export function contextOptions(state, spec) {
const options = [...((state && state.history) || [])];
if (spec && spec.dir && !options.some((o) => o.kind === "spec" && o.id === spec.dir)) {
options.push({ kind: "spec", id: spec.dir, label: "This spec" });
}
return options;
}
const newestReply = (frameChat) => {
const messages = chatOf(frameChat).messages || [];
for (let i = messages.length - 1; i >= 0; i--) if (messages[i].from === "agent") return messages[i];
return null;
};
// The Ask tab's dot: a reply landed that the person has not seen.
export function unreadDot({ lastSeenReplyId, frameChat, viewIsAsk }) {
if (viewIsAsk) return false;
const reply = newestReply(frameChat);
return Boolean(reply) && reply.id !== lastSeenReplyId;
}
export function newestReplyId(frameChat) {
const reply = newestReply(frameChat);
return reply ? reply.id : null;
}
// One chime per reply: only the moment the dot appears.
export function shouldChime(prevDot, nextDot) {
return !prevDot && Boolean(nextDot);
}
// The page's own "has drifted away" threshold for an agent that is waiting.
const ADRIFT_MS = 3 * 60 * 1000;
/**
* Whether nobody is there to answer a chat message. A finished session's agent
* is often still listening through its last wait (the review and dashboard
* buttons on the hand-off card live as long as it does), so finish alone does
* not end the chat — going quiet does. Offline once the agent has been silent
* longer than the page would tolerate before calling it stuck (working) or
* adrift (anything else), which is also the only signal left once the server
* is gone.
*/
export function chatOffline({ finish, agent, agentLastSeenMs, now }) {
const silent = now - agentLastSeenMs;
if (agent && agent.status === "working") return silent > quietLimitMs(agent, STALE_MS);
return silent > quietLimitMs(agent, ADRIFT_MS);
}
@@ -1,90 +0,0 @@
// Plan2Code Web Console - the tab icon's status bar.
//
// The favicon follows the status line with a bar along its bottom edge: dashed
// amber while Plan2Code is busy, solid green when it is the person's move,
// solid red when it needs attention, and none (the plain Planny) once the
// session is finished. It reads from the same calls
// renderStatus() already makes for Planny's mood, so the icon and the line
// beside him can never disagree. No DOM access at module scope: `node --test`
// imports this file.
// Planny exactly as public/favicon.svg draws him (a test keeps the two in
// step), minus the <svg> wrapper so the bar can be layered on top.
export const FAVICON_BODY = `<rect x="4" y="4.6" width="24" height="30" rx="5" fill="#fff4ef" stroke="#3b332c" stroke-width="2.2" />
<path d="M16 9.8 L17.41 13.26 L21.14 13.53 L18.28 15.94 L19.17 19.57 L16 17.6 L12.83 19.57 L13.72 15.94 L10.86 13.53 L14.59 13.26 Z" fill="#ae4f2b" />
<path d="M11.6 22.2 Q16 26.4 20.4 22.2" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />`;
// The bar's color per state. `plain` has none.
export const FAVICON_COLORS = Object.freeze({
busy: "#f5a524",
ready: "#22c55e",
attention: "#e5484d",
});
/**
* Which icon a status line calls for. `mood` and `spin` are what renderStatus()
* handed to say(): `spin` marks something really happening at the other end
* right now, so that is busy. A working mood without the spin is the stale
* line ("has not checked in for a few minutes"), which, like adrift and gone,
* needs attention. `point` is the person's move. A finished session is plain
* unless it is visibly busy again (opening the dashboard, starting a review).
*/
export function faviconState({ mood, spin = false, finished = false } = {}) {
if (spin) return "busy";
if (finished) return "plain";
if (mood === "adrift" || mood === "gone" || mood === "work") return "attention";
if (mood === "point") return "ready";
return "plain";
}
/**
* The whole SVG for a state: Planny, plus a bar across the bottom edge, where
* he is cropped anyway. Busy's bar is dashed on a white strip (a progress bar
* mid-run) and the others solid, so busy differs by pattern as well as color:
* amber and green are close to one color for red-green color-blind eyes.
*/
export function faviconSvg(state) {
const color = FAVICON_COLORS[state];
let badge = "";
if (state === "busy") {
badge = `\n <rect x="0" y="27" width="32" height="5" fill="#ffffff" />\n <path d="M1.5 29.5 L30.5 29.5" stroke="${color}" stroke-width="4" stroke-dasharray="4 2.5" />`;
} else if (color) {
badge = `\n <rect x="0" y="27" width="32" height="5" rx="1" fill="${color}" />`;
}
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">\n ${FAVICON_BODY}${badge}\n</svg>\n`;
}
let shown = "plain";
/**
* Point the page's two icon links at `state`'s icon, only when it changed. The
* SVG link takes the variant as a data URL; the PNG link, for browsers that
* pick the bitmap, gets the same variant drawn through a canvas. Plain goes
* back to the served files.
*/
export function setFavicon(state) {
if (state === shown || typeof document === "undefined") return;
shown = state;
const svgLink = document.querySelector('link[rel="icon"][type="image/svg+xml"]');
const pngLink = document.querySelector('link[rel="icon"][type="image/png"]');
if (state === "plain") {
if (svgLink) svgLink.href = "/favicon.svg";
if (pngLink) pngLink.href = "/favicon.png";
return;
}
const url = "data:image/svg+xml," + encodeURIComponent(faviconSvg(state));
if (svgLink) svgLink.href = url;
if (!pngLink) return;
const img = new Image();
img.onload = () => {
// A newer state won the race while this one was loading.
if (shown !== state) return;
try {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 64;
canvas.getContext("2d").drawImage(img, 0, 0, 64, 64);
pngLink.href = canvas.toDataURL("image/png");
} catch {}
};
img.src = url;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

@@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<rect x="4" y="4.6" width="24" height="30" rx="5" fill="#fff4ef" stroke="#3b332c" stroke-width="2.2" />
<path d="M16 9.8 L17.41 13.26 L21.14 13.53 L18.28 15.94 L19.17 19.57 L16 17.6 L12.83 19.57 L13.72 15.94 L10.86 13.53 L14.59 13.26 Z" fill="#ae4f2b" />
<path d="M11.6 22.2 Q16 26.4 20.4 22.2" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />
</svg>

Before

Width:  |  Height:  |  Size: 443 B

@@ -1,67 +0,0 @@
// Plan2Code Web Console - the Help dialog's tab list and rules.
//
// The source of truth for which tabs Help has, in what order, and which one
// opens. The content itself is HTML in <template id="help-content">
// in index.html. No DOM access at module scope and no imports: the page and
// `node --test` both import this file.
const tab = (id, label, diagram) => Object.freeze({ id, label, diagram });
export const HELP_TABS = Object.freeze([
tab("about", "What this page is", true),
tab("around", "Finding your way around", true),
tab("workspace", "Your workspace", false),
tab("planny", "Reading Planny", true),
tab("answering", "Answering questions", false),
tab("sending", "Sending and what happens next", true),
tab("notes", "Notes and attachments", false),
tab("docs", "Documents and printing", false),
tab("dashboard", "The dashboard", true),
tab("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
tab("finishing", "Stopping and finishing", false),
tab("stuck", "When something looks stuck", true),
tab("prefs", "Keyboard and preferences", false),
tab("privacy", "Privacy and where things are saved", false),
]);
// Not labels.js's BUILD_WORKFLOWS: that one leaves out quick-task, which is a
// build as far as the person watching it is concerned.
const HELP_BUILD_WORKFLOWS = new Set(["implement", "implement-review", "quick-task"]);
// Which tab Help opens on, from where the person is. First match wins.
export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow, workspace, meterRed } = {}) {
const v = view || "";
// Finished comes first: a finished session's server is stopped on purpose,
// which also sets `gone`, and that is not something being stuck.
if (finished || v === "end") return "finishing";
if (gone || adrift) return "stuck";
if (workspace) return "workspace";
if (v === "ask") return "ask";
if (v === "subagents") return "subagents";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v.startsWith("doc:")) return "docs";
if (HELP_BUILD_WORKFLOWS.has(workflow)) return "build";
return "about";
}
// The tab index a key moves to, or -1 when the key is not a tab key.
export function helpKeyTarget(key, index, count) {
switch (key) {
case "ArrowDown":
case "ArrowRight":
return (index + 1) % count;
case "ArrowUp":
case "ArrowLeft":
return (index - 1 + count) % count;
case "Home":
return 0;
case "End":
return count - 1;
default:
return -1;
}
}
File diff suppressed because it is too large. Load diff
@@ -1,31 +0,0 @@
// Activity-line wording the page corrects on the way in. Kept out of app.js so
// `node --test` can import it: no DOM access at module scope.
//
// A build numbers its tasks "Task 4.2" after the phase, but a person watching
// the page counts within the phase, so "Task 4.2 of 6" reads as nonsense
// beside a progress bar that says 2 of 6.
// The only workflows whose activity lines get rewritten.
export const BUILD_WORKFLOWS = new Set(["implement", "implement-review"]);
const PHASE_TASK = /^Task (\d+)\.(\d+) of (\d+)/;
export function taskLabel(text) {
if (typeof text !== "string" || !PHASE_TASK.test(text)) return text;
return text.replace(PHASE_TASK, (_, _phase, n, total) => `Task ${n} of ${total}`);
}
// An activity line as the page shows it: rewritten in a build, as sent
// everywhere else (a plan's "Task 2.1" is a real section number).
export function activityLabel(text, workflow) {
return BUILD_WORKFLOWS.has(workflow) ? taskLabel(text) : text;
}
// What a working agent is doing, for a page with nothing asked yet: its
// activity line, or the headline note it posted instead. Either one means the
// skill has started, so the page leaves its starting screen.
export function workingLine(agent, headline, workflow) {
if (!agent || agent.status !== "working") return "";
if (typeof agent.activity === "string" && agent.activity.trim()) return activityLabel(agent.activity.trim(), workflow);
return typeof headline?.note === "string" ? headline.note.trim() : "";
}
@@ -1,46 +0,0 @@
// Plan2Code Web Console - `@name` suggestions in a text box.
//
// Finds the `@partial` the caret sits in, filters the workspace's folder
// names against it, and splices a pick back into the text. The page owns the
// popover; this file owns the rules. No DOM access at module scope and no
// imports: the page and `node --test` both import this file.
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
// by the workspace rules, and a query typed with a capital otherwise matches
// nothing and opens no suggestions at all.
const NAME_CHAR = /[a-z0-9-]/i;
const MAX_MATCHES = 6;
/**
* The mention the caret is in: `{ start, query }`, where `start` is the index
* of the `@`, or null. The `@` must open the text or follow whitespace or
* `(`, so an email address never offers suggestions.
*/
export function mentionAt(text, caret) {
let i = caret;
while (i > 0 && NAME_CHAR.test(text[i - 1])) i--;
const at = i - 1;
if (at < 0 || text[at] !== "@") return null;
if (at > 0 && !/[\s(]/.test(text[at - 1])) return null;
return { start: at, query: text.slice(i, caret) };
}
// Names starting with the query first, then names containing it, in the
// order given, at most six. Case-folded: folder names are lowercase by rule,
// and "@Repo" should still find @repo rather than claim nothing matches.
export function matchNames(names, query) {
const q = String(query || "").toLowerCase();
const fold = (n) => String(n).toLowerCase();
const prefix = names.filter((n) => fold(n).startsWith(q));
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
return [...prefix, ...inside].slice(0, MAX_MATCHES);
}
// The text with `@partial` replaced by `@name `, and the caret after the space.
export function applyMention(text, caret, mention, name) {
const insert = `@${name} `;
return {
text: text.slice(0, mention.start) + insert + text.slice(caret),
caret: mention.start + insert.length,
};
}
@@ -1,306 +0,0 @@
// Plan2Code Web Console - the session meter's weights, count and wording.
//
// The source of truth for how much each piece of work weighs, how the count
// is folded out of ledger.ndjson, and what the pill says at each level. The
// count is never stored: it is always pointsFrom() over the ledger. No DOM
// access at module scope and no imports: the server, console.mjs, the page
// and `node --test` all import this file.
// The one place the weights live (FR-12). Tune here.
export const WEIGHTS = Object.freeze({
"pathfinder-chart": 2,
// Scores 0: a Pathfinder question now counts through its answers (below).
"pathfinder-question": 0,
// Research reads sources and hands its findings back into the context, with
// nobody answering anything, so each research question scores on its own.
"pathfinder-research": 1,
plan: 2,
"revise-plan": 1,
document: 2,
"implement-phase": 2,
"implement-review-phase": 3,
review: 2,
"quick-task": 1,
init: 2,
"init-update": 2,
finalize: 1,
handoff: 0,
});
// Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder,
// implement and implement-review score only through the agent's `run`
// reports; dashboard and handoff never score.
export const LAUNCH_COUNTED = Object.freeze(
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize"])
);
const weightOf = (key) => (Object.prototype.hasOwnProperty.call(WEIGHTS, key) ? WEIGHTS[key] : 0);
// The event names an agent may report in `run`.
export const RUN_EVENTS = new Set(Object.keys(WEIGHTS));
// Built phases weigh what they did: a `run` for one of these may carry
// `tasks`, the tasks the phase completed, and then scores one point per
// TASKS_PER_POINT tasks (rounded up, at least 1), plus the event's
// TASK_BONUS for work every phase does whatever its size (the review). A
// run without `tasks` falls back to WEIGHTS. Tune here.
export const TASKS_PER_POINT = 3;
export const TASK_BONUS = Object.freeze({
"implement-phase": 0,
"implement-review-phase": 1,
});
export const TASK_EVENTS = Object.freeze(new Set(Object.keys(TASK_BONUS)));
// The most tasks one run may report: past this it is a typo, not a phase.
export const MAX_TASKS = 999;
// A build scores while it runs, not only once it is approved: console.mjs
// writes a `progress` ledger entry whenever a build's `headline.cleared`
// rises, and the build's row scores those tasks at TASKS_PER_POINT with no
// bonus. The phase's `run` then takes the row over with its final score, so
// the total only ever climbs. Workflows whose headline counts tasks:
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(["implement", "implement-review"]));
// Implement + Review reviews every phase as a stage of the build. A `review`
// run inside it is that stage, so it scores the phase's TASK_BONUS when it
// starts, and the phase's own run leaves the bonus out after it.
const BUILT_IN_REVIEW = Object.freeze({ "implement-review": "implement-review-phase" });
/**
* The ledger entry a build's progress post stands for, or null when it adds
* nothing: not a task-counting workflow, no whole `cleared`, or no more tasks
* than this build already has. `seg` is how many phases this skill run has
* finished, so a second phase in the same run starts its own count, but only
* once its headline is back at 0: until then a `cleared` is the finished
* phase's, posted again, and opening a build on it would count it twice.
*/
export function progressEntry(entries, launch, workflow, cleared) {
if (!PROGRESS_WORKFLOWS.has(workflow)) return null;
if (cleared !== 0 && !isTaskCount(cleared)) return null;
const list = Array.isArray(entries) ? entries : [];
const seg = list.filter((e) => e && e.kind === "run" && TASK_EVENTS.has(e.event) && launchOf(e.id) === launch).length;
const build = `${launch}:b${seg}`;
const mine = list.filter((e) => e && e.kind === "progress" && e.build === build);
const entry = (tasks) => ({ kind: "progress", id: `${build}:${tasks}`, build, workflow, tasks });
if (cleared === 0) return seg > 0 && !mine.length ? entry(0) : null;
if (seg > 0 && !mine.length) return null;
const most = mine.reduce((n, e) => Math.max(n, e.tasks), 0);
return cleared > most ? entry(cleared) : null;
}
/** A valid `run.tasks`: a whole number from 1 to MAX_TASKS. */
export function isTaskCount(tasks) {
return Number.isInteger(tasks) && tasks >= 1 && tasks <= MAX_TASKS;
}
/**
* What one `run` scores, from its event and (for a built phase) its tasks.
* `bonus: false` leaves the review bonus out, for a phase whose review
* already scored.
*/
export function runPoints(event, tasks, { bonus = true } = {}) {
if (TASK_EVENTS.has(event) && isTaskCount(tasks)) {
return Math.ceil(tasks / TASKS_PER_POINT) + (bonus ? TASK_BONUS[event] : 0);
}
if (TASK_EVENTS.has(event) && !bonus) return weightOf(event) - TASK_BONUS[event];
return weightOf(event);
}
// Back-and-forth weighs what it took: every answer the person sends from a
// card is an `answer` ledger entry (console.mjs writes one per answered item
// when the agent collects a send), and each skill run scores one point per
// ANSWERS_PER_POINT answers, rounded down. Tune here.
export const ANSWERS_PER_POINT = 2;
// The skill names the answers row uses ("7 answers in Plan").
const WORKFLOW_NAMES = Object.freeze({
dashboard: "the dashboard",
pathfinder: "Pathfinder",
plan: "Plan",
"revise-plan": "Revise plan",
document: "Document",
implement: "Implement",
"implement-review": "Implement + Review",
review: "Review",
"quick-task": "Quick task",
init: "Init",
"init-update": "Init update",
finalize: "Finalize",
handoff: "Handoff",
});
// The skill run an entry belongs to, from its ledger id ("L3:..." -> "L3").
const launchOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(0, id.indexOf(":")) : "L0");
// What each scoring event is called in the meter's list of contributions.
const LAUNCH_LABELS = Object.freeze({
plan: "Plan started",
"revise-plan": "Revise plan started",
document: "Document started",
review: "Review started",
"quick-task": "Quick task started",
init: "Init started",
"init-update": "Init update started",
finalize: "Finalize started",
});
const RUN_LABELS = Object.freeze({
"pathfinder-chart": "Pathfinder map written",
"pathfinder-question": "Pathfinder question settled",
"pathfinder-research": "Pathfinder research done",
plan: "Plan drafted",
"revise-plan": "Plan revised",
document: "Spec documented",
"implement-phase": "Implement phase built",
"implement-review-phase": "Implement + Review phase built",
review: "Code review run",
"quick-task": "Quick task built",
init: "Init run",
"init-update": "Init update run",
finalize: "Finalize run",
handoff: "Handoff written",
});
// The unit a run names, from its ledger id ("L3:phase-2" -> "phase-2").
const unitOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(id.indexOf(":") + 1) : "");
/**
* What the count is made of: one { label, points } per ledger entry that
* scored, in order, and one row per skill run for its answers, where its
* first answer came. An id seen before is skipped, so a repeated `post` never
* counts twice. Entries that weigh nothing are left out.
*/
export function breakdownFrom(entries) {
const seen = new Set();
const rows = [];
const answers = new Map(); // launch id -> { row, count, workflow }
const builds = new Map(); // launch id -> the row of the build in progress
const reviewed = new Set(); // launch ids whose built-in review has scored
for (const entry of Array.isArray(entries) ? entries : []) {
if (!entry || typeof entry !== "object") continue;
if (entry.id !== undefined) {
if (seen.has(entry.id)) continue;
seen.add(entry.id);
}
if (entry.kind === "answer") {
const launch = launchOf(entry.id);
let tally = answers.get(launch);
if (!tally) {
tally = { row: { label: "", points: 0 }, count: 0, workflow: entry.workflow };
answers.set(launch, tally);
rows.push(tally.row);
}
tally.count += 1;
continue;
}
if (entry.kind === "progress") {
if (!isTaskCount(entry.tasks)) continue;
const launch = launchOf(entry.id);
let row = builds.get(launch);
if (!row || row.build !== entry.build) {
row = { label: "", points: 0, build: entry.build, tasks: 0 };
builds.set(launch, row);
rows.push(row);
}
if (entry.tasks > row.tasks) {
row.tasks = entry.tasks;
row.points = Math.ceil(entry.tasks / TASKS_PER_POINT);
const where = WORKFLOW_NAMES[entry.workflow] || "Build";
row.label = `${where}: ${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"} built so far`;
}
continue;
}
let points = 0;
let label = "";
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
points = weightOf(entry.workflow);
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
} else if (entry.kind === "run") {
const launch = launchOf(entry.id);
const builtIn = BUILT_IN_REVIEW[entry.workflow];
if (entry.event === "review" && builtIn) {
// The review stage of Implement + Review: it scores the bonus its
// phase would otherwise carry, once per skill run.
if (reviewed.has(launch)) continue;
reviewed.add(launch);
points = TASK_BONUS[builtIn];
label = `${WORKFLOW_NAMES[entry.workflow]}: code review run`;
} else {
const bonus = !(TASK_EVENTS.has(entry.event) && reviewed.has(launch));
points = runPoints(entry.event, entry.tasks, { bonus });
const unit = unitOf(entry.id);
const counted = TASK_EVENTS.has(entry.event) && isTaskCount(entry.tasks);
const size = counted ? ` (${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"})` : "";
label = (RUN_LABELS[entry.event] || entry.event) + (unit && unit !== entry.event ? `: ${unit}` : "") + size;
}
// A finished phase takes over its build's progress row, in place.
if (TASK_EVENTS.has(entry.event) && builds.has(launch)) {
const row = builds.get(launch);
builds.delete(launch);
row.label = label;
row.points = Math.max(points, row.points);
continue;
}
}
if (points > 0) rows.push({ label, points });
}
for (const { row, count, workflow } of answers.values()) {
row.points = Math.floor(count / ANSWERS_PER_POINT);
const where = WORKFLOW_NAMES[workflow] ? ` in ${WORKFLOW_NAMES[workflow]}` : "";
row.label = `${count} ${count === 1 ? "answer" : "answers"}${where}`;
}
return rows.filter((row) => row.points > 0).map(({ label, points }) => ({ label, points }));
}
/** The session's points, folded from ledger entries in order. */
export function pointsFrom(entries) {
return breakdownFrom(entries).reduce((sum, row) => sum + row.points, 0);
}
export const YELLOW_AT = 5;
export const RED_AT = 10;
export const RING_FULL = 15;
export function levelFor(points) {
if (points < YELLOW_AT) return "green";
if (points < RED_AT) return "yellow";
return "red";
}
// How much of the ring is filled: full at RING_FULL, never below empty.
export function ringFraction(points) {
return Math.max(0, Math.min(points, RING_FULL)) / RING_FULL;
}
export const WORDS = Object.freeze({
green: "Session: fresh",
yellow: "Session: getting long",
red: "Session: time for a fresh start",
});
export function tooltipFor(points) {
const count = `${points} ${points === 1 ? "point" : "points"}`;
switch (levelFor(points)) {
case "green":
return `This session is fresh (${count}).`;
case "yellow":
return `This session is getting long (${count}). A fresh one will soon be sharper.`;
default:
return `This session has done a lot (${count}). The agent may start missing things.`;
}
}
export const RED_BANNER =
"This console session has done a lot. Starting a new console session will keep the agent sharp.";
// Everything the pill draws, from the ledger alone.
export function meterView(entries) {
const points = pointsFrom(entries);
const level = levelFor(points);
return {
points,
level,
fraction: ringFraction(points),
words: WORDS[level],
tooltip: tooltipFor(points),
items: breakdownFrom(entries),
};
}
Loaded 100 of 592 files, more files were not shown because too many files have changed in this diff. Show more