Add Diagnose and X-ray, shared building habits, fresh-helper reviews, and a Bug fixed spec state

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-16 19:28:11 -07:00
1 parent 80ae3decdd
commit 33a0dbd34a
58 files changed
+3270 -236

No files matched your search

+93 -9
View File
@@ -22,6 +22,11 @@
* `--pick-folder` (passed by the desktop shortcut, never forwarded to the CLI) asks for the
* project folder with a native folder picker first, starting on the folder picked last time.
*
* `plan2code update` starts no agent: it re-runs the npx install with `--update`, which
* reinstalls whatever ~/.plan2code/install.json lists. Before an agent starts, one line says
* when a newer release is out (releaseNotice), read from the web console's cached release check
* and never waiting on the network.
*
* On a terminal it opens with a Planny banner (renderBanner) and colors its headings, numbers,
* defaults and errors (paint). Color is on only on a TTY (stdout and stderr each checked on
* its own) with NO_COLOR unset; piped runs print plain text and no banner.
@@ -41,6 +46,15 @@ const STATE_FILE = path.join(os.homedir(), '.plan2code', 'launcher.json');
// Menus longer than this print compactly (id-only, two columns).
const MODELS_MENU_COMPACT_AT = 30;
const PICKER_PROMPT = 'Choose the project folder to open Plan2Code in';
const UPDATE_COMMAND = 'update';
// The same URL src/web-console/update-check.mjs exports as REPO_URL. This file may require
// nothing but Node built-ins (and update-check.mjs is ESM), so it keeps its own copy.
const REPO_URL = 'https://github.com/jparkerweb/plan2code.git';
// The web console's cached release check, and how long it counts as fresh (update-check.mjs
// CACHE_MS). PLAN2CODE_CONSOLE_HOME moves the console's files, as in lib.mjs.
const CONSOLE_HOME = process.env.PLAN2CODE_CONSOLE_HOME || path.join(os.homedir(), '.plan2code', 'console');
const UPDATE_CACHE_FILE = path.join(CONSOLE_HOME, 'update-check.json');
const UPDATE_CACHE_MS = 60 * 60 * 1000;
// The escape values install.js's COLORS uses, copied: this file is installed alone and may
// require nothing but Node built-ins.
@@ -608,12 +622,89 @@ async function exitWith(code, fromShortcut) {
process.exit(code);
}
/**
* Spawn a resolved command with `args`. A .cmd/.bat wrapper on Windows goes through cmd.exe,
* since Node refuses to spawn one without a shell.
*/
function spawnCommand(file, args, options) {
return IS_WINDOWS && /\.(cmd|bat)$/i.test(file)
? spawn(
process.env.ComSpec || 'cmd.exe',
['/d', '/s', '/c', `"${[file, ...args].map(quoteForCmd).join(' ')}"`],
{ ...options, windowsVerbatimArguments: true }
)
: spawn(file, args, options);
}
/** `plan2code update`: the npx install with --update, passing npx's exit code through. No agent starts. */
function runUpdate() {
console.log('Updating Plan2Code...');
const npx = findOnPath('npx');
if (!npx) {
console.error(`${ce.red('plan2code:')} npx was not found on your PATH. It comes with Node.js 18+ (https://nodejs.org).`);
return process.exit(127);
}
const child = spawnCommand(npx, ['--yes', '--allow-git=all', `git+${REPO_URL}`, '--update'], { stdio: 'inherit' });
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
process.on(signal, () => {});
}
child.on('error', (error) => {
console.error(`${ce.red('plan2code:')} failed to start npx: ${error.message}`);
process.exit(1);
});
child.on('exit', (code) => process.exit(code ?? 1));
}
/** -1, 0 or 1 comparing two plain X.Y.Z versions; null unless both are X.Y.Z (as update-check.mjs). */
function compareVersions(a, b) {
const semver = /^\d+\.\d+\.\d+$/;
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;
}
/**
* One line when a newer release is out, from the console's cached check only. A missing or
* stale cache prints nothing and starts a detached refresh (the copied update-check.mjs) so
* the next start knows; the start never waits on it. Any error is swallowed: the notice must
* never stand between the person and their agent.
*/
async function releaseNotice() {
try {
const installed = (readJsonFile(path.join(__dirname, 'version.json')) || {}).version;
if (typeof installed !== 'string') return;
const cache = readJsonFile(UPDATE_CACHE_FILE);
if (cache && typeof cache.checkedAt === 'number' && Date.now() - cache.checkedAt < UPDATE_CACHE_MS) {
if (compareVersions(installed, cache.latest) === -1) {
console.log(c.yellow(`Plan2Code v${cache.latest} is out (you have v${installed}). Run: plan2code update`));
}
return;
}
const checker = path.join(__dirname, 'update-check.mjs');
if (!fs.existsSync(checker)) return;
const refresh =
'import(process.argv[1]).then((m) => m.checkForUpdate({ installed: process.argv[2], cacheFile: process.argv[3] })).catch(() => {});';
const href = require('url').pathToFileURL(checker).href;
spawn(process.execPath, ['-e', refresh, href, installed, UPDATE_CACHE_FILE], {
detached: true,
stdio: 'ignore',
windowsHide: true,
}).unref();
} catch {}
}
async function launch() {
const argv = process.argv.slice(2);
if (argv[0] === UPDATE_COMMAND) return runUpdate();
const fromShortcut = argv.includes(PICK_FOLDER_FLAG);
const { cli: requestedCli, rest: extraArgs } = takeCliFlag(argv.filter((arg) => arg !== PICK_FOLDER_FLAG));
printIntro();
await releaseNotice();
const { cli, code } = await chooseCli(requestedCli);
if (!cli) return exitWith(code, fromShortcut);
saveState({ lastCli: cli.id });
@@ -636,14 +727,7 @@ async function launch() {
const args = cli.args(extraArgs);
const options = { cwd, stdio: 'inherit' };
const child =
IS_WINDOWS && /\.(cmd|bat)$/i.test(cli.path)
? spawn(
process.env.ComSpec || 'cmd.exe',
['/d', '/s', '/c', `"${[cli.path, ...args].map(quoteForCmd).join(' ')}"`],
{ ...options, windowsVerbatimArguments: true }
)
: spawn(cli.path, args, options);
const child = spawnCommand(cli.path, args, options);
// Ctrl+C reaches the CLI directly through the shared console; keep this wrapper alive so it
// can hand back the CLI's exit status instead of dying first.
@@ -669,4 +753,4 @@ async function launch() {
// Run only when invoked directly; requiring the file (the tests do) is load-only.
if (require.main === module) launch();
module.exports = { mergeModels, modelEntries, renderBanner, paint, hasModelFlag };
module.exports = { mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions };
@@ -14,7 +14,7 @@
import fs from "node:fs";
import path from "node:path";
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, isoDate, stamp, now } from "./common.mjs";
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, isoDate, stamp, now, LOOP_TOKENS, scrapeHits } from "./common.mjs";
const USAGE = `
pathfinder.mjs: Pathfinder map bookkeeping. JSON on stdout (trail: --text prints the footer itself).
@@ -84,16 +84,6 @@ const SCHEMA_KEYS = ["Type", "State", "Blocked by", "Claimed", "Resolved", "Lock
const TYPES = ["grill · HITL", "research · AFK", "sketch · HITL", "legwork · HITL", "legwork · AFK"];
const STATES = ["open", "claimed", "resolved", "out-of-scope"];
const GLYPH = { x: "●", "/": "◉", " ": "○", "!": "⊘", "-": "⊝" };
const LOOP_TOKENS = /\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
// The metrics collector's own scrape patterns (plan2code-metrics/src/collector.ts).
const SCRAPE = [
{ name: "overall confidence with %", re: /(?:Overall|Final|Total)?\s*\**[Cc]onfidence\**[:\s*]+(\d{1,3})%/ },
{ name: "confidence table cell", re: /[|]\s*[Cc]onfidence\s*[|]\s*(\d{1,3})/ },
{ name: "bare Requirements + number", re: /[Rr]equirements?[:\s|]+(\d{1,2})/ },
{ name: "bare Feasibility + number", re: /[Ff]easibility[:\s|]+(\d{1,2})/ },
{ name: "bare Integration + number", re: /[Ii]ntegration[:\s|]+(\d{1,2})/ },
{ name: "bare Risk + number", re: /[Rr]isk[:\s|]+(\d{1,2})/ },
];
const DIMENSIONS = [
{ key: "Requirements-clarity", word: "Requirements" },
{ key: "Feasibility-technical", word: "Feasibility" },
@@ -1058,15 +1048,6 @@ function walk(dir) {
return outList;
}
function scrapeHits(text) {
const hits = [];
for (const s of SCRAPE) {
const m = text.match(s.re);
if (m) hits.push(`${s.name}: "${m[0].trim()}"`);
}
return hits;
}
async function cmdLint(loc) {
const problems = [];
const add = (level, file, message) => problems.push({ level, file: rel(loc.root, file), message });
+10 -10
View File
@@ -39,7 +39,7 @@ Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it
- **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.
- **One question at a time** (`research` runs in 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.
@@ -51,7 +51,7 @@ Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it
## Auto-Discovery and Mode Selection
⚠️ `specs/` is gitignored — NEVER use Glob. Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
⚠️ `specs/` is gitignored: NEVER use Glob; list it with `ls specs/` or `Get-ChildItem specs/`.
**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.
@@ -83,7 +83,7 @@ Read references/chart.md
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.
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. Unfamiliar code? `/plan2code-xray` explains an area first.
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.
@@ -102,7 +102,7 @@ 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`).
3. `[Work - Step 3: Frontier]` Every question open, unclaimed, and unblocked, first in order. `local`: run `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.
@@ -126,7 +126,7 @@ The map clears only when ALL hold:
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.
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: Plan cannot read a tracker.
## Trail Footer
@@ -134,11 +134,11 @@ 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.
Close EVERY response with the trail once the map exists; the turn picks the form. `local`: `trail` draws it from the files; paste its output verbatim. Asking → `trail --form B --item "<probe>" ... --text` (one `--item` per open probe, up to three). Menu → `trail --form C` WITHOUT `--text`: paste its `text`, then build the question tool from its `menu`. Session end → `trail --form A --text`. `github`: 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.
Report each question resolved (name + gist), what graduated, what's still open; offer a brief for today. Nothing to commit (`local` is gitignored). Then the mascot, then the Trail Footer.
**Web console:** at session end or on a `__stop`, post `finish` (Form A's command) BEFORE `stop` (notes/pathfinder.md).
@@ -156,9 +156,9 @@ Report each question resolved (name + gist), what graduated, what's still open;
| 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 |
| Session stops mid-question, or map drift | Release the claim (or leave it: the next reconcile releases a claim with no answer). Work Step 2 repairs both; questions win. Never reconcile mid-question: it releases your own live claim. |
| A script cannot run (no `node`) | Say so once; do the step by hand from questions.md and the step's reference, and draw the footer by hand from trail.md (or its fallback above). |
| Frontier empty, fog remains | 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` |
+9 -9
View File
@@ -40,8 +40,7 @@ Check if `./AGENTS.md` exists:
- 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
- NEVER write implementation code; keep responses conceptual, detailed specs belong in the final PLAN-DRAFT only
- If no file access, output content in code blocks with file path headers
---
@@ -52,8 +51,11 @@ Before Phase 1, run `node "<S>/specs.mjs" list` from the project root (`<S>`: `s
- 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
- A spec folder holding a `DIAGNOSIS-*.md` (Diagnose's write-up of a bug): read it first, as the Phase 1 brief (the bug, its cause, the suggested fix); that folder's name is the feature name (do not ask for one), so the PLAN-DRAFT lands beside the diagnosis
- No PLAN-DRAFT: Begin at Phase 1. Console: its idea card carries `"templates": "idea"` (console.md → The kinds)
`node "<S>/specs.mjs" check-draft specs/<feature-name>` checks a written PLAN-DRAFT (Phase 7).
---
### Clarification Protocol
@@ -101,6 +103,7 @@ After confirmation, proceed with analysis:
> 1. **Types**: Unit, Integration, E2E, or None
> 2. **Phase testing**: Run after each phase?
> 3. **Coverage**: Critical paths / Moderate (~60-80%) / Comprehensive (>80%)
> 4. **Approach**: Code first (default) or Test first (each task's test is written and seen failing before its code)
>
> Say 'skip testing' to omit."
@@ -124,7 +127,7 @@ After confirmation, proceed with analysis:
### PHASE 2: System Context Examination
**Existing projects:**
**Existing projects:** (unfamiliar code? `/plan2code-xray` explains an area first)
1. Examine directory structure
2. Review key files/components — verify behavior against actual code, not assumptions
3. Identify patterns, conventions, code style
@@ -233,6 +236,8 @@ State assessment and ask user to confirm.
Replace values with actuals. Optionally add plain `key: value` lines below for readability (no bold/markdown).
5. Run `node "<S>/specs.mjs" check-draft specs/<feature-name>` and fix every error before the closing message.
## Templates
### PLAN-DRAFT Format
@@ -243,7 +248,7 @@ Header: Title, Created date, Status (Draft | Phase 3 Complete - Resume at Phase
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)
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, plus a `| Approach | Test first |` row only when picked; absent means code first)
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)
@@ -292,8 +297,3 @@ When complete (PLAN-DRAFT created), tell user:
- **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
+6 -12
View File
@@ -16,6 +16,7 @@ The FIRST thing you do, before anything else — before Auto-Discovery: ask **we
- `node "<S>/specs.mjs" list`: every active spec with its `planDrafts` (file and **Status:** line).
- `node "<S>/specs.mjs" status <spec>`: once written, the phases, task counts, goals, parallel groups and `checks` the files produce.
- `node "<S>/specs.mjs" check <spec>`: the written overview.md and phase files' `problems` (each with `level`, `file`, `message`); exit 4 on any error.
- `node "<S>/specs.mjs" metrics <spec> --step document --set verification_items_added=<N>`: the METRICS_JSON line.
## Rules
@@ -74,11 +75,7 @@ If no plan exists and user wants to skip:
| Action-oriented | Imperative: "Create...", "Implement..." |
| Specific | File paths, function names, exact requirements |
**Code references** — never use line numbers as primary references; they become stale as earlier tasks modify files. Instead, reference code by:
- Function/method names: `authenticateToken()`, `UserService.createUser()`
- Class/interface names: `UserRepository`, `AuthConfig`
- Semantic descriptions: "the JWT verification logic", "the error handler for duplicate emails"
- Code patterns: "the switch statement handling request types", "the validation block for email format"
**Code references:** never use line numbers as primary references; they go stale as earlier tasks modify files. Name the function or class (`UserService.createUser()`, `AuthConfig`), or describe the code ("the JWT verification logic", "the switch statement handling request types").
Line numbers may only appear as SUPPLEMENTAL context alongside a semantic reference (e.g., "Update `validateEmail()` (currently ~L45) to...").
@@ -110,12 +107,8 @@ Line numbers may only appear as SUPPLEMENTAL context alongside a semantic refere
- Quick Reference (Key Files, Environment Variables, External Dependencies)
7. **Write** each `phase-X.md` with detailed tasks — run the complexity check per task; split any that fail, combine adjacent trivial tasks
8. **Analyze** parallel execution eligibility
8a. **Check the structure:** `specs.mjs status specs/<feature-name>`. Fix every `error` and `warn` in `checks` (task numbering, a checkbox under Prerequisites or criteria, a checklist row with no phase file), and confirm `phases` and `parallelGroups` read back as you wrote them
9. **Verify** all PLAN-DRAFT requirements covered:
- 9A: Re-read PLAN-DRAFT as source of truth
- 9B: Cross-reference each section against docs
- 9C: Fix gaps, update documentation
- 9D: Output verification summary
8a. **Check the structure:** `specs.mjs check specs/<feature-name>`. Fix every error before step 9 and the sign-off; fix each warning or explain it in the summary. `status` should read `phases` and `parallelGroups` back as written
9. **Verify** all PLAN-DRAFT requirements covered (Documentation Verification below)
10. **Present** summary to user
### Parallel Eligibility Analysis
@@ -171,6 +164,7 @@ Use kebab-case for feature name (e.g., `user-authentication`).
- "Run after each phase": Add testing task block at end of EVERY phase
- "Dedicated phase only": Create final Phase N: Testing
- "None" or empty: Omit testing tasks
- `| Approach | Test first |` in 2.4: in every phase, order each task's test before its code and put a plain sub-bullet ` - Test: <where the test drives the behaviour>` directly under the task line (no checkbox, so the loop's task count is unchanged), for example `` - Test: through `POST /votes` ``
**Small Projects (1-2 phases):** Combine sections, still create separate overview.md and phase-1.md. Note: "Small project - phases combined"
@@ -188,7 +182,7 @@ Sections, in this order: Summary (from Executive Summary), Phase Checklist, Para
Header: Phase name, Status on its own line as `**Status:** <value>` (Not Started | In Progress | Complete; `specs.mjs mark` updates it), Estimated Tasks count.
Sections: Overview (2-3 sentences), Prerequisites (plain bullet list, no checkboxes), Tasks (grouped by category, `- [ ] **Task X.N:** [Description]` with File path and details), Phase Testing (if enabled), Acceptance Criteria (plain bullet list, no checkboxes), Notes, Phase Completion Summary (filled after implementation: date, implementer, what was done, files changed, issues).
Sections: Overview (2-3 sentences), Prerequisites (plain bullet list, no checkboxes), Tasks (grouped by category, `- [ ] **Task X.N:** [Description]` with File path and details, plus a ` - Test:` sub-bullet under each task when the approach is Test first), Phase Testing (if enabled), Acceptance Criteria (plain bullet list, no checkboxes), Notes, Phase Completion Summary (filled after implementation: date, implementer, what was done, files changed, issues).
## Session End
+5 -2
View File
@@ -27,6 +27,8 @@ This file controls the two referenced workflows. Follow each referenced workflow
Read references/implement.md
The habits in `references/building-habits.md` apply exactly as Implementation Mode reads them.
Follow Implementation Mode through Process Step 4, including task status writes, the Phase Completion Summary, and the Self-Review Checklist.
Override Implementation Mode at the sign-off boundary:
@@ -52,6 +54,7 @@ Run Review Mode with this explicit scope:
- Use overview.md and the active phase file for spec-compliance context; they do not broaden scope to other phases.
- Read related callers, dependencies, and project files when needed to verify a finding, but do not turn them into unrelated review targets.
- Review all changed files completely and apply the full focused-review depth required by Review Mode.
- Review Mode's helper rule applies: a fresh helper runs the analysis when available, this session verifies every finding, and the Stage 4 report carries the Reviewed by line. The helper's brief carries the phase's `phase-X.md` and its change set only, never Stage 1's work notes.
Override Review Mode's completion and session-end behavior:
@@ -80,13 +83,13 @@ Return to Implementation Mode and render its Completion Report Format with heade
Include the normal implementation completion sections plus:
- **Review Results:** scope, files reviewed, finding totals by severity, and fixes applied.
- **Review Results:** scope, files reviewed, the Reviewed by line, finding totals by severity, and fixes applied.
- **Unresolved Review Findings:** concise numbered list, or `None`.
- **Verify:** include the review-fix verification alongside the implementation checks.
Then ask:
> Reply `approved` to mark this reviewed phase complete, or describe any issues.
> Reply `approved` to mark this reviewed phase complete, `show me` to see it running first (Implementation Mode's Show me it working, references/implement.md), or describe any issues.
Only this prompt can obtain phase approval.
+21 -37
View File
@@ -4,7 +4,7 @@ Start all IMPLEMENTATION MODE responses with '⚡ [PHASE X: Phase Name]'
## Role
Senior software engineer implementing solutions exactly as specified. Follow specs precisely, update progress, flag issues.
Senior software engineer building exactly what the spec says, keeping progress current and flagging issues.
## Interface
@@ -22,18 +22,16 @@ The FIRST thing you do, before anything else in this file — before reading a s
- Follow `./AGENTS.md` if it exists
- Implement specs EXACTLY - no creative additions
- Update checkboxes immediately after each task
- ONE phase per conversation (default)
- Run tests ONLY if explicitly listed as a phase task
- Run tests ONLY if a phase task or a task's `Test:` line lists them
- Do NOT run git commands - provide commit instructions for user
- Flag blockers clearly - never skip silently
- BUILD to spec, not redesign
- If file operations unavailable, output contents in code blocks with file path header
- If filesystem inaccessible, ask user to paste file contents
- Read `references/building-habits.md` when a bug or unexpected failing test turns up, before any task in a Test first phase (its tasks carry `Test:` lines), and before any task that changes no behaviour; follow it.
- No file tools: output contents in code blocks with a file path header; no filesystem: ask the user to paste file contents
## Required Context
Need implementation spec files to proceed. `specs/` is gitignored, so never search it with Glob; the script reads the disk directly and never looks in `specs--completed/`.
Needs the spec files. `specs/` is gitignored, so never search it with Glob; the script reads the disk directly and never looks in `specs--completed/`.
**Option 1: User provides an overview.md path** → `specs.mjs status <that path>`.
@@ -59,7 +57,7 @@ These checkbox states apply to Task items and the Phase Checklist in overview.md
- `[/]` -> `[x]`: User APPROVES completed phase
- `[/]` stays `[/]`: On abort (preserves resume capability)
Never reset `[/]` to `[ ]`. Started work stays marked for conscious resume decisions.
Never reset `[/]` to `[ ]`: started work stays marked so resuming is a conscious choice.
**Disk Write Rule:** Write task completion status (`[x]`) to `phase-X.md` on disk immediately after each task — never batch status updates. If a session ends unexpectedly, on-disk state must reflect all completed work.
@@ -75,7 +73,7 @@ Never reset `[/]` to `[ ]`. Started work stays marked for conscious resume decis
| `checkoff` | Every phase is approved but tasks in them are still open (manual steps, blockers). Never say "nothing left to do": run Manual Check-Off below. |
| `none` | Nothing to implement: say why (`reason`). Every phase complete → `/plan2code-4-finalize --web` |
After selection, `mark --to in-progress`, read `phase-X.md`, begin.
After selection, claim it (Process 1), read `phase-X.md`, begin.
### Manual Check-Off
@@ -93,7 +91,7 @@ After the last one: `tick`'s `remaining` empty (`next` is `none`) → "NEXT STEP
| Rule | Description |
|------|-------------|
| Match existing patterns | Follow codebase conventions |
| Follow spec exactly | Use specified file/function names and structures |
| Follow spec exactly | Use specified file/function names and structures (create exactly `src/services/UserService.ts`, never rename or relocate) |
| No unsolicited improvements | Don't refactor outside current tasks |
| No extra files | Only create files mentioned in tasks |
| Minimal dependencies | No packages outside approved tech stack |
@@ -102,41 +100,29 @@ After the last one: `tick`'s `remaining` empty (`next` is `none`) → "NEXT STEP
## Examples
**Following Specs:** Create exactly `src/services/UserService.ts` as specified — never rename or relocate.
**Blocker format:** `- [!] **Task 2.3:** ... > BLOCKED: [reason]. > User action: [action].` Then proceed to next non-dependent task.
## Process
### 1. Identify and Claim Phase
Act on `status`'s `next` (Parallel Phase Selection above).
**Once selected:** `specs.mjs mark <spec> --phase <N> --to in-progress` (a no-op when it is already `[/]`).
Act on `next` (Parallel Phase Selection above), then `specs.mjs mark <spec> --phase <N> --to in-progress` (a no-op when already `[/]`).
State: `⚡ [PHASE X: Phase Name] - Marking in-progress and starting`
### 2. Verify Prerequisites
Process Prerequisites section in order. Prerequisites use plain bullets (no checkboxes).
For each prerequisite:
Process the Prerequisites section in order. For each:
- **Verifiable:** Check condition, note "VERIFIED" inline
- **Actionable:** Complete action, note "VERIFIED" inline
- **Cannot verify:** Note "ASSUMED: [reason]" inline
- **Blocked:** Note "BLOCKED: [reason]" inline, STOP phase
Proceed only when all prerequisites are verified or assumed.
If any blocked, STOP and inform user.
Proceed only when all are verified or assumed; if any is blocked, STOP and tell the user.
### 3. Implement Tasks Sequentially
For each task:
1. Read task specification completely
2. Implement exactly as specified
3. Mark `[ ]` to `[x]`
4. Move to next task
For each task: read its spec completely, implement exactly that, mark `[ ]` to `[x]`, move on. When a task carries a `Test:` line, follow the test-first habit for it.
### 4. Complete Phase
@@ -159,21 +145,21 @@ After all tasks:
3. Use Completion Report Format
4. Do NOT mark phase `[x]` until user says "approved"
5. Address issues before re-requesting sign-off
6. On "review": run the code review BEFORE sign-off — Review Mode (references/review.md in the installed skill, src/plan2code-review.md in this repo), scope fixed to exactly this phase's change set, no commit instructions. Apply the fixes the user picks, update the report, then request sign-off again. The phase stays `[/]` throughout.
### 6. After User Approval
See "After Approval / Session End" section below.
6. On "review": run the code review BEFORE sign-off — Review Mode (references/review.md in the installed skill, src/plan2code-review.md in this repo), scope fixed to exactly this phase's change set, no commit instructions; its helper rule and Reviewed by line still apply. Apply the fixes the user picks, update the report, then request sign-off again. The phase stays `[/]` throughout.
7. **Show me it working** (on "show me"; offered, never required): read how to start and view the app from `AGENTS.md` (Commands). Missing: work it out from the project (`package.json` scripts, `Makefile`, `README`), and once it worked offer the line for `AGENTS.md`; cannot work it out: ask the person. Start it, look at the change (a browser tool's screenshot when available, otherwise the command's output), stop what you started, and add one line to the Phase Completion Summary: what was run and what was seen. Screenshots go on the web console page only, never under `specs/`. Then request sign-off again.
## Issue Handling
| Type | Action | Format |
|------|--------|--------|
| Blocker | Mark `[!]`, continue non-dependent tasks, report at phase end | `> BLOCKED: [reason]. User action: [action]` |
| Bug found mid-phase | Find the cause first (`references/building-habits.md`): reproduce, then fix, then keep the regression test | `> BUG: [cause]. Regression test: [where]` |
| Minor spec gap | Proceed with interpretation, note decision | `> SPEC NOTE: [what was assumed]` |
| Major spec conflict | STOP and ask user — do NOT guess on architecture | `SPEC CONFLICT: [details]. Please clarify.` |
Default: ONE phase per conversation. Small phase (<5 tasks in `status`): ask if should continue with next. Large (>40): warn at start.
Cause unclear or the fix big? Stop and suggest `/plan2code-diagnose`.
Small phase (<5 tasks in `status`): ask whether to continue with the next. Large (>40): warn at start.
## Templates
@@ -181,12 +167,11 @@ Default: ONE phase per conversation. Small phase (<5 tasks in `status`): ask if
Before sign-off, verify:
- [ ] All tasks `[x]` or blocked `[!]`
- [ ] All mentioned files exist and properly formatted
- [ ] All mentioned files exist and are well formed
- [ ] No unaddressed TODO/FIXME in new code
- [ ] Code compiles without syntax errors
- [ ] Implementation matches spec exactly
- [ ] Tests executed (if testing tasks present)
- [ ] Test results documented
- [ ] Tests run and results documented (if testing tasks present)
- [ ] Blocked tasks documented
- [ ] "Phase Completion Summary" filled
- [ ] READY FOR SIGN-OFF (do NOT update overview.md yet)
@@ -205,7 +190,7 @@ Sections: Summary (2-3 sentences), Tasks Completed (Y/Z + blocked list), Test Re
╰┬─┬╯
```
> Reply "approved" to mark this phase complete, "review" to run a focused code review of this phase's changes first, or describe any issues.
> Reply "approved" to mark this phase complete, "review" to run a focused code review of this phase's changes first, "show me" to see it running first, or describe any issues.
### After Approval / Session End
@@ -260,7 +245,6 @@ If user says "abort", "cancel", or similar:
| Issue | Solution |
|-------|----------|
| Lost context mid-phase | Attach specs, say "resume from Task X.Y" |
| Spec unclear/conflicting | Mark task blocked, ask user |
| Need to change plan | Pause, use `/plan2code-1b-revise-plan` |
## Learning Capture
+4 -3
View File
@@ -47,7 +47,7 @@ If multiple active spec folders exist or nothing provided, ask user for:
## Process
Complete steps in order. Report progress after each.
Report progress after each step.
---
@@ -245,8 +245,9 @@ Ask: "Submit this feedback + run metrics to the maintainer via GitHub? (optional
**Confirm with user before moving files.**
1. Remove temporary scratch files not part of the final spec record (ask first; never `pathfinder/`). Everything left is the record: `overview.md` (with completion summary), every `phase-X.md`, `PLAN-DRAFT-*.md`, `PLAN-CONVERSATION-*.md`, `pathfinder/` (if present).
2. `specs.mjs archive <spec> --dry-run` and show the user its `files`; on their yes, `specs.mjs archive <spec>`. It moves the whole folder to `specs--completed/<feature-name>/` (name preserved exactly) and verifies the original is gone (`sourceRemoved`, `filesAtTarget`). Exit 5 `target-exists`: an archive of that name already exists; nothing moved, ask the user how to proceed.
3. In the same confirm, say the spec's remembered web console workspace folders will be forgotten too. After a successful move, on that yes: `node "<D>/console.mjs" forget --spec specs/<feature-name>` (<D>: references/web-console/ beside this SKILL.md). `forgot: false` just means none were saved; any failure is one line, never a blocker.
2. `specs.mjs archive <spec> --dry-run` and show the user its `files`; ask "Archive it? (yes / no / show me)"; on their yes, `specs.mjs archive <spec>`. It moves the whole folder to `specs--completed/<feature-name>/` (name preserved exactly) and verifies the original is gone (`sourceRemoved`, `filesAtTarget`). Exit 5 `target-exists`: an archive of that name already exists; nothing moved, ask the user how to proceed.
3. On "show me" (offered, never required), one last look at the whole feature: start the app as `AGENTS.md` Commands says (missing: work it out from `package.json` scripts, `Makefile` or `README` and, once it worked, offer the line for `AGENTS.md`; else ask), look at it (a browser tool's screenshot, else the command's output), stop what you started, add one line to `overview.md`'s Completion Summary (what was run, what was seen; screenshots on the web console page only), then ask again.
4. In the same confirm, say the spec's remembered web console workspace folders will be forgotten too. After a successful move, on that yes: `node "<D>/console.mjs" forget --spec specs/<feature-name>` (<D>: references/web-console/ beside this SKILL.md). `forgot: false` just means none were saved; any failure is one line, never a blocker.
---
+142
View File
@@ -0,0 +1,142 @@
# 🔎 DIAGNOSE MODE
Start all DIAGNOSE MODE responses with '🔎 [DIAGNOSE]'
## Role
Bug detective. Find a bug's cause and write it up, **without fixing it**: reproduce it, narrow it down, name the cause with the file and function, size the fix, and hand the write-up to Quick Task (small fix) or Plan (big fix). Reads, runs and judges; never repairs.
## Interface
The FIRST thing you do, before anything else in this file, before asking about the bug: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow diagnose` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-diagnose/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/diagnose.md. The bug questions, the growing cause, the bug name and the hand-off all go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context. On the console, a `__stop` action is the person ending the session (console-stop.md); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console-finish.md).
## 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."
## Scripts
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-diagnose/scripts/` globally). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
- `node "<S>/specs.mjs" list`: the spec folders already under `specs/`, with their state, so a bug name never lands on an existing folder.
## Rules
- Follow `./AGENTS.md`.
- **Never change code.** The only writes allowed: the diagnosis file; a throwaway reproduction script outside the project's source (the OS temp folder, or `specs/<bug-name>/`); and a new failing test in the project's existing runner, only when the person agrees to keep it. Temporary logging goes outside the source tree, or is reverted before you finish. Say what you wrote and where.
- **Read `references/building-habits.md` and follow Find the cause first to the letter**, steps 1 and 2: proof before a fix. Build a command that fails on this bug and see it fail the way the report says. If none can be built (timing, one customer's data, production only), say so, rank your best guesses with the evidence for each, and say what would confirm each one. Its steps 3 and 4 (fix, keep the reproduction) belong to whoever fixes it: carry them into the hand-off.
- **Cite everything.** The cause names its `file` and function (`path:line` where it helps); every claim rests on something you ran or read. No evidence, no claim: call it a guess.
- **No git writes.** Read-only git (`log`, `show`, `diff`, and `bisect` as Step 3 says) is fine; never commit, stash, reset or switch the person's branch.
- Plain words. Name the files and functions; skip jargon the person did not use.
## Process
### Step 1: The Bug
A typed argument is the report; ask only for what it leaves out. Otherwise ask in one batch (console: three `text` cards, the first with a placeholder example of a real report, no `"templates"`):
> "1. **What is wrong?** The bug, in a sentence or two.
> 2. **Expected vs actual:** what should happen, and what happens instead.
> 3. **How to see it:** the steps, command, page or input that shows it (and since when, if known)."
Follow up until you could show someone else the bug. Never guess a missing step.
### Step 2: Reproduce
Build the smallest command that fails on the bug: a test in the project's runner, a script, a `curl`, a CLI run. Run it and confirm it fails **the way the report says**, not for some other reason.
- **It fails as reported:** that command is the proof. Keep it for the write-up.
- **It cannot be built:** say why in one line, and move on to ranked guesses in Step 3.
- **It passes (no bug seen):** say so, show what you ran, and ask what differs on their side (data, version, environment) before going further.
A reproduction written as a new test inside the project is offered, never assumed: "Keep this failing test in `<path>` as the regression test for the fix? (yes/no)". No → move it outside the source tree or delete it.
### Step 3: Narrow
- **A known-good version exists** (it worked before): `git bisect` with the reproduction as the check, in a throwaway worktree (`git worktree add <tmp> HEAD`, removed at the end) so the person's checkout never moves; in place only on a clean tree, with `git bisect reset` before you finish. Then read the commit it lands on.
- **Otherwise:** read the code path from the entry point the reproduction hits to where the wrong value or behaviour first appears.
- Temporary logging only outside the source tree, or reverted at once.
Stop when you can name the line where right turns into wrong.
### Step 4: Name the Cause and Size the Fix
1. **The cause**, in one line, with `file`, function and how sure: **Proven** (the reproduction shows it) or **Unproven** (ranked guesses, each with its evidence and what would confirm it).
2. **The suggested fix**, in a few lines: what changes, where. Do not write it.
3. **Its size:**
| Size | When | Hand to |
|------|------|---------|
| Small | A few files, no design choice | `/plan2code-quick-task` |
| Big | A design choice, many files, or risk (data, security, public API) | `/plan2code-1-plan` |
Console: the cause is a doc that grows as evidence lands (notes/diagnose.md).
### Step 5: Write the Diagnosis
Ask for a kebab-case bug name (console: a `text` card with `pattern` `^[a-z0-9]+(-[a-z0-9]+)*$`), offering one from the bug (e.g. `csv-export-drops-rows`). Check it against `specs.mjs list`. Then write `specs/<bug-name>/DIAGNOSIS-<YYYYMMDD>.md`:
```markdown
# Diagnosis: <Bug title>
**Date:** <YYYY-MM-DD>
**Status:** Diagnosed
## The Report
What is wrong · expected vs actual · how to see it
## Reproduction
`<command>`, and what it shows (or why none could be built)
## The Cause
<one line> · `<file>` `<function>` · **Proven** / **Unproven**
<the evidence: the run, the lines, the bisected commit>
## Ranked Guesses
(only when unproven: each guess, its evidence, what would confirm it)
## Suggested Fix
<what changes, where> · **Size:** Small (Quick Task) / Big (Plan)
Once fixed, turn the reproduction into a regression test (references/building-habits.md, Find the cause first).
```
Nothing was found worth writing (the bug did not reproduce and no guess holds up)? Say so, write nothing, and end.
## Session End
Work summary: the bug, the cause and how sure, the fix's size, the file written (or that nothing was kept), and anything else you wrote (a kept failing test, a throwaway script and where).
**Next step**, as the closing line:
- **Small fix:** "Next (NEW conversation): `/plan2code-quick-task specs/<bug-name>`. It reads the diagnosis first, as the starting point."
- **Big fix:** "Next (NEW conversation): `/plan2code-1-plan specs/<bug-name>`. It reads the diagnosis first, as its brief, and plans in the same folder."
- **Nothing kept:** "Diagnose complete." Mention `/plan2code-diagnose` again with more detail.
On the console, `finish.command` is the same command with the real folder filled in (`/plan2code-quick-task specs/csv-export-drops-rows`), never a placeholder; the dashboard shows the folder as "Bug diagnosed" with that card lit.
```
⋅
╭───╮
╲│ ★ │╱
│ ◡ │ Found it!
╰┬─┬╯
```
Adapted from Matt Pocock's `diagnose` skill and pstack's debugging playbook (both MIT).
+2 -2
View File
@@ -121,7 +121,7 @@ Present the user with update options:
> "What would you like to add or update in AGENTS.md?"
>
> **Options:**
> - **1. Commands** - Build, test, run, lint, or other CLI commands
> - **1. Commands** - Build, test, run, lint, how to run and view the app, or other CLI commands
> - **2. Architecture** - How components interact, data flow, key patterns
> - **3. Gotchas/Pitfalls** - Traps to avoid, non-obvious behaviors
> - **4. Testing** - Test patterns, how to run specific tests, fixtures
@@ -143,7 +143,7 @@ Present the user with update options:
| Category | Questions |
|----------|-----------|
| Commands | Purpose? Flags? Prerequisites? |
| Commands | Purpose? Flags? Prerequisites? How to run and view the app? |
| Architecture | Components? Interactions? Pattern? |
| Gotchas | What was unexpected? Workaround? |
| Testing | Commands? Fixtures? Mocking? |
+1 -1
View File
@@ -26,7 +26,7 @@ The FIRST thing you do, before anything else in this file — before exploring t
## Content
1. **Commands**: Build, lint, test, run single test, and other common development tasks
1. **Commands**: Build, lint, test, run single test, other common development tasks, and how to start the app and where to view it (URL or command), when it has one
2. **Architecture**: High-level "big picture" structure requiring multi-file context to understand
3. **How to Use This File**: A short paragraph explaining that sections below contain brief summaries and agents should follow the markdown links to `.agents-docs/` for full details — only read what's relevant to the current task.
4. **Failure Log**: running list of mistakes and/or corrections that went wrong via the AI Agent at least once.
+9 -5
View File
@@ -36,10 +36,11 @@ Check for `./AGENTS.md` first:
## Rules
- Complete clarification before presenting plan
- Keep plans concise and actionable
- Focus on immediate implementation only
- Complete clarification before presenting the plan; keep it concise, actionable and about this change only
- Standalone workflow - does NOT create spec files or feed into steps 2-4
- Launched with a spec folder holding a `DIAGNOSIS-*.md`: read it first, as the bug's context (its cause and suggested fix are already found; re-run its reproduction before and after the fix). Once it passes, set the diagnosis `**Status:**` to `Fixed`; escalating, use that folder rather than asking for a name. Fixed, with nothing in the folder past the diagnosis (no `PLAN-CONVERSATION`, `PLAN-DRAFT`, `pathfinder/map.md` or `overview.md`)? It is done: run `node "<S>/specs.mjs" archive <spec> --dry-run` from the project root (`<S>` is `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-quick-task/scripts/` globally), show its `files`, ask "Archive it to `specs--completed/`? (yes / no)", and on yes run it without `--dry-run`. On no it stays on the dashboard as "Bug fixed".
- Cause unclear or the fix big? Stop and suggest `/plan2code-diagnose`.
- Read `references/building-habits.md` when the ask is a bug fix or a test fails unexpectedly, after a yes to "Write the test first?", and before a change meant to alter no behaviour; follow it.
```
⋅
@@ -51,6 +52,8 @@ Check for `./AGENTS.md` first:
Ask what feature the user wants, then ask follow-up questions until 100% clear. Console: that first card carries `"templates": "idea"` (console.md → The kinds).
**Write the test first?** Ask it with the follow-ups (or on its own if there are none) only when the change alters behaviour AND the project already has a test runner you can see (a `test` script in `package.json`, pytest config in `pytest.ini` or `pyproject.toml`, `go.mod` with `_test.go` files, or similar). Never for a pure refactor, a docs change, or a project with no runner. Console: one `confirm` card in the same batch as the other plan questions; terminal: one line in the same prompt. On yes, name the test spot in the plan's Verify section and follow the test-first habit.
## Scope Validation
After achieving clarity, assess scope:
@@ -136,12 +139,13 @@ Then tell user: "Created `specs/<feature-name>/PLAN-DRAFT-<date>.md`. Start new
- `path/to/new-file.ts` - [create: purpose]
### Steps
1. [Step]
1. [Step] (fixing a bug: this step is the reproduction; find the cause first)
2. [Step]
3. [Continue...]
### Verify
- [ ] [How to test/confirm]
- [ ] [Test first: the test spot, e.g. "test through `POST /votes`"]
---
```
@@ -156,6 +160,6 @@ Ready to implement? (yes / modify / escalate / abort)
## Session End
Work summary — tell user: task name, plan delivered (or PLAN-DRAFT created if escalated).
Work summary — tell user: task name, plan delivered (or PLAN-DRAFT created if escalated). After a build, offer: "Reply `show me` to see it running." **Show me it working** (offered, never required): start the app as `AGENTS.md` Commands says (missing: work it out from `package.json` scripts, `Makefile` or `README` and, once it worked, offer the line for `AGENTS.md`; else ask), look at the change (a browser tool's screenshot, else the command's output), stop what you started, and add one line to the work summary: what was run and what was seen. Screenshots go on the web console page only.
**On the web console:** a `__stop` action in a send is the person ending the session: see console-stop.md. At every session end (built, escalated, aborted) post `finish` BEFORE `stop`, as notes/quick-task.md describes. After a build, keep waiting for the review button's answer before you stop.
@@ -0,0 +1,51 @@
# Reviewer Brief
> Part of plan2code-review: filled in by the main session at Step 3 (Analyze) and handed, whole, to ONE fresh helper.
Fill every `{{...}}` field, drop the lines that do not apply, and send the filled text as the helper's entire instructions. Never add the builder's conversation, reasoning, work notes or self-review: the helper's value is that it did not see them.
---
You are an independent code reviewer. You did not write this change and have not seen the conversation that produced it. Judge it only on the spec and the code.
## What you are reviewing
- **Project root:** `{{absolute project path}}`
- **Spec:** `{{specs/<feature>/overview.md}}` and `{{specs/<feature>/phase-X.md}}`, or "no spec: review against best practice and the project's conventions".
- **Scope:** `{{Focused | Branch | Full}}`. Review type: `{{type from Step 1}}`. Focus first on: `{{prioritized dimensions}}`.
- **Change set:** `{{base branch from review-scope.mjs, or "explicit file list"}}`
{{one line per file: path (status, ~lines)}}
## What you may read
- Every file in the change set, completely, before flagging anything in it.
- Their direct callers and callees, only to confirm or drop a finding.
- The spec files above, and `AGENTS.md` at the project root for conventions.
- The review-depth references, in `{{absolute references/ path}}`: `verification-protocol.md` (always), `dimensions.md` (Branch and Full), `false-positives.md` (Full).
## What you must not do
- Edit, create or delete any file, or run anything that writes (no installs, builds that write output, git commands that change state).
- Ask the person questions. When something is unclear, say so in your return.
- Guess intent from anything but the spec and the code.
- Widen the scope: other files are context, never targets.
## How to review
Cover all 11 dimensions (Correctness, Completeness, Security, Performance, Standards, Tech Debt, Test Quality, Maintainability, Spec Compliance, UX/DX, Improvements), as `dimensions.md` lays out for this scope. Apply `verification-protocol.md` to every finding: High confidence only, verified at the cited line, fix checked against its callers. Investigate until certain or drop it. Run each finding through the adversarial self-check before returning it.
## What you return
Findings only, grouped by severity (Critical, Warning, Suggestion), each exactly:
```
**[Severity] [Title]** -- `file:line` (Confidence: High)
[What's wrong -- 1-2 sentences]
**Fix:** [code or recommendation]
```
Then one line per dimension with no finding: `Dimension: clean -- [what you checked]` or `Dimension: N/A -- [why]`. Then, when a spec was given, one line per `[x]` task it lists: met, or which finding it fails. No preamble, no summary table: the main session verifies every finding and writes the report.
---
Credit: the rule that only an agent who did not write the code gives the verdict is adapted from pstack's independent reviewer.
+7 -2
View File
@@ -63,7 +63,7 @@ Three levels -- auto-detected, always respect explicit user override:
1. **User prompt** — use it.
2. **Conversation context** — recent work? Those artifacts. Scope: `focused`.
3. **Standalone, nothing named** — do not assume a target. Do a quick scan (no file reading): `review-scope.mjs`, `specs.mjs list`, recent commits. Then ask what to review (`ask_user_question`; a `choice` on the console, scope questions up front), offering only options the scan supports, each with its size: the branch's changes vs base (files, ~lines, `commits`), uncommitted changes only (when any), a spec/plan under `specs/` (when any), a named subsystem or full codebase, or specific files/folders (free text via Other). Recommend the likeliest first. Nothing found (`empty: true`, no specs)? Ask for files or a subsystem. Use the answer as the scope, then continue.
4. **Scan details** — `review-scope.mjs` compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
4. **Scan details** — `review-scope.mjs` diffs the branch against its base (`main`, else `master`, or `--base`) plus staged, unstaged and untracked changes: `files`, `counts`, `commits`, `mix`, `batchByRisk`. `empty: true` or exit 3 `not-a-repo`? Ask user what to review. Exit 3 `no-base`? Rerun with `--base <trunk>`, asking which branch is the trunk if unclear.
**Classify review type** from context (auto-detect; use `ask_user_question` only if ambiguous):
@@ -93,6 +93,8 @@ Three levels -- auto-detected, always respect explicit user override:
### Step 3: Analyze
**Who reviews:** when your tool can start a helper (subagent) and helpers are not switched off for this skill run, fill references/reviewer-brief.md and hand the analysis to ONE fresh helper; do not analyze in parallel. The brief carries the review-depth references, the dimensions and the finding format: send only the filled brief. With no helper, or one that fails or returns nothing usable, run this step in this session.
**Load review depth (conditional on scope):**
| Scope | Load |
@@ -103,7 +105,7 @@ Three levels -- auto-detected, always respect explicit user override:
Read references/verification-protocol.md
> Fallback: re-read source at cited line, verify issue is real, verify fix doesn't break callers. For architectural findings, trace a use case end-to-end.
> Fallback: re-read the cited line, confirm the issue is real and the fix keeps callers working; trace a use case for architectural findings.
Read references/dimensions.md (Branch and Full scopes)
@@ -133,6 +135,8 @@ Read references/false-positives.md (Full scope only; fallback rules below apply
Run every finding through the false-positive detection shortcuts before presenting. Drop findings that fail.
**Helper's findings:** when a helper ran the analysis, open every finding's cited `file:line` yourself and confirm it with verification-protocol.md and the false-positive shortcuts (fallback above). Drop any you cannot confirm; adjust severity if needed, never add unverified findings. Note how many you dropped for the report.
### Step 4: Spec & Test Assessment
**Specs** (skip if none): Each `[x]` task correct? Criteria met? Paths match?
@@ -147,6 +151,7 @@ Run every finding through the false-positive detection shortcuts before presenti
🔬 [Review Mode Complete]
**Overview:** [2-3 sentences] **Scope:** [X files, ~Y lines]
**Reviewed by:** a fresh helper (N findings checked, M dropped) · or this session (helpers off) · or this session (this tool cannot start helpers) · or this session (helper failed). In-session, add once: this review was not independent of the work it reviewed.
**Dimension Coverage:** Report all 11. Clean dimensions grouped on one summary line.
+336
View File
@@ -0,0 +1,336 @@
#!/usr/bin/env node
// xray.mjs: what git history says about the code, for the X-ray skill.
//
// Two reads, both fixed sequences over git with one right answer per repo:
// hotspots (which files change most, which change together, which hot source
// files have no test) and history (one file's commits, who wrote its lines,
// and the pull requests behind it). The script only reads. What the numbers
// mean for the code is the agent's call.
import fs from "node:fs";
import path from "node:path";
import { execFileSync, spawnSync } from "node:child_process";
import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
const USAGE = `
xray.mjs: churn, co-change and one file's history from git. JSON on stdout.
It never changes the repository.
node xray.mjs hotspots [--root <dir>] [--path <area>] [--max-commits 500] [--top 20]
node xray.mjs history <path> [--root <dir>] [--max-commits 50]
hotspots Reads the last --max-commits commits (merges skipped), scoped to
--path when given. Only files tracked at HEAD count (renamed,
deleted and untracked generated files drop out); lockfiles, dist/,
build/ and node_modules/ are left out too. Prints { ok, root,
window: { commits, capped }, churn, pairs, untested }.
churn [{ file, commits }], most changed first.
pairs [{ a, b, together, support }]: files changed together in
at least 3 commits; support is together divided by the
smaller of the two files' commit counts. Highest support
first. Commits touching more than 50 files are left out
of pairs (bulk renames and formatting sweeps).
untested [{ file, commits }]: source files changed in at
least 2 commits, with no test file
anywhere in the repo whose name contains the file's base
name.
capped is true when older commits fell outside the window. Each list
holds at most --top entries.
history One file's story. Prints { ok, path, commits, blame, prs, sources }.
commits [{ hash, date, author, subject }] from git log --follow,
newest first, at most --max-commits.
blame { lines, authors: [{ author, lines, share }], oldest,
newest } at HEAD; null when the file is gone at HEAD.
prs [{ number, subject, title, summary }] parsed from commit
and merge subjects (#123, Merge pull request #123).
title and summary (the body's first paragraph) come from
gh pr view, for at most 10, when gh is installed and
signed in; otherwise they are null.
sources { git: true, blame: true|false,
gh: "used"|"missing"|"unauthenticated"|"timed-out" }.
Exit: 0 ok · 2 bad arguments · 3 not a git repository (not-a-repo), or the
path has no history (no-history).
`;
const GH_TIMEOUT_MS = 5000;
const GH_MAX_PRS = 10;
const PAIR_MIN = 3;
const PAIR_MAX_FILES = 50;
const UNTESTED_MIN = 2;
/** Run git with an args array (never a shell). { ok, out }. */
function git(cwd, args) {
try {
const stdout = execFileSync("git", args, {
cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
maxBuffer: 64 * 1024 * 1024,
windowsHide: true,
// Without this, some reads refresh the index on disk: a write.
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
});
return { ok: true, out: stdout };
} catch {
return { ok: false, out: "" };
}
}
function count(value, flag, fallback) {
if (value === undefined) return fallback;
const n = Number(value);
if (!Number.isInteger(n) || n < 1) fail(EXIT.USAGE, "bad-number", `--${flag} needs a whole number above 0, got "${value}".`, "Run with --help for usage.");
return n;
}
/** The repository's top level for --root, or the not-a-repo failure. */
function repoTop(root) {
const top = fs.existsSync(root) ? git(root, ["rev-parse", "--show-toplevel"]) : { ok: false };
if (!top.ok) {
fail(EXIT.NOT_FOUND, "not-a-repo", `${root} is not inside a git repository.`, "X-ray needs git history; explain mode can still read the code.");
}
return path.resolve(top.out.trim());
}
/** A path from the person (relative to --root) as a forward-slash path relative to the repo top. */
function repoPath(root, top, p) {
const abs = path.resolve(root, p);
// Compare real paths: git prints the real top level, while --root may be an
// 8.3 short name or arrive through a symlink. A path that does not exist
// any more (a deleted file) resolves through its nearest existing ancestor.
let existing = abs;
while (!fs.existsSync(existing) && path.dirname(existing) !== existing) existing = path.dirname(existing);
const real = path.join(fs.realpathSync.native(existing), path.relative(existing, abs));
return path.relative(fs.realpathSync.native(top), real).split(path.sep).join("/");
}
const hasCommits = (top) => git(top, ["rev-parse", "--verify", "-q", "HEAD"]).ok;
/* -------------------------------------------------------------- hotspots */
const LOCKFILES = new Set([
"package-lock.json",
"npm-shrinkwrap.json",
"yarn.lock",
"pnpm-lock.yaml",
"bun.lockb",
"bun.lock",
"Cargo.lock",
"Gemfile.lock",
"poetry.lock",
"Pipfile.lock",
"composer.lock",
"go.sum",
"uv.lock",
"flake.lock",
"packages.lock.json",
]);
function skipped(file) {
const base = file.slice(file.lastIndexOf("/") + 1);
if (LOCKFILES.has(base) || base.endsWith(".lock")) return true;
return /(^|\/)(dist|build|node_modules)\//.test(file);
}
const SOURCE_EXT = /\.(m?[jt]sx?|cjs|cts|mts|py|rb|go|rs|java|kt|kts|scala|cs|fs|php|swift|m|mm|c|cc|cpp|cxx|h|hpp|ex|exs|erl|clj|dart|lua|pl|r|jl|hs|ml|vue|svelte|sh|ps1)$/i;
const TEST_DIR = /(^|\/)(tests?|__tests__|specs?|e2e)\//i;
const TEST_NAME = /([._-](test|spec)s?\.[^/]+$)|(^tests?_)|(_tests?\.[^/]+$)/i;
const baseName = (file) => file.slice(file.lastIndexOf("/") + 1);
const stem = (file) => baseName(file).replace(/\.[^.]+$/, "");
const isTest = (file) => TEST_DIR.test(file) || TEST_NAME.test(baseName(file)) || /^test-/i.test(baseName(file));
/** [hash, [file...]] per commit, newest first, merges skipped. */
function commitFiles(top, limit, scope) {
if (!hasCommits(top)) return [];
const args = ["-c", "core.quotepath=off", "log", "--no-merges", "--no-renames", `-n${limit}`, "--name-only", "--format=%x01%H"];
if (scope) args.push("--", scope);
const log = git(top, args);
if (!log.ok) return [];
return log.out
.split("\x01")
.slice(1)
.map((block) => {
const [hash, ...files] = block.split("\n").map((l) => l.trim());
return [hash, files.filter(Boolean)];
});
}
function hotspots(argv) {
const args = parseArgs(argv, { values: ["root", "path", "max-commits", "top"] });
const root = path.resolve(args.root || ".");
const max = count(args["max-commits"], "max-commits", 500);
const topN = count(args.top, "top", 20);
const top = repoTop(root);
const scope = args.path ? repoPath(root, top, args.path) || "." : null;
// One commit past the window says whether anything older was cut off.
let commits = commitFiles(top, max + 1, scope);
const capped = commits.length > max;
if (capped) commits = commits.slice(0, max);
// Only files tracked at HEAD count: a renamed or deleted file's history
// would otherwise crowd live files out of the top lists, and untracked
// build output (a gitignored skills/) drops out on its own.
const tracked = git(top, ["-c", "core.quotepath=off", "ls-files"]);
const files = tracked.ok ? tracked.out.split("\n").map((l) => l.trim()).filter(Boolean) : [];
const present = new Set(files);
const churn = new Map();
const together = new Map();
for (const [, all] of commits) {
const files = [...new Set(all.filter((f) => present.has(f) && !skipped(f)))].sort();
for (const f of files) churn.set(f, (churn.get(f) || 0) + 1);
if (files.length > PAIR_MAX_FILES) continue;
for (let i = 0; i < files.length; i++) {
for (let j = i + 1; j < files.length; j++) {
const key = `${files[i]}\n${files[j]}`;
together.set(key, (together.get(key) || 0) + 1);
}
}
}
const byChurn = [...churn].map(([file, n]) => ({ file, commits: n })).sort((x, y) => y.commits - x.commits || x.file.localeCompare(y.file));
const pairs = [];
for (const [key, n] of together) {
if (n < PAIR_MIN) continue;
const [a, b] = key.split("\n");
const support = Math.round((n / Math.min(churn.get(a), churn.get(b))) * 100) / 100;
pairs.push({ a, b, together: n, support });
}
pairs.sort((x, y) => y.support - x.support || y.together - x.together || x.a.localeCompare(y.a) || x.b.localeCompare(y.b));
// Tests are looked for across the whole repo, not only inside --path: a
// file under src/ is usually tested from a sibling tests/ folder.
const testNames = files.filter(isTest).map((f) => baseName(f).toLowerCase());
const untested = byChurn.filter(({ file, commits: n }) => {
if (n < UNTESTED_MIN || !SOURCE_EXT.test(file) || isTest(file)) return false;
const name = stem(file).toLowerCase();
return !testNames.some((t) => t.includes(name));
});
out({
ok: true,
root: top,
...(scope ? { path: scope } : {}),
window: { commits: commits.length, capped },
churn: byChurn.slice(0, topN),
pairs: pairs.slice(0, topN),
untested: untested.slice(0, topN),
});
}
/* --------------------------------------------------------------- history */
function blameSummary(top, file) {
const r = git(top, ["blame", "--line-porcelain", "HEAD", "--", file]);
if (!r.ok) return null;
const authors = new Map();
let lines = 0;
let oldest = Infinity;
let newest = -Infinity;
let author = null;
for (const line of r.out.split("\n")) {
if (line.startsWith("author ")) author = line.slice(7);
else if (line.startsWith("author-time ")) {
const t = Number(line.slice(12));
if (t < oldest) oldest = t;
if (t > newest) newest = t;
} else if (line.startsWith("\t")) {
lines++;
authors.set(author, (authors.get(author) || 0) + 1);
}
}
const day = (t) => (Number.isFinite(t) ? new Date(t * 1000).toISOString().slice(0, 10) : null);
return {
lines,
authors: [...authors]
.map(([name, n]) => ({ author: name, lines: n, share: Math.round((n / lines) * 100) / 100 }))
.sort((x, y) => y.lines - x.lines || x.author.localeCompare(y.author)),
oldest: day(oldest),
newest: day(newest),
};
}
const PR_PATTERNS = [/Merge pull request #(\d+)/gi, /#(\d+)\b/g];
function prNumbers(subjects) {
const seen = new Map();
for (const subject of subjects) {
for (const pattern of PR_PATTERNS) {
for (const m of subject.matchAll(pattern)) {
const n = Number(m[1]);
if (!seen.has(n)) seen.set(n, subject);
}
}
}
return [...seen].map(([number, subject]) => ({ number, subject, title: null, summary: null }));
}
/** "used", "missing", "unauthenticated" or "timed-out", filling in prs as it goes. */
function ghDetails(top, prs) {
const gh = (args) => spawnSync("gh", args, { cwd: top, encoding: "utf8", timeout: GH_TIMEOUT_MS, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
const timedOut = (r) => r.error?.code === "ETIMEDOUT" || (r.signal && r.status === null);
const auth = gh(["auth", "status"]);
if (auth.error?.code === "ENOENT") return "missing";
if (timedOut(auth)) return "timed-out";
if (auth.error || auth.status !== 0) return "unauthenticated";
let status = "used";
for (const pr of prs.slice(0, GH_MAX_PRS)) {
const r = gh(["pr", "view", String(pr.number), "--json", "title,body"]);
if (timedOut(r)) {
status = "timed-out";
break;
}
if (r.status !== 0) continue; // an issue number, or a PR this remote does not know
try {
const { title, body } = JSON.parse(r.stdout);
pr.title = title || null;
// The first paragraph that says something, minus any heading lines on
// top of it: GitHub's template puts "## Summary" right above the text.
const paragraphs = (body || "").replace(/\r\n/g, "\n").split(/\n\s*\n/).map((p) => p.replace(/^(#{1,6}\s[^\n]*(\n|$))+/, "").trim());
pr.summary = paragraphs.find(Boolean) || null;
} catch {}
}
return status;
}
function history(argv) {
const args = parseArgs(argv, { values: ["root", "max-commits"] });
const target = args._[0];
if (!target) fail(EXIT.USAGE, "missing-path", "history needs the file to read.", "Run: node xray.mjs history <path>");
const root = path.resolve(args.root || ".");
const max = count(args["max-commits"], "max-commits", 50);
const top = repoTop(root);
const file = repoPath(root, top, target);
const log = hasCommits(top) ? git(top, ["log", "--follow", `-n${max}`, "--format=%H%x1f%aI%x1f%an%x1f%s", "--", file]) : { ok: false };
const commits = (log.ok ? log.out.split("\n") : [])
.filter(Boolean)
.map((line) => {
const [hash, date, author, subject] = line.split("\x1f");
return { hash, date, author, subject };
});
if (!commits.length) {
fail(EXIT.NOT_FOUND, "no-history", `${file} has no commits in this repository.`, "Check the path (relative to --root), or run hotspots to see which files have history.");
}
// Merges hide from a file's own log; the first-parent merges that touched
// it carry the "Merge pull request #N" subjects.
const merges = git(top, ["log", "--first-parent", "--merges", `-n${max}`, "--format=%s", "--", file]);
const subjects = [...commits.map((c) => c.subject), ...(merges.ok ? merges.out.split("\n").filter(Boolean) : [])];
const prs = prNumbers(subjects);
const blame = blameSummary(top, file);
const gh = ghDetails(top, prs);
out({ ok: true, path: file, commits, blame, prs, sources: { git: true, blame: blame !== null, gh } });
}
run(USAGE, async (argv) => {
const [command, ...rest] = argv;
if (command === "hotspots") return hotspots(rest);
if (command === "history") return history(rest);
fail(EXIT.USAGE, "unknown-command", command ? `Unknown command "${command}".` : "No command given.", "Run with --help: the commands are hotspots and history.");
});
+154
View File
@@ -0,0 +1,154 @@
# 🩻 X-RAY MODE
Start all X-RAY MODE responses with '🩻 [X-RAY]'
## Role
Codebase guide. Two jobs, one card: **explain** how and why an area of the code works, citing the files and the history behind it, or **find the rough spots** worth fixing and hand the ones the person picks to Pathfinder or Plan as a brief. Reads, counts and judges; never builds.
## Interface
The FIRST thing you do, before anything else in this file, before the mode question: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow xray` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-xray/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/xray.md. The mode question, the answer or the ranked list, and the save offer all go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context. On the console, a `__stop` action is the person ending the session (console-stop.md); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console-finish.md).
## 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."
## Scripts
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-xray/scripts/` globally). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
- `node "<S>/xray.mjs" hotspots [--path <area>] [--max-commits 500] [--top 20]`: counts from `git` history. `churn` (files by commits), `pairs` (files changed together in 3+ commits, ranked by `support`), `untested` (often-changed source files with no test named after them), and `window` (`capped: true` when the history ran past `--max-commits`).
- `node "<S>/xray.mjs" history <path> [--max-commits 50]`: one file's story. `commits` (hash, date, author, subject, following renames), `blame` (authors by line share, oldest and newest lines), `prs` (titles and first paragraphs, when `gh` works), and `sources` (`gh`: `used`, `missing`, `unauthenticated` or `timed-out`).
- Exit 3 `not-a-repo`: no git history. Explain mode carries on from the code alone; rough-spots mode reads the code and judges without the counts, and says so.
## Rules
- Follow `./AGENTS.md`.
- **Never edit code.** The only files you write are the ones the person asks to keep, under `specs/<name>/`.
- **Cite everything.** Every claim names its file (`path:line` where it helps); every "why" names the commit (short hash) or PR it rests on. No citation, no claim: say it is a guess.
- **Say once which sources could not be used** (no `gh`, `gh` not signed in, no git history), near the top of the answer, so a thin "why" is never read as "there was no reason".
- **Never stop to ask for an install** or a sign-in. Use what is there.
- **The counts are leads, not verdicts.** A script ranks; you read the code and judge.
- Plain words. Name the files and functions; skip jargon the person did not use.
## Process
### Step 1: Mode and Area
A typed argument skips the question:
| Argument | Mode | Area |
|----------|------|------|
| `explain <area>` | Explain | `<area>` |
| `survey` or `survey <area>` | Rough spots | the whole repo, or `<area>` |
| plain text (`how does the exporter work`) | Explain | read from the text |
| none | ask | ask |
Otherwise ask both at once (console: a `choice` and a `text` card in one batch):
> "What do you want to know?
> 1. **Explain an area**: how it works and why it is that way
> 2. **Find the rough spots**: what makes this code hard to change, ranked
>
> Which area? (a folder, file or feature; required to explain, optional for rough spots)"
Explain with no area: ask for one. Never guess the mode from a vague request.
### Step 2a: Explain an Area
1. **Find the area's code.** Search for it, then read its entry points and the files they lean on. Read enough to trace one real use end to end.
2. **Its history.** Run `xray.mjs history` on the 1-5 key files. Read the commits and PRs that shaped them; follow a subject that matters into its diff (`git show <hash> --stat`, then the lines).
3. **Answer:**
```
🩻 [X-RAY] <area>
Sources: code, git history, PRs (or: no gh, git only · no git history, code only)
## In one paragraph
## How it works
Entry points · the flow, step by step · the data it holds and passes · its boundaries (what calls it, what it calls)
## Why it is this way
The decisions behind the shape, each with its commit or PR
## Worth knowing
Traps, odd corners, what a newcomer would get wrong
```
Cite `file` paths in every section and short commit hashes in the "why".
4. **Offer to keep it:** "Save this as `specs/<name>/XRAY-<area-slug>-<date>.md`, as input for Pathfinder or Plan? (yes/no)". `<name>` is the spec folder it belongs to (ask, offering the area's kebab-case slug), `<date>` is `YYYYMMDD`. Yes → write the answer there exactly as shown. Console: the answer is a doc, the offer a `confirm` card.
### Step 2b: Find the Rough Spots
1. **Count.** Run `xray.mjs hotspots` (with `--path` when an area was given).
2. **Read and judge.** Open the top candidates: the strongest `pairs`, the heaviest `churn`, every `untested` file near the top. Look for:
- **Files that always change together**: one idea split across places.
- **Shallow wrappers**: a layer that only passes calls through, adding a place to change.
- **Tangled boundaries**: modules reaching into each other's insides, circular imports, one change rippling outward.
- **Untested hot spots**: code that changes often with nothing to catch a break.
Drop false alarms: a pair that changes together for a good reason (a test beside its code, a schema and its migration), generated files, a churn spike from one big rename.
3. **Present a ranked list**, worst first, at most 10:
```
1. <short name> [files that change together]
Files: a.ts, b.ts, c.ts
Why it hurts: <one sentence, citing the evidence: "changed together in 14 of 16 commits">
Today: to change <X> you must touch a.ts, b.ts and c.ts.
```
Every spot carries a concrete "to change X today you must touch..." example. No spots worth raising: say so, with what you checked, and end.
4. **The pick.** "Which are worth fixing? Reply with numbers, each with an optional note (e.g. `1, 3: the exporter part only`)." Console: a `multi` card, one option per spot, notes in the free text.
5. **Write the brief** with the picked spots only: `specs/<name>/ARCHITECTURE-BRIEF-<YYYYMMDD>.md` (`<name>` asked as above, offering the area's slug or `codebase-health`):
```markdown
# Architecture Brief: <area or "whole codebase">
**Date:** <YYYY-MM-DD> · **Area:** <area> · **Sources:** <as above>
## 1. <short name>
**Files:** ... · **Evidence:** ...
**Today:** to change <X> you must touch ...
**Note:** <the person's note, or none>
```
Nothing picked: write nothing, and say so.
## Session End
Work summary: the mode, the area, the sources used, and the file written (or that nothing was kept).
**Next step:**
- A brief written, the fix big or unclear → "Next (NEW conversation): `/plan2code-0-pathfinder` with `specs/<name>/` as its notes."
- A brief written, the fix settled → "Next (NEW conversation): `/plan2code-1-plan` with `specs/<name>/` as its brief."
- An explain answer saved → whichever of the two fits the person's aim; unsure → ask.
- Nothing kept → "X-ray complete." Mention `/plan2code-xray` again for another area.
On the console, `finish.command` is `/plan2code-0-pathfinder` or `/plan2code-1-plan`, without placeholders.
```
⋅
╭───╮
╲│ ★ │╱
│ ◡ │ X-ray done!
╰┬─┬╯
```
The rough-spots mode adapts Matt Pocock's `improve-codebase-architecture` skill (MIT) and pstack's codebase survey; explain mode adapts pstack's `how` and `why`.
+17 -4
View File
@@ -32,9 +32,11 @@ The page draws the cards itself — you never send the list. It also knows the r
```
- No AGENTS.md → `recommend: "plan2code-init"`; the note says why.
- A spec mid-pipeline → recommend its next step; that card's `details` names where it stands ("Plan drafted", "Phase 2 of 4 is next"). The picker pre-selects the most recently touched spec — recommend for THAT one.
- A spec mid-pipeline → recommend its next step; that card's `details` names where it stands ("Plan drafted", "Phase 2 of 4 is next"). The picker pre-selects the most recently touched spec that is not `fixed` — recommend for THAT one.
- A spec that scans `unrecognized` ("files on disk") is input, not progress: its folder rides along on a Pathfinder or Plan launch as reference, and those are the only pipeline cards it lights. Read the files and recommend the fit — a settled design doc the person wrote is Plan's brief, loose notes are Pathfinder's. No skill generates such a doc; see the table below for what each one does write. Never flag Document or anything downstream of it for such a spec.
- Nothing on disk → `recommend: "plan2code-0-pathfinder"`; the note invites the first idea.
- A `diagnosed` spec ("Bug diagnosed") is a bug Diagnose wrote up: recommend Quick Task, or Plan when its `DIAGNOSIS-<date>.md` sizes the fix as big; its folder rides along on either launch.
- A `fixed` spec ("Bug fixed") is a diagnosed bug Quick Task fixed but did not archive: finished, so never recommend for it or name it in the note; the picker never pre-selects one and hides it while unavailable workflows are hidden. The person archives it (Quick Task offers that once the bug is fixed) or deletes it with the picker's ✕.
- Nothing on disk, or only `fixed` specs → `recommend: "plan2code-0-pathfinder"`; the note invites the first idea.
- Recommend only what you would tell a person who asked "where do I start?". When in doubt, no flag and a neutral note — the page falls back to flagging the selected spec's own next step.
- `recommend` must name a lit card for the initial selection. If the person switches specs or starts fresh, the page derives the suggestion and detail from its scan instead.
@@ -51,7 +53,7 @@ Ground truth for menu notes and Ask-tab answers. For anything beyond this table,
| 0-pathfinder | the idea, loose notes | `pathfinder/map.md`, `pathfinder/questions/NN-<slug>.md`; cleared → `PLAN-DRAFT-<date>.md` |
| 1-plan | idea or `PLAN-DRAFT` | `PLAN-DRAFT-<date>.md`, `PLAN-CONVERSATION-<date>.md` |
| 1b-revise-plan | `overview.md`, `phase-X.md` | the same, revised |
| quick-task | the ask | code; escalated → `PLAN-DRAFT-<date>.md` |
| quick-task | the ask; a `DIAGNOSIS-*.md` when launched on one | code; the diagnosis set to `Fixed`, then the folder moved to `specs--completed/` on a yes; escalated → `PLAN-DRAFT-<date>.md` |
| 2-document | `PLAN-DRAFT`, `PLAN-CONVERSATION` (optional) | `overview.md`, `phase-X.md` |
| 3-implement(-review) | `overview.md`, `phase-X.md` | code; `[x]` marks + completion summary in `phase-X.md` |
| review | spec, diff | the fixes picked; no spec writes |
@@ -59,6 +61,8 @@ Ground truth for menu notes and Ask-tab answers. For anything beyond this table,
| handoff | conversation, spec, git | `<timestamp>-handoff.md` (OS temp or `handoffs/`) |
| changelog | `CHANGELOG.md`, `package.json`, git history | `CHANGELOG.md` entries, `package.json` version; no commits |
| git | git status, branches, diffs, `AGENTS.md` | commits, branches; optional `.gitignore`, push, publish; no spec writes |
| xray | the codebase, `git` history, `gh` when present | an answer; `ARCHITECTURE-BRIEF-<date>.md` or `XRAY-<area>-<date>.md` when asked |
| diagnose | the bug, the codebase, `references/building-habits.md` | `DIAGNOSIS-<date>.md`; no code changes |
## A pick arrives
@@ -72,7 +76,7 @@ A card click is a send whose action carries the skill:
"reply": "Start Implement (/plan2code-3-implement) for specs/lunch-vote, right here in this session." }
```
`__launch` names no question; like `__stop` it is about the session. `spec` is the picker's selected spec dir — present only when the launched skill takes a spec and the person picked one; absent means "start from scratch".
`__launch` names no question; like `__stop` it is about the session. `spec` is the picker's selected spec dir — present only when the launched skill takes a spec (or is Quick Task on a `diagnosed` spec) and the person picked one; absent means "start from scratch".
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your own file-read tool instead.** Every Plan2Code skill below the dashboard ships `disable-model-invocation: true` on purpose — it exists to be read and followed inline, not launched as a sub-skill — and calling one through a skill-invocation tool errors out and strands the hand-off mid-launch.
@@ -101,6 +105,15 @@ If `skill` is not in the table below, say so on the page and stay the dashboard.
| plan2code-1b-revise-plan | revise-plan | | plan2code-4-finalize | finalize |
| plan2code-quick-task | quick-task | | plan2code-handoff | handoff |
| plan2code-git | git | | plan2code-changelog | changelog |
| plan2code-xray | xray | | plan2code-diagnose | diagnose |
## A delete arrives
The ✕ on a picker chip asks for that spec to go, after a two-step confirm on the page: `{ "i": "__delete", "type": "delete", "spec": "specs/<name>" }`. The page never deletes; you do, through the console's checked command, never your own `rm`:
1. `node "<D>/console.mjs" delete-spec --spec <action.spec>` from the project root. Exit 0 → `{ ok, removed }`. Exit 3 → refused, `message` says why (not `specs/<name>`, a link, missing); nothing was touched.
2. `node "<D>/console.mjs" open --resume <sid> --no-open --workflow dashboard`, which rescans `specs/`.
3. Post the menu again with `--wait`; the note says what was deleted, or why it was not. Stay the dashboard.
## Coming back from another skill
+31
View File
@@ -0,0 +1,31 @@
# Building Habits
> Read by Quick Task, Implement, Implement + Review and Diagnose at the moments they name. Never invoked as a skill.
## Find the cause first
When a bug is reported or turns up, or a test fails unexpectedly:
1. Before changing any code, build a command that fails on this bug: a test, a script, a `curl`, a CLI run. Run it and see it fail the way the bug report says.
2. If no such command can be built (timing, one customer's data, production only), say so. List your best guesses, ranked, with the evidence for each, and let the person decide whether to fix on a guess.
3. Name the cause in one line, fix it, then run the reproduction again and see it pass.
4. Keep the reproduction: turn it into a regression test in the project's existing test runner. With no runner, describe it in the summary and discard it. Never add a test framework for it. When Test first also applies, the reproduction is that first failing test: write it once.
## Test first
Applies only when the phase's tasks carry `Test:` lines (the plan picked Test first), or the person said yes to "Write the test first?" in Quick Task. For each task:
1. Write the test at the task's named test spot (its `Test:` line, or the plan's Verify section).
2. Run it and see it fail for the right reason: the behaviour is missing, not a typo or an import error.
3. Write the code until the test passes. Keep the change to what the test asks for.
4. Never weaken, skip or delete a test to make it pass. If the test itself is wrong, say so and fix the test on its own.
## Pin behaviour first
For a task meant to change no behaviour (a restructure, a rename, a move):
1. Before touching the code, add or confirm tests that cover what the task touches.
2. Run them and see them pass.
3. Make the change.
4. Run the same tests, unchanged. They must pass. A test that needs editing means behaviour changed: stop and say so.
Adapted from Matt Pocock's `diagnose` and `tdd` skills and pstack's debugging playbook (both MIT).
+26
View File
@@ -210,6 +210,32 @@ export function rel(root, p) {
return path.relative(root, p).split(path.sep).join("/") || ".";
}
/* ------------------------------------------------- planning-file patterns */
// The loop completion markers. The loop scans specs/ for them, so no planning
// file may contain one. The one copy every skill script checks against.
export const LOOP_TOKENS = /\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
// The metrics collector's own scrape patterns (plan2code-metrics/src/collector.ts).
export const SCRAPE = [
{ name: "overall confidence with %", re: /(?:Overall|Final|Total)?\s*\**[Cc]onfidence\**[:\s*]+(\d{1,3})%/ },
{ name: "confidence table cell", re: /[|]\s*[Cc]onfidence\s*[|]\s*(\d{1,3})/ },
{ name: "bare Requirements + number", re: /[Rr]equirements?[:\s|]+(\d{1,2})/ },
{ name: "bare Feasibility + number", re: /[Ff]easibility[:\s|]+(\d{1,2})/ },
{ name: "bare Integration + number", re: /[Ii]ntegration[:\s|]+(\d{1,2})/ },
{ name: "bare Risk + number", re: /[Rr]isk[:\s|]+(\d{1,2})/ },
];
/** Every SCRAPE pattern that matches `text`, as `<name>: "<match>"`. */
export function scrapeHits(text) {
const hits = [];
for (const s of SCRAPE) {
const m = text.match(s.re);
if (m) hits.push(`${s.name}: "${m[0].trim()}"`);
}
return hits;
}
/* --------------------------------------------------------- the web console */
// The web console ships beside these scripts in every installed skill
+153 -3
View File
@@ -14,7 +14,7 @@
import fs from "node:fs";
import path from "node:path";
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleLib, isoDate, phaseFiles } from "./common.mjs";
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleLib, isoDate, phaseFiles, LOOP_TOKENS, scrapeHits } from "./common.mjs";
const USAGE = `
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
@@ -32,6 +32,22 @@ specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
phases, and consistency checks. <spec> is specs/<name>, <name>, or a path
to its overview.md.
node specs.mjs check <spec> [--root <dir>]
Fail on a malformed spec: status's error and warn checks, plus every
checkbox under ## Tasks being a "- [ ] **Task N.M:**" line, no loop
completion token and no bare metric word (outside a METRICS_JSON
comment) in overview.md or a phase file. An indented " - Test:"
sub-bullet is fine. Exit 4 with the problems when any is an error.
node specs.mjs check-draft <file|spec> [--root <dir>]
Fail on a malformed PLAN-DRAFT (a path, or a spec's newest non-archived
draft): its **Status:** line; for a Complete draft, the sections
Document reads, a ### Phase heading in section 5 and a parseable
METRICS_JSON comment (warns when no phase names an FR- item); always no
loop completion token and no bare metric word (Plan's own Confidence
header line is allowed; a pathfinder-written draft has none). Exit 4 on
any error.
node specs.mjs metrics <spec> --step document|finalize [--set key=value ...]
The METRICS_JSON comment for that step, countable fields computed from
the files; judgment fields come from --set (numbers only).
@@ -752,10 +768,144 @@ async function cmdArchive(args) {
});
}
/* ---------------------------------------------------------------- checks */
// METRICS_JSON comments are the one place a metric word may sit beside a number.
const METRICS_COMMENT_RE = /<!--\s*METRICS_JSON[\s\S]*?-->/g;
// The collector's confidence patterns. Plan's draft header carries a
// "**Confidence:** NN%" line on purpose (the collector's fallback when
// METRICS_JSON is missing), so a Plan-written draft is exempt from these two.
const CONFIDENCE_HITS = ["overall confidence with %", "confidence table cell"];
function proseChecks(text, file, add, { allowConfidence = false } = {}) {
const m = text.match(LOOP_TOKENS);
if (m) add("error", file, "loop-token", `contains the loop completion token ${m[0]} (the loop scans specs/ for these)`);
for (const h of scrapeHits(text.replace(METRICS_COMMENT_RE, ""))) {
if (allowConfidence && CONFIDENCE_HITS.some((name) => h.startsWith(`${name}:`))) continue;
add("error", file, "metric-word", `metrics-scraper bait (${h}); hyphenate the label or reword`);
}
}
// The lint-style report: ok with the problems when nothing is an error, else
// the failure shape (error, message, next, the same lines on stderr), written
// here rather than through fail(), which would drop the problems list.
function checkReport(command, base, problems) {
const errors = problems.filter((p) => p.level === "error").length;
const report = { ...base, errors, warnings: problems.length - errors, problems };
if (!errors) {
out({ ok: true, ...report });
return;
}
const message = `${command} found ${errors} error${errors === 1 ? "" : "s"}.`;
const next = `Fix each error in problems, then rerun ${command}.`;
out({ ok: false, error: `${command}-failed`, message, next, ...report });
process.stderr.write(`error: ${message}\nnext: ${next}\n`);
process.exitCode = EXIT.INVALID;
}
async function cmdCheck(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1], { allowArchived: true });
const problems = [];
const add = (level, file, code, message) => problems.push({ level, file, code, message });
const at = (name) => `${spec.rel}/${name}`;
const files = phaseFiles(spec.dir);
// status's own checks, each pinned to the phase file it opens with (by its
// real name: status says phase-N.md even for a phase-1-setup.md), else
// overview.md (a missing file or checklist row is fixed in the overview).
for (const c of specStatus(spec).checks) {
if (c.level !== "error" && c.level !== "warn") continue;
const named = c.code !== "missing-checklist-row" && c.message.match(/^phase-(\d+)/i);
add(c.level, at(named && files.has(Number(named[1])) ? files.get(Number(named[1])) : "overview.md"), c.code, c.message);
}
const names = [...(fs.existsSync(path.join(spec.dir, "overview.md")) ? ["overview.md"] : []), ...[...files.keys()].sort((a, b) => a - b).map((n) => files.get(n))];
for (const name of names) {
const text = readText(path.join(spec.dir, name)) || "";
if (name !== "overview.md") {
const tasks = section(text, /^#{1,6}\s+Tasks\b/i);
for (const [i, line] of (tasks ? tasks.lines : []).entries()) {
if (CHECKBOX_RE.test(line) && !TASK_RE.test(line)) {
add("error", at(name), "bad-task-line", `${name}:${tasks.start + 2 + i} is a checkbox under Tasks that is not a task line ("- [ ] **Task N.M:**"): ${line.trim().slice(0, 120)}`);
}
}
}
proseChecks(text, at(name), add);
}
checkReport("check", { spec: spec.rel, checked: names.map(at) }, problems);
}
const DRAFT_STATUSES = ["Draft", "Phase 3 Complete - Resume at Phase 4", "Escalated from Quick Task - Resume at Phase 2", "Complete"];
// The headings Document reads out of a Complete draft.
const DRAFT_SECTIONS = [
{ name: "## 1. Executive Summary", re: /^##\s+1\.\s+Executive Summary\b/im },
{ name: "## 2. Requirements", re: /^##\s+2\.\s+Requirements\b/im },
{ name: "### 2.1", re: /^###\s+2\.1\b/m },
{ name: "### 2.4", re: /^###\s+2\.4\b/m },
{ name: "## 3. Tech Stack", re: /^##\s+3\.\s+Tech Stack\b/im },
{ name: "## 4. Architecture", re: /^##\s+4\.\s+Architecture\b/im },
{ name: "## 5. Implementation Phases", re: /^##\s+5\.\s+Implementation Phases\b/im },
{ name: "## 6. Risks and Mitigations", re: /^##\s+6\.\s+Risks and Mitigations\b/im },
{ name: "## 7. Success Criteria", re: /^##\s+7\.\s+Success Criteria\b/im },
{ name: "## 9. Assumptions", re: /^##\s+9\.\s+Assumptions\b/im },
];
/** A PLAN-DRAFT path, or a spec whose newest non-archived draft is used. */
function resolveDraft(root, arg) {
if (arg && /\.md$/i.test(arg) && !/\/overview\.md$/i.test(arg.replace(/\\/g, "/"))) {
const file = path.resolve(root, arg);
if (!fs.existsSync(file)) fail(EXIT.NOT_FOUND, "draft-not-found", `No file at ${rel(root, file)}.`, "Pass a PLAN-DRAFT-*.md path, or the spec folder to check its newest draft.");
return file;
}
const spec = resolveSpec(root, arg, { allowArchived: true });
const live = planDrafts(spec.dir).filter((d) => !d.archived);
if (!live.length) fail(EXIT.NOT_FOUND, "no-draft", `${spec.rel} has no PLAN-DRAFT-*.md.`, "Write the PLAN-DRAFT first (Plan's Phase 7), or pass its path.");
return path.join(spec.dir, live.at(-1).file);
}
async function cmdCheckDraft(args) {
const root = path.resolve(args.root || ".");
const file = resolveDraft(root, args._[1]);
const shown = rel(root, file);
const text = readText(file) || "";
const problems = [];
const add = (level, f, code, message) => problems.push({ level, file: f, code, message });
const status = statusOf(text);
const value = status === null ? null : status.trim();
if (value === null) add("error", shown, "bad-status", "has no **Status:** line");
else if (!DRAFT_STATUSES.includes(value)) add("error", shown, "bad-status", `**Status:** "${value}" is not one of ${DRAFT_STATUSES.join(" | ")}`);
// Only a Complete draft is read by Document; the others (a pathfinder draft
// at Resume at Phase 4 has placeholder sections by design) get the light check.
if (value === "Complete") {
for (const s of DRAFT_SECTIONS) if (!s.re.test(text)) add("error", shown, "missing-section", `has no ${s.name} heading (Document reads it)`);
const phasesSec = section(text, /^##\s+5\.\s+Implementation Phases\b/i);
if (phasesSec && !phasesSec.lines.some((l) => /^###\s+Phase\b/i.test(l))) add("error", shown, "no-phases", "section 5 has no ### Phase heading");
// Whitespace after METRICS_JSON, as the collector's own pattern requires.
const metrics = text.match(/<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/);
let parsed = false;
if (metrics) {
try {
JSON.parse(metrics[1]);
parsed = true;
} catch {}
}
if (!parsed) add("error", shown, "no-metrics", metrics ? "the METRICS_JSON comment does not parse as JSON" : "has no <!-- METRICS_JSON {...} --> comment (Plan's Phase 7 writes it)");
const frSec = section(text, /^###\s+2\.1\b/);
if (frSec && phasesSec && /\bFR-\d+/.test(frSec.lines.join("\n")) && !/\bFR-\d+/.test(phasesSec.lines.join("\n"))) {
add("warn", shown, "untraced-requirements", "section 2.1 lists FR- items but no phase in section 5 names one");
}
}
// A pathfinder-written draft (no METRICS_JSON yet) carries no confidence
// line, as pathfinder.mjs lint already holds it to.
const byPathfinder = /plan2code-0-pathfinder/.test(text) && !/METRICS_JSON/.test(text);
proseChecks(text, shown, add, { allowConfidence: !byPathfinder });
checkReport("check-draft", { checked: [shown], status: value }, problems);
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "step", "phase", "to", "task"], lists: ["set"] });
const cmd = args._[0];
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, tick: cmdTick, archive: cmdArchive };
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, metrics, mark, tick, archive. Run with --help.");
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, tick: cmdTick, archive: cmdArchive, check: cmdCheck, "check-draft": cmdCheckDraft };
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, check, check-draft, metrics, mark, tick, archive. Run with --help.");
await commands[cmd](args);
});
+7 -1
View File
@@ -51,6 +51,9 @@ for whichever comes first:
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.
- **The helper rule still applies:** a fresh helper runs the analysis when
available, you verify every finding, and the report carries its Reviewed by
line.
- **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,
@@ -116,15 +119,18 @@ review set it to its own stage):
"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": "show", "label": "Show me it working" },
{ "id": "approve", "label": "Approve this phase" },
{ "id": "changes", "label": "I want changes" }
],
"token": { "approve": "approved", "changes": "needs changes", "show": "show me" },
"thread": [{ "who": "agent", "text": "Review done: 2 of 3 findings fixed; the rest is written up in the findings tab." }]
}]
}
```
Review Mode's own closing gate ("Reply approved to commit") is this card:
`show` runs as `notes/implement.md` → Show me it working says, then reopens
this card without it. 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 `notes/implement.md` → After
approval: the finish.
+16 -1
View File
@@ -17,7 +17,7 @@ menu judgment and the launch steps; this is what the page does around them.
```
`spec` is the picker's selected spec dir, present only when the launched skill
takes a spec and the person picked one. `resume` is the one command to run
takes a spec (or is Quick Task on a `diagnosed` spec) and the person picked one. `resume` is the one command to run
first, before reading anything: it reuses the live server and turns the page
from the menu into the skill's starting screen while you read. `skillFile` is
the skill to read next (absent outside an install: then
@@ -63,3 +63,18 @@ person's turn by itself.
A `__stop` before a pick ends the session the usual way: `finish` (paused
headline, `"command": "/plan2code"`) then `stop` (`console-stop.md`).
## A delete
The ✕ on a picker chip, after the page's two-step confirm (what goes, then
the spec's name typed), sends `{ "i": "__delete", "type": "delete", "spec":
"specs/<name>" }` with a `reply` saying it is for good. It is no hop: it
carries no `resume`, and you stay the dashboard. The console never writes into
a project, so the page only asks; delete through
`node "<CONSOLE>" delete-spec --spec <spec>`, never your own `rm`. It takes
only an existing `specs/<name>` folder inside the worktree (never a link,
never deeper, never `specs--completed/`), exits 3 with `message` on a refusal
having touched nothing, and drops the workspace remembered for that spec.
Then `open --resume <sid> --no-open --workflow dashboard` to rescan, and post
the menu again with `--wait`, its note saying what went or why it did not.
The page shows the chip as "Deleting…" until that rescan lands.
+2 -2
View File
@@ -9,7 +9,7 @@ The page's top bar shows a meter of how much work this console session has
done (green, yellow, red), so the person knows when a fresh session would be
sharper. It is advice only and never blocks anything. The console counts
launches itself: Plan, Revise plan, Document, Review, Quick task, Init, Init
update, Finalize, Git and Changelog score when their session opens, and there is nothing to
update, Finalize, Git, Changelog, X-ray and Diagnose score when their session opens, and there is nothing to
post for them.
It counts answers itself too: every card the person answers in a send adds to
@@ -27,7 +27,7 @@ Per-unit work is yours to report, with `run` in any post:
nothing now: answers count instead), `pathfinder-research`, `plan`,
`revise-plan`, `document`, `implement-phase`, `implement-review-phase`,
`review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`,
`git`, `changelog`, `git-commits` and `git-conflict` (Git's own, see
`git`, `changelog`, `xray`, `diagnose`, `git-commits` and `git-conflict` (Git's own, see
`notes/git.md`).
An unknown event is exit `3`. Post only the events your notes name: a skill
that scores when its session opens (the list above this one) already has its
+7 -2
View File
@@ -39,7 +39,7 @@ several are due at once (a build's start), read them in one batch.
| --- | --- |
| `building.md` (`building`) | You run `implement`, `implement-review` or `quick-task`: right after `open`, then `notes/implement.md` or `notes/quick-task.md`. |
| `building-review.md` (`building-review`) | A build's review is asked for on the page (a `review` verdict, `__review`, Implement + Review's Stage 2). |
| `notes/<workflow>.md` (`<workflow>`) | Right after `open`: `init` (also init-update), `pathfinder`, `plan`, `revise-plan`, `document`, `implement` (also implement-review), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`. The dashboard's is `console-launches.md`. |
| `notes/<workflow>.md` (`<workflow>`) | Right after `open`: `init` (also init-update), `pathfinder`, `plan`, `revise-plan`, `document`, `implement` (also implement-review), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`. The dashboard's is `console-launches.md`. |
| `console-launches.md` (`launches`) | You are the dashboard. |
| `console-finish.md` (`finish`) | Before your first `finish` post, and when a send carries `__commit`, or `__dashboard` from a finished screen. |
| `console-stop.md` (`stop`) | A send carries `__stop`, or `__dashboard` with no finish up; or your notes say to post a `stopWarning`. |
@@ -65,7 +65,7 @@ terminal — that path loses nothing, and they can switch either way at any time
1. `node "<CONSOLE>" open --workflow <w>`, where `<w>` is one of `dashboard`,
`init`, `init-update`, `pathfinder`, `quick-task`, `plan`, `revise-plan`,
`document`, `implement`, `implement-review`, `review`, `finalize`,
`handoff`, `git`, `changelog`. Get it right: the page decides from it what
`handoff`, `git`, `changelog`, `xray`, `diagnose`. Get it right: the page decides from it what
to offer and what stopping costs. `--title` defaults to the folder name;
`--spec specs/<idea>` when you already know the spec. It prints
`{"ok":true,"sid":"...","session":"...","url":"...","terminalLine":"→ Look at the web console: ..."}`
@@ -164,6 +164,7 @@ An action whose `i` starts with `__` is about the session, not a question:
| `__stop`, `__dashboard` (no finish up) | `console-stop.md` |
| `__commit`, `__dashboard` (from a finished screen) | `console-finish.md` |
| `__launch` | `console-launches.md` |
| `__delete` | `console-launches.md` (the dashboard only) |
| `__brief` | `notes/pathfinder.md` |
| `__review`, `__done` | `building-review.md` |
| `__git` | `notes/git.md` |
@@ -352,6 +353,10 @@ with `"_delete": true` removes the whole tab).
(relative to the project, never outside it). Re-send the block, or the doc
with `"refresh": true`, after the file changes. `"select": "tasks"` keeps only
its `- [ ] **Task N.M:**` lines. Never paste a file you could name.
- **`image`** instead of `md`: `{ "id", "image": "shots/run.png", "alt": "..." }`
shows a PNG, JPEG or WebP (5 MB at most) saved directly in the session's
`shots/` folder (the `session` path `open` printed), named with letters,
digits, `.`, `_` or `-`; anything else is exit `3`.
- **`version`** moves by itself: a known doc whose content changed is the next
version. Send one only to jump; it never goes back. Write a one-line `note`
when you change a doc, and `"stale": true` while answers it does not reflect
+31 -2
View File
@@ -42,6 +42,7 @@ import {
ensureDir,
fileStamp,
forgetWorkspace,
removeSpec,
handOff,
handleFile,
healthOk,
@@ -88,6 +89,7 @@ import {
updateState,
UPLOAD_MAX_AGE_MS,
resolveDocFiles,
resolveDocImages,
validate,
validateChat,
workspaceForAgent,
@@ -267,6 +269,7 @@ async function cmdOpen() {
// refresh never re-reads the last skill's files into the new page.
try {
patch = resolveDocFiles(patch, base(structuredClone(state)), worktree);
patch = resolveDocImages(patch, base(structuredClone(state)), dir);
} catch (e) {
die(e.message, 3);
}
@@ -656,6 +659,7 @@ function postOnce() {
if (!before) die("that session has no state", 1);
try {
patch = resolveDocFiles(patch, before, before.worktree || repoRoots().worktree);
patch = resolveDocImages(patch, before, dir);
} catch (e) {
die(e.message, 3);
}
@@ -1301,6 +1305,24 @@ function cmdForget() {
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
}
/* ---------------------------------------------------------- delete-spec */
// The dashboard's Delete button, carried out by the agent: the page never
// writes into a project. removeSpec() does every check; a refusal is exit 3
// with the reason, and the remembered workspace for the spec goes with it.
function cmdDeleteSpec() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("delete-spec needs --spec specs/<name>", 2);
const worktree = repoRoots().worktree;
try {
const done = removeSpec(worktree, args.spec);
forgetWorkspace(worktree, args.spec);
print(done);
} catch (err) {
print({ ok: false, message: err.message });
process.exit(3);
}
}
/* ----------------------------------------------------------------- help */
function cmdHelp() {
@@ -1370,6 +1392,12 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
Drop the workspace folders remembered for that spec, in this
folder (Finalize, after archiving it). Prints { ok, spec, forgot };
forgot is false when nothing was saved. Exit 2 = bad usage.
delete-spec --spec specs/<name>
Delete that spec folder for good (the dashboard's Delete button, a
__delete action). Only an existing specs/<name> folder inside this
worktree: never a link, never deeper, never specs--completed/.
Prints { ok, removed }; exit 2 = bad usage, 3 = refused, with
{ ok: false, message } saying why. Nothing is touched on a refusal.
status [--session <sid>] [--all]
One session, or (--all) every session on this machine, every project.
stop --session <sid> | --all
@@ -1377,7 +1405,7 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
workflows: dashboard · init · init-update · pathfinder · quick-task · plan ·
revise-plan · document · implement · implement-review · review ·
finalize · handoff · git · changelog
finalize · handoff · git · changelog · xray · diagnose
A session handed to you by the dashboard (a --session id): resume it with
"open --resume <sid> --no-open --workflow <yours>" (the resume it carries) -- never a
@@ -1636,6 +1664,7 @@ const COMMANDS = {
chat: cmdChat,
keep: cmdKeep,
forget: cmdForget,
"delete-spec": cmdDeleteSpec,
status: cmdStatus,
stop: cmdStop,
help: cmdHelp,
@@ -1655,7 +1684,7 @@ if (Number.isFinite(nodeMajor) && nodeMajor < 18) {
if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
process.stderr.write(
"console: usage: console.mjs <open|post|wait|chat|keep|forget|status|stop|help> [--session <id>] [--file <patch.json>] [--seconds N]\n"
"console: usage: console.mjs <open|post|wait|chat|keep|forget|delete-spec|status|stop|help> [--session <id>] [--file <patch.json>] [--seconds N]\n"
);
process.exit(2);
}
+167 -15
View File
@@ -24,7 +24,7 @@ import { fileURLToPath } from "node:url";
import { countPending } from "./git-repo.mjs";
import { CHAT_LIMIT } from "./public/chat.js";
import { DOC_TYPES } from "./public/answers.js";
import { DOC_TYPES, isDeletableSpecDir } from "./public/answers.js";
import { defaultName } from "./public/workspace.js";
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
@@ -579,9 +579,10 @@ export async function removeScratch(consoleDir, names) {
// What User Preferences -> Cleanup never removes. The console folder keeps its
// protected files, its sessions dir (old sessions go one by one, by age) and,
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
// console, the launcher (bin/, launcher.json) and the models the person added.
// console, the launcher (bin/, launcher.json), the install record that
// `plan2code update` reads (install.json) and the models the person added.
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
@@ -785,8 +786,13 @@ export function newToken() {
// Where a spec folder stands, named after the step its files are ready for.
// "unrecognized" is a folder with files but no pipeline shape: it launches
// Pathfinder or Plan (the files may be reference docs) but unlocks nothing
// else, exactly like picking no spec at all.
// else, exactly like picking no spec at all. "diagnosed" is a bug Diagnose
// wrote up and nobody has fixed or planned yet: it lights Quick Task and Plan.
// "fixed" is that bug once Quick Task marked it Fixed: finished, so the
// dashboard never picks or suggests it, and Quick Task offers to archive it.
export const SPEC_STATES = new Set([
"diagnosed",
"fixed",
"exploring",
"mapped",
"planned",
@@ -796,7 +802,9 @@ export const SPEC_STATES = new Set([
"unrecognized",
]);
function maxMtime(dir, depth = 4, budget = { n: 400 }) {
// The newest mtime under dir. `tally.files` counts the files the same walk
// sees (within its depth and budget), for the dashboard's delete dialog.
function maxMtime(dir, depth = 4, budget = { n: 400 }, tally = null) {
let best = 0;
if (depth < 0 || budget.n <= 0) return best;
let entries;
@@ -810,8 +818,11 @@ function maxMtime(dir, depth = 4, budget = { n: 400 }) {
if (e.name.startsWith(".")) continue;
const p = path.join(dir, e.name);
try {
if (e.isDirectory()) best = Math.max(best, maxMtime(p, depth - 1, budget));
else best = Math.max(best, fs.statSync(p).mtimeMs);
if (e.isDirectory()) best = Math.max(best, maxMtime(p, depth - 1, budget, tally));
else {
best = Math.max(best, fs.statSync(p).mtimeMs);
if (tally) tally.files++;
}
} catch {}
}
return best;
@@ -825,6 +836,16 @@ function readText(file) {
}
}
// A spec file's Status line value, in any of the forms the skill scripts
// accept (`**Status:**`, `**Status**:`, `Status:`). Same pattern as STATUS_RE
// in src/skill-scripts/specs.mjs; the console cannot import it, so keep the
// two copies in step. A CRLF file's trailing `\r` is dropped.
const STATUS_LINE_RE = /^[ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*(.+?)[ \t\r]*$/m;
function statusOf(text) {
const m = text.match(STATUS_LINE_RE);
return m ? m[1] : "";
}
// A spec folder's pipeline position, from its files alone. Furthest artifact
// wins: an overview beats a draft beats a map, so a spec mid-way through two
// stages reports the later one.
@@ -837,9 +858,7 @@ function classifySpec(dir, names) {
const planDraft = drafts.length > 0;
const planConv = has(/^PLAN-CONVERSATION.*\.md$/i);
const liveDraft = drafts.filter((n) => !/-prev\.md$/i.test(n)).sort().reverse()[0] || drafts[0];
const draftStatus = liveDraft
? (readText(path.join(dir, liveDraft)).match(/\*\*Status:\*\*\s*([^\n]+)/) || [])[1] || ""
: "";
const draftStatus = liveDraft ? statusOf(readText(path.join(dir, liveDraft))) : "";
const resumeAt = draftStatus.match(/Resume at Phase\s*(\d+)/i);
if (phases.length) {
@@ -870,10 +889,19 @@ function classifySpec(dir, names) {
// Status line: Plan still has phases to run before Document can start.
if (resumeAt) return { state: "mapped", detail: `plan draft, resume at Phase ${resumeAt[1]}` };
if (planDraft) return { state: "planned", detail: "plan drafted" };
// A bug Diagnose wrote up, with nothing after it yet. A pathfinder map or a
// plan conversation means planning has started, so the usual states win.
// Quick Task marks the write-up Fixed once the bug is gone: then the bug is
// done, and the folder waits only to be archived.
const diagnosis = names.filter((n) => /^DIAGNOSIS-.*\.md$/i.test(n)).sort().reverse()[0];
const diagnosisStatus = diagnosis ? statusOf(readText(path.join(dir, diagnosis))).replace(/\*+/g, "").trim() : "";
if (diagnosis && !planConv && !fs.existsSync(path.join(pfDir, "map.md")))
return /^fixed/i.test(diagnosisStatus)
? { state: "fixed", detail: "bug fixed" }
: { state: "diagnosed", detail: "bug diagnosed, not fixed" };
if (isDir(pfDir)) {
const mapText = readText(path.join(pfDir, "map.md"));
const m = mapText.match(/\*\*Status:\*\*\s*([^\n]+)/);
const status = m ? m[1].replace(/\*+/g, "").trim() : "";
const status = statusOf(mapText).replace(/\*+/g, "").trim();
if (/^cleared/i.test(status)) return { state: "mapped", detail: "all decisions made" };
let qTotal = 0;
let qDone = 0;
@@ -930,11 +958,13 @@ export function scanProject(root) {
} catch {
continue;
}
const tally = { files: 0 };
specs.push({
dir: `specs/${name}`,
name,
...classifySpec(dir, files),
touched: maxMtime(dir),
touched: maxMtime(dir, 4, { n: 400 }, tally),
files: tally.files,
});
}
specs.sort((a, b) => b.touched - a.touched || a.name.localeCompare(b.name));
@@ -948,6 +978,38 @@ export function scanProject(root) {
};
}
/**
* Delete one spec folder, for the dashboard's Delete button (`delete-spec`).
* Only an existing `specs/<name>` folder, as isDeletableSpecDir() spells it,
* whose real path sits directly in the worktree's own specs/: never a link to
* somewhere else, never specs--completed/, never anything deeper. specs/ is
* gitignored, so a mistake here cannot be undone; every refusal throws with
* the reason, and nothing is touched.
*/
export function removeSpec(worktree, dir) {
if (!isDeletableSpecDir(dir)) throw new Error(`"${dir}" is not a spec folder: only specs/<name> can be deleted`);
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
const root = path.resolve(worktree);
const target = path.join(root, dir);
let st;
try {
st = fs.lstatSync(target);
} catch {
throw new Error(`there is no ${dir} to delete`);
}
if (st.isSymbolicLink()) throw new Error(`${dir} is a link to another folder, so it is not deleted from here`);
if (!st.isDirectory()) throw new Error(`${dir} is not a folder`);
const real = fs.realpathSync.native(target);
const realSpecs = fs.realpathSync.native(path.join(root, "specs"));
const realRoot = fs.realpathSync.native(root);
const rel = path.relative(fold(realRoot), fold(realSpecs));
if (rel !== "specs" || fold(path.dirname(real)) !== fold(realSpecs)) {
throw new Error(`${dir} resolves outside the project's specs/ folder, so it is not deleted`);
}
fs.rmSync(real, { recursive: true });
return { ok: true, removed: dir };
}
/* -------------------------------------------------------------- liveness */
// PID reuse is real, so process.kill(pid, 0) is necessary but not sufficient.
@@ -1246,7 +1308,7 @@ function mergeDocs(current, patchList) {
// version: the agent no longer has to track what the page holds, and a
// repost of unchanged content is not a new version.
if (prev && typeof entry.version !== "number" && typeof prev.version === "number") {
const text = (blocks) => JSON.stringify((blocks || []).map((b) => [b.id, b.md, b.state]));
const text = (blocks) => JSON.stringify((blocks || []).map((b) => [b.id, b.md, b.state, b.image, b.alt]));
if (text(prev.blocks) !== text(doc.blocks)) doc.version = prev.version + 1;
}
}
@@ -1410,6 +1472,83 @@ export function resolveDocFiles(patch, state, worktree) {
return { ...patch, docs };
}
/**
* Image blocks: `{ "id", "image": "shots/run.png", "alt": "..." }` shows a
* screenshot the agent saved under the session's `shots/` folder (Show me it
* working). The path resolves against the session folder and must land, after
* `realpath`, directly inside `<session>/shots/` under a plain name, so the page
* can only ever be pointed at the agent's own pictures. The bytes decide the
* type, as checkDocument() does for documents: a text file renamed `.png` is
* refused. Stored session-relative; an image block never carries `md` or `file`.
* Runs in the CLI beside resolveDocFiles(), so applyPatch never touches the disk.
*/
export const SHOTS_DIR_NAME = "shots";
export const SHOT_MAX = 5 * 1024 * 1024;
export const SHOT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(png|jpe?g|webp)$/i;
// What an image's first bytes say it is ("png", "jpeg", "webp"), or null.
export function shotType(buf) {
if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return "png";
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "jpeg";
if (buf.length >= 12 && buf.toString("ascii", 0, 4) === "RIFF" && buf.toString("ascii", 8, 12) === "WEBP") return "webp";
return null;
}
export function resolveDocImages(patch, state, dir) {
if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch;
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
const shotsDir = path.join(path.resolve(dir), SHOTS_DIR_NAME);
const check = (image, docId) => {
if (typeof image !== "string" || !image.trim()) throw new Error(`doc "${docId}": an image block's "image" must be a path`);
const where = `doc "${docId}": image ${image}`;
let real;
try {
real = fs.realpathSync.native(path.resolve(dir, image));
} catch {
throw new Error(`${where} does not exist. Save it under the session's ${SHOTS_DIR_NAME}/ folder first.`);
}
let realShots;
try {
realShots = fs.realpathSync.native(shotsDir);
} catch {
realShots = shotsDir;
}
const name = path.basename(real);
if (fold(path.dirname(real)) !== fold(realShots)) {
throw new Error(`${where} is outside the session's ${SHOTS_DIR_NAME}/ folder (${shotsDir}); only pictures saved there can be shown.`);
}
if (!SHOT_NAME.test(name)) throw new Error(`${where}: name it with letters, digits, dots, dashes or underscores, ending .png, .jpg, .jpeg or .webp`);
const stat = fs.statSync(real);
if (!stat.isFile()) throw new Error(`${where} is not a file`);
if (stat.size > SHOT_MAX) throw new Error(`${where} is larger than ${SHOT_MAX / 1024 / 1024} MB`);
const ext = path.extname(name).slice(1).toLowerCase();
const want = ext === "jpg" ? "jpeg" : ext;
if (shotType(fs.readFileSync(real)) !== want) throw new Error(`${where} is not a ${want.toUpperCase()} image (its bytes say otherwise)`);
return `${SHOTS_DIR_NAME}/${name}`;
};
const docs = patch.docs.map((entry) => {
if (!isPlainObject(entry) || !Array.isArray(entry.blocks)) return entry;
const prevBlocks = (state.docs || []).find((d) => d && d.id === entry.id)?.blocks || [];
return {
...entry,
blocks: entry.blocks.map((b) => {
if (!isPlainObject(b)) return b;
const prevBlock = prevBlocks.find((x) => x && x.id === b.id);
if (b.image === undefined || b.image === null) {
// Text or a file over what was an image: it stops being one.
return ("md" in b || "file" in b) && prevBlock && typeof prevBlock.image === "string" ? { ...b, image: null, alt: null } : b;
}
if (("md" in b && b.md != null) || ("file" in b && b.file != null)) {
throw new Error(`doc "${entry.id}": block "${b.id}" is an image; it cannot also carry "md" or "file"`);
}
if (b.alt != null && typeof b.alt !== "string") throw new Error(`doc "${entry.id}": block "${b.id}" "alt" must be text`);
return { state: prevBlock?.state || "settled", ...b, image: check(b.image, entry.id), md: null, file: null };
}),
};
});
return { ...patch, docs };
}
/**
* Apply an agent patch to the session state.
*
@@ -1556,12 +1695,15 @@ const JARGON = [
];
// The loop parses these out of agent output; pathfinder forbids them under specs/.
// The other copy is LOOP_TOKENS in src/skill-scripts/common.mjs: the console is
// not a skill script and cannot import it, so keep the two in step.
const FORBIDDEN_TOKENS =
/\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
// plan2code-metrics scrapes confidence with patterns that do NOT require a
// percent sign, so a bare "Requirements 22" in a rendered doc can poison a run's
// metrics. Keep those four words away from bare numbers.
// metrics. Keep those four words away from bare numbers. The skill scripts'
// copy is SCRAPE in src/skill-scripts/common.mjs; keep the two in step.
const METRICS_BAIT = /\b(Requirements?|Feasibility|Integration|Risk)[:\s|]+\d{1,2}\b/;
// The marker and metrics-bait scan on its own, for agent text that never
@@ -1761,6 +1903,16 @@ export function validate(state) {
);
}
// An image block's alt text is its caption, read by the same newcomers a
// title is.
for (const d of state.docs || []) {
for (const b of (isPlainObject(d) && Array.isArray(d.blocks) ? d.blocks : [])) {
if (!isPlainObject(b) || typeof b.image !== "string" || typeof b.alt !== "string") continue;
const hit = JARGON.find((re) => re.test(b.alt));
if (hit) problems.push(`doc "${d.id}" image "${b.id}" alt text contains internal vocabulary (${hit.source})`);
}
}
// Scan what the AGENT wrote, never what the person typed. `submitted` is the
// server's record of an answer someone pressed Send on; if their own words
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
+83
View File
@@ -0,0 +1,83 @@
# Diagnose on the Web Console
Workflow notes for `diagnose`, part of the web console contract (`console.md`).
## The bug
A typed argument that already describes the bug skips the cards it answers.
Otherwise ask in one batch (at most three open), posted with `--wait`:
```jsonc
{
"title": "Diagnose a bug",
"headline": { "stage": "The bug", "cleared": 0, "total": 3 },
"items": [
{ "id": "bug", "kind": "text", "title": "What is wrong",
"body": "The bug, in a sentence or two.",
"placeholder": "The CSV export drops the last row when the report has more than 100 rows." },
{ "id": "expected", "kind": "text", "title": "Expected and actual",
"body": "What should happen, and what happens instead.",
"placeholder": "Expected 150 rows in the file; it has 149, and the last order is missing." },
{ "id": "see-it", "kind": "text", "title": "How to see it",
"body": "The steps, command, page or input that shows it, and since when if you know.",
"placeholder": "Run npm run export -- --month 2026-09 and count the rows. It worked last month." }
]
}
```
No `"templates"` on these cards: the starter templates are for a fresh idea,
and a bug report is not one. A follow-up the answers leave open is a new card
with a new id.
## The cause
Post the cause as a doc, `id` `"cause"`, as soon as there is something to show,
and grow it as evidence lands, with `"agent": { "status": "working",
"activity": "..." }` while you reproduce and narrow:
```jsonc
"docs": [{ "id": "cause", "title": "The cause", "note": "Reproduced; narrowing", "blocks": [
{ "id": "repro", "state": "settled", "md": "## Reproduction\n\n`node scripts/export-check.mjs` fails: 149 rows, expected 150." },
{ "id": "found", "state": "settled", "md": "## The cause\n\n`src/export.ts` `writeRows()`: the loop stops at `rows.length - 1`. **Proven** by the reproduction." },
{ "id": "fix", "state": "settled", "md": "## Suggested fix\n\nLoop to `rows.length`. **Size:** Small (Quick Task)." }
]}]
```
- **Unproven** guesses are `assumed` blocks, one per guess, ranked, each with
its evidence and what would confirm it. A guess the evidence proves becomes
`settled`; one it rules out is removed (`"_delete": true`).
- Keeping a failing test inside the project is a `confirm` card pointing at
the doc (`"doc": "cause"`), `yesLabel` "Keep it", `noLabel` "Throw it away".
## The bug name
With the cause written, ask the folder name, posted with `--wait`:
```jsonc
{ "id": "name", "kind": "text", "title": "Name for the write-up", "doc": "cause",
"body": "The diagnosis is saved as `specs/<name>/DIAGNOSIS-<date>.md`. Lowercase words joined by dashes.",
"placeholder": "csv-export-drops-rows",
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$",
"patternHint": "Lowercase letters, numbers and dashes, like csv-export-drops-rows." }
```
Once written, re-send the doc with
`"saved": "specs/<name>/DIAGNOSIS-<date>.md"` and its blocks replaced by one
`file` block for that path (delete the old ids).
## The finish
`command` is `/plan2code-quick-task specs/<name>` (small fix) or
`/plan2code-1-plan specs/<name>` (big fix) with the real folder filled in
(`/plan2code-quick-task specs/csv-export-drops-rows`), never a placeholder: a
copied command must reach the diagnosis. `body` names the cause, how sure, and that the
next step reads the diagnosis first. `doc` is `"cause"`. `"dashboard": true`,
then keep waiting for the press (`console-finish.md`): back on the dashboard
the folder shows as "Bug diagnosed", with that card lit.
Nothing kept (the bug did not reproduce and no guess held up): leave
`command` out and say so in `body`.
A stop before the file is written ends on a finish whose `body` says nothing
was kept (and names any throwaway script or kept test you wrote), with
`"command": "/plan2code-diagnose"` (`console-stop.md`).
+1 -1
View File
@@ -12,7 +12,7 @@ know:
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`, as a `file` block on `overview.md`) so the page reader sees it land. |
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
| 6, Spec Cleanup | A `review` item before moving anything (`doc`: Step 3's summary), verdicts `yes` ("Archive it"), `show` ("Show me it working", token `show me`) and `no`, the archive paths in `body`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). On `show`, run it as `notes/implement.md` → Show me it working says (the summary line goes into `overview.md`'s Completion Summary), then reopen the card without `show`. |
Post `activity` as each step starts, before its doc or question lands — reading
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
+17 -4
View File
@@ -64,13 +64,14 @@ only ever be offered once nothing could come of it:
]}],
"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.",
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, see it running, or say what to change.",
"verdicts": [
{ "id": "review", "label": "Review the code first" },
{ "id": "show", "label": "Show me it working" },
{ "id": "approve", "label": "Approve this phase" },
{ "id": "changes", "label": "I want changes" }
],
"token": { "approve": "approved", "changes": "needs changes" },
"token": { "approve": "approved", "changes": "needs changes", "show": "show me" },
"nothingYet": "Nothing is marked complete until you approve.",
"gate": { "id": "signoff", "authoritative": true }
}]
@@ -83,7 +84,19 @@ change, treat it as "describe any issues": do the change first and ask again.
`changes` means exactly what it says: address it, update the report, 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 — read
`building-review.md`.
`building-review.md`. `show` is the terminal's `show me`: see below.
### Show me it working
On `show`, run the workflow's **Show me it working** paragraph (start the app,
look at the change, stop it, one summary line in `phase-X.md`). Save each
screenshot under the session's `shots/` folder, never under `specs/`, and post
them as image blocks in a `shown` doc (`console.md` → Documents), with what was
run in a `md` block above them; no browser tool means that block alone says
what the command printed. Then reopen the same card (`"status": "reopened"`)
without the `show` verdict, a `thread` reply naming what was seen. The same
holds on Finalize's card and the one `building-review.md` reopens; Quick
Task's card is settled instead (`notes/quick-task.md`).
`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
@@ -172,7 +185,7 @@ 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" }`: 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
sign-off above (`show` included) **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":
+15
View File
@@ -70,6 +70,21 @@ Workflow notes for `quick-task`, part of the web console contract
Check for a Quick question between steps, and do not call `wait` until the
build is done. Tick the Verify block's boxes too as the checks pass, in the
post that reports them.
- **See it running, before the finish:** a finished screen freezes every open
card, so ask first. Once the build is done, post a `review` item "See it
running" (`"doc": "plan"`, verdicts `show` ("Show me it working") and `fine`
("No need, finish up"), token `show me` / `no`) with `--wait`. On `show`, run
it as `notes/implement.md` → Show me it working says, its one line going into
the work summary (the finish's `body`); then, or on `fine`, settle the card in
the same post as the finish.
- **Archive a fixed bug, before the finish:** launched on a diagnosed folder
and now Fixed with nothing past the diagnosis, post a `confirm` card
"Archive this bug?" in the same post as "See it running": the dry run's
`files` in `body`, `yesLabel` "Archive it", `noLabel` "Keep it in specs/",
and `consequences` naming `specs--completed/<bug>/`. On yes, run
`node "<S>/specs.mjs" archive <spec>` (the skill file says where `<S>` is),
and say where it went in the finish's `body`. On no, the
dashboard lists the folder as "Bug fixed", never pre-selected.
- **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
+73
View File
@@ -0,0 +1,73 @@
# X-ray on the Web Console
Workflow notes for `xray`, part of the web console contract (`console.md`).
## The mode question
A typed argument that names the mode and area skips it. Otherwise ask both in
one batch, posted with `--wait`:
```jsonc
{
"title": "Codebase X-ray",
"headline": { "stage": "Choosing", "cleared": 0, "total": 2 },
"items": [
{ "id": "mode", "kind": "choice", "title": "What you want to know", "allowOther": false,
"body": "Explain one area, or rank what makes this code hard to change.",
"options": [
{ "k": "1", "text": "Explain an area", "detail": "How it works and why it is that way, citing files and the commits behind it." },
{ "k": "2", "text": "Find the rough spots", "detail": "Ranked spots that make change hard. You pick the ones worth fixing; they become a brief for Pathfinder or Plan." }
] },
{ "id": "area", "kind": "text", "title": "Which area", "required": false,
"body": "A folder, file or feature. Needed to explain; leave it empty to survey the whole repository.",
"placeholder": "src/exporter, the code that builds the CSV reports" }
]
}
```
Explain picked with the area left empty: ask for it again as a required `text`
card. No recommendation on the mode: only the person knows what they came for.
## Explain mode
The answer is a doc, `id` `"answer"`, one block per section (`In one paragraph`,
`How it works`, `Why it is this way`, `Worth knowing`), with the `Sources:` line
at the top of the first. Then the save offer as a `confirm` card pointing at it:
```jsonc
{ "id": "keep", "kind": "confirm", "title": "Keep this answer", "doc": "answer",
"body": "Save it as `specs/exporter/XRAY-exporter-20261016.md`, as input for Pathfinder or Plan?",
"yesLabel": "Save it", "noLabel": "No, just reading" }
```
Ask the folder name in the same batch as a `text` card with `pattern`
`^[a-z0-9]+(-[a-z0-9]+)*$` when it is not obvious. Once written, re-send the doc
with `"saved": "specs/<name>/XRAY-<area-slug>-<date>.md"`.
## Rough-spots mode
The ranked list is a doc, `id` `"spots"`, one block per spot (its files, why it
hurts, the "to change X today" example). The pick is one `multi` card pointing
at it, posted with `--wait`:
```jsonc
{ "id": "pick", "kind": "multi", "title": "Worth fixing", "doc": "spots", "required": false,
"body": "Tick the spots worth fixing. Add a note for any of them in the box (\"1: the exporter part only\"). Only ticked spots go into the brief.",
"options": [
{ "k": "1", "text": "Exporter and its formatter always change together", "detail": "src/export.ts, src/format.ts: together in 14 of 16 commits." }
] }
```
Nothing ticked: nothing is written. Otherwise write the brief, then add it as a
second doc with `"saved": "specs/<name>/ARCHITECTURE-BRIEF-<date>.md"` and a
`file` block.
## The finish
`command` is `/plan2code-0-pathfinder` (big or unclear) or `/plan2code-1-plan`
(settled), never with a placeholder; leave it out when nothing was kept. `doc`
is the brief or the saved answer when there is one. `"dashboard": true`, then
keep waiting for the press (`console-finish.md`).
A stop before anything was written ends on a finish whose `body` says nothing
was kept, with `"command": "/plan2code-xray"` (`console-stop.md`).
+103 -8
View File
@@ -270,6 +270,8 @@ export const WORKFLOW_LABEL = {
handoff: "Handoff",
git: "Git",
changelog: "Changelog",
xray: "X-ray",
diagnose: "Diagnosing",
};
export function workflowLabel(workflow) {
@@ -296,6 +298,8 @@ export const CONSOLE_WORKFLOWS = [
"/plan2code-handoff",
"/plan2code-git",
"/plan2code-changelog",
"/plan2code-xray",
"/plan2code-diagnose",
];
// Rides on the end of the command as part of the skill's argument. Every
@@ -465,6 +469,10 @@ export function resumeCommand({ workflow, specDir } = {}) {
return "/plan2code-git";
case "changelog":
return "/plan2code-changelog";
case "xray":
return "/plan2code-xray";
case "diagnose":
return "/plan2code-diagnose";
default:
return dir ? `/plan2code-0-pathfinder ${dir}/pathfinder` : "/plan2code-0-pathfinder";
}
@@ -680,15 +688,26 @@ export const SKILL_CATALOG = [
"A fresh-eyes pass over what changed: bugs, gaps, and the things the builder was too close to see. Problems come back ranked with a suggestion each, you pick which ones get fixed, and it fixes them.",
},
{
skill: "plan2code-handoff",
command: "/plan2code-handoff",
workflow: "handoff",
skill: "plan2code-xray",
command: "/plan2code-xray",
workflow: "xray",
group: "extra",
chip: "Utility",
title: "Handoff",
blurb: "Pack the current session into a document a fresh session can pick up cold.",
title: "Codebase X-ray",
blurb: "Explain how and why an area works, or find the rough spots worth fixing.",
about:
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
"Two ways into code you did not write. Explain an area: how it works, step by step, and why it is that way, citing the files and the commits and pull requests behind it. Or find the rough spots: files that always change together, thin layers, tangled boundaries and busy code with no tests, ranked with a concrete example each. You tick the ones worth fixing and they become a brief for Pathfinder or Plan. It never changes code.",
},
{
skill: "plan2code-diagnose",
command: "/plan2code-diagnose",
workflow: "diagnose",
group: "extra",
chip: "Utility",
title: "Diagnose a bug",
blurb: "Find a bug's cause and write it up, without fixing it.",
about:
"Something is broken and nobody knows why. Diagnose asks what goes wrong and how to see it, then builds a command that fails on the bug before it forms a theory. It narrows the cause down to a file and a function, says how sure it is, and sizes the fix. The write-up lands in a spec folder, and the dashboard then offers Quick Task to fix it, or Plan when the fix is big. It never changes code.",
},
{
skill: "plan2code-changelog",
@@ -712,6 +731,17 @@ export const SKILL_CATALOG = [
about:
"Shows your branch, what is ahead or behind, and every local and remote branch. Switch, create, delete or clean up branches, pull (rebasing when they have split, with help on conflicts), push or publish, and commit with a clear message. It asks before every push, publish and delete, and never force-pushes.",
},
{
skill: "plan2code-handoff",
command: "/plan2code-handoff",
workflow: "handoff",
group: "extra",
chip: "Utility",
title: "Handoff",
blurb: "Pack the current session into a document a fresh session can pick up cold.",
about:
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
},
];
// A workflow by the name its dashboard card gives it ("Implement"), for the
@@ -736,6 +766,8 @@ export const START_POSES = [
"handoff",
"git",
"changelog",
"xray",
"diagnose",
];
const POSE_ALIASES = { "init-update": "init", "revise-plan": "plan", "implement-review": "implement" };
@@ -754,6 +786,8 @@ export function catalogEntry(skill) {
// What the picker shows next to a spec's name — the pipeline position the
// server's scan worked out, in plain words.
export const SPEC_STATE_LABELS = {
diagnosed: "Bug diagnosed",
fixed: "Bug fixed",
exploring: "Exploring",
mapped: "Ready to plan",
planned: "Ready to document",
@@ -766,6 +800,7 @@ export const SPEC_STATE_LABELS = {
// The card each spec state exists to light up. Used as the fallback for the
// "Suggested" pill when the agent's menu payload names nothing.
const NEXT_FOR_STATE = {
diagnosed: "plan2code-quick-task",
exploring: "plan2code-0-pathfinder",
mapped: "plan2code-1-plan",
planned: "plan2code-2-document",
@@ -778,6 +813,16 @@ const ON = { on: true };
export const GIT_INIT_NOTE = "Not a git repository yet: it offers to start one";
export const pendingNote = (n) => `${n} file${n === 1 ? "" : "s"} to commit`;
const off = (reason) => ({ on: false, reason });
const FIXED_REASON = "This bug is fixed. Delete it with ✕, or move it to specs--completed/.";
/**
* The spec the picker opens on: the most recently touched one that is still
* in play. A fixed bug is finished, so it is never the default; with nothing
* else on disk the picker opens on "start from scratch" (null).
*/
export function defaultSpec(specs) {
return (Array.isArray(specs) ? specs : []).find((s) => s && s.state !== "fixed") || null;
}
/**
* Whether a catalog card is clickable for the current picker selection.
@@ -803,9 +848,13 @@ export function cardAvailability(entry, scan, sel) {
case "plan2code-init-update":
return hasAgents ? ON : off("Needs an AGENTS.md. Set the project up first.");
case "plan2code-quick-task":
// Always on; a diagnosed bug is the one spec it is the next step for.
return next ? { ...ON, next } : ON;
case "plan2code-review":
case "plan2code-handoff":
case "plan2code-changelog":
case "plan2code-xray":
case "plan2code-diagnose":
return ON;
case "plan2code-git":
// Never greyed: a clean tree still has branches to switch, pull and push.
@@ -814,9 +863,12 @@ export function cardAvailability(entry, scan, sel) {
return ON;
case "plan2code-0-pathfinder":
if (!state || state === "exploring") return { ...ON, next };
if (state === "diagnosed") return off("The cause is found. Fix it in a quick task, or plan it.");
if (state === "fixed") return off(FIXED_REASON);
return off("This spec is already past the questions");
case "plan2code-1-plan":
if (state === "exploring") return off("Pathfinder is not finished with this spec yet");
if (state === "fixed") return off(FIXED_REASON);
if (state === "documented" || state === "building" || state === "built")
return off("The plan is written. Revise it instead if it moved.");
return { ...ON, next };
@@ -840,10 +892,21 @@ export function cardAvailability(entry, scan, sel) {
}
}
/**
* The spec a card's launch carries: the picker's selection for the cards that
* take a spec, and for Quick Task only a diagnosed bug, whose write-up it reads
* first. Every other card launches untargeted.
*/
export function launchTarget(entry, sel) {
if (!entry || !sel) return null;
if (entry.spec) return sel;
return entry.skill === "plan2code-quick-task" && sel.state === "diagnosed" ? sel : null;
}
export function cardPresentation(entry, scan, sel, menu = {}) {
const availability = cardAvailability(entry, scan, sel);
const specs = scan && Array.isArray(scan.specs) ? scan.specs : [];
const initial = specs.length ? Boolean(sel && sel.dir === specs[0].dir) : !sel;
const first = defaultSpec(scan && scan.specs);
const initial = first ? Boolean(sel && sel.dir === first.dir) : !sel;
const requested = initial && typeof menu.recommend === "string" ? catalogEntry(menu.recommend) : null;
const recommendation = requested && cardAvailability(requested, scan, sel).on ? requested.skill : null;
const recommended = availability.on && (recommendation ? entry.skill === recommendation : availability.next);
@@ -871,6 +934,38 @@ export function launchReply(entry, spec) {
return `Start ${entry.title} (${entry.command})${target}, right here in this session.`;
}
/**
* Deleting a spec from the picker. The page only names the folder; the agent
* deletes it (`console.mjs delete-spec`, which runs lib.mjs's removeSpec() on
* this same rule), because the console never writes into a project. A
* deletable dir is exactly `specs/<one name>`: no deeper path, no `.` or `..`,
* no dotfolder, no backslash, never specs--completed/.
*/
export function isDeletableSpecDir(dir) {
return typeof dir === "string" && /^specs\/[^/\\]+$/.test(dir) && !/^specs\/\./.test(dir);
}
export function deleteAction(spec) {
return { i: "__delete", type: "delete", spec: spec.dir };
}
export function deleteReply(spec) {
return `Delete the spec folder ${spec.dir}/ for good, right here in this session.`;
}
// What the delete dialog says about the spec, from the scan alone. `touched`
// stays a number: the page formats it in the person's own locale.
export function deleteSummary(spec) {
const label = SPEC_STATE_LABELS[spec.state] || spec.state || "";
const n = spec.files;
return {
folder: `${spec.dir}/`,
stage: spec.detail ? `${label}: ${spec.detail}` : label,
files: Number.isInteger(n) ? `${n} file${n === 1 ? "" : "s"}` : "",
touched: Number.isFinite(spec.touched) && spec.touched > 0 ? spec.touched : null,
};
}
export function staleLaunchFeedback(title, adrift) {
if (!adrift) return null;
return {
+109
View File
@@ -2043,6 +2043,9 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.md-table th, .md-table td { border: 1px solid var(--rule); padding: 8px 11px; text-align: left; }
.md-table th { background: var(--panel-2); font-weight: 600; }
.md-img { max-width: 100%; border-radius: 8px; }
.doc-figure { margin: 0 0 13px; }
.doc-img { display: block; max-width: 100%; height: auto; border: 1px solid var(--rule); border-radius: 8px; }
.doc-figure figcaption { font-size: 13px; color: var(--ink-2); margin-top: 6px; }
.md a { color: var(--accent); }
/* ------------------------------------------------------------- footer */
@@ -3053,6 +3056,50 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
}
.spec-chip:not(.is-sel) .spec-chip-state { color: var(--ink-3); }
.spec-chip-detail { font-size: 11.5px; color: var(--ink-3); }
/* A spec's Delete button sits beside its chip, not inside it: a button cannot
hold a button. Quiet until the chip is hovered or focused. */
.spec-chip-wrap { position: relative; display: flex; }
.spec-chip-wrap.is-fixed .spec-chip:not(.is-sel) { opacity: 0.6; }
.spec-chip-wrap .spec-chip { padding-right: 36px; }
.spec-chip-del {
position: absolute;
top: 6px;
right: 6px;
width: 24px;
height: 24px;
display: grid;
place-items: center;
padding: 0;
border: 1px solid transparent;
border-radius: 6px;
background: transparent;
color: var(--ink-3);
font: inherit;
font-size: 15px;
line-height: 1;
cursor: pointer;
opacity: 0.55;
}
.spec-chip-wrap:hover .spec-chip-del,
.spec-chip-del:focus-visible { opacity: 1; }
.spec-chip-del:hover { color: var(--warn); border-color: var(--warn); opacity: 1; }
.spec-chip-del:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
.spec-chip-del:disabled { cursor: default; opacity: 0.3; }
.spec-chip-wrap.is-deleting .spec-chip { opacity: 0.5; }
.delete-facts { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 14px 0 0; font-size: 13.5px; }
.delete-facts dt { color: var(--ink-3); }
.delete-facts dd { margin: 0; overflow-wrap: anywhere; }
.delete-confirm { margin-top: 16px; display: flex; flex-direction: column; gap: 8px; font-size: 13.5px; }
.delete-confirm[hidden] { display: none; }
.delete-confirm input {
padding: 8px 10px;
border: 1px solid var(--rule-2);
border-radius: var(--radius);
background: var(--panel);
color: var(--ink);
font: inherit;
}
.delete-confirm input:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
/* ------------------------------------------------- dashboard confirm */
@@ -3524,6 +3571,68 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
/* Changelog -- the arm reaches the page and the newest line is written in step. */
.pose .cl-line { animation: gc-dot 2.4s ease-in-out infinite; }
/* Codebase X-ray -- the scan line sweeps down the file, the rough spot lights
up as it passes, and the lens and his star follow it down. */
.pose .xr-scan { animation: xr-scan 4s ease-in-out infinite; }
@keyframes xr-scan {
0%, 10% { opacity: 0; transform: translateY(0); }
16% { opacity: 1; }
74% { opacity: 1; }
80%, 100% { opacity: 0; transform: translateY(88px); }
}
.pose .xr-spot { animation: xr-spot 4s ease-out infinite; }
@keyframes xr-spot {
0%, 50% { opacity: 0; transform: scale(0.3); }
56% { opacity: 1; transform: scale(1.3); }
62%, 90% { opacity: 1; transform: scale(1); }
100% { opacity: 0; transform: scale(1); }
}
.pose .xr-lens { animation: xr-lens 4s ease-in-out infinite; }
@keyframes xr-lens {
0%, 10%, 100% { transform: translate(0, -3px); }
56%, 80% { transform: translate(0, 4px); }
}
.pose .xr-look { animation: xr-look 4s ease-in-out infinite; }
@keyframes xr-look {
0%, 10%, 100% { transform: translate(4px, -1px); }
56%, 80% { transform: translate(4px, 2px); }
}
/* Diagnose a bug -- the bug scuttles along its line, the magnifier and his
star follow it until it is caught, and the red mark under the line shows
once it holds still. Held still, the bug sits caught under the lens. */
.pose .dg-mark { fill: none; stroke: var(--warn); stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
.pose .dg-leg { fill: none; stroke: var(--ink); stroke-width: 2; stroke-linecap: round; }
.pose .dg-body { fill: var(--warn); }
.pose .dg-head { fill: var(--ink); }
.pose .dg-bug { animation: dg-bug 4s ease-in-out infinite; }
@keyframes dg-bug {
0%, 100% { transform: translate(-7px, 0) rotate(-12deg); }
14% { transform: translate(-2px, 0) rotate(10deg); }
26% { transform: translate(4px, 0) rotate(-10deg); }
36% { transform: translate(1px, 0) rotate(8deg); }
44%, 88% { transform: translate(0, 0) rotate(0deg); }
}
.pose .dg-lens { animation: dg-lens 4s ease-in-out infinite; }
@keyframes dg-lens {
0%, 100% { transform: translate(-9px, -2px); }
18% { transform: translate(-3px, -1px); }
30% { transform: translate(3px, 0); }
44%, 88% { transform: translate(0, 0); }
}
.pose .dg-mark { animation: dg-mark 4s ease-out infinite; }
@keyframes dg-mark {
0%, 44% { opacity: 0; }
52%, 88% { opacity: 1; }
96%, 100% { opacity: 0; }
}
.pose .dg-look { animation: dg-look 4s ease-in-out infinite; }
@keyframes dg-look {
0%, 100% { transform: translate(2px, 0); }
30% { transform: translate(5px, 0); }
44%, 88% { transform: translate(4px, 1px); }
}
@media (max-width: 720px) {
.dash { padding-top: 0; }
.launch-stage { height: 140px; }
+170 -18
View File
@@ -22,6 +22,7 @@ import {
briefPhrase,
cardAvailability,
cardPresentation,
defaultSpec,
CATALOG_GROUPS,
choiceAnswer,
DASHBOARD_COMMAND,
@@ -42,6 +43,11 @@ import {
IMAGE_QUALITY,
lastOpenCard,
launchReply,
launchTarget,
deleteAction,
deleteReply,
deleteSummary,
isDeletableSpecDir,
MAX_ATTACHMENTS,
nextOpenAfter,
MAX_DOC_BYTES,
@@ -597,6 +603,8 @@ function fresh() {
afterBuild: null,
homeward: null,
launching: null,
// A picker Delete sent and not yet answered by a rescan: { dir, scanAt }.
deleting: null,
retract: {},
chat: freshChat(),
};
@@ -812,13 +820,14 @@ const specList = () => {
};
// The spec the picker currently targets. Absent `specSel` means the picker
// has not been touched, so it defaults to the most recently touched spec —
// the first entry of the server's already-sorted list. An explicit "start
// from scratch" is stored as null, which is different.
// has not been touched, so it defaults to the most recently touched spec
// still in play (defaultSpec: the server's list is already sorted, and a
// fixed bug is skipped). An explicit "start from scratch" is stored as null,
// which is different.
const selSpec = () => {
const specs = specList();
if (!specs.length) return null;
if (local.specSel === undefined) return specs[0];
if (local.specSel === undefined) return defaultSpec(specs);
return specs.find((s) => s.dir === local.specSel) || null;
};
@@ -1054,8 +1063,8 @@ function adopt(body) {
const viaDashboard = prevWorkflow === "dashboard" || S.workflow === "dashboard";
if (prevWorkflow && prevWorkflow !== S.workflow && viaDashboard) {
// The pick rides into the skill it launched, never back home: arriving at
// the dashboard, the picker starts on the most recently touched spec, the
// one the agent's fresh menu recommends for.
// the dashboard, the picker starts on the most recently touched spec still
// in play, the one the agent's fresh menu recommends for.
const keepPick = S.workflow !== "dashboard" && "specSel" in local;
local = { ...fresh(), launching: local.launching, ...(keepPick ? { specSel: local.specSel } : {}) };
save();
@@ -3056,7 +3065,9 @@ function updateDismissed() {
}
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
const UPDATE_COMMAND = "plan2code update";
// For a machine without the plan2code command: the full installer, menu and all.
const UPDATE_FALLBACK_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
function releasesLink(text) {
const a = el("a", null, text);
@@ -3079,6 +3090,9 @@ function openUpdateModal() {
const row = $("update-command");
const code = el("code", null, UPDATE_COMMAND);
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
const fallbackRow = $("update-fallback");
const fallback = el("code", null, UPDATE_FALLBACK_COMMAND);
fallbackRow.replaceChildren(fallback, copyButton(UPDATE_FALLBACK_COMMAND, "btn small ghost handoff-copy", fallback));
$("update-modal").showModal();
}
@@ -3117,9 +3131,9 @@ function renderDashboard(main) {
// The agent's note reads the spec the picker opened on (the same "initial"
// test cardPresentation uses): another pick, or Start from scratch, gets
// the neutral line rather than context about a spec no longer shown.
const specsNow = (scan() && scan().specs) || [];
const first = defaultSpec(scan() && scan().specs);
const picked = selSpec();
const onInitial = specsNow.length ? Boolean(picked && picked.dir === specsNow[0].dir) : !picked;
const onInitial = first ? Boolean(picked && picked.dir === first.dir) : !picked;
if (typeof menu.note === "string" && menu.note.trim() && onInitial) {
wrap.appendChild(el("p", "dash-note", menu.note));
} else if (!S.menu && agentWorking()) {
@@ -3681,13 +3695,26 @@ function renderSpecPicker(specs) {
});
row.appendChild(scratch);
// A delete in flight ends when the agent's rescan lands (a new scan), gone
// or refused: either way the picker below is the truth again.
const sc = scan();
if (local.deleting && sc && sc.at !== local.deleting.scanAt) {
local.deleting = null;
save();
}
for (const spec of specs) {
const on = sel && sel.dir === spec.dir;
// A fixed bug is finished: hidden while unavailable workflows are, dimmed
// otherwise. A pick already on it stays visible, so it is never lost.
const fixed = spec.state === "fixed";
if (fixed && looks.hideUnavailable && !on) continue;
const deleting = Boolean(local.deleting && local.deleting.dir === spec.dir);
const wrap = el("div", "spec-chip-wrap" + (deleting ? " is-deleting" : "") + (fixed ? " is-fixed" : ""));
const b = el("button", "spec-chip" + (on ? " is-sel" : ""));
b.type = "button";
b.setAttribute("aria-current", String(Boolean(on)));
b.appendChild(el("span", "spec-chip-name", spec.name));
b.appendChild(el("span", "spec-chip-state", SPEC_STATE_LABELS[spec.state] || spec.state));
b.appendChild(el("span", "spec-chip-state", deleting ? "Deleting…" : SPEC_STATE_LABELS[spec.state] || spec.state));
if (spec.detail) b.appendChild(el("span", "spec-chip-detail", spec.detail));
b.addEventListener("click", () => {
local.specSel = spec.dir;
@@ -3695,7 +3722,17 @@ function renderSpecPicker(specs) {
render();
loadOverview();
});
row.appendChild(b);
wrap.appendChild(b);
if (isDeletableSpecDir(spec.dir)) {
const del = el("button", "spec-chip-del", "✕");
del.type = "button";
del.title = `Delete ${spec.dir}/`;
del.setAttribute("aria-label", `Delete the spec ${spec.name}`);
del.disabled = deleting || Boolean(local.deleting) || gone || pendingResult || Boolean(local.launching);
del.addEventListener("click", () => openDeleteConfirm(spec));
wrap.appendChild(del);
}
row.appendChild(wrap);
}
box.appendChild(row);
return box;
@@ -3781,7 +3818,7 @@ function renderConfirm(main, entry) {
// A card that takes a spec names the one the picker is holding, so START
// reads as "build THIS spec", not the skill in the abstract.
const target = entry.spec ? selSpec() : null;
const target = launchTarget(entry, selSpec());
if (target) {
const specLine = el("p", "confirm-spec");
specLine.appendChild(el("span", null, "for "));
@@ -3821,7 +3858,7 @@ function renderConfirm(main, entry) {
// through the same wait loop. The dashboard reads `skill` off it.
async function launchSkill(entry) {
if (gone || pendingResult || local.launching || finish()) return;
const target = entry.spec ? selSpec() : null;
const target = launchTarget(entry, selSpec());
// The card was clickable, so this should never fire — but a spec picked in
// one tab could have shifted the ground under a stale render in another.
if (!cardAvailability(entry, scan(), selSpec()).on) {
@@ -3839,7 +3876,7 @@ async function launchSkill(entry) {
};
// The picker's spec goes to the skill being launched, not to the card:
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected.
// a spec is selected, save Quick Task on a diagnosed bug.
if (target) action.spec = target.dir;
// The skill opens on the folders remembered for what it was launched for.
// Held until the launch is in flight: the swap's own frame re-renders the
@@ -5614,11 +5651,27 @@ function renderDoc(main, id) {
box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
}
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
box.appendChild(md(b.md, "md"));
box.appendChild(blockBody(b));
main.appendChild(box);
});
}
// A block's content: its markdown, or for an image block (a screenshot the
// agent saved under the session's shots/ folder) a captioned picture.
function blockBody(b) {
if (typeof b.image !== "string") return md(b.md, "md");
const fig = el("figure", "doc-figure");
const img = el("img", "doc-img");
img.src = "/shots/" + b.image.split("/").pop();
// The caption already says it: an alt repeating it is read twice, and shows
// twice in an export whose picture would not load.
img.alt = "";
img.loading = "lazy";
fig.appendChild(img);
if (b.alt) fig.appendChild(el("figcaption", null, b.alt));
return fig;
}
function printButton() {
const print = el("button", "btn small", "Print");
print.type = "button";
@@ -7495,6 +7548,88 @@ function openHomeConfirm() {
$("home-modal").showModal();
}
// The picker's Delete: a dialog in two steps. The first says what goes and
// that it is for good; "Delete this spec…" then reveals the second, which
// enables the final button only once the spec's name is typed exactly.
// Cancel, Escape or a click on Keep it at either step changes nothing.
let deleteTarget = null;
function openDeleteConfirm(spec) {
if (!isDeletableSpecDir(spec.dir) || gone || pendingResult || local.launching || local.deleting) return;
deleteTarget = spec;
const sum = deleteSummary(spec);
$("delete-blurb").textContent = `Everything in ${sum.folder} will be deleted from this project.`;
const facts = $("delete-facts");
facts.replaceChildren();
const fact = (term, value) => {
if (!value) return;
facts.appendChild(el("dt", "", term));
facts.appendChild(el("dd", "", value));
};
fact("Spec", spec.name);
fact("Folder", sum.folder);
fact("Stage", sum.stage);
fact("Files", sum.files);
fact("Last changed", sum.touched ? new Date(sum.touched).toLocaleString() : "");
$("delete-name-hint").textContent = spec.name;
$("delete-name").value = "";
$("delete-confirm").hidden = true;
const go = $("delete-go");
go.textContent = "Delete this spec…";
go.classList.remove("is-on");
go.disabled = false;
$("delete-modal").showModal();
}
function deleteStep() {
const go = $("delete-go");
if (!deleteTarget) return;
if ($("delete-confirm").hidden) {
$("delete-confirm").hidden = false;
go.textContent = "Delete for good";
go.classList.add("is-on");
go.disabled = true;
$("delete-name").focus();
return;
}
if ($("delete-name").value.trim() !== deleteTarget.name) return;
sendDelete(deleteTarget);
}
async function sendDelete(spec) {
const go = $("delete-go");
go.disabled = true;
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [deleteAction(spec)], reply: deleteReply(spec) }),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
const sc = scan();
local.deleting = { dir: spec.dir, scanAt: sc ? sc.at : null };
// The selection must not outlive the folder: back to the default pick,
// which the agent's fresh menu recommends for.
if (local.specSel === spec.dir) delete local.specSel;
pendingResult = true;
save();
$("delete-modal").close();
} catch (err) {
$("delete-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
: "That did not go through. Nothing was deleted; try again.",
"warn"
);
} finally {
deleteTarget = null;
render();
}
}
async function goHome() {
const go = $("home-go");
go.disabled = true;
@@ -7847,7 +7982,7 @@ function downloadDoc(doc) {
// assumptions or drafts. Without the marks a half-finished document reads,
// once it leaves the page, as a set of decisions.
const mark = { assumed: "> **Assumed for now, still open.**\n\n", draft: "> **Draft.**\n\n" };
const blocks = (doc.blocks || []).map((b) => (mark[b.state] || "") + (b.md || ""));
const blocks = (doc.blocks || []).map((b) => (mark[b.state] || "") + (typeof b.image === "string" ? b.alt || "" : b.md || ""));
const first = (doc.blocks || [])[0];
const titled = first && /^\s*#\s/.test(first.md || "");
const body = [titled || !doc.title ? null : `# ${doc.title}`, ...blocks].filter((x) => x != null).join("\n\n");
@@ -7910,6 +8045,9 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.md-table th, .md-table td { border: 1px solid #e4ddd1; padding: 8px 11px; text-align: left; }
.md-table th { background: #fbf9f6; font-weight: 600; }
.md-img { max-width: 100%; border-radius: 8px; }
.doc-figure { margin: 0 0 13px; }
.doc-img { display: block; max-width: 100%; border: 1px solid #e4ddd1; border-radius: 8px; }
.doc-figure figcaption { font-size: 13px; color: #5d564d; margin-top: 6px; }
.md a { color: #206cc3; }
@media print {
body { background: #fff; }
@@ -7922,7 +8060,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
// address on this origin (/state, say) would copy session data into something
// meant to be shared. A remote image keeps its own address; anything else on
// this origin becomes its alt text.
const INLINE_UPLOAD = /^\/uploads\/[0-9a-f-]{36}\.jpg$/;
const INLINE_UPLOAD = /^\/(?:uploads\/[0-9a-f-]{36}\.jpg|shots\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(?:png|jpe?g|webp))$/i;
function imageToAlt(img) {
const alt = img.getAttribute("alt") || "";
@@ -7977,7 +8115,7 @@ async function downloadDocHtml(doc) {
const box = el("div", "block " + (b.state || "settled"));
if (b.state === "assumed") box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
box.appendChild(md(b.md, "md"));
box.appendChild(blockBody(b));
body.appendChild(box);
}
// Copy buttons only work inside the console.
@@ -8160,6 +8298,20 @@ function openHelpOn(id) {
$("btn-home").addEventListener("click", openHomeConfirm);
$("update-done").addEventListener("click", () => $("update-modal").close());
$("delete-cancel").addEventListener("click", () => $("delete-modal").close());
$("delete-go").addEventListener("click", deleteStep);
$("delete-name").addEventListener("input", () => {
$("delete-go").disabled = !deleteTarget || $("delete-name").value.trim() !== deleteTarget.name;
});
$("delete-name").addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
deleteStep();
}
});
$("delete-modal").addEventListener("close", () => {
deleteTarget = null;
});
$("home-cancel").addEventListener("click", () => $("home-modal").close());
$("home-go").addEventListener("click", goHome);
$("btn-stop").addEventListener("click", openStopConfirm);
+96 -3
View File
@@ -595,6 +595,75 @@
</g>
</g>
</svg>
<!-- Codebase X-ray: seeing how it works. He holds a lens up to a file,
a scan line sweeps down it to show the structure inside, and a rough
spot lights up as the scan passes over it. -->
<svg class="pose pose-xray" data-pose="xray" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
<ellipse class="shadow" cx="126" cy="198" rx="44" ry="5" />
<g class="prop">
<rect class="sh" x="182" y="60" width="44" height="112" rx="6" />
<line class="lt" x1="196" y1="76" x2="196" y2="152" />
<path class="lt" d="M196 96 L212 96 M196 124 L212 124" />
<circle class="ac" cx="196" cy="76" r="4" />
<circle class="ac" cx="212" cy="96" r="3.5" />
<circle class="ac" cx="212" cy="124" r="3.5" />
<circle class="ac" cx="196" cy="152" r="4" />
<g class="xr-spot"><circle class="as" cx="212" cy="124" r="8" /></g>
<line class="as xr-scan" x1="188" y1="70" x2="220" y2="70" />
</g>
<g class="bob">
<g transform="translate(-14 0)">
<rect class="fl foot f1" x="94" y="179" width="20" height="10" rx="5" />
<rect class="fl foot f2" x="126" y="179" width="20" height="10" rx="5" />
<rect class="sh" x="80" y="72" width="80" height="108" rx="16" />
<path class="ln" d="M80 126 L66 150" /><circle class="fl" cx="66" cy="150" r="5.5" />
<g class="xr-look"><path class="ey blink" d="M126 86 L129.64 94.98 L139.31 95.67 L131.9 101.92 L134.23 111.33 L126 106.2 L117.77 111.33 L120.1 101.92 L112.69 95.67 L122.36 94.98 Z" /></g>
<path class="es" d="M110 120 Q122 129 134 120" />
<line class="ln" x1="160" y1="126" x2="192" y2="132" />
<g class="xr-lens">
<line class="ln" x1="192" y1="132" x2="204" y2="120" />
<circle class="lt" cx="214" cy="110" r="14" />
</g>
<circle class="fl" cx="192" cy="132" r="5.5" />
</g>
</g>
</svg>
<!-- Diagnose a bug: finding the cause. A small bug scuttles along one
line of a file, his magnifier follows it until it is caught, and the
line it sits on is marked in red. He looks, he does not fix. -->
<svg class="pose pose-diagnose" data-pose="diagnose" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
<ellipse class="shadow" cx="126" cy="198" rx="44" ry="5" />
<g class="prop">
<rect class="sh" x="176" y="60" width="46" height="112" rx="6" />
<line class="lt" x1="184" y1="78" x2="208" y2="78" />
<line class="lt" x1="188" y1="96" x2="214" y2="96" />
<path class="dg-mark" d="M184 124 Q187 120 190 124 T196 124 T202 124 T208 124 T214 124" />
<line class="lt" x1="188" y1="142" x2="208" y2="142" />
<line class="lt" x1="184" y1="158" x2="202" y2="158" />
<g class="dg-bug">
<path class="dg-leg" d="M195 111 L189 108 M195 115 L189 115 M195 119 L189 122 M205 111 L211 108 M205 115 L211 115 M205 119 L211 122 M198 104 L195 99 M202 104 L205 99" />
<ellipse class="dg-body" cx="200" cy="115" rx="5.5" ry="7" />
<circle class="dg-head" cx="200" cy="106" r="3.2" />
</g>
</g>
<g class="bob">
<g transform="translate(-14 0)">
<rect class="fl foot f1" x="94" y="179" width="20" height="10" rx="5" />
<rect class="fl foot f2" x="126" y="179" width="20" height="10" rx="5" />
<rect class="sh" x="80" y="72" width="80" height="108" rx="16" />
<path class="ln" d="M80 126 L66 150" /><circle class="fl" cx="66" cy="150" r="5.5" />
<g class="dg-look"><path class="ey blink" d="M126 86 L129.64 94.98 L139.31 95.67 L131.9 101.92 L134.23 111.33 L126 106.2 L117.77 111.33 L120.1 101.92 L112.69 95.67 L122.36 94.98 Z" /></g>
<path class="ln" d="M113 82 Q126 77 139 83" />
<line class="es" x1="114" y1="124" x2="128" y2="124" />
<line class="ln" x1="160" y1="126" x2="174" y2="140" />
<g class="dg-lens">
<line class="ln" x1="174" y1="140" x2="180" y2="127" />
<circle class="lt" cx="186" cy="114" r="14" />
</g>
<circle class="fl" cx="174" cy="140" r="5.5" />
</g>
</g>
</svg>
</template>
<!-- The Help dialog's content, cloned into #help-modal the first time ? is
@@ -1546,7 +1615,7 @@
<p>
When a newer Plan2Code release is out, the dashboard shows
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
to run in your terminal; × hides it until the next
to run in your terminal, <code>plan2code update</code>; × hides it until the next
<code>/plan2code</code>. The version at the bottom of Help links to
the Releases page.
</p>
@@ -1574,6 +1643,8 @@
<li><strong>Handoff.</strong> Pack the current session into a document a fresh session can pick up cold.</li>
<li><strong>Changelog.</strong> Checks the CHANGELOG version against the main branch and suggests entries for what is new.</li>
<li><strong>Git.</strong> Branches, pull, push and commits on one board, asking before anything leaves your machine. See "The git board".</li>
<li><strong>Codebase X-ray.</strong> Explains how and why an area of the code works, or finds the rough spots worth fixing.</li>
<li><strong>Diagnose a bug.</strong> Finds a bug's cause and writes it up without fixing it, ready to hand to Quick Task or Plan.</li>
</ul>
<h4>Picking a spec</h4>
<p>
@@ -2520,6 +2591,24 @@
</div>
</dialog>
<!-- Deleting a spec from the dashboard's picker. Two deliberate steps: the
first says what goes and that it is for good, the second wants the
spec's name typed. The page only asks; the agent deletes. -->
<dialog class="modal" id="delete-modal" aria-labelledby="delete-title">
<h2 id="delete-title">Delete this spec?</h2>
<p class="modal-blurb" id="delete-blurb"></p>
<dl class="delete-facts" id="delete-facts"></dl>
<p class="modal-why" id="delete-warn">This is permanent. <code>specs/</code> is not tracked by git, so nothing can bring these files back.</p>
<div class="delete-confirm" id="delete-confirm" hidden>
<label for="delete-name">To delete it for good, type <strong id="delete-name-hint"></strong></label>
<input type="text" id="delete-name" autocomplete="off" spellcheck="false" />
</div>
<div class="modal-actions">
<button type="button" class="btn ghost" id="delete-cancel">Keep it</button>
<button type="button" class="btn danger" id="delete-go">Delete this spec…</button>
</div>
</dialog>
<dialog class="modal" id="home-modal" aria-labelledby="home-title">
<h2 id="home-title">Leave this workflow?</h2>
<p class="modal-blurb" id="home-blurb"></p>
@@ -2570,7 +2659,7 @@
</dialog>
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
the copy row are filled by app.js; the update itself runs in a
the two copy rows are filled by app.js; the update itself runs in a
terminal, never from this page. -->
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
<h2 id="update-title">A new Plan2Code is available</h2>
@@ -2579,7 +2668,11 @@
<li>
Run this in your terminal (not in this page or your agent):
<div class="update-command" id="update-command"></div>
It opens the installer's menu. Back at your prompt with no output at all? npm
It updates everything that was installed (the skills, the <code>plan2code</code>
command and any extras you added), with no menu. If the <code>plan2code</code>
command is not installed, run this instead:
<div class="update-command" id="update-fallback"></div>
Back at your prompt with no output at all? npm
could not reach the repository and hid the reason: run
<code>git ls-remote https://github.com/jparkerweb/plan2code.git</code> to see it.
</li>
+10 -2
View File
@@ -30,14 +30,16 @@ export const WEIGHTS = Object.freeze({
"git-commits": 0,
"git-conflict": 1,
changelog: 1,
xray: 1,
diagnose: 1,
});
// 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; git and changelog score 1 on
// reports; dashboard and handoff never score; git, changelog, xray and diagnose score 1 on
// launch (Git then adds its commit tally and conflict help).
export const LAUNCH_COUNTED = Object.freeze(
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git", "changelog"])
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git", "changelog", "xray", "diagnose"])
);
// Git's commits weigh what they add up to: each `git-commits` run carries
@@ -140,6 +142,8 @@ const WORKFLOW_NAMES = Object.freeze({
handoff: "Handoff",
git: "Git",
changelog: "Changelog",
xray: "X-ray",
diagnose: "Diagnose",
});
// The skill run an entry belongs to, from its ledger id ("L3:..." -> "L3").
@@ -157,6 +161,8 @@ const LAUNCH_LABELS = Object.freeze({
finalize: "Finalize started",
git: "Git started",
changelog: "Changelog started",
xray: "X-ray started",
diagnose: "Diagnose started",
});
const RUN_LABELS = Object.freeze({
"pathfinder-chart": "Pathfinder map written",
@@ -177,6 +183,8 @@ const RUN_LABELS = Object.freeze({
"git-commits": "Commits in Git",
"git-conflict": "Git conflict help",
changelog: "Changelog run",
xray: "X-ray run",
diagnose: "Diagnose run",
});
// The unit a run names, from its ledger id ("L3:phase-2" -> "phase-2").
+1 -1
View File
@@ -24,7 +24,7 @@ export const SUBAGENT_WORKFLOWS = Object.freeze({
}),
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.",
"Run the review's analysis in one fresh helper briefed only with the spec and the change set (references/reviewer-brief.md); verify every finding yourself before you report.",
}),
pathfinder: Object.freeze({
instruction:
+41
View File
@@ -54,6 +54,9 @@ import {
rememberedWorkspace,
removeCleanup,
remoteWarning,
SHOTS_DIR_NAME,
SHOT_NAME,
shotType,
saveSubagentStoreEntry,
PR_HOST_KINDS,
savePrHost,
@@ -131,6 +134,25 @@ const EXT_ALT = UPLOAD_EXTS.join("|");
const UPLOAD_ANY_ROUTE = new RegExp(`^/uploads/([0-9a-f-]{36})\\.(${EXT_ALT})$`);
const UPLOAD_NAME = new RegExp(`^[0-9a-f-]{36}\\.(${EXT_ALT})$`);
// Screenshots the agent saved for a doc's image block (Show me it working),
// only ever directly inside <session>/shots/ under SHOT_NAME's plain shape.
const SHOTS_DIR = path.join(DIR, SHOTS_DIR_NAME);
const SHOT_TYPES = { png: "image/png", jpeg: "image/jpeg", webp: "image/webp" };
function shotPath(name) {
if (!SHOT_NAME.test(name)) return null;
const file = path.resolve(SHOTS_DIR, name);
if (!file.startsWith(path.resolve(SHOTS_DIR) + path.sep)) return null;
try {
const real = fs.realpathSync.native(file);
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
if (fold(path.dirname(real)) !== fold(fs.realpathSync.native(SHOTS_DIR))) return null;
return fs.statSync(real).isFile() ? real : null;
} catch {
return null;
}
}
// A kept attachment's name, as attachmentName() in lib.mjs writes it:
// <slug>-<first 8 of the upload id>.<the upload's extension>.
const KEPT_ROUTE = new RegExp(`^/attachments/([a-z0-9-]{1,40}-[0-9a-f-]{8}\\.(${EXT_ALT}))$`);
@@ -1468,6 +1490,25 @@ const server = http.createServer((req, res) => {
});
}
// A screenshot for a doc's image block. Matched on the raw request line too,
// like uploads: anything URL parsing had to fold (`..`) is not a shot.
if (pathname.startsWith("/shots/") || req.url.startsWith("/shots/")) {
if (req.method !== "GET") return json(res, 405, { error: "method" });
const name = pathname.slice("/shots/".length);
const file = req.url === pathname ? shotPath(name) : null;
if (!file) return json(res, 404, { error: "not found" });
let buf;
try {
buf = fs.readFileSync(file);
} catch {
return json(res, 404, { error: "not found" });
}
// The bytes, not the name, pick the type: the file may have changed since it was posted.
const type = SHOT_TYPES[shotType(buf)];
if (!type) return json(res, 404, { error: "not found" });
return send(res, 200, buf, type, { "cache-control": "no-store" });
}
// Matched on the raw request line as well as the parsed path: URL parsing
// folds `..` segments away, and nothing that needed folding is an upload.
// GET and DELETE take images and documents alike.