Port upstream skill scripts into v2.4.1: deterministic workflow steps run as Node scripts beside each SKILL.md (specs, pathfinder, feedback payload, commit message, review scope, agent files, handoff path) with tests, the prompt limit rises to 20,000 chars, upstream review fixes are folded in (linked agent files never overwrite AGENTS.md, review stops with no base, paste-safe commit commands, Pathfinder number high-water mark and dry runs), and web console workspace folders are remembered per project and spec, with Finalize forgetting an archived spec's list

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-04 12:17:05 -07:00
1 parent 5cbc6edce2
commit 7d54941b75
243 files changed
+23698 -1607

No files matched your search

+33 -22
View File
@@ -33,9 +33,13 @@ Read references/github-issues.md — REQUIRED on `github`, skip on `local`.
Recorded as the first `## Ground rules` bullet (`**Backend:** local|github`), never re-asked or switched. Either way the PLAN-DRAFT lands in local `specs/<idea>/` — downstream steps read files, not issues.
## Scripts
On `local`, the map's bookkeeping is a script; the decisions are yours. `node "<S>/pathfinder.mjs" <command> specs/<idea>/pathfinder`, run from the project root, where `<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-0-pathfinder/scripts/` globally). It prints one JSON object. Exit 0 is success; anything else carries `message` and `next`, so do what `next` says. Exit 5 (refused) means a rule would break: never work around it by editing the files by hand. `--help` lists every command; they are named at the steps below. It reads local files only: on `github`, the backend playbook does each step with `gh` (except `lint`, which checks the local briefs and PLAN-DRAFT once one exists), and a `no-map` result there is expected, never a cue to chart.
## Project Context
Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it answers. If missing, fold it into the Step 0 gate batch: *"No `AGENTS.md`. Pathfinder can chart without it. Continue, or run `plan2code-init` first?"* Record it in `## Ground rules`.
Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it answers. If missing, fold it into the Step 0 gate batch: *"No `AGENTS.md`. Pathfinder can chart without it. Continue, or run `plan2code-init` first?"* Record the outcome as the first line of `## Ground rules`: ``- `AGENTS.md` exists and governs.`` or, when missing, exactly ``- `AGENTS.md` is absent.`` (the handoff reads it).
## Rules
@@ -49,12 +53,13 @@ Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it
- **Reserved names — never create inside `pathfinder/`:** `overview.md`, `phase-<N>.md`, `PLAN-DRAFT-*.md`, `PLAN-CONVERSATION-*.md`.
- **Never emit the loop's completion tokens under `specs/`** — `TASK_COMPLETE`, `PHASE_COMPLETE`, `ALL_TASKS_COMPLETE`, `IMPLEMENTATION_COMPLETE`, `SPEC_COMPLETE`, `WORK_COMPLETE`. It scans for them.
- **No `- [ ]` checkboxes inside question files**, and no `METRICS_JSON` anywhere.
- **Lint before every Session End** (on `github`, once a brief or PLAN-DRAFT is on local disk; it checks those): `lint` checks the rules above, the schema lines, `Blocked by:` targets and cycles, and metrics-scraper bait. Fix every error it lists (exit 4) before you stop.
## Auto-Discovery and Mode Selection
⚠️ `specs/` is gitignored — NEVER use Glob. Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
**Brief/recap/minutes asked?** → read references/brief.md: reconcile, write plain-English `briefs/brief-<YYYYMMDD>.md` (decisions in range, still open, next step), STOP. Never resolves.
**Brief/recap/minutes asked?** → read references/brief.md: `reconcile`, then `brief-data --range <range>` (`github`: its brief section), write plain-English `briefs/brief-<YYYYMMDD>.md` from the output, STOP. Never resolves.
**Identify the idea FIRST** (from the argument, or ask), then evaluate for THAT idea — first match wins. An issue URL or number means `github`; else look for a local map, then `gh issue list --label pathfinder:map` for `Map: <idea>`.
@@ -81,15 +86,15 @@ Read references/chart.md
> Fallback: confirm the outcome with the human FIRST; only then grill the destination, then breadth-first; write the map and one question per sharp decision.
0. `[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. `[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. `[Step 2: Destination]` Grill until it is one or two lines. It fixes scope — settle it first.
3. `[Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter.
4. `[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. `[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. `[Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass — on `github`, create all first, wire edges second. The rest stays fog. Include a `grill · HITL` testing-posture question; `/plan2code-1-plan` Phase 1 needs it.
7. `[Step 7: Index]` Fill `## Question Checklist` from the files (`local` only). Set `**Status:** Working`.
8. `[Step 8: Fire research]` One subagent per `research` question, in parallel. Each writes only its `## Evidence`, never decides. **Wait for all** (they die with the terminal), then Session End.
0. `[Chart - Step 0: Intent Gate]` **Before creating anything**, use AskUserQuestion for the outcome and WAIT: **chart a map** (foggy — Step 1), **`/plan2code-1-plan`** (clear — STOP), **`/plan2code-quick-task`** (tiny — STOP). HITL, never self-select "chart".
1. `[Chart - Step 1: Name and backend]` Only after the gate says "chart." Confirm the kebab-case idea name, then ask — HITL, never self-picked — **local files or GitHub Issues?** Recommend `local` for solo work; offer `github` only if preflight passes, naming the repo's visibility. THEN the first write.
2. `[Chart - Step 2: Destination]` Grill until it is one or two lines. It fixes scope — settle it first.
3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter.
4. `[Chart - Step 4: Map the frontier]` Grill again **breadth-first**: fan out, never deep on one thread. Surface the open decisions and what is takeable now.
5. `[Chart - Step 5: Create the map]` `**Status:** Charting`, Destination, Ground rules (backend first), an empty index, the fog in `## Not yet specified`. Say once where it lives and who sees it.
6. `[Chart - Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass — on `github`, create all first, wire edges second. The rest stays fog. Include a `grill · HITL` testing-posture question; `/plan2code-1-plan` Phase 1 needs it.
7. `[Chart - Step 7: Index]` `local`: `reconcile` fills `## Question Checklist` from the files (every missing row, with its marker). Either backend: set `**Status:** Working`. `local`: then `lint`.
8. `[Chart - Step 8: Fire research]` One subagent per `research` question, in parallel. Each writes only its `## Evidence`, never decides. **Wait for all** (they die with the terminal), then Session End.
**No fog at Step 4?** Small enough to plan directly: create no map, keep the recon as a local file, attach it to `/plan2code-1-plan`, STOP. Charting resolves nothing by hand — stop at Step 8.
@@ -101,15 +106,18 @@ Read references/resolve.md
Assume NO memory of any prior session.
1. `[Step 1: Load]` Read the map whole. No question yet.
2. `[Step 2: Reconcile]` **Always.** Read every question. `## Answer` written but the state disagrees? The answer wins. Claimed with no `## Answer`? A crash: release it, say so. Rebuild every marker from the questions; backfill a missing `Resolved:` date from the claim. Research without `Research complete:`? Re-fire it.
3. `[Step 3: Frontier]` Every question open, unclaimed, and unblocked. First in order.
4. `[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.** Frontier empty but questions remain? All blocked — report the chain, STOP. Stranded on an `out-of-scope` blocker? Re-frame or rule out, re-run Step 3. Nothing open? The Clearing Gate.
5. `[Step 5: Zoom]` Read the claimed question in full, plus any closed question it references. Obey `## Ground rules`.
6. `[Step 6: Resolve]` Route by type per the resolve playbook. HITL needs the human's own words.
7. `[Step 7: Record]` Write `## Answer`: the decision, what was rejected and why, consequences, a one-line `**Gist:**`. Sources under `## Evidence`. Mark it resolved, dated today, index the gist + date on the map, bump `**Updated:**`.
8. `[Step 8: Graduate]` Fog now sharp? Write those questions, delete the graduated bullets. Past the destination? Rule it out of scope, one line in `## Out of scope`. Invalidated? Re-frame or rule out.
9. `[Step 9: Menu]` Run The Clearing Gate. Not cleared: fork-menu (Form C) — pick → Step 4, stop → Session End.
1. `[Work - Step 1: Load]` Read the map whole. No question yet.
2. `[Work - Step 2: Reconcile]` **Always.** `local`: run `reconcile`. The answer wins: a question whose `## Answer` its state contradicts is resolved, a missing `Resolved:` is backfilled from the claim (today if none), a claim with no `## Answer` (a crash) is released, and every marker is rebuilt from the questions. Tell the human each `repairs` entry in one line. Re-fire every question in `refire` (research cut off before its `Research complete:` line; resolve.md → Interrupted research). `--dry-run` first if the map looks badly off. `github`: the reconcile checks in the backend playbook.
3. `[Work - Step 3: Frontier]` Every question open, unclaimed, and unblocked, first in order. `local`: run `frontier` (`frontier`, `blocked` with each blocker, `stranded`, `nextNN`, `counts`).
4. `[Work - Step 4: Choose and claim]` The one the user named, else first on the frontier. Mark it claimed on the question and the map, **saved before any work** (`local`: `claim <NN>`, which refuses a blocked or non-open question and a second open claim). A `research` pick fires unclaimed instead (resolve.md); then claim the next one.
- Stranded on an `out-of-scope` blocker? Check this first: re-frame or rule out, re-run Step 3.
- Frontier empty but questions remain (`allBlocked`)? Report the chain, STOP.
- Nothing open (`nothingOpen`)? The Clearing Gate.
5. `[Work - Step 5: Zoom]` Read the claimed question in full, plus any closed question it references. Obey `## Ground rules`.
6. `[Work - Step 6: Resolve]` Route by type per the resolve playbook. HITL needs the human's own words.
7. `[Work - Step 7: Record]` Write `## Answer`: the decision, what was rejected and why, consequences, a one-line `**Gist:**` last. Sources under `## Evidence`. Mark it resolved, dated today, index the gist + date on the map, bump `**Updated:**` (`local`: `resolve <NN>` does all four; its `unblocked` list feeds the menu).
8. `[Work - Step 8: Graduate]` Fog now sharp? Write those questions (`local`: numbered from `nextNN`, then `reconcile` to index them), delete the graduated bullets. Past the destination? Rule it out of scope, one line in `## Out of scope` (`local`: `rule-out <NN> --reason "<why>"`; handle anything it reports `stranded`). Invalidated? Re-frame or rule out.
9. `[Work - Step 9: Menu]` Run The Clearing Gate. Not cleared: fork-menu (Form C; resolve.md §Cadence) — pick → Step 4, stop → Session End.
## The Clearing Gate
@@ -124,7 +132,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
Any failing: name it, keep working. All passing: follow the handoff playbook, set `**Status:** Cleared`, 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 — `/plan2code-1-plan` cannot read a tracker.
## Trail Footer
@@ -132,6 +140,8 @@ Read references/trail.md
> Fallback: once the map exists, end every response with a marker path (`●` done · `◉` here · `○` open · `⊘` blocked · `⊝` out of scope) `START`→`⚑`, a named legend, a plain-English confidence note, then ONE closer: asking → Form B, `WAITING ON YOU`, no command; menu → Form C, `NEXT UP` + `OR START FRESH`; session end → Form A, `NEXT STEP` + resume command with `--web` (map issue URL on `github`).
Close EVERY response with the trail once the map exists. You pick the form by what the turn does. `local`: `trail` draws it from the files, so paste its output verbatim. Asking → Form B, `trail --form B --item "<probe>" ... --text` (one `--item` per open probe, up to three). Menu after a decision → Form C, `trail --form C` WITHOUT `--text`: paste its `text`, then build the question tool from its `menu`. Session end → Form A, `trail --form A --text`. `github`: draw it by hand per the backend playbook.
## Session End
Report each question resolved (name + gist), what graduated, what's still open; offer a brief for today. Nothing to commit — `local` is gitignored, `github` already on the tracker. Then the mascot, then the Trail Footer.
@@ -152,7 +162,8 @@ 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. Work Step 2 repairs both; questions win. |
| Session stops mid-question, or map drift | Release the claim, note why (or leave it: the next reconcile releases a claim with no answer). Work Step 2 repairs both; questions win. Never reconcile mid-question: it would release your own live claim. |
| A script cannot run (no `node`) | Say so once; do the step by hand from questions.md (markers, blocking, schema) and the reference that names the step. Footer by hand: the trail's glyph path, then Form A `NEXT STEP · start a new conversation and run:` + the command, Form B `WAITING ON YOU · answer here, in this conversation:` + the items, or Form C `OR START FRESH · new conversation, paste:` + the command. |
| Frontier empty, fog remains | Not sharp yet. Grill it into a question, or clear the map |
| Reference file missing | Use the fallback blockquote under its `Read` line |
| `gh` fails mid-session on a `github` map | Report and STOP. Falling back to local forks the map |
@@ -2,7 +2,7 @@
> Loaded when the user's argument asks for a brief. Produces one plain-English report file for a date range — the artifact a PM pastes into Slack or reads aloud in a meeting. The only mutation BRIEF mode ever performs is the Work Step 2 reconcile; it never claims, resolves, or answers a question.
> **Backend note.** The report is IDENTICAL either way — same sections, same plain-English rules — and the brief file always lands on **local disk** under `specs/<idea>/pathfinder/briefs/`, even on `**Backend:** github`. What differs is where the inputs come from: on `github` the range filter reads each question issue's close date instead of a `Resolved:` line, and the open / blocked / out-of-scope sections come from the frontier query rather than the checklist — see `github-issues.md`.
> **Backend note.** The report is IDENTICAL either way — same sections, same plain-English rules — and the brief file always lands on **local disk** under `specs/<idea>/pathfinder/briefs/`, even on `**Backend:** github`. What differs is where the inputs come from: on `github` the range filter reads each question issue's close date instead of a `Resolved:` line, and the open / blocked / out-of-scope sections come from the frontier query rather than the checklist — see `github-issues.md`. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
## When it fires
@@ -14,17 +14,17 @@ The argument (or message) asks for a `brief`, `summary`, `recap`, or `minutes` f
/plan2code-0-pathfinder full brief for specs/<idea>/pathfinder
```
Range grammar is deliberately loose: `today` (the default when unstated) · `this week` · `since <date>` · an explicit `<date>..<date>` · `full` (everything since the map was created). Get today's date from the shell — never guess it.
Translate the person's words into the script's range: `today` (the default when unstated) · `this-week` (Monday through today) · `since:<YYYY-MM-DD>` · `<YYYY-MM-DD>..<YYYY-MM-DD>` · `full` (everything since the map was created). Resolve a relative phrase ("since Tuesday") to a date yourself; the script takes dates only and reads today from the clock.
No `map.md` for the idea? There is nothing to brief — say so and route to charting. `**Status:** Cleared`? A brief is still legitimate: cover the full history and point at the PLAN-DRAFT in `## Next step`.
## Procedure
1. **Resolve the idea** exactly as Auto-Discovery does (shell only — `specs/` is gitignored, Glob silently fails).
2. **Reconcile first, in full** (Work Step 2): files win over markers, stale claims reset to `open`, absent `Resolved:` dates backfilled from `Claimed:`. Save the repaired map. A brief must never disagree with the map it summarizes — this is why BRIEF mode reconciles rather than reporting drift.
3. **Filter**: resolved questions whose `Resolved:` date falls in the range. Out-of-scope rulings are NOT date-filtered — they are standing scope boundaries and appear in every brief.
4. **Write** `specs/<idea>/pathfinder/briefs/brief-<YYYYMMDD>.md` (create `briefs/` if absent). The filename carries today's date regardless of range — the `**Covers:**` line disambiguates. Same-day re-runs overwrite: a brief is a report, not a record; the question files remain the record.
5. **Report** in chat: the file path, the range, one line on any reconcile repairs. Then the Trail Footer, Form A (the session is over; the command routes by map status as usual).
1. **Resolve the idea** exactly as Auto-Discovery does.
2. **Reconcile first**: `node "<S>/pathfinder.mjs" reconcile specs/<idea>/pathfinder`. A brief must never disagree with the map it summarizes, which is why BRIEF mode repairs drift rather than reporting it. Keep its `repairs` for step 5.
3. **Gather**: `node "<S>/pathfinder.mjs" brief-data specs/<idea>/pathfinder --range <range>`. It filters resolved questions by `Resolved:` date and returns every section's source (below), the file to write, and `drift` / `undatedResolved` (both empty after step 2; if not, rerun step 2). Out-of-scope rulings are never date-filtered: standing scope boundaries appear in every brief.
4. **Write** the file at its `file` path (create `briefs/` if absent). The name carries today's date regardless of range; the `**Covers:**` line disambiguates. Same-day re-runs overwrite (`exists: true`): a brief is a report, not a record; the question files remain the record.
5. **Report** in chat: the file path, the range, one line on any reconcile repairs. Then the Trail Footer, Form A (the session is over; the command routes by map status as usual). Run `lint` first: it checks the brief for percent signs and scraper bait.
## The template
@@ -78,17 +78,17 @@ Run: `/plan2code-0-pathfinder specs/audit-log-export/pathfinder`
**How each section is built:**
| Section | Source | Rendering rule |
| Section | `brief-data` field | Rendering rule |
|---|---|---|
| Heading + `**Covers:**` | Idea name in words; the range; `<resolved>/<total>` using the trail's counting rule (out-of-scope rows excluded from the total) | |
| Where this is headed | `## Destination`, verbatim | Never paraphrase it |
| Decided `<in range>` | Resolved files with `Resolved:` in range | Question name bold, gist as the first line, rejected alternatives compressed to ONE line each with the why in parentheses. `Locked: yes` renders as *Recorded as hard to reverse.* — never the word "locked" |
| Ruled out | `## Out of scope`, all of it | One line each: name + why |
| Open - ready to decide next | The frontier (open, unclaimed, unblocked) | Flag anything a resolution in range just unblocked: "can now be decided; X landed <day>" |
| Open - waiting on something first | `[!]` blocked rows | Name the blocker in plain words ("waiting on the export format decision"), never `Blocked by: 02` |
| Still taking shape | `## Not yet specified` | Lightly rephrase each bullet into one plain sentence |
| How solid is this? | The map's `**Confidence:**` line | ONLY via trail.md's plain-English mapping (solid / solid-but-borderline / not yet). Omit the section if the map has no confidence line |
| Next step | Map status | `Working`/`Charting` → the pathed resume command; `Cleared` → point at the PLAN-DRAFT and `/plan2code-1-plan` |
| Heading + `**Covers:**` | `title`, `covers`, `progress` | `progress` already uses the trail's counting rule (out-of-scope excluded from the total) |
| Where this is headed | `destination` | Verbatim. Never paraphrase it |
| Decided `<in range>` | `decidedHeading`, `decided` (`name`, `gist`, `rejected`, `hardToReverse`) | Question name bold, gist as the first line, each `rejected` entry compressed to ONE line with the why in parentheses. `hardToReverse` renders as *Recorded as hard to reverse.* — never the word "locked". Empty → `note` |
| Ruled out | `ruledOut` | One line each: name + why, link markup dropped |
| Open - ready to decide next | `ready` | Flag each `justUnblockedBy`: "can now be decided; X landed <day>" |
| Open - waiting on something first | `waiting` | Name the blocker in plain words ("waiting on the export format decision"), never `Blocked by: 02` |
| Still taking shape | `fog` | Lightly rephrase each bullet into one plain sentence |
| How solid is this? | `confidence` | Already the plain-English line. Omit the section when it is null |
| Next step | `nextStep` | `command` as given; with a `plan`, point at that PLAN-DRAFT too |
Nothing decided in the range? Keep the file honest: "No decisions were recorded in this period." under Decided, and render the open sections as usual — a meeting that only surfaced questions still gets minutes.
@@ -351,7 +351,7 @@ Fog gathers **only toward the destination**. The destination fixes the scope, so
| Reopening | Automatic, as answers land | Only if the destination is redrawn — and then as a fresh effort, not a resumption |
| The act | An admission of ignorance | A scoping decision |
Ruling something out of scope is a **scoping act, not a step on the route**. When a question you already created turns out to sit past the destination — mis-scoped in during charting, or exposed by a later answer — set `State: out-of-scope`, mark its row `[-]`, and leave one line in `## Out of scope` giving the gist and the reason, linking the question by name. It does not get an `## Answer` and it is not a decision the route walked.
Ruling something out of scope is a **scoping act, not a step on the route**. When a question you already created turns out to sit past the destination — mis-scoped in during charting, or exposed by a later answer — run `rule-out <NN> --reason "<why>"` (resolve.md, Ruling a question out of scope mid-work): it sets `State: out-of-scope`, marks its row `[-]` and leaves one linked line in `## Out of scope` with the reason. Then handle anything it reports `stranded`. It does not get an `## Answer` and it is not a decision the route walked.
Watch for **stranded** questions: a live question whose `Blocked by:` names something now out of scope will never unblock. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
@@ -369,7 +369,7 @@ The rules:
2. **Blockers get lower numbers.** If *Row-count ceiling* blocks *Delivery channel*, the ceiling is `02` and delivery is `05`. This makes `Blocked by: 02` readable at a glance and makes "lowest `NN` first" on the frontier a sane traversal order.
3. **`00` is always the codebase context.** Never anything else.
4. **`NN` is never reused and never renumbered.** Not when a question is ruled out of scope, not when one is deleted, not to close a gap in the sequence. Links and `Blocked by:` lines would rot silently. Gaps in the numbering are normal and harmless.
5. **The next number is max + 1**, computed from the directory listing, not from the map.
5. **The next number is max + 1**, and `frontier` reports it as `nextNN`: one past the highest `NN` in the directory listing, on any `Blocked by:` line, or in any `questions/NN-` link in the map or a question file, and never below the map's `**Next NN:**` line. That line is a high-water mark the script keeps (every write command updates it, and it only rises), so even a deleted question that nothing links to any more never has its number handed out again. Never edit it by hand.
6. **Only depend on what genuinely gates the question.** A `Blocked by:` chain that is really a preference for reading order strangles the frontier. Ask: could this question be answered — badly but honestly — without the blocker? If yes, it is not blocked.
7. **Cycles are a phrasing bug.** If A blocks B and B blocks A, the two are one decision. Merge them or re-frame one to drop the edge.
8. **Refer by name in prose.** Bare numbers appear only on `Blocked by:` lines.
@@ -410,11 +410,16 @@ Say once, at Step 5: *"This map lives in gitignored `specs/` — local to you, n
**Status:** Working
**Updated:** 2026-08-03
**Confidence:** Requirements-clarity 18/25 · Feasibility-technical 14/25 · Integration-points 16/25 · Risk-assessment 14/25
**Next NN:** 07
<!-- Status: Charting while the map is being built (Chart Steps 1-6) -> Working once the
checklist is indexed (Chart Step 7) -> Cleared only when the Clearing Gate passes.
A fresh session routes on this line, so it must be correct before the session ends. -->
<!-- Next NN: the number the next new question file takes. Kept by the script (reconcile
adds it at Chart Step 7 and every write command raises it); it never goes down, so a
deleted question's number is never reused. Leave it out at Step 5; never edit it. -->
<!-- Confidence: four dimensions, each scored out of 25, re-scored at every resolution.
The Clearing Gate requires all four at 18/25 or better. Score against evidence. -->
@@ -431,7 +436,9 @@ plan, not at shipped code. Continuous streaming to external systems is not on th
## Ground rules
<!-- Standing constraints for every session on this map. Read before choosing a question,
obeyed while resolving it. Nothing here is re-asked. -->
obeyed while resolving it. Nothing here is re-asked. The first line records AGENTS.md:
"- `AGENTS.md` exists and governs." or, when it is missing, exactly
"- `AGENTS.md` is absent." (the handoff then routes to /plan2code-init first). -->
- `AGENTS.md` exists and governs. Its conventions are not re-litigated by any question here.
- One question _file_ at a time; the fork-menu between decisions; a fresh session recommended after ~3. `research` questions may run as parallel subagents.
@@ -401,6 +401,8 @@ Form B is unchanged — a turn that asks the human something still says `WAITING
Form C — the fork-menu after a recorded decision — is unchanged in shape, with two substitutions: the takeable options come from the frontier query rather than the checklist rows, and the `OR START FRESH` command carries the map issue URL. The `RECOMMENDED` marker and the ~3-decision checkpoint work exactly as `trail.md` describes.
With no script to draw them, the labels are exact: Form A `NEXT STEP · start a new conversation and run:`, Form B `WAITING ON YOU · answer here, in this conversation:`, Form C `OR START FRESH · new conversation, paste:`. The Form C question tool uses the header `Next step` and the question "Continue here, or start fresh? Everything is saved." (add "I recommend starting fresh, to keep me sharp." at the ~3-decision checkpoint). Its options are up to three takeable question names plus `Start fresh`, one marked `RECOMMENDED`.
---
## BRIEF mode
@@ -2,22 +2,28 @@
Loaded at The Clearing Gate. Turns a cleared map into `specs/<idea>/PLAN-DRAFT-<YYYYMMDD>.md` that `/plan2code-1-plan` resumes from at Phase 4, then freezes `pathfinder/` as the rationale record.
**Backend note.** The scoring rubric, the hard caps, the honesty rules, the template, and the mapping table are the same either way — and the draft is written to local disk either way, because `/plan2code-1-plan` reads a file, not a tracker. On `**Backend:** github`, `github-issues.md` replaces only the preflight table, the question links (issue URLs, already absolute), and the freeze steps.
**Backend note.** The scoring rubric, the hard caps, the honesty rules, the template, and the mapping table are the same either way — and the draft is written to local disk either way, because `/plan2code-1-plan` reads a file, not a tracker. On `**Backend:** github`, `github-issues.md` replaces only the preflight table, the question links (issue URLs, already absolute), and the freeze steps. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
Nothing here is creative. The gate is scored, the mapping is fixed, the template is literal. Follow it exactly or the resuming plan session silently loses work.
## Preflight — before scoring anything
| # | Check | If it fails |
|---|---|---|
| 1 | Re-run the reconcile pass: read every file in `questions/`, rebuild every map marker from the files | Fix the map first. Markers are derived, never authored. |
| 2 | Zero `[ ]`, zero `[/]`, zero `[!]` rows in `## Question Checklist` | Not cleared. Return to the frontier. |
| 3 | `## Not yet specified` is empty | Not cleared. Graduate the fog into questions, or admit it is out of scope. |
| 4 | Every `[x]` row's file has a real `## Answer` with a `**Gist:**` | The file wins over the marker. Repair, then re-check. |
| 5 | `ls specs/<idea>/` shows no existing `PLAN-DRAFT-*.md` | One already exists — read it. Update it in place; never add a second dated draft. |
| 6 | The destination is reachable with nothing left to decide — no `## Answer` defers a choice to "whoever implements this" | Not cleared. Name the open decision and graduate it into a question. |
Run `reconcile`, then `node "<S>/pathfinder.mjs" gate specs/<idea>/pathfinder`. Its `checks` cover the mechanical preflight, read from the files:
Only after all six pass do you score the four dimensions.
| `checks` id | Means | If it fails |
|---|---|---|
| `markers-match-files` | The map's markers are the files' (reconcile ran) | Run `reconcile`. Markers are derived, never authored. |
| `no-open-claimed-blocked` | Zero `[ ]`, `[/]`, `[!]` | Not cleared. Return to the frontier. |
| `fog-empty` | `## Not yet specified` is empty | Not cleared. Graduate the fog into questions, or admit it is out of scope. |
| `every-resolved-has-gist` | Every resolved file has a real `## Answer` with a `**Gist:**` | The file wins over the marker. Repair, then re-check. |
| `hard-caps` | None of the Requirements, Feasibility or Risk caps below holds (the Integration cap is yours to check) | That dimension cannot exceed 17: fix the record first. |
| `scores-at-least-18` | The map's `**Confidence:**` line has all four at 18 or better | Not cleared. Keep working the weak dimension. |
`existingPlanDraft` lists a `PLAN-DRAFT-*.md` already in `specs/<idea>/`: read it and update it in place, never add a second dated draft. `planDraftPath` is the file to write either way.
One preflight item stays yours: **the destination is reachable with nothing left to decide**: no `## Answer` defers a choice to "whoever implements this". If one does, the map is not cleared: name the open decision and graduate it into a question.
Score the four dimensions (below), write them to the map's `**Confidence:**` line, and rerun `gate` until `mechanicalPass` is true.
## The clearing-gate scoring rubric
@@ -45,7 +51,7 @@ The 18-boundary is the honest line between *"needs designing"* and *"needs decid
### Hard caps
A cap overrides your judgment. While a cap condition holds, the dimension **cannot** exceed 17, so the gate cannot pass.
A cap overrides your judgment. While a cap condition holds, the dimension **cannot** exceed 17, so the gate cannot pass. `gate` reports the Requirements, Feasibility and Risk caps from the files (`caps`); the Integration cap needs you to match the destination's systems to questions.
| Cap | Condition |
|---|---|
@@ -107,7 +113,7 @@ Consequences of that being a literal string match:
- Copy it byte for byte. Plain ASCII hyphen-minus surrounded by single spaces. An en dash, a colon, or "Phase 3 complete" in lower case breaks the match and 1-plan starts over at Phase 1 — throwing away every decision the map holds.
- It goes on its own `**Status:**` line in the header block, not buried in prose.
- The file must be named `PLAN-DRAFT-<YYYYMMDD>.md` and live directly in `specs/<idea>/`. `PLAN-DRAFT-*.md` is a reserved name inside `pathfinder/` — never write it there.
- Get the date from the shell (`date +%Y%m%d` in Bash, `Get-Date -Format yyyyMMdd` in PowerShell). Do not guess it.
- Use the date in `gate`'s `planDraftPath` (it reads the clock). Do not guess it. On `github` (no `gate`), take today's date from the shell and check `ls specs/<idea>/` for an existing draft.
**Discovery is shell-only.** `specs/` is gitignored, so Glob silently returns nothing and every downstream skill would report "no PLAN-DRAFT found". Use `ls specs/` and `ls specs/<idea>/` (Bash) or `Get-ChildItem specs/` (PowerShell) — the same rule 1-plan and `/plan2code-2-document` follow when they look for the file you are about to write.
@@ -338,6 +344,8 @@ The reason is exact. When a PLAN-DRAFT carries no `METRICS_JSON` comment, the me
Never drop the footer to make the file tidier. It is load-bearing.
After writing the draft, run `lint`: it scans a pathfinder-written PLAN-DRAFT with the metrics collector's own patterns and names any bait that reached the page.
## System Context and Scope Assessment — why they buy you Phase 4
These two named, unnumbered sections are what make "Resume at Phase 4" legitimate rather than a shortcut. They stand in for the phases pathfinder already did the work of:
@@ -19,7 +19,7 @@ specs/<idea>/
## Numbering
`NN` is zero-padded from `00`, assigned in dependency order (blockers lower), **never reused or renumbered** — links and `Blocked by:` would rot silently. Next = max + 1. `00` is always `00-codebase-context.md`, never anything else. Gaps in the sequence are normal and harmless.
`NN` is zero-padded from `00`, assigned in dependency order (blockers lower), **never reused or renumbered** — links and `Blocked by:` would rot silently. Next = max + 1 (`frontier`'s `nextNN`), never below the map's `**Next NN:**` high-water line, which the script keeps so a deleted question's number stays retired (chart.md, Step 6 rule 5). A one-digit file name (`1-export.md`) still reads as `01`, but `lint` asks for the rename. `00` is always `00-codebase-context.md`, never anything else. Gaps in the sequence are normal and harmless.
## The six schema lines
@@ -42,4 +42,6 @@ Each question file carries six contiguous `Key: value` lines after its H1 — NO
**Map markers**, rebuilt from the files every session: `[ ]` open — **these rows ARE the frontier** · `[/]` claimed · `[x]` resolved · `[!]` open but blocked · `[-]` out of scope. Resolved rows carry the gist plus the `Resolved:` date in italics: `— <gist> *(YYYY-MM-DD)*`.
`scripts/pathfinder.mjs` implements exactly these rules (`reconcile` rebuilds the markers, `frontier` computes blocking, `lint` checks the schema), so this file is the reference for reading its output and for writing a question file. Apply the rules by hand only when the script cannot run.
**Unblocked** ⟺ every `NN` in `Blocked by:` is `resolved`. **Stranded:** a blocker gone `out-of-scope` never resolves — the question is not merely blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
@@ -2,7 +2,7 @@
> Loaded at the top of MODE B. Work Step 6 routes here by `Type:`; Work Step 8 uses the fog procedure at the end.
>
> **Backend note.** Every resolution technique here is backend-independent — the type table, the primary-source rule, the sketch tiers, the checklist discipline, the `## Answer` anatomy. On `**Backend:** github`, `Type:` is a `pathfinder:<type>-<mode>` label, `## Answer` and `## Evidence` are comments rather than file sections, and a research subagent gets an issue URL instead of a path; see `github-issues.md`. Sketches stay on local disk regardless.
> **Backend note.** Every resolution technique here is backend-independent — the type table, the primary-source rule, the sketch tiers, the checklist discipline, the `## Answer` anatomy. On `**Backend:** github`, `Type:` is a `pathfinder:<type>-<mode>` label, `## Answer` and `## Evidence` are comments rather than file sections, and a research subagent gets an issue URL instead of a path; see `github-issues.md`. Sketches stay on local disk regardless. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
Every question resolves into the SAME shape — a filled `## Answer` plus whatever `## Evidence` backs it. The type only decides how you get there.
@@ -14,7 +14,7 @@ Every question resolves into the SAME shape — a filled `## Answer` plus whatev
| `legwork · HITL` | Human does, agent waits | No | The human confirmed it is done |
| `grill · HITL` | Human decides, agent interrogates | No — but probes batch, up to 3 per turn | The human said it in their own words |
**One question _file_ at a time** holds for every row except `research` — several may resolve in one session, but strictly in sequence, per the Cadence below. HITL rows are never self-answered — an agent that writes its own `## Answer` on a `grill` has broken the skill.
**One question _file_ at a time** holds for every row except `research` — several may resolve in one session, but strictly in sequence, per the Cadence below. `research` is also the one type that is **never claimed**: its subagents fire unclaimed (the file stays `State: open`), so `claim` and its one-claim rule govern grill, sketch and legwork only, and a grill can be claimed while research runs. A research question is finished with `## Answer` plus `resolve` once its subagent is back, or re-fired from `reconcile`'s `refire` if it was cut off. HITL rows are never self-answered — an agent that writes its own `## Answer` on a `grill` has broken the skill.
Every file you create along the way — question files, sketch READMEs — opens with the banner:
@@ -42,7 +42,7 @@ The restart costs one paste and loses nothing: every claim, answer, and map upda
- Read only what the cycle needs: the claimed question file plus resolved neighbors' *gists* (Work Step 5). Never re-read the whole `questions/` directory between cycles — reconcile ran once at session start, and this session is the only writer.
- The menu renders from the map's checklist rows, never from re-reading question files.
- Strictly one claim open at any moment. Claim → record → release, then the menu. Never two.
- Strictly one claim open at any moment. Claim → record → release, then the menu. Never two. (Research subagents run unclaimed beside it; see the top of this file.)
**Group sessions.** When Product and Engineering (or any room) work the map together, the grilling playbook's group-session rules apply: probes address the room, the recap captures the decision in the room's words, and a contested pick is never recorded as decided — both positions go under `## Evidence`, the question stays `open`, and the menu moves on (or offer to convert it to `sketch`; reacting to something concrete resolves more standoffs than argument). At Session End, offer `write a brief for today` — the brief doubles as the meeting minutes.
@@ -52,7 +52,7 @@ The restart costs one paste and loses nothing: every claim, answer, and map upda
## `research · AFK`
The only type an agent resolves alone, and the only type that may run several at once. Charting fires them in a batch at Chart Step 8; MODE B fires any that appear later the same way.
The only type an agent resolves alone, and the only type that may run several at once. Charting fires them in a batch at Chart Step 8; MODE B fires any that appear later the same way, unclaimed: never run `claim` on a research question. When one tops the frontier at Work Step 4, fire it, then claim the first non-research question.
### Spin up a subagent
@@ -78,7 +78,7 @@ Subagents run inside this session's process, even when the harness runs them in
### Interrupted research
At Work Step 2 (Reconcile), any research question that is not resolved and whose `## Evidence` lacks the `**Research complete:**` line was never finished: a closed terminal, a crash, a rate limit. Re-fire its subagent with the same brief, plus one instruction: keep what is already in `## Evidence`, verify it, fill the gaps, then write the line. Say so in one line to the human. A map written before this line existed shows the same symptom; re-firing it costs a little time and nothing else.
At Work Step 2, `reconcile` lists in `refire` every research question that is not resolved and whose `## Evidence` lacks the `**Research complete:**` line (with its path and `## Question` text for the brief): it was never finished, by a closed terminal, a crash, a rate limit. Re-fire its subagent with the same brief, plus one instruction: keep what is already in `## Evidence`, verify it, fill the gaps, then write the line. Say so in one line to the human. A map written before this line existed shows the same symptom; re-firing it costs a little time and nothing else.
### Primary sources only
@@ -421,7 +421,7 @@ If the legwork turns out to BE the deliverable rather than an unblocker — you
> "This has stopped being legwork that unblocks a decision and become the work itself. Pathfinder plans; it doesn't build. I'm ruling this out of scope and it belongs in planning."
Rule the question `out-of-scope`, mark the map row `[-]`, add one line to `## Out of scope` naming what it turned into, and hand off to `/plan2code-1-plan` for that piece. Never let pathfinder quietly become the implementation.
Rule the question out with `rule-out <NN> --reason "<what it turned into>"` (it marks the row `[-]` and adds the `## Out of scope` line), and hand off to `/plan2code-1-plan` for that piece. Never let pathfinder quietly become the implementation.
---
@@ -446,7 +446,7 @@ A good grill `## Answer` contains four things:
## Writing the `## Answer`
Same anatomy for every type. Append it at Work Step 7; never edit `## Question` to match the answer. In the same write, set `State: resolved` **and** `Resolved:` to today's date (`YYYY-MM-DD`, from the shell, never guessed) — the date is what lets a brief report "decided on <day>", so a resolution without it is incomplete.
Same anatomy for every type. Append it at Work Step 7; never edit `## Question` to match the answer. Then run `node "<S>/pathfinder.mjs" resolve specs/<idea>/pathfinder <NN>`: it sets `State: resolved` **and** `Resolved:` to today (from the clock; the date is what lets a brief report "decided on <day>"), and writes the map row from your `**Gist:**`. It refuses an Answer with no Gist line.
| Part | Required | Content |
|---|---|---|
@@ -519,7 +519,7 @@ The map row it produces — gist, then the `Resolved:` date in italics:
1. **Re-read `## Not yet specified` in full.** Every bullet, every session, after every resolution. Not the ones you remember — you are assuming no memory of prior sessions, and the bullet that graduates is usually the one you forgot was there.
2. **Ask of each bullet: did the answer just make this sharp?** Can you now write a `## Question` paragraph a stranger could act on, without "we'll need to figure out" anywhere in it?
3. **If yes, write the question file NOW** — in this same session, before Work Step 9. Next `NN` = max existing + 1, never reused. Fill all five metadata lines, with `Blocked by:` wired in the same pass. Add its `[ ]` or `[!]` row to `## Question Checklist`.
3. **If yes, write the question file NOW** — in this same session, before Work Step 9. Its `NN` is `frontier`'s `nextNN` (max existing + 1, from the directory, never reused). Fill all six schema lines, with `Blocked by:` wired in the same pass. `reconcile` then adds its `[ ]` or `[!]` row to `## Question Checklist`.
4. **DELETE the bullet from `## Not yet specified`.** Immediately, in the same edit as writing the file.
5. **If no, leave the bullet alone** — untouched, not reworded into something that merely sounds sharper.
6. **Re-check the counts.** One fog patch may graduate into three questions, or into none. Both are normal. A patch that graduates into three was written at the right coarseness; a patch that graduates into exactly one every time was probably a question all along.
@@ -538,10 +538,9 @@ Detection is cheap: after writing any graduated question file, re-read `## Not y
The destination fixes the scope. When a resolution reveals that a question — the one you just claimed, or another on the map — sits past the destination:
1. Set that file's `State: out-of-scope`. Do NOT write a `## Answer`; there is no decision, only a scope boundary. Add one line under `## Question` saying why it is out.
2. Set its map row to `[-]`.
3. Add one line to `## Out of scope`: the name as a link, plus the reason.
4. Check for **stranded** questions — anything whose `Blocked by:` names it. A blocker that is `out-of-scope` will never be `resolved`, so the dependent is permanently blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
1. Decide the one-line reason. Do NOT write a `## Answer`; there is no decision, only a scope boundary.
2. Run `node "<S>/pathfinder.mjs" rule-out specs/<idea>/pathfinder <NN> --reason "<why>"`. It sets `State: out-of-scope`, adds the reason under `## Question`, marks the row `[-]` and adds the linked line to `## Out of scope`.
3. Handle its `stranded` list: questions whose `Blocked by:` names it. A blocker that is `out-of-scope` will never be `resolved`, so the dependent is permanently blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
Out-of-scope work never graduates back. The frontier stops at the destination. It returns only if the destination is redrawn, and then as a fresh effort with a fresh map.
@@ -559,9 +558,9 @@ An answer can also break questions that already exist. Three cases:
| What happened | Do this |
|---|---|
| The question still matters but is asked wrong | **Re-frame.** Rewrite `## Question` in place. Keep `NN`, keep the file, keep the links. Add one line noting which answer forced the re-frame. |
| The question no longer exists — the answer subsumed it | **Delete the file and its map row.** Add one line to the answering question's `## Answer` consequences saying what it absorbed. Do not renumber anything. |
| The question no longer exists — the answer subsumed it | **Delete the file, then run `reconcile`** (it drops the map row). Add one line to the answering question's `## Answer` consequences saying what it absorbed. Do not renumber anything. |
| The question is now two questions | **Re-frame the original to the narrower half; write a new file at max+1 for the other.** Wire `Blocked by:` between them if one gates the other. |
Never leave a question standing that you know is wrong on the theory that a later session will notice. It will not — it assumes no memory, and a well-formed `## Question` reads as intentional.
Two hard constraints on all three cases: **`NN` is never reused and never renumbered** — links and `Blocked by:` lines would rot silently. And every re-frame or deletion is reflected in the map's `## Question Checklist` in the same edit, so the index never disagrees with the files.
Two hard constraints on all three cases: **`NN` is never reused and never renumbered** — links and `Blocked by:` lines would rot silently. And run `reconcile` straight after any re-frame or deletion, so the index never disagrees with the files (it drops the row of a deleted file and adds one for a new file).
+57 -165
View File
@@ -2,193 +2,85 @@
> Loaded at the top of the skill. Read once; it applies to EVERY response in both modes. Defines the map visual and the pathed resume command that close each turn.
>
> **Backend note.** The glyphs, the two forms, and the discipline are identical either way. On `**Backend:** github` the inputs come from the sub-issue query rather than the checklist, and Form A's command is the map issue URL — see `github-issues.md`.
> **Backend note.** The glyphs, the two forms, and the discipline are identical either way. On `**Backend:** github` the inputs come from the sub-issue query rather than the checklist, and Form A's command is the map issue URL — see `github-issues.md`. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
The trail is how a human with no memory of the last session sees, at a glance, how far the map has come and what is left — and copies the exact command to resume without hunting for a path that lives in gitignored `specs/`. It closes every response once a map exists.
It is **presentation only**. Rebuild it fresh from `map.md` each response; never write it to disk, and never let it emit a loop token (`TASK_COMPLETE`, `PHASE_COMPLETE`, and the rest). It is an index of an index — the question files remain ground truth.
---
## When it renders
| Situation | Footer? |
|---|---|
| `map.md` exists and the turn **ends the session** — Session End, a cleared map, a fully blocked frontier | **Yes**, both parts: the trail, then the resume command (Form A) |
| `map.md` exists and the turn **asks the human something** — a probe batch, a sketch put up for reaction, a `legwork · HITL` checklist | **Yes**, but with the waiting form of Part 2 (Form B). Never a resume command — see below |
| `map.md` exists and the turn **offers the menu after a recorded decision** — the continue-or-stop fork of the Work cadence | **Yes**, the fork form of Part 2 (Form C): the takeable questions AND the resume command as the stop branch |
| Intent Gate (Step 0), the no-fog off-ramp, or any route-and-stop before Step 5 | **No** — no map on disk yet, and no path to resume. There is nothing to draw. |
One idea per session, so there is only ever one trail. Draw the trail for the active idea and no other.
---
## The two parts
Always in this order, after everything else in the response:
1. **The trail** — the horizontal path plus its legend and confidence line. Identical on every turn.
2. **The next line** — either the pathed resume command or the waiting notice, chosen by turn type.
### Part 1 — the trail
It is **presentation only**, rebuilt fresh from the files every response and never written to disk. The script draws it; you choose its form.
```
🧭 audit-log-export · Working · 2/7 cleared
node "<S>/pathfinder.mjs" trail specs/<idea>/pathfinder --form A|B|C [--item "<probe>" ...] --text
```
`--text` prints the footer itself: paste it verbatim as the last thing in the response. Use it for Forms A and B. For Form C leave `--text` off: the JSON carries the same `text` plus the `menu` the question tool needs. Run `reconcile` first in a session (Work Step 2) so the files it reads are settled.
---
## When it renders, and which form
The **turn type** picks the form, never the map's status. This is the one decision the script cannot make for you.
| Situation | Footer |
|---|---|
| `map.md` exists and the turn **ends the session** — Session End, a cleared map, a fully blocked frontier, a parked grill | **Form A**: the trail, then the resume command |
| `map.md` exists and the turn **asks the human something** — a probe batch, a sketch put up for reaction, a `legwork · HITL` checklist, the Chart Step 2 destination grill, the Chart Step 4 frontier grill | **Form B**: the trail, then the waiting notice. Never a resume command |
| `map.md` exists and the turn **offers the menu after a recorded decision** — the continue-or-stop fork of the Work cadence | **Form C**: the trail, the `OR START FRESH` command, then the question tool |
| Intent Gate (Step 0), the no-fog off-ramp, or any route-and-stop before Step 5 | **None** — no map on disk yet, and no path to resume |
One idea per session, so there is only ever one trail.
### What the script draws (so you can read it, not build it)
```
🧭 audit-log-export · Working · 2/6 cleared
START ●━●━◉··○··○··⊘··⊝ ····⚑
● done · ◉ here · ○ open · ⊘ blocked · ⊝ out of scope · ⚑ destination · ~4 fog
1 Codebase context ✔ · 2 Export format ✔ · 3 Row-count ceiling ◀ here
4 Export authorization · 5 Testing posture · 6 Delivery channel (blocked:3) · 7 SIEM push (out of scope)
1 Codebase context ✔ · 2 Export format ✔ · 3 Row-count ceiling ◀ here · 4 Export authorization
5 Testing posture · 6 Delivery channel (blocked:3) · 7 SIEM push (out of scope)
Confidence: solid, but Risk is borderline.
```
How each line is built, top to bottom:
- **Heading** — `🧭 <idea> · <Status> · <resolved>/<total> cleared`. `<Status>` is the map's `**Status:**` verbatim (`Charting` / `Working` / `Cleared`). `<resolved>` counts `[x]` rows; `<total>` counts every question row **except** out-of-scope `[-]` rows (a ruled-out question is off the route, not an unfinished stop).
- **The path** — one glyph per question row in `NN` order, left to right, from `START` to the `⚑` destination. Connectors carry meaning: solid `━` joins stops already walked (everything up to and including `◉ here`); dashed `··` joins stops still ahead. After the last question glyph, a fog stretch `····` then `⚑` — drop both if there is no fog and join straight to `⚑` with `━`.
- **The legend** — only the glyphs actually on this path, so a map with no blocked question does not advertise `⊘`. Append `~N fog` when `## Not yet specified` holds N bullets.
- **The named legend** — the same `NN` order, `<NN> <Name>` each, `·`-separated, wrapping across lines as needed. Tag each: `✔` resolved, `◀ here` the claimed one, `(blocked:NN)` with its blocker, `(out of scope)`. Names come straight from the checklist rows.
- **Confidence** — the map's four internal scores (Requirements / Feasibility / Integration / Risk, each out of 25) exist for the Clearing Gate, not the human. Never print the raw numbers or the `R·F·I·K` letters. Instead, reduce them to one plain-English line:
| Scores | Line |
|---|---|
| All four ≥ 20 | `Confidence: solid.` |
| All four ≥ 18, one or more sitting at 18-19 | `Confidence: solid, but <Dimension> is borderline.` (name every dimension in that range, comma-separated) |
| Any dimension < 18 | `Confidence: not yet — <Dimension(s)> still need work.` |
Omit the whole line if the map has no `**Confidence:**` line yet.
### Glyph reference
| Glyph | Map marker | Meaning |
|---|---|---|
| `●` | `[x]` | resolved — a stop already walked |
| `◉` | `[/]` | the claimed question — you are here |
| `○` | `[ ]` | open, on the frontier |
| `⊘` | `[!]` | open but blocked |
| `⊝` | `[-]` | ruled out of scope |
| `⚑` | — | the destination |
| `····` | — | the fog still between the last question and the destination |
### Part 2 — the next line
Part 2 answers exactly one question for the human: **is this turn over, or is it my move?** It has three forms, and the **turn type** picks between them — not the map's status.
#### Form A — the turn ends the session
```
NEXT STEP · start a new conversation and run:
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder --web`
```
The path is always relative and always ends `/pathfinder` — that is exactly the argument this skill's Auto-Discovery resolves an idea from, so the human pastes it back with zero edits. Fill `<idea>` from the active map's directory; never leave the `<spec-folder>` placeholder in a rendered footer.
The command target follows the map's status, but the sentence is always the same shape — `start a new conversation and run:` followed by the command on its own line:
| Status | Command |
|---|---|
| `Charting` / `Working` | `/plan2code-0-pathfinder specs/<idea>/pathfinder --web` |
| `Cleared` | `/plan2code-1-plan --web` — point at the PLAN-DRAFT the Clearing Gate wrote |
| `Cleared`, but `## Ground rules` records `AGENTS.md` **absent** | `/plan2code-init` FIRST (offer `questions/00-codebase-context.md`), then `/plan2code-1-plan --web` |
#### Form B — the turn asks the human something
Any turn whose next move is theirs and happens **in this same conversation**: a batch of grill probes, a sketch put up for reaction, a `legwork · HITL` checklist, the Chart Step 2 destination grill, the Chart Step 4 frontier grill.
```
WAITING ON YOU · answer here, in this conversation:
Q1 Duration model · Q2 Contract while held · Q3 Placement & restore
```
Name every outstanding item at its stable number so a partial reply is cheap to give and a dropped probe is visible to both of you. `·`-separated on one line; one per line if the names run long. Never more items than the three-probe cap allows.
**Emit no resume command on a Form B turn.** There is nothing to resume — the session is alive and holding a claim. A resume command here reads as *we're done*, and the human either walks away mid-decision or burns the next turn asking what you meant. This is the single most common way the footer misfires, and it costs the batch the round trips batching was introduced to save.
One exception: `grilling.md`'s unreachable-human procedure. Parking a mid-grill question and stopping IS a session end — use Form A, and say in the body that the question is parked mid-grill with its batch outstanding.
#### Form C — the menu after a recorded decision
Used ONLY on the Work cadence's fork-menu turn (resolve.md §Cadence), immediately after an `## Answer` landed and the map row flipped `[x]`. It is the one legitimate hybrid: an *explicit* continue-or-stop fork where the resume command IS the stop branch, not a farewell.
First print the stop branch, clearly labeled:
```
OR START FRESH · new conversation, paste:
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder --web`
```
Then invoke the structured question tool (header `Next step`) asking: "Continue here, or start fresh? Everything is saved." Options: up to three takeable question names, then `Start fresh`. Put each question's gist / newly-unblocked note in its description. The automatic `Other` path lets the human name another frontier question not shown. Mark one option's description `RECOMMENDED` — early in the session that is a question; at the checkpoint it is `Start fresh`.
Rules for Form C:
- **The command label is mandatory and exact:** `OR START FRESH · new conversation, paste:`. It makes the command the stop branch, not a farewell. Never render a bare command on a menu turn.
- **The choice itself always uses the structured tool.** Never print `NEXT UP` as a prose menu when the tool exists.
- Options come from the map's checklist rows (names + gists), takeable questions only. Flag anything the decision just recorded unblocked. The fourth slot is `Start fresh`; `Other` covers a frontier question omitted from the top three.
- **The recommendation carries the checkpoint** (resolve.md §Cadence): early in a session recommend a question; after ~3 resolved this session — or after a heavy, contested, or `Locked: yes` decision — recommend `Start fresh`, with the reason said in the question text ("to keep me sharp").
- **Form C never replaces Form B.** A turn that asks probes, shows a sketch, or hands over a checklist is Form B, no command. Form C fires only between decisions, when nothing is claimed.
- If the human walks away mid-menu, nothing is stranded: no claim is open, and the command to come back is already on screen.
---
## State-by-state examples
**Charting, mid-grill, no question claimed yet** (`◉` is omitted; the frontier head is the first `○`). The Chart Step 4 frontier grill is a Form B turn — the batch is above, so the footer says stay:
```
🧭 audit-log-export · Charting · 1/5 cleared
START ●··○··○··○··○ ····⚑
● done · ○ open · ⚑ destination · ~6 fog
1 Codebase context ✔ · 2 Export format · 3 Export authorization · 4 Testing posture · 5 Row-count ceiling
Confidence: not yet — Requirements, Feasibility, Integration, Risk still need work.
WAITING ON YOU · answer here, in this conversation:
Q1 Data · Q2 Surface · Q3 Permissions
```
**Working, a claimed question mid-grill** — probes are out, the claim is held, nothing is resolved yet. Same trail, Form B again. Note that Q2 is a re-ask carried over at its original number from a batch that came back partial:
```
🧭 audit-log-export · Working · 2/7 cleared
START ●━●━◉··○··○··⊘··⊝ ····⚑
● done · ◉ here · ○ open · ⊘ blocked · ⊝ out of scope · ⚑ destination · ~4 fog
1 Codebase context ✔ · 2 Export format ✔ · 3 Row-count ceiling ◀ here
4 Export authorization · 5 Testing posture · 6 Delivery channel (blocked:3) · 7 SIEM push (out of scope)
Confidence: not yet — Feasibility, Integration, Risk still need work.
WAITING ON YOU · answer here, in this conversation:
Q2 Ceiling behaviour past the cap (re-ask) · Q3 Who sees the truncation warning
```
**Frontier fully blocked** — report the chain in the body; the trail shows why nothing is takeable. Work Step 4 stops the session here, so Form A:
- The heading counts resolved questions over every question except out-of-scope ones.
- One glyph per question in `NN` order: `●` resolved, `◉` claimed, `○` open, `⊘` blocked, `⊝` out of scope. A solid `━` leads into a walked stop (`●`, `◉`); `··` leads into one still ahead. `····⚑` stands for the fog; with no fog the path ends `━⚑` once every stop is walked (or ruled out) and `··⚑` while any is still ahead. A cleared map ends `━⚑ arrived` and drops both legend lines.
- The named legend numbers stops by position, and `(blocked:3)` points at stop 3.
- The confidence line is the map's four internal scores reduced to plain English: `solid` (all ≥ 20), `solid, but <Dimension> is borderline` (all ≥ 18, some at 18-19), `not yet — <Dimension(s)> still need work` (any < 18). The raw numbers never reach the human. No `**Confidence:**` line on the map, no confidence line in the trail.
```
🧭 audit-log-export · Working · 5/7 cleared
START ●━●━●━●━●━⊘··⊘ ⚑
● done · ⊘ blocked · ⚑ destination
6 Delivery channel (blocked:2) · 7 Notification (blocked:6)
Confidence: not yet — Feasibility, Risk still need work.
---
NEXT STEP · start a new conversation and run:
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder --web`
```
## Form A — the turn ends the session
**Cleared** — every stop walked, fog empty, command hands off:
The command follows the map's status: `/plan2code-0-pathfinder specs/<idea>/pathfinder --web` while `Charting` / `Working`; `/plan2code-1-plan --web` once `Cleared`; and `/plan2code-init` first when `## Ground rules` records `AGENTS.md` absent and it still is. The path is the exact argument Auto-Discovery resolves an idea from, so the human pastes it back with zero edits.
```
🧭 audit-log-export · Cleared · 8/8 cleared
START ●━●━●━●━●━●━●━●━⚑ arrived
Confidence: solid.
## Form B — the turn asks the human something
NEXT STEP · start a new conversation and run:
`/plan2code-1-plan --web`
```
Pass every outstanding item as `--item`, at its stable number (`--item "Q1 Duration model"`), so a partial reply is cheap and a dropped probe is visible to both of you. The script refuses more than three: the three-probe cap.
At `Cleared` the named legend is optional — the destination is reached and the PLAN-DRAFT is the thing to point at. Keep the confidence line; the Clearing Gate leaned on it.
**Emit no resume command on a Form B turn.** There is nothing to resume — the session is alive and holding a claim. A resume command here reads as *we're done*, and the human either walks away mid-decision or burns the next turn asking what you meant. This is the single most common way the footer misfires, and it costs the batch the round trips batching was introduced to save.
One exception: `grilling.md`'s unreachable-human procedure. Parking a mid-grill question and stopping IS a session end — use Form A, and say in the body that the question is parked mid-grill with its batch outstanding.
## Form C — the menu after a recorded decision
Used ONLY on the Work cadence's fork-menu turn (resolve.md §Cadence), immediately after `resolve` recorded an `## Answer`. The script refuses it while a question is claimed or once the map is `Cleared`. Pass `--resolved-this-session <N>`, and `--heavy` when the decision just recorded was heavy, contested, or `Locked: yes`.
It prints the stop branch, labeled `OR START FRESH · new conversation, paste:`, and returns `menu`: the header, the question text, up to three takeable questions plus `Start fresh`, and which option to mark `RECOMMENDED` (a question early in the session; `Start fresh` after ~3 resolved or a heavy decision, with the reason in the question text, "to keep me sharp").
Then invoke the structured question tool with that menu. Put each question's gist or newly-unblocked note (from `resolve`'s `unblocked`) in its description. The automatic `Other` path lets the human name a frontier question not shown (`menu.more`).
Rules for Form C:
- **The command label is mandatory and exact.** It makes the command the stop branch, not a farewell. Never render a bare command on a menu turn.
- **The choice itself always uses the structured tool.** Never print `NEXT UP` as a prose menu when the tool exists.
- **Form C never replaces Form B.** A turn that asks probes, shows a sketch, or hands over a checklist is Form B, no command. Form C fires only between decisions, when nothing is claimed.
- If the human walks away mid-menu, nothing is stranded: no claim is open, and the command to come back is already on screen.
---
## Discipline
- **Never print a bare resume command on a turn that asks a question.** The footer must not tell the human to leave a conversation you are still waiting in. Before you write Part 2, ask whether the response above it ends with something for them to answer: mid-question (probes, sketch, checklist) → Form B, no command, no exceptions but the parked-grill one; between decisions at the fork-menu → Form C, where the command appears ONLY under its `OR START FRESH` label as the explicit stop branch.
- **Alignment is not the point.** Glyphs sit in `NN` order and the legend names them in the same order; do not burn effort column-aligning numbers under waypoints across variable-width glyphs. Legibility over pixels.
- **Rebuild, never cache.** The markers come from the current `map.md`, which Work Step 2 has already reconciled against the question files this session. A footer that disagrees with the checklist above it means you drew from memory.
- **Never print a bare resume command on a turn that asks a question.** Before you choose the form, ask whether the response above it ends with something for them to answer: mid-question (probes, sketch, checklist) → Form B, no exceptions but the parked-grill one; between decisions at the fork-menu → Form C.
- **Draw it, never type it.** A hand-built trail drifts from the files; the script reads them every time. If the trail disagrees with the checklist above it, run `reconcile`, but only at session start or while nothing is claimed: `reconcile` resets a claim with no answer to `open`, so mid-question it would drop your own live claim. With a claim open, finish that question instead; `resolve` rebuilds the checklist, and the next trail is drawn from it. On `github` (the script cannot read the tracker), build it by hand from the sub-issue query, following "What the script draws" exactly.
- **One trail.** Never render two ideas' trails, and never invent a stop the map does not list.
@@ -556,8 +556,15 @@ enforces it, so never tell someone to keep asking past it.
The person can add folders beside the one the session started in (a shared
library, a design folder), from the footer's folder label. Together they are
the session's **workspace**: context for every skill run in this console
session, each folder addressed by a short `@name`. It outlives dashboard hops;
a new console session starts with the original folder alone.
session, each folder addressed by a short `@name`. It outlives dashboard hops,
and it is remembered: every change is saved to `workspaces.json` beside
`looks.json` (never into the project), keyed by the folder the session runs
in and then by spec. A session with a spec opens on that spec's list, one with
none on the project's; a spec with nothing saved starts as a copy of the
project's list. The dashboard's picker swaps the list as the selection moves,
and a `specDir` you post mid-run takes the current list with it. There is
nothing for you to load: `open` prints the list, and a switch of spec on a
resume reaches you as ordinary workspace changes on your next `wait`.
### What you are told
@@ -767,7 +774,7 @@ that is what the person is there to download. The finish carries no
sees the Trail Footer, and without this their last screen promises a question
that is never coming.
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
and `pathfinder-research` (id = the question's file slug) as each research
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
subagent reports back, or when you resolve a `research` question yourself
(Posting an update → Session meter). Other questions score through their
answers, so there is nothing to post for them.
@@ -820,7 +827,7 @@ know:
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) 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`. |
| 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). |
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
@@ -41,6 +41,7 @@ import {
die,
ensureDir,
fileStamp,
forgetWorkspace,
handOff,
handleFile,
healthOk,
@@ -65,6 +66,7 @@ import {
readLedger,
readWorkspace,
reapHandles,
rememberedWorkspace,
remoteWarning,
removeScratch,
removeSessions,
@@ -73,6 +75,7 @@ import {
SESSION_MAX_AGE_MS,
sessionDir,
sleepSync,
specKey,
staleScratch,
staleSessions,
sweepUploads,
@@ -317,7 +320,7 @@ async function cmdOpen() {
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
} catch {}
const workspace = workspaceOnOpen(dir, worktree);
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
// Month-old sessions and scratch files: listed before the print so the
// agent can see what went, removed after it so the page waits for nothing.
@@ -403,10 +406,11 @@ async function cmdOpen() {
* The workspace as `open` hands it to the agent, and the cursor seeded to
* match: the agent now has the whole list, so no change up to here is owed.
* Read-only on workspace.json, which only the server writes; on a fresh
* session the server has not made it yet, so the original folder stands in.
* session the server has not made it yet, so what was remembered for this
* folder and spec stands in, the same list the server is about to make.
*/
function workspaceOnOpen(dir, worktree) {
const ws = readWorkspace(dir) || initialWorkspace(worktree);
function workspaceOnOpen(dir, worktree, specDir) {
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
try {
writeWorkspaceCursor(dir, ws.version || 0);
@@ -946,6 +950,18 @@ function realNearest(p) {
return path.join(fs.realpathSync(existing), path.relative(existing, p));
}
/* --------------------------------------------------------------- forget */
// Drop the folder list remembered for one spec (Finalize, once the spec is
// archived). The project's own list and every other spec's are untouched.
function cmdForget() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
let spec = specKey(args.spec);
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
const worktree = repoRoots().worktree;
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
}
/* ----------------------------------------------------------------- help */
function cmdHelp() {
@@ -961,7 +977,8 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
first post. --file is optional, and --title defaults to the
project's folder name. Also prints workspace: { folders: [{ name,
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name.
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
@@ -988,6 +1005,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
Copy a cited note attachment into specs/<idea>/attachments/. Prints
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
missing. Paste link as it is.
forget --spec specs/<idea>
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.
status [--session <sid>] [--all]
One session, or every session belonging to this project.
stop --session <sid> | --all
@@ -1206,6 +1227,7 @@ const COMMANDS = {
wait: cmdWait,
chat: cmdChat,
keep: cmdKeep,
forget: cmdForget,
status: cmdStatus,
stop: cmdStop,
help: cmdHelp,
@@ -178,8 +178,8 @@ function lockStale(lock) {
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn) {
const lock = path.join(dir, STATE_LOCK_FILE);
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
const lock = path.join(dir, lockName);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
@@ -188,7 +188,7 @@ export function withStateLock(dir, fn) {
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
@@ -487,8 +487,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks and the pointer to this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
function isScratchName(name) {
return (
@@ -1619,17 +1620,125 @@ export function readWorkspace(dir) {
return readJson(path.join(dir, WORKSPACE_FILE), null);
}
// A fresh workspace: just the original folder, named after itself.
export function initialWorkspace(worktree) {
// A fresh workspace: the original folder, named after itself, plus whatever
// was remembered for this folder and spec (rememberedWorkspace() below).
export function initialWorkspace(worktree, remembered = null) {
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
if (remembered && remembered.original) {
if (remembered.original.name) original.name = remembered.original.name;
if (remembered.original.description) original.description = remembered.original.description;
}
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
id: "f" + (i + 1),
path: f.path,
name: f.name,
description: f.description || "",
...(f.nested ? { nested: true } : {}),
}));
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
}
/* ------------------------------------------------ remembered workspaces */
// The folder list outlives the console session: one file for the person,
// beside looks.json, keyed by the folder a session runs in and then by spec.
// Never under specs/: the paths are this machine's, and the server never
// writes into a project.
//
// { "projects": { "<folded worktree>": {
// "path": "<worktree>",
// "project": { original, folders, at }, // no spec picked
// "specs": { "specs/<name>": { original, folders, at } } } } }
//
// `original` holds the first folder's name and description only (its path is
// always the session's own); `folders` the added ones as { path, name,
// description, nested? }. Two writers, the server on every change and
// `console.mjs forget`, each a read-modify-write of one key.
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
const foldKey = (p) => {
const resolved = path.resolve(String(p || ""));
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
};
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
export function specKey(specDir) {
return String(specDir || "")
.trim()
.replace(/\\/g, "/")
.replace(/^\.\//, "")
.replace(/\/+$/, "");
}
function readStore() {
const saved = readJson(WORKSPACES_FILE, null);
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
}
/**
* What was remembered for this folder and spec: `{ entry, from }`, where
* `from` is "spec" when the spec has its own list, "project" when it falls
* back to the project's (a spec's list starts as a copy of it), and null
* when nothing was ever saved.
*/
export function rememberedWorkspace(worktree, specDir) {
const project = readStore().projects[foldKey(worktree)];
if (!project) return { entry: null, from: null };
const spec = specKey(specDir);
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
}
// The workspace's folders as the store keeps them.
export function rememberable(ws) {
const folders = (ws && ws.folders) || [];
const first = folders.find((f) => f.original) || {};
return {
version: 0,
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
missing: [],
changes: [],
remote: "",
original: { name: first.name || "", description: first.description || "" },
folders: folders
.filter((f) => !f.original)
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
at: nowIso(),
};
}
// Every server and `console.mjs forget` writes the one file, so each
// read-modify-write holds this lock beside it.
const WORKSPACES_LOCK = "workspaces.json.lock";
// Save the list for this folder and spec ("" for the project's own).
export function rememberWorkspace(worktree, specDir, ws) {
ensureDir(path.dirname(WORKSPACES_FILE));
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
}
function saveRemembered(worktree, specDir, ws) {
const store = readStore();
const key = foldKey(worktree);
const project = store.projects[key] || { path: path.resolve(worktree) };
const spec = specKey(specDir);
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
else project.project = rememberable(ws);
store.projects[key] = project;
writeJsonAtomic(WORKSPACES_FILE, store);
}
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
export function forgetWorkspace(worktree, specDir) {
const spec = specKey(specDir);
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
}
function dropRemembered(worktree, spec) {
const store = readStore();
const project = store.projects[foldKey(worktree)];
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
delete project.specs[spec];
writeJsonAtomic(WORKSPACES_FILE, store);
return true;
}
// Single-writer rule: only server.mjs may call this.
export function writeWorkspace(dir, ws) {
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
@@ -2505,6 +2505,9 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
actions stay put. */
.modal.workspace { max-width: 680px; }
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
.workspace .modal-blurb { margin-bottom: 6px; }
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
.workspace-list {
list-style: none; margin: 0; padding: 0;
display: grid; gap: 12px;
@@ -2542,6 +2542,7 @@ function renderDashboard(main) {
const specs = specList();
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
wrap.appendChild(hideUnavailableToggle());
if (!local.launching && !launchScoping) syncWorkspaceScope();
// "Unavailable" is the scan's verdict for the selected spec, not the
// momentary greying while a launch is in flight or the server is away, so
@@ -2963,6 +2964,11 @@ async function launchSkill(entry) {
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected.
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
// dashboard, which would otherwise sync back to the picker's spec.
launchScoping = true;
await syncWorkspaceScope(target ? target.dir : "");
try {
const res = await fetch("/submit", {
method: "POST",
@@ -2973,6 +2979,7 @@ async function launchSkill(entry) {
}),
});
if (res.status === 409) {
launchScoping = false;
pendingResult = true;
banner("Your last pick is still being picked up. One moment.", "info");
return;
@@ -2980,10 +2987,12 @@ async function launchSkill(entry) {
if (!res.ok) throw new Error(String(res.status));
sound("startSkill");
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
launchScoping = false;
pendingResult = true;
save();
render();
} catch {
launchScoping = false;
banner("That did not go through. Nothing was lost; try again.", "warn");
}
}
@@ -5854,6 +5863,32 @@ async function postJson(url, body) {
}
}
/* The workspace follows the dashboard's picker: the folders remembered for
the selected spec, or the project's own under "Start from scratch". The
server swaps the list and remembers every change after it. */
let scopeAsked = null;
// True from a launch's scope sync until its send has gone (or failed).
let launchScoping = false;
async function syncWorkspaceScope(spec) {
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
scopeAsked = want;
const { status, body } = await postJson("/workspace/scope", { spec: want });
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
scopeAsked = null;
if ($("workspace-modal").open) renderWorkspace();
}
// The dialog's "Remembered for" line: whose list this is.
function workspaceScopeText() {
const scope = (wsFrame && wsFrame.scope) || "";
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
const spec = specList().find((s) => s.dir === scope);
const name = spec ? spec.name : scope.split("/").pop();
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
}
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
// The folder whose Remove is waiting on its inline confirm, by id.
@@ -5893,6 +5928,7 @@ function renderWorkspace() {
}
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
$("workspace-scope").textContent = workspaceScopeText();
}
function workspaceRow(f) {
@@ -833,10 +833,28 @@
Click the folder name in the middle of the bottom bar. It shows your
folder's name and branch, such as <strong>shop · main</strong>, and
<strong>shop + 2 folders · main</strong> once you have added some.
The workspace lasts for this console session only: it carries across
steps you start from the dashboard, and a new console session starts
with just the folder you started in.
It carries across steps you start from the dashboard.
</p>
<h4>Remembered for next time</h4>
<ul>
<li>
Every change is saved as you make it, so the next console session in
this folder starts with the same folders.
</li>
<li>
Each spec keeps its own list. The first time you pick a spec on the
dashboard it starts as a copy of the project's list (the one shown
under <strong>Start from scratch</strong>), and after that the two
are separate. Picking a spec loads its list; the line under the
dialog's title says whose list you are looking at.
</li>
<li>
The lists live in <code>workspaces.json</code> in your own
Plan2Code settings folder, beside your look and feel, never in the
project. Finalize offers to forget a spec's list when it archives the
spec.
</li>
</ul>
<h4>Adding a folder</h4>
<ul>
<li>
@@ -1363,9 +1381,10 @@
<h4>What it counts</h4>
<p>
Each step you run here adds points: a plan or a set of documents
weighs more than a single answered question, and a built phase more
still, by how many tasks it completed: a big phase adds more than a
small one. Every two questions you answer add a point too, so a long
weighs more than a quick task, and a built phase more still, by how
many tasks it completed: a big phase adds more than a small one.
Every two questions you answer within one step add a point too
(rounded down, so a single answer adds nothing), so a long
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
points, with what it added. It is a rule of thumb, not a
reading of Plan2Code's real memory: long sessions tend to make it
@@ -2003,6 +2022,7 @@
The folders the agent uses as context this session. It reads the extra ones for
reference and only changes them if you ask.
</p>
<p class="workspace-scope" id="workspace-scope"></p>
<ul class="workspace-list" id="workspace-list"></ul>
<div class="workspace-add">
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
@@ -45,7 +45,10 @@ import {
readLedger,
readOverview,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
remoteWarning,
specKey,
typedCount,
withStateLock,
writeJsonAtomic,
@@ -326,7 +329,9 @@ function workspaceNow() {
return ws;
}
const root = sessionWorktree();
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
const scope = specKey(stateNow?.specDir);
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
@@ -347,13 +352,87 @@ function saveWorkspace(ws) {
// One change: a new version, an entry in the change log the agent is handed,
// the file, and every open page.
function bumpWorkspace(ws, change) {
function bumpWorkspace(ws, change, { remember = true } = {}) {
ws.version = (ws.version || 0) + 1;
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
saveWorkspace(ws);
// Remembered for the next console session too. A folder gone missing or
// found again is not a change of mind, so it is not saved.
if (remember) rememberNow(ws);
pushState();
}
function rememberNow(ws) {
const root = sessionWorktree();
if (!root) return;
try {
rememberWorkspace(root, ws.scope || "", ws);
} catch {}
}
/**
* Point the workspace at another spec ("" for the project's own list) and
* swap in what was remembered there, logging each difference as a change so
* the agent's cursor stays truthful. A spec with nothing saved starts from
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
* list it has and saves it as the spec's (`seed: "current"`, a spec created
* mid-run). Folders keep their ids when their path stays.
*/
function setScope(ws, spec, seed = "project") {
const root = sessionWorktree();
const next = specKey(spec);
if (!root || (ws.scope || "") === next) return false;
const found = rememberedWorkspace(root, next);
ws.scope = next;
if (next && found.from !== "spec" && seed === "current") {
saveWorkspace(ws);
rememberNow(ws);
pushState();
return true;
}
const want = initialWorkspace(root, found.entry).folders;
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
const kept = new Set();
const folders = [];
const changes = [];
for (const w of want) {
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
if (!have) {
folders.push({ ...w, id: "pending" });
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
continue;
}
kept.add(have);
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
if ((have.description || "") !== (w.description || "")) {
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
}
folders.push({ ...have, name: w.name, description: w.description || "" });
}
for (const f of ws.folders) {
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
}
ws.folders = folders.filter((f) => f.id !== "pending");
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
if (!changes.length) {
saveWorkspace(ws);
pushState();
}
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
checkFolders(ws);
return true;
}
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
// learns its spec late) takes the workspace with it.
function followSpecDir(state) {
const spec = specKey(state && state.specDir);
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
}
function isFolder(p) {
try {
return fs.statSync(p).isDirectory();
@@ -370,10 +449,10 @@ function checkFolders(ws) {
const marked = ws.missing.includes(f.id);
if (!there && !marked) {
ws.missing = [...ws.missing, f.id];
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
} else if (there && marked) {
ws.missing = ws.missing.filter((id) => id !== f.id);
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
}
}
}
@@ -402,8 +481,8 @@ function folderIssues(entries) {
}
function workspaceView() {
const { folders, missing, remote } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) };
const { folders, missing, remote, scope } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
}
// Whether child sits strictly under parent.
@@ -492,6 +571,7 @@ function bootWorkspace() {
saveWorkspace(ws);
}
checkFolders(ws);
followSpecDir(stateNow);
}
/**
@@ -1403,6 +1483,24 @@ const server = http.createServer((req, res) => {
});
}
// Which list the workspace is: a spec's, or the project's (`spec` empty).
// The dashboard's picker sends it as the selection moves and before a
// launch, so a skill opens on the list of the spec it was launched for.
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
try {
setScope(workspaceNow(), spec, "project");
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, workspaceView());
});
}
// Only ever returns a path: the page then adds it through /workspace/add.
if (pathname === "/workspace/browse" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
@@ -1561,6 +1659,9 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
pushState();
}
lastStateStamp = stamp;
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-02",
"releaseDate": "2026-10-04",
"mode": "utility"
}
@@ -0,0 +1,247 @@
// Plan2Code skill scripts: shared plumbing.
//
// Every script in a skill's scripts/ directory imports this file. It owns the
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
//
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
// on a handled failure.
// stderr a one-line human diagnostic on failure (the same message + next).
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
// 4 invalid input or a check that failed · 5 refused (would clobber
// or break a rule).
//
// Node 18+ built-ins only, no build step: this ships inside every skill.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
export class CliError extends Error {
constructor(exit, error, message, next) {
super(message);
this.exit = exit;
this.error = error;
this.next = next;
}
}
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
export function fail(exit, error, message, next) {
throw new CliError(exit, error, message, next);
}
export function out(obj) {
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
}
/**
* Parse argv into { _: positionals, <flag>: value }.
* `booleans` names flags that take no value; every other `--flag` takes the
* next argument, and repeats of a flag listed in `lists` collect into an array.
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
* silently changes behavior.
*/
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
const known = new Set([...booleans, ...values, ...lists, "help"]);
const args = { _: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) {
args._.push(a);
continue;
}
let name = a.slice(2);
let value;
const eq = name.indexOf("=");
if (eq !== -1) {
value = name.slice(eq + 1);
name = name.slice(0, eq);
}
if (!known.has(name)) {
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
}
if (name === "help" || booleans.includes(name)) {
args[name] = true;
continue;
}
if (value === undefined) {
if (i + 1 >= argv.length) {
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
}
value = argv[++i];
}
if (lists.includes(name)) (args[name] ||= []).push(value);
else args[name] = value;
}
return args;
}
/**
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
* failure shape plus an exit code, and anything else into exit 1 with the stack
* on stderr. Sets process.exitCode rather than calling process.exit(), so
* stdout is never cut off mid-write.
*/
export async function run(usage, main) {
try {
const argv = process.argv.slice(2);
if (argv.includes("--help") || argv.includes("-h")) {
process.stdout.write(usage.trim() + "\n");
return;
}
await main(argv);
} catch (err) {
if (err instanceof CliError) {
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
process.exitCode = err.exit;
return;
}
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
process.exitCode = EXIT.CRASH;
}
}
/* ------------------------------------------------------------------ time */
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
// is what "today" means to the person reading the date in their files.
export function now() {
const pinned = process.env.PLAN2CODE_NOW;
if (pinned) {
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
const d = new Date(pinned);
if (!Number.isNaN(d.getTime())) return d;
}
return new Date();
}
const pad = (n) => String(n).padStart(2, "0");
/** YYYY-MM-DD */
export function isoDate(d = now()) {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
/** YYYYMMDD */
export function compactDate(d = now()) {
return isoDate(d).replace(/-/g, "");
}
/** YYYY-MM-DD HH:mm */
export function stamp(d = now()) {
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** HHMMSS */
export function clock(d = now()) {
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
}
/* ----------------------------------------------------------------- files */
export function readText(file) {
try {
return fs.readFileSync(file, "utf8");
} catch {
return null;
}
}
export function isDir(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
/** Write a file only when its content changes. Returns true when it wrote. */
export function writeIfChanged(file, content) {
const current = readText(file);
if (current === content) return false;
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
return true;
}
/** Normalise line endings for parsing; keep the original for writing back. */
export function eol(text) {
return text.includes("\r\n") ? "\r\n" : "\n";
}
/**
* phase-N.md per phase number. An exact phase-N.md always wins over a sibling
* such as phase-1-old.md; more than one candidate is reported, never guessed.
* Shared so every script that counts a spec's tasks reads the same files.
*/
export function phaseFiles(dir) {
const files = new Map();
const extra = new Map();
for (const name of fs.readdirSync(dir).sort()) {
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
if (!m) continue;
const n = Number(m[1]);
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
if (!files.has(n)) files.set(n, name);
else if (exact) {
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
files.set(n, name);
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
}
files.extra = extra;
return files;
}
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
export function rel(root, p) {
return path.relative(root, p).split(path.sep).join("/") || ".";
}
/* --------------------------------------------------------- the web console */
// The web console ships beside these scripts in every installed skill
// (references/web-console/), and in this repo it sits at src/web-console/. Its
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
// metrics-bait scan, so the scripts import it rather than keep a second copy.
const CONSOLE_LIB_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
];
let consoleLibPromise;
export function consoleLib() {
consoleLibPromise ||= (async () => {
for (const candidate of CONSOLE_LIB_CANDIDATES) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-lib-missing",
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
);
})();
return consoleLibPromise;
}
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
export function version() {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const text = readText(file);
if (!text) continue;
try {
const v = JSON.parse(text).version;
if (typeof v === "string") return v;
} catch {}
}
return null;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,22 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"mode": "utility"
}
+1 -1
View File
@@ -54,7 +54,7 @@ Check if `./AGENTS.md` exists:
### Check for Existing Progress
Before Phase 1, check for existing `PLAN-DRAFT-*.md` under `specs/` (`ls specs/` via shell — never Glob; it is gitignored):
Before Phase 1, run `node "<S>/specs.mjs" list` from the project root (`<S>`: `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-1-plan/scripts/` globally). It reads gitignored `specs/` (Glob silently finds nothing there) and gives each spec's `planDrafts` with its **Status:** line (`-prev` copies are `archived`; ignore them). Route on that status:
- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4
- Status "Escalated from Quick Task - Resume at Phase 2": Acknowledge, verify requirements, skip to Phase 2
- Status "Draft" or "Complete": Ask user how to proceed
@@ -556,8 +556,15 @@ enforces it, so never tell someone to keep asking past it.
The person can add folders beside the one the session started in (a shared
library, a design folder), from the footer's folder label. Together they are
the session's **workspace**: context for every skill run in this console
session, each folder addressed by a short `@name`. It outlives dashboard hops;
a new console session starts with the original folder alone.
session, each folder addressed by a short `@name`. It outlives dashboard hops,
and it is remembered: every change is saved to `workspaces.json` beside
`looks.json` (never into the project), keyed by the folder the session runs
in and then by spec. A session with a spec opens on that spec's list, one with
none on the project's; a spec with nothing saved starts as a copy of the
project's list. The dashboard's picker swaps the list as the selection moves,
and a `specDir` you post mid-run takes the current list with it. There is
nothing for you to load: `open` prints the list, and a switch of spec on a
resume reaches you as ordinary workspace changes on your next `wait`.
### What you are told
@@ -767,7 +774,7 @@ that is what the person is there to download. The finish carries no
sees the Trail Footer, and without this their last screen promises a question
that is never coming.
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
and `pathfinder-research` (id = the question's file slug) as each research
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
subagent reports back, or when you resolve a `research` question yourself
(Posting an update → Session meter). Other questions score through their
answers, so there is nothing to post for them.
@@ -820,7 +827,7 @@ know:
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) 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`. |
| 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). |
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
@@ -41,6 +41,7 @@ import {
die,
ensureDir,
fileStamp,
forgetWorkspace,
handOff,
handleFile,
healthOk,
@@ -65,6 +66,7 @@ import {
readLedger,
readWorkspace,
reapHandles,
rememberedWorkspace,
remoteWarning,
removeScratch,
removeSessions,
@@ -73,6 +75,7 @@ import {
SESSION_MAX_AGE_MS,
sessionDir,
sleepSync,
specKey,
staleScratch,
staleSessions,
sweepUploads,
@@ -317,7 +320,7 @@ async function cmdOpen() {
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
} catch {}
const workspace = workspaceOnOpen(dir, worktree);
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
// Month-old sessions and scratch files: listed before the print so the
// agent can see what went, removed after it so the page waits for nothing.
@@ -403,10 +406,11 @@ async function cmdOpen() {
* The workspace as `open` hands it to the agent, and the cursor seeded to
* match: the agent now has the whole list, so no change up to here is owed.
* Read-only on workspace.json, which only the server writes; on a fresh
* session the server has not made it yet, so the original folder stands in.
* session the server has not made it yet, so what was remembered for this
* folder and spec stands in, the same list the server is about to make.
*/
function workspaceOnOpen(dir, worktree) {
const ws = readWorkspace(dir) || initialWorkspace(worktree);
function workspaceOnOpen(dir, worktree, specDir) {
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
try {
writeWorkspaceCursor(dir, ws.version || 0);
@@ -946,6 +950,18 @@ function realNearest(p) {
return path.join(fs.realpathSync(existing), path.relative(existing, p));
}
/* --------------------------------------------------------------- forget */
// Drop the folder list remembered for one spec (Finalize, once the spec is
// archived). The project's own list and every other spec's are untouched.
function cmdForget() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
let spec = specKey(args.spec);
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
const worktree = repoRoots().worktree;
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
}
/* ----------------------------------------------------------------- help */
function cmdHelp() {
@@ -961,7 +977,8 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
first post. --file is optional, and --title defaults to the
project's folder name. Also prints workspace: { folders: [{ name,
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name.
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
@@ -988,6 +1005,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
Copy a cited note attachment into specs/<idea>/attachments/. Prints
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
missing. Paste link as it is.
forget --spec specs/<idea>
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.
status [--session <sid>] [--all]
One session, or every session belonging to this project.
stop --session <sid> | --all
@@ -1206,6 +1227,7 @@ const COMMANDS = {
wait: cmdWait,
chat: cmdChat,
keep: cmdKeep,
forget: cmdForget,
status: cmdStatus,
stop: cmdStop,
help: cmdHelp,
@@ -178,8 +178,8 @@ function lockStale(lock) {
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn) {
const lock = path.join(dir, STATE_LOCK_FILE);
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
const lock = path.join(dir, lockName);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
@@ -188,7 +188,7 @@ export function withStateLock(dir, fn) {
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
@@ -487,8 +487,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks and the pointer to this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
function isScratchName(name) {
return (
@@ -1619,17 +1620,125 @@ export function readWorkspace(dir) {
return readJson(path.join(dir, WORKSPACE_FILE), null);
}
// A fresh workspace: just the original folder, named after itself.
export function initialWorkspace(worktree) {
// A fresh workspace: the original folder, named after itself, plus whatever
// was remembered for this folder and spec (rememberedWorkspace() below).
export function initialWorkspace(worktree, remembered = null) {
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
if (remembered && remembered.original) {
if (remembered.original.name) original.name = remembered.original.name;
if (remembered.original.description) original.description = remembered.original.description;
}
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
id: "f" + (i + 1),
path: f.path,
name: f.name,
description: f.description || "",
...(f.nested ? { nested: true } : {}),
}));
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
}
/* ------------------------------------------------ remembered workspaces */
// The folder list outlives the console session: one file for the person,
// beside looks.json, keyed by the folder a session runs in and then by spec.
// Never under specs/: the paths are this machine's, and the server never
// writes into a project.
//
// { "projects": { "<folded worktree>": {
// "path": "<worktree>",
// "project": { original, folders, at }, // no spec picked
// "specs": { "specs/<name>": { original, folders, at } } } } }
//
// `original` holds the first folder's name and description only (its path is
// always the session's own); `folders` the added ones as { path, name,
// description, nested? }. Two writers, the server on every change and
// `console.mjs forget`, each a read-modify-write of one key.
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
const foldKey = (p) => {
const resolved = path.resolve(String(p || ""));
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
};
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
export function specKey(specDir) {
return String(specDir || "")
.trim()
.replace(/\\/g, "/")
.replace(/^\.\//, "")
.replace(/\/+$/, "");
}
function readStore() {
const saved = readJson(WORKSPACES_FILE, null);
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
}
/**
* What was remembered for this folder and spec: `{ entry, from }`, where
* `from` is "spec" when the spec has its own list, "project" when it falls
* back to the project's (a spec's list starts as a copy of it), and null
* when nothing was ever saved.
*/
export function rememberedWorkspace(worktree, specDir) {
const project = readStore().projects[foldKey(worktree)];
if (!project) return { entry: null, from: null };
const spec = specKey(specDir);
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
}
// The workspace's folders as the store keeps them.
export function rememberable(ws) {
const folders = (ws && ws.folders) || [];
const first = folders.find((f) => f.original) || {};
return {
version: 0,
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
missing: [],
changes: [],
remote: "",
original: { name: first.name || "", description: first.description || "" },
folders: folders
.filter((f) => !f.original)
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
at: nowIso(),
};
}
// Every server and `console.mjs forget` writes the one file, so each
// read-modify-write holds this lock beside it.
const WORKSPACES_LOCK = "workspaces.json.lock";
// Save the list for this folder and spec ("" for the project's own).
export function rememberWorkspace(worktree, specDir, ws) {
ensureDir(path.dirname(WORKSPACES_FILE));
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
}
function saveRemembered(worktree, specDir, ws) {
const store = readStore();
const key = foldKey(worktree);
const project = store.projects[key] || { path: path.resolve(worktree) };
const spec = specKey(specDir);
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
else project.project = rememberable(ws);
store.projects[key] = project;
writeJsonAtomic(WORKSPACES_FILE, store);
}
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
export function forgetWorkspace(worktree, specDir) {
const spec = specKey(specDir);
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
}
function dropRemembered(worktree, spec) {
const store = readStore();
const project = store.projects[foldKey(worktree)];
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
delete project.specs[spec];
writeJsonAtomic(WORKSPACES_FILE, store);
return true;
}
// Single-writer rule: only server.mjs may call this.
export function writeWorkspace(dir, ws) {
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
@@ -2505,6 +2505,9 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
actions stay put. */
.modal.workspace { max-width: 680px; }
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
.workspace .modal-blurb { margin-bottom: 6px; }
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
.workspace-list {
list-style: none; margin: 0; padding: 0;
display: grid; gap: 12px;
@@ -2542,6 +2542,7 @@ function renderDashboard(main) {
const specs = specList();
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
wrap.appendChild(hideUnavailableToggle());
if (!local.launching && !launchScoping) syncWorkspaceScope();
// "Unavailable" is the scan's verdict for the selected spec, not the
// momentary greying while a launch is in flight or the server is away, so
@@ -2963,6 +2964,11 @@ async function launchSkill(entry) {
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected.
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
// dashboard, which would otherwise sync back to the picker's spec.
launchScoping = true;
await syncWorkspaceScope(target ? target.dir : "");
try {
const res = await fetch("/submit", {
method: "POST",
@@ -2973,6 +2979,7 @@ async function launchSkill(entry) {
}),
});
if (res.status === 409) {
launchScoping = false;
pendingResult = true;
banner("Your last pick is still being picked up. One moment.", "info");
return;
@@ -2980,10 +2987,12 @@ async function launchSkill(entry) {
if (!res.ok) throw new Error(String(res.status));
sound("startSkill");
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
launchScoping = false;
pendingResult = true;
save();
render();
} catch {
launchScoping = false;
banner("That did not go through. Nothing was lost; try again.", "warn");
}
}
@@ -5854,6 +5863,32 @@ async function postJson(url, body) {
}
}
/* The workspace follows the dashboard's picker: the folders remembered for
the selected spec, or the project's own under "Start from scratch". The
server swaps the list and remembers every change after it. */
let scopeAsked = null;
// True from a launch's scope sync until its send has gone (or failed).
let launchScoping = false;
async function syncWorkspaceScope(spec) {
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
scopeAsked = want;
const { status, body } = await postJson("/workspace/scope", { spec: want });
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
scopeAsked = null;
if ($("workspace-modal").open) renderWorkspace();
}
// The dialog's "Remembered for" line: whose list this is.
function workspaceScopeText() {
const scope = (wsFrame && wsFrame.scope) || "";
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
const spec = specList().find((s) => s.dir === scope);
const name = spec ? spec.name : scope.split("/").pop();
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
}
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
// The folder whose Remove is waiting on its inline confirm, by id.
@@ -5893,6 +5928,7 @@ function renderWorkspace() {
}
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
$("workspace-scope").textContent = workspaceScopeText();
}
function workspaceRow(f) {
@@ -833,10 +833,28 @@
Click the folder name in the middle of the bottom bar. It shows your
folder's name and branch, such as <strong>shop · main</strong>, and
<strong>shop + 2 folders · main</strong> once you have added some.
The workspace lasts for this console session only: it carries across
steps you start from the dashboard, and a new console session starts
with just the folder you started in.
It carries across steps you start from the dashboard.
</p>
<h4>Remembered for next time</h4>
<ul>
<li>
Every change is saved as you make it, so the next console session in
this folder starts with the same folders.
</li>
<li>
Each spec keeps its own list. The first time you pick a spec on the
dashboard it starts as a copy of the project's list (the one shown
under <strong>Start from scratch</strong>), and after that the two
are separate. Picking a spec loads its list; the line under the
dialog's title says whose list you are looking at.
</li>
<li>
The lists live in <code>workspaces.json</code> in your own
Plan2Code settings folder, beside your look and feel, never in the
project. Finalize offers to forget a spec's list when it archives the
spec.
</li>
</ul>
<h4>Adding a folder</h4>
<ul>
<li>
@@ -1363,9 +1381,10 @@
<h4>What it counts</h4>
<p>
Each step you run here adds points: a plan or a set of documents
weighs more than a single answered question, and a built phase more
still, by how many tasks it completed: a big phase adds more than a
small one. Every two questions you answer add a point too, so a long
weighs more than a quick task, and a built phase more still, by how
many tasks it completed: a big phase adds more than a small one.
Every two questions you answer within one step add a point too
(rounded down, so a single answer adds nothing), so a long
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
points, with what it added. It is a rule of thumb, not a
reading of Plan2Code's real memory: long sessions tend to make it
@@ -2003,6 +2022,7 @@
The folders the agent uses as context this session. It reads the extra ones for
reference and only changes them if you ask.
</p>
<p class="workspace-scope" id="workspace-scope"></p>
<ul class="workspace-list" id="workspace-list"></ul>
<div class="workspace-add">
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
@@ -45,7 +45,10 @@ import {
readLedger,
readOverview,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
remoteWarning,
specKey,
typedCount,
withStateLock,
writeJsonAtomic,
@@ -326,7 +329,9 @@ function workspaceNow() {
return ws;
}
const root = sessionWorktree();
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
const scope = specKey(stateNow?.specDir);
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
@@ -347,13 +352,87 @@ function saveWorkspace(ws) {
// One change: a new version, an entry in the change log the agent is handed,
// the file, and every open page.
function bumpWorkspace(ws, change) {
function bumpWorkspace(ws, change, { remember = true } = {}) {
ws.version = (ws.version || 0) + 1;
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
saveWorkspace(ws);
// Remembered for the next console session too. A folder gone missing or
// found again is not a change of mind, so it is not saved.
if (remember) rememberNow(ws);
pushState();
}
function rememberNow(ws) {
const root = sessionWorktree();
if (!root) return;
try {
rememberWorkspace(root, ws.scope || "", ws);
} catch {}
}
/**
* Point the workspace at another spec ("" for the project's own list) and
* swap in what was remembered there, logging each difference as a change so
* the agent's cursor stays truthful. A spec with nothing saved starts from
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
* list it has and saves it as the spec's (`seed: "current"`, a spec created
* mid-run). Folders keep their ids when their path stays.
*/
function setScope(ws, spec, seed = "project") {
const root = sessionWorktree();
const next = specKey(spec);
if (!root || (ws.scope || "") === next) return false;
const found = rememberedWorkspace(root, next);
ws.scope = next;
if (next && found.from !== "spec" && seed === "current") {
saveWorkspace(ws);
rememberNow(ws);
pushState();
return true;
}
const want = initialWorkspace(root, found.entry).folders;
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
const kept = new Set();
const folders = [];
const changes = [];
for (const w of want) {
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
if (!have) {
folders.push({ ...w, id: "pending" });
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
continue;
}
kept.add(have);
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
if ((have.description || "") !== (w.description || "")) {
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
}
folders.push({ ...have, name: w.name, description: w.description || "" });
}
for (const f of ws.folders) {
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
}
ws.folders = folders.filter((f) => f.id !== "pending");
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
if (!changes.length) {
saveWorkspace(ws);
pushState();
}
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
checkFolders(ws);
return true;
}
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
// learns its spec late) takes the workspace with it.
function followSpecDir(state) {
const spec = specKey(state && state.specDir);
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
}
function isFolder(p) {
try {
return fs.statSync(p).isDirectory();
@@ -370,10 +449,10 @@ function checkFolders(ws) {
const marked = ws.missing.includes(f.id);
if (!there && !marked) {
ws.missing = [...ws.missing, f.id];
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
} else if (there && marked) {
ws.missing = ws.missing.filter((id) => id !== f.id);
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
}
}
}
@@ -402,8 +481,8 @@ function folderIssues(entries) {
}
function workspaceView() {
const { folders, missing, remote } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) };
const { folders, missing, remote, scope } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
}
// Whether child sits strictly under parent.
@@ -492,6 +571,7 @@ function bootWorkspace() {
saveWorkspace(ws);
}
checkFolders(ws);
followSpecDir(stateNow);
}
/**
@@ -1403,6 +1483,24 @@ const server = http.createServer((req, res) => {
});
}
// Which list the workspace is: a spec's, or the project's (`spec` empty).
// The dashboard's picker sends it as the selection moves and before a
// launch, so a skill opens on the list of the spec it was launched for.
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
try {
setScope(workspaceNow(), spec, "project");
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, workspaceView());
});
}
// Only ever returns a path: the page then adds it through /workspace/add.
if (pathname === "/workspace/browse" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
@@ -1561,6 +1659,9 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
pushState();
}
lastStateStamp = stamp;
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-02",
"releaseDate": "2026-10-04",
"mode": "utility"
}
+247
View File
@@ -0,0 +1,247 @@
// Plan2Code skill scripts: shared plumbing.
//
// Every script in a skill's scripts/ directory imports this file. It owns the
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
//
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
// on a handled failure.
// stderr a one-line human diagnostic on failure (the same message + next).
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
// 4 invalid input or a check that failed · 5 refused (would clobber
// or break a rule).
//
// Node 18+ built-ins only, no build step: this ships inside every skill.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
export class CliError extends Error {
constructor(exit, error, message, next) {
super(message);
this.exit = exit;
this.error = error;
this.next = next;
}
}
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
export function fail(exit, error, message, next) {
throw new CliError(exit, error, message, next);
}
export function out(obj) {
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
}
/**
* Parse argv into { _: positionals, <flag>: value }.
* `booleans` names flags that take no value; every other `--flag` takes the
* next argument, and repeats of a flag listed in `lists` collect into an array.
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
* silently changes behavior.
*/
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
const known = new Set([...booleans, ...values, ...lists, "help"]);
const args = { _: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) {
args._.push(a);
continue;
}
let name = a.slice(2);
let value;
const eq = name.indexOf("=");
if (eq !== -1) {
value = name.slice(eq + 1);
name = name.slice(0, eq);
}
if (!known.has(name)) {
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
}
if (name === "help" || booleans.includes(name)) {
args[name] = true;
continue;
}
if (value === undefined) {
if (i + 1 >= argv.length) {
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
}
value = argv[++i];
}
if (lists.includes(name)) (args[name] ||= []).push(value);
else args[name] = value;
}
return args;
}
/**
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
* failure shape plus an exit code, and anything else into exit 1 with the stack
* on stderr. Sets process.exitCode rather than calling process.exit(), so
* stdout is never cut off mid-write.
*/
export async function run(usage, main) {
try {
const argv = process.argv.slice(2);
if (argv.includes("--help") || argv.includes("-h")) {
process.stdout.write(usage.trim() + "\n");
return;
}
await main(argv);
} catch (err) {
if (err instanceof CliError) {
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
process.exitCode = err.exit;
return;
}
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
process.exitCode = EXIT.CRASH;
}
}
/* ------------------------------------------------------------------ time */
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
// is what "today" means to the person reading the date in their files.
export function now() {
const pinned = process.env.PLAN2CODE_NOW;
if (pinned) {
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
const d = new Date(pinned);
if (!Number.isNaN(d.getTime())) return d;
}
return new Date();
}
const pad = (n) => String(n).padStart(2, "0");
/** YYYY-MM-DD */
export function isoDate(d = now()) {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
/** YYYYMMDD */
export function compactDate(d = now()) {
return isoDate(d).replace(/-/g, "");
}
/** YYYY-MM-DD HH:mm */
export function stamp(d = now()) {
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** HHMMSS */
export function clock(d = now()) {
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
}
/* ----------------------------------------------------------------- files */
export function readText(file) {
try {
return fs.readFileSync(file, "utf8");
} catch {
return null;
}
}
export function isDir(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
/** Write a file only when its content changes. Returns true when it wrote. */
export function writeIfChanged(file, content) {
const current = readText(file);
if (current === content) return false;
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
return true;
}
/** Normalise line endings for parsing; keep the original for writing back. */
export function eol(text) {
return text.includes("\r\n") ? "\r\n" : "\n";
}
/**
* phase-N.md per phase number. An exact phase-N.md always wins over a sibling
* such as phase-1-old.md; more than one candidate is reported, never guessed.
* Shared so every script that counts a spec's tasks reads the same files.
*/
export function phaseFiles(dir) {
const files = new Map();
const extra = new Map();
for (const name of fs.readdirSync(dir).sort()) {
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
if (!m) continue;
const n = Number(m[1]);
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
if (!files.has(n)) files.set(n, name);
else if (exact) {
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
files.set(n, name);
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
}
files.extra = extra;
return files;
}
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
export function rel(root, p) {
return path.relative(root, p).split(path.sep).join("/") || ".";
}
/* --------------------------------------------------------- the web console */
// The web console ships beside these scripts in every installed skill
// (references/web-console/), and in this repo it sits at src/web-console/. Its
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
// metrics-bait scan, so the scripts import it rather than keep a second copy.
const CONSOLE_LIB_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
];
let consoleLibPromise;
export function consoleLib() {
consoleLibPromise ||= (async () => {
for (const candidate of CONSOLE_LIB_CANDIDATES) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-lib-missing",
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
);
})();
return consoleLibPromise;
}
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
export function version() {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const text = readText(file);
if (!text) continue;
try {
const v = JSON.parse(text).version;
if (typeof v === "string") return v;
} catch {}
}
return null;
}
+676
View File
@@ -0,0 +1,676 @@
#!/usr/bin/env node
// specs.mjs: where every spec under specs/ stands, read from its files.
//
// The pipeline skills (plan, document, implement, revise-plan, finalize,
// review, handoff) all need the same filesystem facts: which specs exist, what
// a spec's PLAN-DRAFT says, which phases are open, how many tasks are done.
// Those have one correct answer, so this script computes them instead of each
// prompt re-deriving them by hand. It also performs the two mechanical writes
// (a Phase Checklist marker, the archive move), with --dry-run.
//
// Shell listing only matters to people: specs/ is gitignored, so editor search
// tools skip it. This script reads the disk directly and does not care.
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";
const USAGE = `
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
node specs.mjs list [--root <dir>]
Every active spec under specs/ (never specs--completed/), newest first:
state, detail, PLAN-DRAFT files with their **Status:** line, overview,
phase count. Also the names already archived in specs--completed/.
node specs.mjs status <spec> [--root <dir>]
One spec in full: the overview's Phase Checklist, Parallel Execution
Groups, per-phase task counts by marker, task-numbering problems,
completion, the implement phase-selection verdict ("next"), the pending
phases, and consistency checks. <spec> is specs/<name>, <name>, or a path
to its overview.md.
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).
document: total_tasks, tasks_per_phase, phase_count,
parallel_groups_identified computed; pass
--set verification_items_added=N (your Verification Summary's
Added total; the VERIFICATION comments are reported as a check).
finalize: completion_rate_at_audit, tasks_completed, tasks_total; pass
--set verification_failures_found=N
--set documentation_updates_needed=N.
node specs.mjs mark <spec> --phase <N> --to open|in-progress|done [--dry-run]
Set phase N's Phase Checklist marker in overview.md ([ ], [/], [x]).
done also sets the phase file's Status line (**Status:**, **Status**:
or Status:) to Complete (and warns if tasks are unfinished); open on a
Complete phase sets it to In Progress. Warns when the phase file has no
Status line. Refuses a phase with duplicate checklist rows, and refuses
in-progress -> open (started work stays marked).
node specs.mjs archive <spec> [--dry-run]
Move specs/<name>/ to specs--completed/<name>/. Refuses if the target
exists, or if <spec> is not a folder directly under specs/.
Markers: [ ] pending · [/] in progress · [x] complete · [!] blocked · [?] assumed.
Exit: 0 ok · 2 bad arguments · 3 spec not found · 4 cannot parse / check
failed · 5 refused.
`;
/* ------------------------------------------------------------- resolving */
function realOrResolved(p) {
try {
return fs.realpathSync.native(p);
} catch {
return path.resolve(p);
}
}
const samePath = (a, b) => (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
// Read-only commands (status, metrics) accept an archived spec, because
// Finalize reads its own spec after Step 6 moved it. Writes never do.
function resolveSpec(root, arg, { allowArchived = false } = {}) {
if (!arg) fail(EXIT.USAGE, "missing-spec", "Name the spec: specs/<name>, <name>, or its overview.md path.", "Run `specs.mjs list` to see the active specs.");
let p = arg.replace(/\\/g, "/").replace(/\/+$/, "");
if (/\/overview\.md$/i.test(p) || /\/phase-[^/]*\.md$/i.test(p)) p = p.replace(/\/[^/]+$/, "");
const abs = path.isAbsolute(p) ? p : p.includes("/") ? path.join(root, p) : path.join(root, "specs", p);
const relPath = rel(root, abs);
if (!allowArchived && /(^|\/)specs--completed(\/|$)/.test(relPath)) {
fail(EXIT.REFUSED, "archived-spec", `${relPath} is archived; the pipeline only changes active specs under specs/.`, "Pick an active spec from `specs.mjs list`.");
}
// A spec is a folder directly under specs/ (or specs--completed/ for a read).
// Without this, `archive .` would move all of specs/ and `archive ./src` a
// source folder.
const homes = [path.join(root, "specs"), ...(allowArchived ? [path.join(root, "specs--completed")] : [])].map(realOrResolved);
const parent = realOrResolved(path.dirname(path.resolve(abs)));
if (!homes.some((h) => samePath(h, parent))) {
fail(EXIT.REFUSED, "not-a-spec", `${relPath} is not a spec folder: a spec sits directly under specs/${allowArchived ? " (or specs--completed/)" : ""}.`, "Pass specs/<name> or <name>; run `specs.mjs list` to see the active specs.");
}
if (!isDir(abs)) {
fail(EXIT.NOT_FOUND, "spec-not-found", `No spec folder at ${relPath}.`, "Run `specs.mjs list` from the project root (or pass --root) to see the active specs.");
}
return { dir: abs, rel: relPath, name: path.basename(abs) };
}
/* -------------------------------------------------------------- parsing */
const MARKERS = { " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" };
// Task 2.3, a lettered sub-task 3.6a, or a named one such as a testing task 1.T.
const TASK_RE = /^\s*[-*] \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
const CHECKBOX_RE = /^\s*[-*] \[(.)\]/;
// The Status line in any of the forms people write it: **Status:**, **Status**:
// or a plain Status:, optionally as a list item. Groups: everything up to the
// value (kept as written when the value is rewritten), the value, trailing blanks.
const STATUS_RE = /^([ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*)(.+?)([ \t]*)$/m;
function statusOf(text) {
const m = (text || "").match(STATUS_RE);
return m ? m[2] : null;
}
/** A markdown section's lines: from its heading to the next heading of the same or higher level. */
function section(text, headingRe) {
const lines = text.split(/\r?\n/);
const start = lines.findIndex((l) => /^#{1,6}\s/.test(l) && headingRe.test(l));
if (start === -1) return null;
const level = lines[start].match(/^#+/)[0].length;
let end = lines.length;
for (let i = start + 1; i < lines.length; i++) {
const m = lines[i].match(/^(#+)\s/);
if (m && m[1].length <= level) {
end = i;
break;
}
}
return { start, end, lines: lines.slice(start + 1, end) };
}
function plainText(s) {
return s
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/[*_`]/g, "")
.replace(/\s+/g, " ")
.trim();
}
/** Phase Checklist rows: the first "Phase N" on each checkbox line names the phase. */
function parseChecklist(overview) {
const sec = section(overview, /Phase Checklist/i);
if (!sec) return { found: false, phases: [], unparsed: [] };
const phases = [];
const unparsed = [];
sec.lines.forEach((line, i) => {
const m = line.match(CHECKBOX_RE);
if (!m) return;
const text = plainText(line.replace(CHECKBOX_RE, ""));
const num = text.match(/\bPhase\s+(\d+)\b/i);
if (!num) {
unparsed.push({ line: sec.start + 2 + i, text: line.trim() });
return;
}
const after = text.slice(num.index + num[0].length).replace(/^\s*[:\-–—]\s*/, "");
const name = after.split(/\s+[-–—]\s+|\s+\(|\s+_\(|:\s|\s+see\s+phase-/i)[0].replace(/\s*phase-\d+\.md\s*$/i, "").trim();
phases.push({
number: Number(num[1]),
marker: m[1],
state: MARKERS[m[1]] || "unknown",
name: name.replace(/\s*\[Milestone[^\]]*\]\s*$/i, "") || `Phase ${num[1]}`,
line: sec.start + 2 + i,
});
});
return { found: true, phases, unparsed };
}
/** "2, 3", "2-4" and "2–4" (or an em dash) alike: ranges expand, so a group cell never loses a phase. */
function phaseList(cell) {
const outList = [];
for (const part of cell.match(/\d+\s*[-–\u2014]\s*\d+|\d+/g) || []) {
const r = part.match(/^(\d+)\s*[-–\u2014]\s*(\d+)$/);
if (r && Number(r[2]) >= Number(r[1]) && Number(r[2]) - Number(r[1]) < 100) {
for (let n = Number(r[1]); n <= Number(r[2]); n++) outList.push(n);
} else outList.push(...part.match(/\d+/g).map(Number));
}
return [...new Set(outList)];
}
/** Parallel Execution Groups table: real groups only (a named group with 2+ phases). */
function parseGroups(overview) {
const sec = section(overview, /Parallel Execution Groups/i);
if (!sec) return { found: false, groups: [] };
const groups = [];
const seen = new Set();
for (const line of sec.lines) {
if (!/^\s*\|/.test(line) || /^\s*\|[\s:|-]+\|\s*$/.test(line)) continue;
const cells = line.split("|").slice(1, -1).map((c) => c.trim());
if (cells.length < 2 || /^group$/i.test(cells[0])) continue;
const id = plainText(cells[0]);
const phases = phaseList(cells[1]);
// "None", a dash, a single phase, a group its author labelled sequential
// ("A (sequential)"), or a Phases cell written as a chain ("1 → 2") is not
// a parallel group.
if (!id || /^(none|-|–|—)$/i.test(id) || /\bsequential\b/i.test(id) || /→|->|\bthen\b/i.test(cells[1]) || phases.length < 2) continue;
const key = `${id}:${phases.join(",")}`;
if (seen.has(key)) continue;
seen.add(key);
groups.push({ id, phases, reason: plainText(cells[2] || "") });
}
return { found: true, groups };
}
function firstSentence(text) {
const t = plainText(text);
const m = t.match(/^(.+?[.!?])(\s|$)/);
return (m ? m[1] : t).slice(0, 240);
}
function parsePhaseFile(file, number) {
const text = readText(file) || "";
const lines = text.split(/\r?\n/);
const title = (lines.find((l) => /^#\s/.test(l)) || "").replace(/^#\s+/, "").trim();
const status = statusOf(text);
const counts = { pending: 0, "in-progress": 0, complete: 0, blocked: 0, assumed: 0, unknown: 0 };
const tasks = [];
const strayCheckboxes = [];
const unmatchedTasks = [];
let heading = "";
lines.forEach((line, i) => {
const h = line.match(/^#{1,6}\s+(.*)$/);
if (h) heading = plainText(h[1]);
const t = line.match(TASK_RE);
if (t) {
const state = MARKERS[t[1]] || "unknown";
counts[state]++;
const named = !/^\d+$/.test(t[3]);
tasks.push({ id: `${t[2]}.${t[3]}${t[4]}`, phase: Number(t[2]), seq: named ? null : Number(t[3]), named, suffix: t[4], marker: t[1], state, line: i + 1 });
return;
}
// A line that looks like a task but is not counted as one (Task 1.4A,
// "1. [ ] **Task", a non-bold "- [ ] Task 1.3") would make the audit undercount.
if (/^\s*(?:[-*]|\d+\.)\s+\[.\].*\bTask\s+\d+\./i.test(line)) unmatchedTasks.push({ line: i + 1, text: line.trim().slice(0, 120) });
if (CHECKBOX_RE.test(line)) strayCheckboxes.push({ line: i + 1, section: heading, text: line.trim().slice(0, 120) });
});
// Numbering: every task belongs to this phase, the base numbers run 1..n with
// no gaps or repeats, and a lettered task (3.6a) sits after its base (3.6).
// Named tasks (1.T) are outside the numeric sequence.
const numbering = [];
const bases = [];
for (const t of tasks) {
if (t.phase !== number) numbering.push(`Task ${t.id} is in phase-${number}.md but numbered for Phase ${t.phase}`);
if (!t.suffix && !t.named) bases.push(t.seq);
}
const seenIds = new Set();
for (const t of tasks) {
if (seenIds.has(t.id)) numbering.push(`Task ${t.id} appears more than once`);
seenIds.add(t.id);
if (t.suffix && !t.named && !bases.includes(t.seq)) numbering.push(`Task ${t.id} has no base Task ${t.phase}.${t.seq}`);
}
bases.forEach((seq, i) => {
if (seq !== i + 1 && !numbering.some((n) => n.startsWith("Task numbering"))) {
numbering.push(`Task numbering is not sequential: expected ${number}.${i + 1}, found ${number}.${seq}`);
}
});
const overviewSec = section(text, /^#{1,6}\s+Overview\b/i);
const goalText = overviewSec ? overviewSec.lines.join("\n").split(/\n\s*\n/).map((p) => p.trim()).find((p) => p && !/^[-*|>]/.test(p)) : "";
return {
title,
status,
goal: goalText ? firstSentence(goalText) : null,
total: tasks.length,
counts,
open: counts.pending + counts["in-progress"] + counts.blocked + counts.unknown,
// Open work a phase cannot be approved over; blocked tasks may stand ([!] is allowed at sign-off).
unfinished: counts.pending + counts["in-progress"] + counts.unknown,
tasks,
numbering,
strayCheckboxes,
unmatchedTasks,
};
}
function planDrafts(dir) {
return fs
.readdirSync(dir)
.filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n))
.sort()
.map((file) => ({
file,
archived: /-prev\.md$/i.test(file),
status: statusOf(readText(path.join(dir, file))),
}));
}
/* ---------------------------------------------------------------- status */
function specStatus(spec) {
const overviewPath = path.join(spec.dir, "overview.md");
const overview = readText(overviewPath);
const files = phaseFiles(spec.dir);
// An empty overview.md still exists; only a missing one is "no overview".
const hasOverview = overview !== null;
const checklist = hasOverview ? parseChecklist(overview) : { found: false, phases: [], unparsed: [] };
const groups = hasOverview ? parseGroups(overview) : { found: false, groups: [] };
const checks = [];
const check = (level, code, message) => checks.push({ level, code, message });
for (const [n, names] of files.extra) {
check("warn", "duplicate-phase-file", `Phase ${n} has more than one file: using ${files.get(n)}, ignoring ${names.join(", ")}`);
}
const rowsByNumber = new Map();
for (const r of checklist.phases) rowsByNumber.set(r.number, [...(rowsByNumber.get(r.number) || []), r]);
for (const [n, rows] of rowsByNumber) {
if (rows.length > 1) check("error", "duplicate-checklist-row", `Phase ${n} has ${rows.length} rows in the Phase Checklist (overview.md lines ${rows.map((r) => r.line).join(", ")}); the first one is used`);
}
const phases = [];
const numbers = new Set([...checklist.phases.map((p) => p.number), ...files.keys()]);
for (const number of [...numbers].sort((a, b) => a - b)) {
const row = checklist.phases.find((p) => p.number === number) || null;
const file = files.get(number) || null;
const parsed = file ? parsePhaseFile(path.join(spec.dir, file), number) : null;
phases.push({
number,
name: row ? row.name : parsed ? parsed.title.replace(/^Phase\s+\d+\s*[:\-–—]?\s*/i, "") : `Phase ${number}`,
checklist: row ? row.state : null,
marker: row ? row.marker : null,
file,
status: parsed ? parsed.status : null,
goal: parsed ? parsed.goal : null,
tasks: parsed ? { total: parsed.total, open: parsed.open, ...parsed.counts } : null,
blockedTasks: parsed ? parsed.tasks.filter((t) => t.state === "blocked").map((t) => t.id) : [],
assumedTasks: parsed ? parsed.tasks.filter((t) => t.state === "assumed").map((t) => t.id) : [],
openTasks: parsed ? parsed.tasks.filter((t) => ["pending", "in-progress", "blocked", "unknown"].includes(t.state)).map((t) => t.id) : [],
});
if (!row && hasOverview) check("error", "missing-checklist-row", `phase-${number}.md has no row in overview.md's Phase Checklist`);
if (row && !file) check("error", "missing-phase-file", `Phase Checklist lists Phase ${number} but there is no phase-${number}.md`);
if (parsed) {
for (const n of parsed.numbering) check("error", "task-numbering", `phase-${number}.md: ${n}`);
// Prerequisites and criteria are plain bullets by rule; other checkbox
// blocks (a Phase Testing list) are the template's own and are not tasks.
for (const s of parsed.strayCheckboxes.filter((c) => /prerequisite|criteria/i.test(c.section))) {
check("warn", "criteria-checkbox", `phase-${number}.md:${s.line} is a checkbox under "${s.section}"; prerequisites and criteria use plain bullets`);
}
if (parsed.total === 0) check("warn", "no-tasks", `phase-${number}.md has no **Task ${number}.N:** checkbox lines`);
for (const u of parsed.unmatchedTasks) {
check("warn", "uncounted-task", `phase-${number}.md:${u.line} looks like a task but is not counted (a task line is "- [ ] **Task ${number}.N:**"): ${u.text}`);
}
const done = parsed.counts.complete + parsed.counts.assumed;
const rowDone = row && (row.state === "complete" || row.state === "assumed");
// A phase may be approved with blocked [!] tasks left (Implementation
// Mode's self-review allows "[x] or blocked [!]"); only unfinished work is an error.
if (rowDone && parsed.unfinished > 0) {
check("error", "checked-with-open-tasks", `Phase ${number} is [${row.marker}] in overview.md but ${parsed.unfinished} task(s) are not done (${phases.at(-1).openTasks.filter((id) => !phases.at(-1).blockedTasks.includes(id)).join(", ")})`);
} else if (rowDone && parsed.counts.blocked > 0) {
check("info", "approved-with-blocked", `Phase ${number} is [${row.marker}] with ${parsed.counts.blocked} blocked task(s) (${phases.at(-1).blockedTasks.join(", ")})`);
}
if (row && row.state === "pending" && parsed.total > 0 && done > 0) {
// Done tasks under a [ ] phase with work still open is what a re-opened
// phase looks like (revise-plan); with nothing open it is a missed mark.
if (parsed.unfinished > 0) check("info", "partly-done-unchecked", `Phase ${number} is [ ] with ${done} task(s) done and ${parsed.unfinished} open (normal for a re-opened phase)`);
else check("warn", "unchecked-with-done-tasks", `Phase ${number} is [ ] in overview.md but all ${done} unblocked task(s) are done`);
}
if (row && !rowDone && row.state !== "pending" && parsed.total > 0 && parsed.unfinished === 0) {
check("info", "done-not-approved", `Phase ${number}: every task is done but overview.md still shows [${row.marker}] (normal until the user approves the phase)`);
}
}
}
if (!hasOverview) check("error", "no-overview", `${spec.rel} has no overview.md`);
else if (!checklist.found) check("error", "no-checklist", "overview.md has no ## Phase Checklist section");
for (const u of checklist.unparsed) check("warn", "unparsed-checklist-row", `overview.md:${u.line} is a checkbox in the Phase Checklist with no "Phase N" in it: ${u.text}`);
for (const g of groups.groups) {
for (const n of g.phases) if (!numbers.has(n)) check("error", "group-unknown-phase", `Parallel group ${g.id} names Phase ${n}, which does not exist`);
}
// Totals. Completed = [x] plus [?] (assumed complete); [?] is reported on its own too.
// Incomplete = [ ] + [/] (+ unreadable markers); Blocked is its own column.
const totals = { total: 0, complete: 0, assumed: 0, pending: 0, "in-progress": 0, blocked: 0, unknown: 0 };
for (const p of phases) if (p.tasks) for (const k of Object.keys(totals)) totals[k] += p.tasks[k] || 0;
const completed = totals.complete + totals.assumed;
const completion = totals.total ? completed / totals.total : null;
return {
ok: true,
spec: spec.rel,
name: spec.name,
overview: hasOverview ? "overview.md" : null,
planDrafts: planDrafts(spec.dir),
phases,
parallelGroups: groups.groups,
totals: { ...totals, completed, incomplete: totals.pending + totals["in-progress"] + totals.unknown },
completion: completion === null ? null : Number(completion.toFixed(4)),
completionPercent: completion === null ? null : Math.round(completion * 100),
next: nextPhase(phases, groups.groups, checklist.found),
pending: phases
.filter((p) => p.checklist && p.checklist !== "complete" && p.checklist !== "assumed")
.map((p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null, open: p.tasks ? p.tasks.open : null, goal: p.goal })),
checks,
};
}
/**
* Implementation Mode's phase-selection table, applied mechanically.
* 2+ workable phases in the same parallel group, consecutive -> choose (warn if all [/])
* a single [/] -> ask-resume · a single [ ] -> auto-start · nothing workable -> none
*/
function nextPhase(phases, groups, haveChecklist) {
if (!haveChecklist) return { action: "none", reason: "no Phase Checklist in overview.md" };
const ordered = phases.filter((p) => p.checklist);
const isDone = (p) => p.checklist === "complete" || p.checklist === "assumed";
const workable = ordered.filter((p) => p.checklist === "pending" || p.checklist === "in-progress");
if (!workable.length) {
return { action: "none", reason: ordered.length && ordered.every(isDone) ? "every phase is complete" : "no [ ] or [/] phase in the Phase Checklist" };
}
const first = workable[0];
const brief = (p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null });
// A blocked [!] phase ahead of the pick is skipped, but never silently.
const skipped = ordered.slice(0, ordered.indexOf(first)).filter((p) => !isDone(p)).map(brief);
const note = skipped.length ? { skipped, warning: `skipping ${skipped.map((p) => `Phase ${p.number} [${p.state}]`).join(", ")} ahead of it` } : {};
const group = groups.find((g) => g.phases.includes(first.number));
if (group) {
// Consecutive same-group incomplete phases, in checklist order, starting at the first workable one.
const run = [];
for (const p of ordered.slice(ordered.indexOf(first))) {
if (!group.phases.includes(p.number)) break;
if (isDone(p)) continue;
if (p.checklist === "pending" || p.checklist === "in-progress") run.push(p);
else break;
}
if (run.length >= 2) {
const allStarted = run.every((p) => p.checklist === "in-progress");
const warnings = [
...(allStarted ? ["every option is already [/]: another agent may be working on it, so picking one risks duplicated work"] : []),
...(note.warning ? [note.warning] : []),
];
return {
action: "choose",
group: group.id,
options: run.map(brief),
...(note.skipped ? { skipped: note.skipped } : {}),
...(warnings.length ? { warning: warnings.join("; ") } : {}),
};
}
}
return { action: first.checklist === "in-progress" ? "ask-resume" : "auto-start", phase: brief(first), ...note };
}
/* --------------------------------------------------------------- commands */
async function cmdList(args) {
const root = path.resolve(args.root || ".");
const { scanProject } = await consoleLib();
const scan = scanProject(root);
const specs = scan.specs.map((s) => {
const dir = path.join(root, s.dir);
let names = [];
try {
names = fs.readdirSync(dir);
} catch {}
return {
dir: s.dir,
name: s.name,
state: s.state,
detail: s.detail,
touched: s.touched ? new Date(s.touched).toISOString() : null,
planDrafts: planDrafts(dir),
overview: names.includes("overview.md"),
phaseFiles: names.filter((n) => /^phase-\d+\b.*\.md$/i.test(n)).length,
pathfinder: isDir(path.join(dir, "pathfinder")),
};
});
let completed = [];
try {
completed = fs.readdirSync(path.join(root, "specs--completed")).filter((n) => isDir(path.join(root, "specs--completed", n))).sort();
} catch {}
out({
ok: true,
root,
hasAgents: scan.hasAgents,
specsDir: isDir(path.join(root, "specs")),
specs,
completed,
...(specs.length ? {} : { note: "No active specs under specs/." }),
});
}
async function cmdStatus(args) {
const root = path.resolve(args.root || ".");
out(specStatus(resolveSpec(root, args._[1], { allowArchived: true })));
}
function countVerificationAdded(dir) {
let n = 0;
for (const name of fs.readdirSync(dir)) {
if (!/\.md$/i.test(name) || /^PLAN-/i.test(name)) continue;
n += ((readText(path.join(dir, name)) || "").match(/<!--\s*VERIFICATION:\s*Added\b/gi) || []).length;
}
return n;
}
async function cmdMetrics(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1], { allowArchived: true });
const step = args.step;
if (step !== "document" && step !== "finalize") fail(EXIT.USAGE, "bad-step", "--step must be document or finalize.", "Plan's METRICS_JSON is written by hand in its Phase 7.");
const sets = {};
for (const kv of args.set || []) {
const m = kv.match(/^([a-z_]+)=(-?\d+(?:\.\d+)?)$/);
if (!m) fail(EXIT.USAGE, "bad-set", `--set ${kv} is not key=number.`, "Example: --set verification_failures_found=1");
sets[m[1]] = Number(m[2]);
}
// --set supplies the judgment fields only; the computed ones are never overridden.
const SETTABLE = { document: ["verification_items_added"], finalize: ["verification_failures_found", "documentation_updates_needed"] };
for (const k of Object.keys(sets)) {
if (!SETTABLE[step].includes(k)) fail(EXIT.USAGE, "bad-set", `--set ${k} is not a field you supply for --step ${step}.`, `Only ${SETTABLE[step].join(", ")}; the rest is computed from the files.`);
}
const st = specStatus(spec);
const withTasks = st.phases.filter((p) => p.tasks);
let metrics;
let hint;
if (step === "document") {
// verification_items_added is the Added total of the Verification Summary
// you presented, not something the files record, so it comes from --set.
// The <!-- VERIFICATION: Added --> comments are a cross-check only.
if (!("verification_items_added" in sets)) fail(EXIT.USAGE, "missing-set", "document needs --set verification_items_added=N (the Added column total of your Verification Summary).", `The spec has ${countVerificationAdded(spec.dir)} <!-- VERIFICATION: Added --> comment(s), as a cross-check.`);
metrics = {
step: "document",
total_tasks: st.totals.total,
tasks_per_phase: withTasks.map((p) => p.tasks.total),
phase_count: st.phases.length,
parallel_groups_identified: st.parallelGroups.length,
...sets,
};
hint = { verificationCommentsFound: countVerificationAdded(spec.dir) };
} else {
const missing = ["verification_failures_found", "documentation_updates_needed"].filter((k) => !(k in sets));
if (missing.length) fail(EXIT.USAGE, "missing-set", `finalize needs ${missing.map((k) => `--set ${k}=N`).join(" and ")}.`, "Those two counts are your judgment from Steps 2 and 4.");
metrics = {
step: "finalize",
completion_rate_at_audit: st.completion === null ? 0 : Number(st.completion.toFixed(2)),
tasks_completed: st.totals.completed,
tasks_total: st.totals.total,
...sets,
};
}
out({ ok: true, spec: spec.rel, metrics, comment: `<!-- METRICS_JSON ${spacedJson(metrics)} -->`, ...(hint || {}), checks: st.checks.filter((c) => c.level === "error") });
}
// The house style of every METRICS_JSON comment: {"key": value, "list": [1, 2]}.
function spacedJson(obj) {
const v = (x) => (Array.isArray(x) ? `[${x.map(v).join(", ")}]` : x && typeof x === "object" ? spacedJson(x) : JSON.stringify(x));
return `{${Object.entries(obj).map(([k, x]) => `${JSON.stringify(k)}: ${v(x)}`).join(", ")}}`;
}
const TO = { open: " ", "in-progress": "/", done: "x" };
async function cmdMark(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1]);
const number = Number(args.phase);
if (!Number.isInteger(number) || number < 0) fail(EXIT.USAGE, "bad-phase", "--phase needs a phase number.", "Example: --phase 2");
if (!(args.to in TO)) fail(EXIT.USAGE, "bad-to", "--to must be open, in-progress or done.", "open = [ ], in-progress = [/], done = [x]");
const overviewPath = path.join(spec.dir, "overview.md");
const overview = readText(overviewPath);
if (overview === null) fail(EXIT.NOT_FOUND, "no-overview", `${spec.rel} has no overview.md.`, "Run /plan2code-2-document first.");
const checklist = parseChecklist(overview);
const rows = checklist.phases.filter((p) => p.number === number);
const row = rows[0];
if (!row) fail(EXIT.NOT_FOUND, "no-row", `overview.md's Phase Checklist has no row for Phase ${number}.`, "Run `specs.mjs status` to see the phases it lists.");
if (rows.length > 1) fail(EXIT.REFUSED, "duplicate-row", `Phase ${number} has ${rows.length} rows in the Phase Checklist (lines ${rows.map((r) => r.line).join(", ")}); marking one would be a guess.`, "Remove the duplicate row, then rerun.");
const target = TO[args.to];
if (row.marker === "/" && target === " ") {
fail(EXIT.REFUSED, "no-reset", `Phase ${number} is [/]; started work is never reset to [ ].`, "Leave it [/] (a later session resumes it), or mark it done once approved.");
}
const changes = [];
const lines = overview.split(/\r?\n/);
const idx = row.line - 1;
const next = lines[idx].replace(/\[(.)\]/, `[${target}]`);
if (next !== lines[idx]) {
lines[idx] = next;
changes.push({ file: `${spec.rel}/overview.md`, line: row.line, from: `[${row.marker}]`, to: `[${target}]` });
}
// The phase file's Status line follows: done -> Complete; re-opening a Complete
// phase -> In Progress (revise-plan), so the two files never disagree.
let phaseText = null;
let phasePath = null;
let unfinished = [];
const warnings = [];
const file = phaseFiles(spec.dir).get(number);
if (file) {
phasePath = path.join(spec.dir, file);
const text = readText(phasePath) || "";
const parsed = parsePhaseFile(phasePath, number);
unfinished = parsed.tasks.filter((t) => ["pending", "in-progress", "unknown"].includes(t.state)).map((t) => t.id);
const status = statusOf(text);
const want = target === "x" ? "Complete" : target === " " && status && /^complete$/i.test(status) ? "In Progress" : null;
if (status && want && status !== want) {
phaseText = text.replace(STATUS_RE, (_, before, _value, after) => before + want + after);
changes.push({ file: `${spec.rel}/${file}`, field: "Status", from: status, to: want });
}
// done and open keep the Status line in step; with none to find, say so.
if (!status && target !== "/") warnings.push(`${file} has no Status line, so only the Phase Checklist checkbox changed; add a "**Status:** <value>" line under its title.`);
}
if (!args["dry-run"]) {
if (changes.some((c) => c.file.endsWith("overview.md"))) fs.writeFileSync(overviewPath, lines.join(eol(overview)));
if (phaseText !== null) fs.writeFileSync(phasePath, phaseText);
}
const doneEarly = target === "x" && unfinished.length > 0;
if (doneEarly) warnings.unshift(`Phase ${number} was marked done with ${unfinished.length} unfinished task(s): ${unfinished.join(", ")}. Mark only a phase the user approved.`);
out({
ok: true,
spec: spec.rel,
phase: number,
name: row.name,
dryRun: !!args["dry-run"],
changed: changes.length > 0,
changes,
...(warnings.length ? { warning: warnings.join(" ") } : {}),
...(doneEarly ? { unfinished } : {}),
});
}
function listRel(dir, base = dir) {
const outList = [];
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) outList.push(...listRel(p, base));
else outList.push(rel(base, p));
}
return outList.sort();
}
async function cmdArchive(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1]);
const target = path.join(root, "specs--completed", spec.name);
if (fs.existsSync(target)) {
fail(EXIT.REFUSED, "target-exists", `specs--completed/${spec.name}/ already exists; nothing was moved.`, "Ask the user whether to merge by hand or archive under another name.");
}
const files = listRel(spec.dir);
if (!args["dry-run"]) {
fs.mkdirSync(path.dirname(target), { recursive: true });
try {
fs.renameSync(spec.dir, target);
} catch (err) {
// A rename across volumes (or a locked file on Windows) fails; copy then remove.
try {
fs.cpSync(spec.dir, target, { recursive: true, errorOnExist: true, force: false });
} catch (copyErr) {
fail(EXIT.INVALID, "archive-failed", `Could not move or copy ${spec.rel} (${err.code || err.message}; copy: ${copyErr.code || copyErr.message}).`, `Close anything holding files in ${spec.rel} open, check specs--completed/${spec.name} for a partial copy, then rerun.`);
}
try {
fs.rmSync(spec.dir, { recursive: true, force: true });
} catch (rmErr) {
fail(EXIT.INVALID, "source-not-removed", `Copied to specs--completed/${spec.name}/ but could not remove ${spec.rel} (${rmErr.code || rmErr.message}); both copies now exist.`, `Close whatever holds files in ${spec.rel} open, then delete it by hand. The archive is complete.`);
}
}
}
const sourceGone = args["dry-run"] ? null : !fs.existsSync(spec.dir);
const moved = args["dry-run"] ? null : listRel(target);
if (!args["dry-run"] && !(sourceGone && moved.length === files.length)) {
fail(
EXIT.INVALID,
"archive-unverified",
`The move of ${spec.rel} to specs--completed/${spec.name}/ did not verify: ${moved.length} of ${files.length} file(s) at the target, and ${spec.rel} ${sourceGone ? "is gone" : "still exists"}.`,
`Compare ${spec.rel} with specs--completed/${spec.name}/ and finish the move by hand; archive refuses to rerun while the target exists.`
);
}
out({
ok: true,
dryRun: !!args["dry-run"],
from: spec.rel,
to: `specs--completed/${spec.name}`,
files,
...(args["dry-run"] ? {} : { sourceRemoved: sourceGone, filesAtTarget: moved.length, archivedOn: isoDate() }),
});
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "step", "phase", "to"], lists: ["set"] });
const cmd = args._[0];
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, archive: cmdArchive };
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, metrics, mark, archive. Run with --help.");
await commands[cmd](args);
});
@@ -0,0 +1,22 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"mode": "utility"
}
+13 -12
View File
@@ -29,11 +29,17 @@ The FIRST thing you do, before anything else in this file — before Step 1, bef
- **Question options:** Never offer 'execute', 'implement', or any execution-shaped synonym. Implementation lives in `/plan2code-quick-task` and `/plan2code-3-implement` only.
- **Web console exception:** the console's temporary payload files (outside the repo, in the session folder `open` prints) are the one allowed write outside `specs/`. They are messages to the page, never project files.
## Scripts
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-1b-revise-plan/scripts/` globally). Run from the project root; each prints one JSON object, and on a non-zero exit `next` says what to do. They only ever touch `specs/`.
- `node "<S>/specs.mjs" list`: the active specs (it reads gitignored `specs/`, where Glob silently finds nothing).
- `node "<S>/specs.mjs" status <spec>`: phases, task counts by marker, `checks`, `pending`.
- `node "<S>/specs.mjs" mark <spec> --phase <N> --to open`: re-open a completed phase in overview.md.
## Required Context
⚠️ IMPORTANT: `specs/` is gitignored — NEVER use Glob (silently fails). Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
Request these files if not provided:
Find the spec with `specs.mjs list`, then request these files if not provided:
- `specs/<feature-name>/overview.md`
- All `specs/<feature-name>/phase-X.md` files
@@ -89,13 +95,11 @@ Present findings and confirm understanding before continuing.
1. [Change description]
2. [Change description]
```
⋅
╭───╮
│ ★ │╱
╱│ ~ │ Here's the plan. What do you think?
╰┬─┬╯
```
Approve the spec-update plan? (approve / refine / abort). Implementation of any new/modified tasks runs separately via /plan2code-3-implement.
```
@@ -130,24 +134,21 @@ Approve the spec-update plan? (approve / refine / abort). Implementation of any
- Added: [date]
- Reason: [reason]
```
- Update overview.md: `[x]` → `[ ]`
- Update overview.md: `[x]` → `[ ]` (`specs.mjs mark <spec> --phase <N> --to open`, which also sets that phase file's `**Status:**` back to In Progress)
- Add comment: `<!-- Re-opened: [date] - [reason] -->`
### STEP 4: Consistency Check
`🔄 [REVISION] Step 4: Consistency Check`
Verify updated specs are consistent:
Run `specs.mjs status <spec>`. Its `checks` cover the mechanical items: task numbers sequential (`task-numbering`), overview.md checklist matches the phase files (`missing-checklist-row`, `missing-phase-file`), incomplete phases unchecked and complete ones checked (`checked-with-open-tasks`, `unchecked-with-done-tasks`; `partly-done-unchecked` is the normal look of a phase you just re-opened). Then verify the rest yourself:
- [ ] Task numbers sequential
- [ ] Phase dependencies valid
- [ ] No orphaned references
- [ ] Tech stack updated if needed
- [ ] Success criteria achievable
- [ ] overview.md checklist matches phase files
- [ ] Incomplete phases unchecked, complete phases checked
Report and resolve issues before continuing.
Report and resolve issues (every `error` in `checks` included), then rerun `status` before continuing.
### STEP 5: Summary
@@ -241,7 +242,7 @@ If user says "abort" or "cancel":
Work summary — tell user: change type, tasks added/modified/removed, phases re-opened (if any).
**Pending phases after revision** — read overview.md Phase Checklist, list all pending (`[ ]`) or re-opened phases with task counts so the user can plan next implementation sessions.
**Pending phases after revision** — list `status`'s `pending` (every phase not `[x]`, re-opened ones included) with its task count so the user can plan next implementation sessions.
Returning context: Revised specs in `specs/<feature-name>/`. Run `/plan2code-3-implement --web` in a new conversation to continue implementation.
@@ -556,8 +556,15 @@ enforces it, so never tell someone to keep asking past it.
The person can add folders beside the one the session started in (a shared
library, a design folder), from the footer's folder label. Together they are
the session's **workspace**: context for every skill run in this console
session, each folder addressed by a short `@name`. It outlives dashboard hops;
a new console session starts with the original folder alone.
session, each folder addressed by a short `@name`. It outlives dashboard hops,
and it is remembered: every change is saved to `workspaces.json` beside
`looks.json` (never into the project), keyed by the folder the session runs
in and then by spec. A session with a spec opens on that spec's list, one with
none on the project's; a spec with nothing saved starts as a copy of the
project's list. The dashboard's picker swaps the list as the selection moves,
and a `specDir` you post mid-run takes the current list with it. There is
nothing for you to load: `open` prints the list, and a switch of spec on a
resume reaches you as ordinary workspace changes on your next `wait`.
### What you are told
@@ -767,7 +774,7 @@ that is what the person is there to download. The finish carries no
sees the Trail Footer, and without this their last screen promises a question
that is never coming.
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
and `pathfinder-research` (id = the question's file slug) as each research
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
subagent reports back, or when you resolve a `research` question yourself
(Posting an update → Session meter). Other questions score through their
answers, so there is nothing to post for them.
@@ -820,7 +827,7 @@ know:
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) 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`. |
| 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). |
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
@@ -41,6 +41,7 @@ import {
die,
ensureDir,
fileStamp,
forgetWorkspace,
handOff,
handleFile,
healthOk,
@@ -65,6 +66,7 @@ import {
readLedger,
readWorkspace,
reapHandles,
rememberedWorkspace,
remoteWarning,
removeScratch,
removeSessions,
@@ -73,6 +75,7 @@ import {
SESSION_MAX_AGE_MS,
sessionDir,
sleepSync,
specKey,
staleScratch,
staleSessions,
sweepUploads,
@@ -317,7 +320,7 @@ async function cmdOpen() {
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
} catch {}
const workspace = workspaceOnOpen(dir, worktree);
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
// Month-old sessions and scratch files: listed before the print so the
// agent can see what went, removed after it so the page waits for nothing.
@@ -403,10 +406,11 @@ async function cmdOpen() {
* The workspace as `open` hands it to the agent, and the cursor seeded to
* match: the agent now has the whole list, so no change up to here is owed.
* Read-only on workspace.json, which only the server writes; on a fresh
* session the server has not made it yet, so the original folder stands in.
* session the server has not made it yet, so what was remembered for this
* folder and spec stands in, the same list the server is about to make.
*/
function workspaceOnOpen(dir, worktree) {
const ws = readWorkspace(dir) || initialWorkspace(worktree);
function workspaceOnOpen(dir, worktree, specDir) {
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
try {
writeWorkspaceCursor(dir, ws.version || 0);
@@ -946,6 +950,18 @@ function realNearest(p) {
return path.join(fs.realpathSync(existing), path.relative(existing, p));
}
/* --------------------------------------------------------------- forget */
// Drop the folder list remembered for one spec (Finalize, once the spec is
// archived). The project's own list and every other spec's are untouched.
function cmdForget() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
let spec = specKey(args.spec);
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
const worktree = repoRoots().worktree;
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
}
/* ----------------------------------------------------------------- help */
function cmdHelp() {
@@ -961,7 +977,8 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
first post. --file is optional, and --title defaults to the
project's folder name. Also prints workspace: { folders: [{ name,
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name.
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
@@ -988,6 +1005,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
Copy a cited note attachment into specs/<idea>/attachments/. Prints
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
missing. Paste link as it is.
forget --spec specs/<idea>
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.
status [--session <sid>] [--all]
One session, or every session belonging to this project.
stop --session <sid> | --all
@@ -1206,6 +1227,7 @@ const COMMANDS = {
wait: cmdWait,
chat: cmdChat,
keep: cmdKeep,
forget: cmdForget,
status: cmdStatus,
stop: cmdStop,
help: cmdHelp,
@@ -178,8 +178,8 @@ function lockStale(lock) {
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn) {
const lock = path.join(dir, STATE_LOCK_FILE);
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
const lock = path.join(dir, lockName);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
@@ -188,7 +188,7 @@ export function withStateLock(dir, fn) {
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
@@ -487,8 +487,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks and the pointer to this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
function isScratchName(name) {
return (
@@ -1619,17 +1620,125 @@ export function readWorkspace(dir) {
return readJson(path.join(dir, WORKSPACE_FILE), null);
}
// A fresh workspace: just the original folder, named after itself.
export function initialWorkspace(worktree) {
// A fresh workspace: the original folder, named after itself, plus whatever
// was remembered for this folder and spec (rememberedWorkspace() below).
export function initialWorkspace(worktree, remembered = null) {
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
if (remembered && remembered.original) {
if (remembered.original.name) original.name = remembered.original.name;
if (remembered.original.description) original.description = remembered.original.description;
}
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
id: "f" + (i + 1),
path: f.path,
name: f.name,
description: f.description || "",
...(f.nested ? { nested: true } : {}),
}));
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
}
/* ------------------------------------------------ remembered workspaces */
// The folder list outlives the console session: one file for the person,
// beside looks.json, keyed by the folder a session runs in and then by spec.
// Never under specs/: the paths are this machine's, and the server never
// writes into a project.
//
// { "projects": { "<folded worktree>": {
// "path": "<worktree>",
// "project": { original, folders, at }, // no spec picked
// "specs": { "specs/<name>": { original, folders, at } } } } }
//
// `original` holds the first folder's name and description only (its path is
// always the session's own); `folders` the added ones as { path, name,
// description, nested? }. Two writers, the server on every change and
// `console.mjs forget`, each a read-modify-write of one key.
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
const foldKey = (p) => {
const resolved = path.resolve(String(p || ""));
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
};
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
export function specKey(specDir) {
return String(specDir || "")
.trim()
.replace(/\\/g, "/")
.replace(/^\.\//, "")
.replace(/\/+$/, "");
}
function readStore() {
const saved = readJson(WORKSPACES_FILE, null);
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
}
/**
* What was remembered for this folder and spec: `{ entry, from }`, where
* `from` is "spec" when the spec has its own list, "project" when it falls
* back to the project's (a spec's list starts as a copy of it), and null
* when nothing was ever saved.
*/
export function rememberedWorkspace(worktree, specDir) {
const project = readStore().projects[foldKey(worktree)];
if (!project) return { entry: null, from: null };
const spec = specKey(specDir);
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
}
// The workspace's folders as the store keeps them.
export function rememberable(ws) {
const folders = (ws && ws.folders) || [];
const first = folders.find((f) => f.original) || {};
return {
version: 0,
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
missing: [],
changes: [],
remote: "",
original: { name: first.name || "", description: first.description || "" },
folders: folders
.filter((f) => !f.original)
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
at: nowIso(),
};
}
// Every server and `console.mjs forget` writes the one file, so each
// read-modify-write holds this lock beside it.
const WORKSPACES_LOCK = "workspaces.json.lock";
// Save the list for this folder and spec ("" for the project's own).
export function rememberWorkspace(worktree, specDir, ws) {
ensureDir(path.dirname(WORKSPACES_FILE));
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
}
function saveRemembered(worktree, specDir, ws) {
const store = readStore();
const key = foldKey(worktree);
const project = store.projects[key] || { path: path.resolve(worktree) };
const spec = specKey(specDir);
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
else project.project = rememberable(ws);
store.projects[key] = project;
writeJsonAtomic(WORKSPACES_FILE, store);
}
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
export function forgetWorkspace(worktree, specDir) {
const spec = specKey(specDir);
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
}
function dropRemembered(worktree, spec) {
const store = readStore();
const project = store.projects[foldKey(worktree)];
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
delete project.specs[spec];
writeJsonAtomic(WORKSPACES_FILE, store);
return true;
}
// Single-writer rule: only server.mjs may call this.
export function writeWorkspace(dir, ws) {
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
@@ -2505,6 +2505,9 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
actions stay put. */
.modal.workspace { max-width: 680px; }
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
.workspace .modal-blurb { margin-bottom: 6px; }
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
.workspace-list {
list-style: none; margin: 0; padding: 0;
display: grid; gap: 12px;
@@ -2542,6 +2542,7 @@ function renderDashboard(main) {
const specs = specList();
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
wrap.appendChild(hideUnavailableToggle());
if (!local.launching && !launchScoping) syncWorkspaceScope();
// "Unavailable" is the scan's verdict for the selected spec, not the
// momentary greying while a launch is in flight or the server is away, so
@@ -2963,6 +2964,11 @@ async function launchSkill(entry) {
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected.
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
// dashboard, which would otherwise sync back to the picker's spec.
launchScoping = true;
await syncWorkspaceScope(target ? target.dir : "");
try {
const res = await fetch("/submit", {
method: "POST",
@@ -2973,6 +2979,7 @@ async function launchSkill(entry) {
}),
});
if (res.status === 409) {
launchScoping = false;
pendingResult = true;
banner("Your last pick is still being picked up. One moment.", "info");
return;
@@ -2980,10 +2987,12 @@ async function launchSkill(entry) {
if (!res.ok) throw new Error(String(res.status));
sound("startSkill");
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
launchScoping = false;
pendingResult = true;
save();
render();
} catch {
launchScoping = false;
banner("That did not go through. Nothing was lost; try again.", "warn");
}
}
@@ -5854,6 +5863,32 @@ async function postJson(url, body) {
}
}
/* The workspace follows the dashboard's picker: the folders remembered for
the selected spec, or the project's own under "Start from scratch". The
server swaps the list and remembers every change after it. */
let scopeAsked = null;
// True from a launch's scope sync until its send has gone (or failed).
let launchScoping = false;
async function syncWorkspaceScope(spec) {
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
scopeAsked = want;
const { status, body } = await postJson("/workspace/scope", { spec: want });
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
scopeAsked = null;
if ($("workspace-modal").open) renderWorkspace();
}
// The dialog's "Remembered for" line: whose list this is.
function workspaceScopeText() {
const scope = (wsFrame && wsFrame.scope) || "";
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
const spec = specList().find((s) => s.dir === scope);
const name = spec ? spec.name : scope.split("/").pop();
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
}
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
// The folder whose Remove is waiting on its inline confirm, by id.
@@ -5893,6 +5928,7 @@ function renderWorkspace() {
}
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
$("workspace-scope").textContent = workspaceScopeText();
}
function workspaceRow(f) {
@@ -833,10 +833,28 @@
Click the folder name in the middle of the bottom bar. It shows your
folder's name and branch, such as <strong>shop · main</strong>, and
<strong>shop + 2 folders · main</strong> once you have added some.
The workspace lasts for this console session only: it carries across
steps you start from the dashboard, and a new console session starts
with just the folder you started in.
It carries across steps you start from the dashboard.
</p>
<h4>Remembered for next time</h4>
<ul>
<li>
Every change is saved as you make it, so the next console session in
this folder starts with the same folders.
</li>
<li>
Each spec keeps its own list. The first time you pick a spec on the
dashboard it starts as a copy of the project's list (the one shown
under <strong>Start from scratch</strong>), and after that the two
are separate. Picking a spec loads its list; the line under the
dialog's title says whose list you are looking at.
</li>
<li>
The lists live in <code>workspaces.json</code> in your own
Plan2Code settings folder, beside your look and feel, never in the
project. Finalize offers to forget a spec's list when it archives the
spec.
</li>
</ul>
<h4>Adding a folder</h4>
<ul>
<li>
@@ -1363,9 +1381,10 @@
<h4>What it counts</h4>
<p>
Each step you run here adds points: a plan or a set of documents
weighs more than a single answered question, and a built phase more
still, by how many tasks it completed: a big phase adds more than a
small one. Every two questions you answer add a point too, so a long
weighs more than a quick task, and a built phase more still, by how
many tasks it completed: a big phase adds more than a small one.
Every two questions you answer within one step add a point too
(rounded down, so a single answer adds nothing), so a long
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
points, with what it added. It is a rule of thumb, not a
reading of Plan2Code's real memory: long sessions tend to make it
@@ -2003,6 +2022,7 @@
The folders the agent uses as context this session. It reads the extra ones for
reference and only changes them if you ask.
</p>
<p class="workspace-scope" id="workspace-scope"></p>
<ul class="workspace-list" id="workspace-list"></ul>
<div class="workspace-add">
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
@@ -45,7 +45,10 @@ import {
readLedger,
readOverview,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
remoteWarning,
specKey,
typedCount,
withStateLock,
writeJsonAtomic,
@@ -326,7 +329,9 @@ function workspaceNow() {
return ws;
}
const root = sessionWorktree();
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
const scope = specKey(stateNow?.specDir);
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
@@ -347,13 +352,87 @@ function saveWorkspace(ws) {
// One change: a new version, an entry in the change log the agent is handed,
// the file, and every open page.
function bumpWorkspace(ws, change) {
function bumpWorkspace(ws, change, { remember = true } = {}) {
ws.version = (ws.version || 0) + 1;
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
saveWorkspace(ws);
// Remembered for the next console session too. A folder gone missing or
// found again is not a change of mind, so it is not saved.
if (remember) rememberNow(ws);
pushState();
}
function rememberNow(ws) {
const root = sessionWorktree();
if (!root) return;
try {
rememberWorkspace(root, ws.scope || "", ws);
} catch {}
}
/**
* Point the workspace at another spec ("" for the project's own list) and
* swap in what was remembered there, logging each difference as a change so
* the agent's cursor stays truthful. A spec with nothing saved starts from
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
* list it has and saves it as the spec's (`seed: "current"`, a spec created
* mid-run). Folders keep their ids when their path stays.
*/
function setScope(ws, spec, seed = "project") {
const root = sessionWorktree();
const next = specKey(spec);
if (!root || (ws.scope || "") === next) return false;
const found = rememberedWorkspace(root, next);
ws.scope = next;
if (next && found.from !== "spec" && seed === "current") {
saveWorkspace(ws);
rememberNow(ws);
pushState();
return true;
}
const want = initialWorkspace(root, found.entry).folders;
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
const kept = new Set();
const folders = [];
const changes = [];
for (const w of want) {
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
if (!have) {
folders.push({ ...w, id: "pending" });
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
continue;
}
kept.add(have);
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
if ((have.description || "") !== (w.description || "")) {
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
}
folders.push({ ...have, name: w.name, description: w.description || "" });
}
for (const f of ws.folders) {
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
}
ws.folders = folders.filter((f) => f.id !== "pending");
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
if (!changes.length) {
saveWorkspace(ws);
pushState();
}
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
checkFolders(ws);
return true;
}
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
// learns its spec late) takes the workspace with it.
function followSpecDir(state) {
const spec = specKey(state && state.specDir);
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
}
function isFolder(p) {
try {
return fs.statSync(p).isDirectory();
@@ -370,10 +449,10 @@ function checkFolders(ws) {
const marked = ws.missing.includes(f.id);
if (!there && !marked) {
ws.missing = [...ws.missing, f.id];
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
} else if (there && marked) {
ws.missing = ws.missing.filter((id) => id !== f.id);
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
}
}
}
@@ -402,8 +481,8 @@ function folderIssues(entries) {
}
function workspaceView() {
const { folders, missing, remote } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) };
const { folders, missing, remote, scope } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
}
// Whether child sits strictly under parent.
@@ -492,6 +571,7 @@ function bootWorkspace() {
saveWorkspace(ws);
}
checkFolders(ws);
followSpecDir(stateNow);
}
/**
@@ -1403,6 +1483,24 @@ const server = http.createServer((req, res) => {
});
}
// Which list the workspace is: a spec's, or the project's (`spec` empty).
// The dashboard's picker sends it as the selection moves and before a
// launch, so a skill opens on the list of the spec it was launched for.
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
try {
setScope(workspaceNow(), spec, "project");
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, workspaceView());
});
}
// Only ever returns a path: the page then adds it through /workspace/add.
if (pathname === "/workspace/browse" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
@@ -1561,6 +1659,9 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
pushState();
}
lastStateStamp = stamp;
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-02",
"releaseDate": "2026-10-04",
"mode": "utility"
}
@@ -0,0 +1,247 @@
// Plan2Code skill scripts: shared plumbing.
//
// Every script in a skill's scripts/ directory imports this file. It owns the
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
//
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
// on a handled failure.
// stderr a one-line human diagnostic on failure (the same message + next).
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
// 4 invalid input or a check that failed · 5 refused (would clobber
// or break a rule).
//
// Node 18+ built-ins only, no build step: this ships inside every skill.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
export class CliError extends Error {
constructor(exit, error, message, next) {
super(message);
this.exit = exit;
this.error = error;
this.next = next;
}
}
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
export function fail(exit, error, message, next) {
throw new CliError(exit, error, message, next);
}
export function out(obj) {
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
}
/**
* Parse argv into { _: positionals, <flag>: value }.
* `booleans` names flags that take no value; every other `--flag` takes the
* next argument, and repeats of a flag listed in `lists` collect into an array.
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
* silently changes behavior.
*/
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
const known = new Set([...booleans, ...values, ...lists, "help"]);
const args = { _: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) {
args._.push(a);
continue;
}
let name = a.slice(2);
let value;
const eq = name.indexOf("=");
if (eq !== -1) {
value = name.slice(eq + 1);
name = name.slice(0, eq);
}
if (!known.has(name)) {
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
}
if (name === "help" || booleans.includes(name)) {
args[name] = true;
continue;
}
if (value === undefined) {
if (i + 1 >= argv.length) {
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
}
value = argv[++i];
}
if (lists.includes(name)) (args[name] ||= []).push(value);
else args[name] = value;
}
return args;
}
/**
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
* failure shape plus an exit code, and anything else into exit 1 with the stack
* on stderr. Sets process.exitCode rather than calling process.exit(), so
* stdout is never cut off mid-write.
*/
export async function run(usage, main) {
try {
const argv = process.argv.slice(2);
if (argv.includes("--help") || argv.includes("-h")) {
process.stdout.write(usage.trim() + "\n");
return;
}
await main(argv);
} catch (err) {
if (err instanceof CliError) {
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
process.exitCode = err.exit;
return;
}
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
process.exitCode = EXIT.CRASH;
}
}
/* ------------------------------------------------------------------ time */
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
// is what "today" means to the person reading the date in their files.
export function now() {
const pinned = process.env.PLAN2CODE_NOW;
if (pinned) {
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
const d = new Date(pinned);
if (!Number.isNaN(d.getTime())) return d;
}
return new Date();
}
const pad = (n) => String(n).padStart(2, "0");
/** YYYY-MM-DD */
export function isoDate(d = now()) {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
/** YYYYMMDD */
export function compactDate(d = now()) {
return isoDate(d).replace(/-/g, "");
}
/** YYYY-MM-DD HH:mm */
export function stamp(d = now()) {
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** HHMMSS */
export function clock(d = now()) {
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
}
/* ----------------------------------------------------------------- files */
export function readText(file) {
try {
return fs.readFileSync(file, "utf8");
} catch {
return null;
}
}
export function isDir(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
/** Write a file only when its content changes. Returns true when it wrote. */
export function writeIfChanged(file, content) {
const current = readText(file);
if (current === content) return false;
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
return true;
}
/** Normalise line endings for parsing; keep the original for writing back. */
export function eol(text) {
return text.includes("\r\n") ? "\r\n" : "\n";
}
/**
* phase-N.md per phase number. An exact phase-N.md always wins over a sibling
* such as phase-1-old.md; more than one candidate is reported, never guessed.
* Shared so every script that counts a spec's tasks reads the same files.
*/
export function phaseFiles(dir) {
const files = new Map();
const extra = new Map();
for (const name of fs.readdirSync(dir).sort()) {
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
if (!m) continue;
const n = Number(m[1]);
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
if (!files.has(n)) files.set(n, name);
else if (exact) {
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
files.set(n, name);
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
}
files.extra = extra;
return files;
}
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
export function rel(root, p) {
return path.relative(root, p).split(path.sep).join("/") || ".";
}
/* --------------------------------------------------------- the web console */
// The web console ships beside these scripts in every installed skill
// (references/web-console/), and in this repo it sits at src/web-console/. Its
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
// metrics-bait scan, so the scripts import it rather than keep a second copy.
const CONSOLE_LIB_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
];
let consoleLibPromise;
export function consoleLib() {
consoleLibPromise ||= (async () => {
for (const candidate of CONSOLE_LIB_CANDIDATES) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-lib-missing",
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
);
})();
return consoleLibPromise;
}
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
export function version() {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const text = readText(file);
if (!text) continue;
try {
const v = JSON.parse(text).version;
if (typeof v === "string") return v;
} catch {}
}
return null;
}
@@ -0,0 +1,676 @@
#!/usr/bin/env node
// specs.mjs: where every spec under specs/ stands, read from its files.
//
// The pipeline skills (plan, document, implement, revise-plan, finalize,
// review, handoff) all need the same filesystem facts: which specs exist, what
// a spec's PLAN-DRAFT says, which phases are open, how many tasks are done.
// Those have one correct answer, so this script computes them instead of each
// prompt re-deriving them by hand. It also performs the two mechanical writes
// (a Phase Checklist marker, the archive move), with --dry-run.
//
// Shell listing only matters to people: specs/ is gitignored, so editor search
// tools skip it. This script reads the disk directly and does not care.
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";
const USAGE = `
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
node specs.mjs list [--root <dir>]
Every active spec under specs/ (never specs--completed/), newest first:
state, detail, PLAN-DRAFT files with their **Status:** line, overview,
phase count. Also the names already archived in specs--completed/.
node specs.mjs status <spec> [--root <dir>]
One spec in full: the overview's Phase Checklist, Parallel Execution
Groups, per-phase task counts by marker, task-numbering problems,
completion, the implement phase-selection verdict ("next"), the pending
phases, and consistency checks. <spec> is specs/<name>, <name>, or a path
to its overview.md.
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).
document: total_tasks, tasks_per_phase, phase_count,
parallel_groups_identified computed; pass
--set verification_items_added=N (your Verification Summary's
Added total; the VERIFICATION comments are reported as a check).
finalize: completion_rate_at_audit, tasks_completed, tasks_total; pass
--set verification_failures_found=N
--set documentation_updates_needed=N.
node specs.mjs mark <spec> --phase <N> --to open|in-progress|done [--dry-run]
Set phase N's Phase Checklist marker in overview.md ([ ], [/], [x]).
done also sets the phase file's Status line (**Status:**, **Status**:
or Status:) to Complete (and warns if tasks are unfinished); open on a
Complete phase sets it to In Progress. Warns when the phase file has no
Status line. Refuses a phase with duplicate checklist rows, and refuses
in-progress -> open (started work stays marked).
node specs.mjs archive <spec> [--dry-run]
Move specs/<name>/ to specs--completed/<name>/. Refuses if the target
exists, or if <spec> is not a folder directly under specs/.
Markers: [ ] pending · [/] in progress · [x] complete · [!] blocked · [?] assumed.
Exit: 0 ok · 2 bad arguments · 3 spec not found · 4 cannot parse / check
failed · 5 refused.
`;
/* ------------------------------------------------------------- resolving */
function realOrResolved(p) {
try {
return fs.realpathSync.native(p);
} catch {
return path.resolve(p);
}
}
const samePath = (a, b) => (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
// Read-only commands (status, metrics) accept an archived spec, because
// Finalize reads its own spec after Step 6 moved it. Writes never do.
function resolveSpec(root, arg, { allowArchived = false } = {}) {
if (!arg) fail(EXIT.USAGE, "missing-spec", "Name the spec: specs/<name>, <name>, or its overview.md path.", "Run `specs.mjs list` to see the active specs.");
let p = arg.replace(/\\/g, "/").replace(/\/+$/, "");
if (/\/overview\.md$/i.test(p) || /\/phase-[^/]*\.md$/i.test(p)) p = p.replace(/\/[^/]+$/, "");
const abs = path.isAbsolute(p) ? p : p.includes("/") ? path.join(root, p) : path.join(root, "specs", p);
const relPath = rel(root, abs);
if (!allowArchived && /(^|\/)specs--completed(\/|$)/.test(relPath)) {
fail(EXIT.REFUSED, "archived-spec", `${relPath} is archived; the pipeline only changes active specs under specs/.`, "Pick an active spec from `specs.mjs list`.");
}
// A spec is a folder directly under specs/ (or specs--completed/ for a read).
// Without this, `archive .` would move all of specs/ and `archive ./src` a
// source folder.
const homes = [path.join(root, "specs"), ...(allowArchived ? [path.join(root, "specs--completed")] : [])].map(realOrResolved);
const parent = realOrResolved(path.dirname(path.resolve(abs)));
if (!homes.some((h) => samePath(h, parent))) {
fail(EXIT.REFUSED, "not-a-spec", `${relPath} is not a spec folder: a spec sits directly under specs/${allowArchived ? " (or specs--completed/)" : ""}.`, "Pass specs/<name> or <name>; run `specs.mjs list` to see the active specs.");
}
if (!isDir(abs)) {
fail(EXIT.NOT_FOUND, "spec-not-found", `No spec folder at ${relPath}.`, "Run `specs.mjs list` from the project root (or pass --root) to see the active specs.");
}
return { dir: abs, rel: relPath, name: path.basename(abs) };
}
/* -------------------------------------------------------------- parsing */
const MARKERS = { " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" };
// Task 2.3, a lettered sub-task 3.6a, or a named one such as a testing task 1.T.
const TASK_RE = /^\s*[-*] \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
const CHECKBOX_RE = /^\s*[-*] \[(.)\]/;
// The Status line in any of the forms people write it: **Status:**, **Status**:
// or a plain Status:, optionally as a list item. Groups: everything up to the
// value (kept as written when the value is rewritten), the value, trailing blanks.
const STATUS_RE = /^([ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*)(.+?)([ \t]*)$/m;
function statusOf(text) {
const m = (text || "").match(STATUS_RE);
return m ? m[2] : null;
}
/** A markdown section's lines: from its heading to the next heading of the same or higher level. */
function section(text, headingRe) {
const lines = text.split(/\r?\n/);
const start = lines.findIndex((l) => /^#{1,6}\s/.test(l) && headingRe.test(l));
if (start === -1) return null;
const level = lines[start].match(/^#+/)[0].length;
let end = lines.length;
for (let i = start + 1; i < lines.length; i++) {
const m = lines[i].match(/^(#+)\s/);
if (m && m[1].length <= level) {
end = i;
break;
}
}
return { start, end, lines: lines.slice(start + 1, end) };
}
function plainText(s) {
return s
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/[*_`]/g, "")
.replace(/\s+/g, " ")
.trim();
}
/** Phase Checklist rows: the first "Phase N" on each checkbox line names the phase. */
function parseChecklist(overview) {
const sec = section(overview, /Phase Checklist/i);
if (!sec) return { found: false, phases: [], unparsed: [] };
const phases = [];
const unparsed = [];
sec.lines.forEach((line, i) => {
const m = line.match(CHECKBOX_RE);
if (!m) return;
const text = plainText(line.replace(CHECKBOX_RE, ""));
const num = text.match(/\bPhase\s+(\d+)\b/i);
if (!num) {
unparsed.push({ line: sec.start + 2 + i, text: line.trim() });
return;
}
const after = text.slice(num.index + num[0].length).replace(/^\s*[:\-–—]\s*/, "");
const name = after.split(/\s+[-–—]\s+|\s+\(|\s+_\(|:\s|\s+see\s+phase-/i)[0].replace(/\s*phase-\d+\.md\s*$/i, "").trim();
phases.push({
number: Number(num[1]),
marker: m[1],
state: MARKERS[m[1]] || "unknown",
name: name.replace(/\s*\[Milestone[^\]]*\]\s*$/i, "") || `Phase ${num[1]}`,
line: sec.start + 2 + i,
});
});
return { found: true, phases, unparsed };
}
/** "2, 3", "2-4" and "2–4" (or an em dash) alike: ranges expand, so a group cell never loses a phase. */
function phaseList(cell) {
const outList = [];
for (const part of cell.match(/\d+\s*[-–\u2014]\s*\d+|\d+/g) || []) {
const r = part.match(/^(\d+)\s*[-–\u2014]\s*(\d+)$/);
if (r && Number(r[2]) >= Number(r[1]) && Number(r[2]) - Number(r[1]) < 100) {
for (let n = Number(r[1]); n <= Number(r[2]); n++) outList.push(n);
} else outList.push(...part.match(/\d+/g).map(Number));
}
return [...new Set(outList)];
}
/** Parallel Execution Groups table: real groups only (a named group with 2+ phases). */
function parseGroups(overview) {
const sec = section(overview, /Parallel Execution Groups/i);
if (!sec) return { found: false, groups: [] };
const groups = [];
const seen = new Set();
for (const line of sec.lines) {
if (!/^\s*\|/.test(line) || /^\s*\|[\s:|-]+\|\s*$/.test(line)) continue;
const cells = line.split("|").slice(1, -1).map((c) => c.trim());
if (cells.length < 2 || /^group$/i.test(cells[0])) continue;
const id = plainText(cells[0]);
const phases = phaseList(cells[1]);
// "None", a dash, a single phase, a group its author labelled sequential
// ("A (sequential)"), or a Phases cell written as a chain ("1 → 2") is not
// a parallel group.
if (!id || /^(none|-|–|—)$/i.test(id) || /\bsequential\b/i.test(id) || /→|->|\bthen\b/i.test(cells[1]) || phases.length < 2) continue;
const key = `${id}:${phases.join(",")}`;
if (seen.has(key)) continue;
seen.add(key);
groups.push({ id, phases, reason: plainText(cells[2] || "") });
}
return { found: true, groups };
}
function firstSentence(text) {
const t = plainText(text);
const m = t.match(/^(.+?[.!?])(\s|$)/);
return (m ? m[1] : t).slice(0, 240);
}
function parsePhaseFile(file, number) {
const text = readText(file) || "";
const lines = text.split(/\r?\n/);
const title = (lines.find((l) => /^#\s/.test(l)) || "").replace(/^#\s+/, "").trim();
const status = statusOf(text);
const counts = { pending: 0, "in-progress": 0, complete: 0, blocked: 0, assumed: 0, unknown: 0 };
const tasks = [];
const strayCheckboxes = [];
const unmatchedTasks = [];
let heading = "";
lines.forEach((line, i) => {
const h = line.match(/^#{1,6}\s+(.*)$/);
if (h) heading = plainText(h[1]);
const t = line.match(TASK_RE);
if (t) {
const state = MARKERS[t[1]] || "unknown";
counts[state]++;
const named = !/^\d+$/.test(t[3]);
tasks.push({ id: `${t[2]}.${t[3]}${t[4]}`, phase: Number(t[2]), seq: named ? null : Number(t[3]), named, suffix: t[4], marker: t[1], state, line: i + 1 });
return;
}
// A line that looks like a task but is not counted as one (Task 1.4A,
// "1. [ ] **Task", a non-bold "- [ ] Task 1.3") would make the audit undercount.
if (/^\s*(?:[-*]|\d+\.)\s+\[.\].*\bTask\s+\d+\./i.test(line)) unmatchedTasks.push({ line: i + 1, text: line.trim().slice(0, 120) });
if (CHECKBOX_RE.test(line)) strayCheckboxes.push({ line: i + 1, section: heading, text: line.trim().slice(0, 120) });
});
// Numbering: every task belongs to this phase, the base numbers run 1..n with
// no gaps or repeats, and a lettered task (3.6a) sits after its base (3.6).
// Named tasks (1.T) are outside the numeric sequence.
const numbering = [];
const bases = [];
for (const t of tasks) {
if (t.phase !== number) numbering.push(`Task ${t.id} is in phase-${number}.md but numbered for Phase ${t.phase}`);
if (!t.suffix && !t.named) bases.push(t.seq);
}
const seenIds = new Set();
for (const t of tasks) {
if (seenIds.has(t.id)) numbering.push(`Task ${t.id} appears more than once`);
seenIds.add(t.id);
if (t.suffix && !t.named && !bases.includes(t.seq)) numbering.push(`Task ${t.id} has no base Task ${t.phase}.${t.seq}`);
}
bases.forEach((seq, i) => {
if (seq !== i + 1 && !numbering.some((n) => n.startsWith("Task numbering"))) {
numbering.push(`Task numbering is not sequential: expected ${number}.${i + 1}, found ${number}.${seq}`);
}
});
const overviewSec = section(text, /^#{1,6}\s+Overview\b/i);
const goalText = overviewSec ? overviewSec.lines.join("\n").split(/\n\s*\n/).map((p) => p.trim()).find((p) => p && !/^[-*|>]/.test(p)) : "";
return {
title,
status,
goal: goalText ? firstSentence(goalText) : null,
total: tasks.length,
counts,
open: counts.pending + counts["in-progress"] + counts.blocked + counts.unknown,
// Open work a phase cannot be approved over; blocked tasks may stand ([!] is allowed at sign-off).
unfinished: counts.pending + counts["in-progress"] + counts.unknown,
tasks,
numbering,
strayCheckboxes,
unmatchedTasks,
};
}
function planDrafts(dir) {
return fs
.readdirSync(dir)
.filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n))
.sort()
.map((file) => ({
file,
archived: /-prev\.md$/i.test(file),
status: statusOf(readText(path.join(dir, file))),
}));
}
/* ---------------------------------------------------------------- status */
function specStatus(spec) {
const overviewPath = path.join(spec.dir, "overview.md");
const overview = readText(overviewPath);
const files = phaseFiles(spec.dir);
// An empty overview.md still exists; only a missing one is "no overview".
const hasOverview = overview !== null;
const checklist = hasOverview ? parseChecklist(overview) : { found: false, phases: [], unparsed: [] };
const groups = hasOverview ? parseGroups(overview) : { found: false, groups: [] };
const checks = [];
const check = (level, code, message) => checks.push({ level, code, message });
for (const [n, names] of files.extra) {
check("warn", "duplicate-phase-file", `Phase ${n} has more than one file: using ${files.get(n)}, ignoring ${names.join(", ")}`);
}
const rowsByNumber = new Map();
for (const r of checklist.phases) rowsByNumber.set(r.number, [...(rowsByNumber.get(r.number) || []), r]);
for (const [n, rows] of rowsByNumber) {
if (rows.length > 1) check("error", "duplicate-checklist-row", `Phase ${n} has ${rows.length} rows in the Phase Checklist (overview.md lines ${rows.map((r) => r.line).join(", ")}); the first one is used`);
}
const phases = [];
const numbers = new Set([...checklist.phases.map((p) => p.number), ...files.keys()]);
for (const number of [...numbers].sort((a, b) => a - b)) {
const row = checklist.phases.find((p) => p.number === number) || null;
const file = files.get(number) || null;
const parsed = file ? parsePhaseFile(path.join(spec.dir, file), number) : null;
phases.push({
number,
name: row ? row.name : parsed ? parsed.title.replace(/^Phase\s+\d+\s*[:\-–—]?\s*/i, "") : `Phase ${number}`,
checklist: row ? row.state : null,
marker: row ? row.marker : null,
file,
status: parsed ? parsed.status : null,
goal: parsed ? parsed.goal : null,
tasks: parsed ? { total: parsed.total, open: parsed.open, ...parsed.counts } : null,
blockedTasks: parsed ? parsed.tasks.filter((t) => t.state === "blocked").map((t) => t.id) : [],
assumedTasks: parsed ? parsed.tasks.filter((t) => t.state === "assumed").map((t) => t.id) : [],
openTasks: parsed ? parsed.tasks.filter((t) => ["pending", "in-progress", "blocked", "unknown"].includes(t.state)).map((t) => t.id) : [],
});
if (!row && hasOverview) check("error", "missing-checklist-row", `phase-${number}.md has no row in overview.md's Phase Checklist`);
if (row && !file) check("error", "missing-phase-file", `Phase Checklist lists Phase ${number} but there is no phase-${number}.md`);
if (parsed) {
for (const n of parsed.numbering) check("error", "task-numbering", `phase-${number}.md: ${n}`);
// Prerequisites and criteria are plain bullets by rule; other checkbox
// blocks (a Phase Testing list) are the template's own and are not tasks.
for (const s of parsed.strayCheckboxes.filter((c) => /prerequisite|criteria/i.test(c.section))) {
check("warn", "criteria-checkbox", `phase-${number}.md:${s.line} is a checkbox under "${s.section}"; prerequisites and criteria use plain bullets`);
}
if (parsed.total === 0) check("warn", "no-tasks", `phase-${number}.md has no **Task ${number}.N:** checkbox lines`);
for (const u of parsed.unmatchedTasks) {
check("warn", "uncounted-task", `phase-${number}.md:${u.line} looks like a task but is not counted (a task line is "- [ ] **Task ${number}.N:**"): ${u.text}`);
}
const done = parsed.counts.complete + parsed.counts.assumed;
const rowDone = row && (row.state === "complete" || row.state === "assumed");
// A phase may be approved with blocked [!] tasks left (Implementation
// Mode's self-review allows "[x] or blocked [!]"); only unfinished work is an error.
if (rowDone && parsed.unfinished > 0) {
check("error", "checked-with-open-tasks", `Phase ${number} is [${row.marker}] in overview.md but ${parsed.unfinished} task(s) are not done (${phases.at(-1).openTasks.filter((id) => !phases.at(-1).blockedTasks.includes(id)).join(", ")})`);
} else if (rowDone && parsed.counts.blocked > 0) {
check("info", "approved-with-blocked", `Phase ${number} is [${row.marker}] with ${parsed.counts.blocked} blocked task(s) (${phases.at(-1).blockedTasks.join(", ")})`);
}
if (row && row.state === "pending" && parsed.total > 0 && done > 0) {
// Done tasks under a [ ] phase with work still open is what a re-opened
// phase looks like (revise-plan); with nothing open it is a missed mark.
if (parsed.unfinished > 0) check("info", "partly-done-unchecked", `Phase ${number} is [ ] with ${done} task(s) done and ${parsed.unfinished} open (normal for a re-opened phase)`);
else check("warn", "unchecked-with-done-tasks", `Phase ${number} is [ ] in overview.md but all ${done} unblocked task(s) are done`);
}
if (row && !rowDone && row.state !== "pending" && parsed.total > 0 && parsed.unfinished === 0) {
check("info", "done-not-approved", `Phase ${number}: every task is done but overview.md still shows [${row.marker}] (normal until the user approves the phase)`);
}
}
}
if (!hasOverview) check("error", "no-overview", `${spec.rel} has no overview.md`);
else if (!checklist.found) check("error", "no-checklist", "overview.md has no ## Phase Checklist section");
for (const u of checklist.unparsed) check("warn", "unparsed-checklist-row", `overview.md:${u.line} is a checkbox in the Phase Checklist with no "Phase N" in it: ${u.text}`);
for (const g of groups.groups) {
for (const n of g.phases) if (!numbers.has(n)) check("error", "group-unknown-phase", `Parallel group ${g.id} names Phase ${n}, which does not exist`);
}
// Totals. Completed = [x] plus [?] (assumed complete); [?] is reported on its own too.
// Incomplete = [ ] + [/] (+ unreadable markers); Blocked is its own column.
const totals = { total: 0, complete: 0, assumed: 0, pending: 0, "in-progress": 0, blocked: 0, unknown: 0 };
for (const p of phases) if (p.tasks) for (const k of Object.keys(totals)) totals[k] += p.tasks[k] || 0;
const completed = totals.complete + totals.assumed;
const completion = totals.total ? completed / totals.total : null;
return {
ok: true,
spec: spec.rel,
name: spec.name,
overview: hasOverview ? "overview.md" : null,
planDrafts: planDrafts(spec.dir),
phases,
parallelGroups: groups.groups,
totals: { ...totals, completed, incomplete: totals.pending + totals["in-progress"] + totals.unknown },
completion: completion === null ? null : Number(completion.toFixed(4)),
completionPercent: completion === null ? null : Math.round(completion * 100),
next: nextPhase(phases, groups.groups, checklist.found),
pending: phases
.filter((p) => p.checklist && p.checklist !== "complete" && p.checklist !== "assumed")
.map((p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null, open: p.tasks ? p.tasks.open : null, goal: p.goal })),
checks,
};
}
/**
* Implementation Mode's phase-selection table, applied mechanically.
* 2+ workable phases in the same parallel group, consecutive -> choose (warn if all [/])
* a single [/] -> ask-resume · a single [ ] -> auto-start · nothing workable -> none
*/
function nextPhase(phases, groups, haveChecklist) {
if (!haveChecklist) return { action: "none", reason: "no Phase Checklist in overview.md" };
const ordered = phases.filter((p) => p.checklist);
const isDone = (p) => p.checklist === "complete" || p.checklist === "assumed";
const workable = ordered.filter((p) => p.checklist === "pending" || p.checklist === "in-progress");
if (!workable.length) {
return { action: "none", reason: ordered.length && ordered.every(isDone) ? "every phase is complete" : "no [ ] or [/] phase in the Phase Checklist" };
}
const first = workable[0];
const brief = (p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null });
// A blocked [!] phase ahead of the pick is skipped, but never silently.
const skipped = ordered.slice(0, ordered.indexOf(first)).filter((p) => !isDone(p)).map(brief);
const note = skipped.length ? { skipped, warning: `skipping ${skipped.map((p) => `Phase ${p.number} [${p.state}]`).join(", ")} ahead of it` } : {};
const group = groups.find((g) => g.phases.includes(first.number));
if (group) {
// Consecutive same-group incomplete phases, in checklist order, starting at the first workable one.
const run = [];
for (const p of ordered.slice(ordered.indexOf(first))) {
if (!group.phases.includes(p.number)) break;
if (isDone(p)) continue;
if (p.checklist === "pending" || p.checklist === "in-progress") run.push(p);
else break;
}
if (run.length >= 2) {
const allStarted = run.every((p) => p.checklist === "in-progress");
const warnings = [
...(allStarted ? ["every option is already [/]: another agent may be working on it, so picking one risks duplicated work"] : []),
...(note.warning ? [note.warning] : []),
];
return {
action: "choose",
group: group.id,
options: run.map(brief),
...(note.skipped ? { skipped: note.skipped } : {}),
...(warnings.length ? { warning: warnings.join("; ") } : {}),
};
}
}
return { action: first.checklist === "in-progress" ? "ask-resume" : "auto-start", phase: brief(first), ...note };
}
/* --------------------------------------------------------------- commands */
async function cmdList(args) {
const root = path.resolve(args.root || ".");
const { scanProject } = await consoleLib();
const scan = scanProject(root);
const specs = scan.specs.map((s) => {
const dir = path.join(root, s.dir);
let names = [];
try {
names = fs.readdirSync(dir);
} catch {}
return {
dir: s.dir,
name: s.name,
state: s.state,
detail: s.detail,
touched: s.touched ? new Date(s.touched).toISOString() : null,
planDrafts: planDrafts(dir),
overview: names.includes("overview.md"),
phaseFiles: names.filter((n) => /^phase-\d+\b.*\.md$/i.test(n)).length,
pathfinder: isDir(path.join(dir, "pathfinder")),
};
});
let completed = [];
try {
completed = fs.readdirSync(path.join(root, "specs--completed")).filter((n) => isDir(path.join(root, "specs--completed", n))).sort();
} catch {}
out({
ok: true,
root,
hasAgents: scan.hasAgents,
specsDir: isDir(path.join(root, "specs")),
specs,
completed,
...(specs.length ? {} : { note: "No active specs under specs/." }),
});
}
async function cmdStatus(args) {
const root = path.resolve(args.root || ".");
out(specStatus(resolveSpec(root, args._[1], { allowArchived: true })));
}
function countVerificationAdded(dir) {
let n = 0;
for (const name of fs.readdirSync(dir)) {
if (!/\.md$/i.test(name) || /^PLAN-/i.test(name)) continue;
n += ((readText(path.join(dir, name)) || "").match(/<!--\s*VERIFICATION:\s*Added\b/gi) || []).length;
}
return n;
}
async function cmdMetrics(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1], { allowArchived: true });
const step = args.step;
if (step !== "document" && step !== "finalize") fail(EXIT.USAGE, "bad-step", "--step must be document or finalize.", "Plan's METRICS_JSON is written by hand in its Phase 7.");
const sets = {};
for (const kv of args.set || []) {
const m = kv.match(/^([a-z_]+)=(-?\d+(?:\.\d+)?)$/);
if (!m) fail(EXIT.USAGE, "bad-set", `--set ${kv} is not key=number.`, "Example: --set verification_failures_found=1");
sets[m[1]] = Number(m[2]);
}
// --set supplies the judgment fields only; the computed ones are never overridden.
const SETTABLE = { document: ["verification_items_added"], finalize: ["verification_failures_found", "documentation_updates_needed"] };
for (const k of Object.keys(sets)) {
if (!SETTABLE[step].includes(k)) fail(EXIT.USAGE, "bad-set", `--set ${k} is not a field you supply for --step ${step}.`, `Only ${SETTABLE[step].join(", ")}; the rest is computed from the files.`);
}
const st = specStatus(spec);
const withTasks = st.phases.filter((p) => p.tasks);
let metrics;
let hint;
if (step === "document") {
// verification_items_added is the Added total of the Verification Summary
// you presented, not something the files record, so it comes from --set.
// The <!-- VERIFICATION: Added --> comments are a cross-check only.
if (!("verification_items_added" in sets)) fail(EXIT.USAGE, "missing-set", "document needs --set verification_items_added=N (the Added column total of your Verification Summary).", `The spec has ${countVerificationAdded(spec.dir)} <!-- VERIFICATION: Added --> comment(s), as a cross-check.`);
metrics = {
step: "document",
total_tasks: st.totals.total,
tasks_per_phase: withTasks.map((p) => p.tasks.total),
phase_count: st.phases.length,
parallel_groups_identified: st.parallelGroups.length,
...sets,
};
hint = { verificationCommentsFound: countVerificationAdded(spec.dir) };
} else {
const missing = ["verification_failures_found", "documentation_updates_needed"].filter((k) => !(k in sets));
if (missing.length) fail(EXIT.USAGE, "missing-set", `finalize needs ${missing.map((k) => `--set ${k}=N`).join(" and ")}.`, "Those two counts are your judgment from Steps 2 and 4.");
metrics = {
step: "finalize",
completion_rate_at_audit: st.completion === null ? 0 : Number(st.completion.toFixed(2)),
tasks_completed: st.totals.completed,
tasks_total: st.totals.total,
...sets,
};
}
out({ ok: true, spec: spec.rel, metrics, comment: `<!-- METRICS_JSON ${spacedJson(metrics)} -->`, ...(hint || {}), checks: st.checks.filter((c) => c.level === "error") });
}
// The house style of every METRICS_JSON comment: {"key": value, "list": [1, 2]}.
function spacedJson(obj) {
const v = (x) => (Array.isArray(x) ? `[${x.map(v).join(", ")}]` : x && typeof x === "object" ? spacedJson(x) : JSON.stringify(x));
return `{${Object.entries(obj).map(([k, x]) => `${JSON.stringify(k)}: ${v(x)}`).join(", ")}}`;
}
const TO = { open: " ", "in-progress": "/", done: "x" };
async function cmdMark(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1]);
const number = Number(args.phase);
if (!Number.isInteger(number) || number < 0) fail(EXIT.USAGE, "bad-phase", "--phase needs a phase number.", "Example: --phase 2");
if (!(args.to in TO)) fail(EXIT.USAGE, "bad-to", "--to must be open, in-progress or done.", "open = [ ], in-progress = [/], done = [x]");
const overviewPath = path.join(spec.dir, "overview.md");
const overview = readText(overviewPath);
if (overview === null) fail(EXIT.NOT_FOUND, "no-overview", `${spec.rel} has no overview.md.`, "Run /plan2code-2-document first.");
const checklist = parseChecklist(overview);
const rows = checklist.phases.filter((p) => p.number === number);
const row = rows[0];
if (!row) fail(EXIT.NOT_FOUND, "no-row", `overview.md's Phase Checklist has no row for Phase ${number}.`, "Run `specs.mjs status` to see the phases it lists.");
if (rows.length > 1) fail(EXIT.REFUSED, "duplicate-row", `Phase ${number} has ${rows.length} rows in the Phase Checklist (lines ${rows.map((r) => r.line).join(", ")}); marking one would be a guess.`, "Remove the duplicate row, then rerun.");
const target = TO[args.to];
if (row.marker === "/" && target === " ") {
fail(EXIT.REFUSED, "no-reset", `Phase ${number} is [/]; started work is never reset to [ ].`, "Leave it [/] (a later session resumes it), or mark it done once approved.");
}
const changes = [];
const lines = overview.split(/\r?\n/);
const idx = row.line - 1;
const next = lines[idx].replace(/\[(.)\]/, `[${target}]`);
if (next !== lines[idx]) {
lines[idx] = next;
changes.push({ file: `${spec.rel}/overview.md`, line: row.line, from: `[${row.marker}]`, to: `[${target}]` });
}
// The phase file's Status line follows: done -> Complete; re-opening a Complete
// phase -> In Progress (revise-plan), so the two files never disagree.
let phaseText = null;
let phasePath = null;
let unfinished = [];
const warnings = [];
const file = phaseFiles(spec.dir).get(number);
if (file) {
phasePath = path.join(spec.dir, file);
const text = readText(phasePath) || "";
const parsed = parsePhaseFile(phasePath, number);
unfinished = parsed.tasks.filter((t) => ["pending", "in-progress", "unknown"].includes(t.state)).map((t) => t.id);
const status = statusOf(text);
const want = target === "x" ? "Complete" : target === " " && status && /^complete$/i.test(status) ? "In Progress" : null;
if (status && want && status !== want) {
phaseText = text.replace(STATUS_RE, (_, before, _value, after) => before + want + after);
changes.push({ file: `${spec.rel}/${file}`, field: "Status", from: status, to: want });
}
// done and open keep the Status line in step; with none to find, say so.
if (!status && target !== "/") warnings.push(`${file} has no Status line, so only the Phase Checklist checkbox changed; add a "**Status:** <value>" line under its title.`);
}
if (!args["dry-run"]) {
if (changes.some((c) => c.file.endsWith("overview.md"))) fs.writeFileSync(overviewPath, lines.join(eol(overview)));
if (phaseText !== null) fs.writeFileSync(phasePath, phaseText);
}
const doneEarly = target === "x" && unfinished.length > 0;
if (doneEarly) warnings.unshift(`Phase ${number} was marked done with ${unfinished.length} unfinished task(s): ${unfinished.join(", ")}. Mark only a phase the user approved.`);
out({
ok: true,
spec: spec.rel,
phase: number,
name: row.name,
dryRun: !!args["dry-run"],
changed: changes.length > 0,
changes,
...(warnings.length ? { warning: warnings.join(" ") } : {}),
...(doneEarly ? { unfinished } : {}),
});
}
function listRel(dir, base = dir) {
const outList = [];
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) outList.push(...listRel(p, base));
else outList.push(rel(base, p));
}
return outList.sort();
}
async function cmdArchive(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1]);
const target = path.join(root, "specs--completed", spec.name);
if (fs.existsSync(target)) {
fail(EXIT.REFUSED, "target-exists", `specs--completed/${spec.name}/ already exists; nothing was moved.`, "Ask the user whether to merge by hand or archive under another name.");
}
const files = listRel(spec.dir);
if (!args["dry-run"]) {
fs.mkdirSync(path.dirname(target), { recursive: true });
try {
fs.renameSync(spec.dir, target);
} catch (err) {
// A rename across volumes (or a locked file on Windows) fails; copy then remove.
try {
fs.cpSync(spec.dir, target, { recursive: true, errorOnExist: true, force: false });
} catch (copyErr) {
fail(EXIT.INVALID, "archive-failed", `Could not move or copy ${spec.rel} (${err.code || err.message}; copy: ${copyErr.code || copyErr.message}).`, `Close anything holding files in ${spec.rel} open, check specs--completed/${spec.name} for a partial copy, then rerun.`);
}
try {
fs.rmSync(spec.dir, { recursive: true, force: true });
} catch (rmErr) {
fail(EXIT.INVALID, "source-not-removed", `Copied to specs--completed/${spec.name}/ but could not remove ${spec.rel} (${rmErr.code || rmErr.message}); both copies now exist.`, `Close whatever holds files in ${spec.rel} open, then delete it by hand. The archive is complete.`);
}
}
}
const sourceGone = args["dry-run"] ? null : !fs.existsSync(spec.dir);
const moved = args["dry-run"] ? null : listRel(target);
if (!args["dry-run"] && !(sourceGone && moved.length === files.length)) {
fail(
EXIT.INVALID,
"archive-unverified",
`The move of ${spec.rel} to specs--completed/${spec.name}/ did not verify: ${moved.length} of ${files.length} file(s) at the target, and ${spec.rel} ${sourceGone ? "is gone" : "still exists"}.`,
`Compare ${spec.rel} with specs--completed/${spec.name}/ and finish the move by hand; archive refuses to rerun while the target exists.`
);
}
out({
ok: true,
dryRun: !!args["dry-run"],
from: spec.rel,
to: `specs--completed/${spec.name}`,
files,
...(args["dry-run"] ? {} : { sourceRemoved: sourceGone, filesAtTarget: moved.length, archivedOn: isoDate() }),
});
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "step", "phase", "to"], lists: ["set"] });
const cmd = args._[0];
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, archive: cmdArchive };
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, metrics, mark, archive. Run with --help.");
await commands[cmd](args);
});
@@ -0,0 +1,22 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"mode": "utility"
}
+16 -7
View File
@@ -16,6 +16,14 @@ Technical writer transforming planning documents into precise, complete implemen
The FIRST thing you do, before anything else — before Auto-Discovery: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow document` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec` once known), then <D>/console.md → Documentation. Switchable anytime. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console.md → Launches), then Auto-Discovery. `__stop` ends it; post `finish` BEFORE `stop` at every end.
## Scripts
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-2-document/scripts/` globally). Run from the project root; each prints one JSON object, and on a non-zero exit `next` says what to do.
- `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" metrics <spec> --step document --set verification_items_added=<N>`: the METRICS_JSON line.
## Rules
- Follow `./AGENTS.md` if it exists
@@ -28,11 +36,11 @@ The FIRST thing you do, before anything else — before Auto-Discovery: ask **we
## Auto-Discovery
⚠️ IMPORTANT: `specs/` is gitignored — NEVER use Glob (silently fails). Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
`specs/` is gitignored, so Glob silently finds nothing there; `specs.mjs` reads it directly.
**Before asking user for input:**
1. Run `ls specs/` then check each folder for `PLAN-DRAFT-*.md`
1. Run `specs.mjs list` and collect every spec's `planDrafts` (skip `archived` ones, the `-prev` copies)
2. **One found:** Use it, inform user: "Found: `specs/<feature>/PLAN-DRAFT-<date>.md`"
3. **Multiple found:** List all, ask which to document
4. **None found:** Fall back to Required Context below
@@ -107,6 +115,7 @@ 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
@@ -176,13 +185,13 @@ Use kebab-case for feature name (e.g., `user-authentication`).
### overview.md
Header: Title, Created date, Source (PLAN-DRAFT path), Status (Not Started | In Progress | Complete).
Header: Title, Created date, Source (PLAN-DRAFT path), Status on its own line as `**Status:** <value>` (Not Started | In Progress | Complete).
Sections: Summary (from Executive Summary), Tech Stack table (exact copy from PLAN-DRAFT), Architecture (Pattern + Component Overview table), Risks and Mitigations table, Success Criteria checklist, Phase Checklist, Parallel Execution Groups table (from analysis), Quick Reference (Key Files, Environment Variables, External Dependencies), Completion Summary (filled during finalization).
### phase-X.md
Header: Phase name, Status, Estimated Tasks count.
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).
@@ -216,13 +225,13 @@ Total tasks: Y
Parallel Execution: [Groups or "None - sequential only"]
```
Also append a machine-parseable metrics comment to the END of `overview.md` for the metrics pipeline:
Also append a machine-parseable metrics comment to the END of `overview.md` for the metrics pipeline, shaped like:
```
<!-- METRICS_JSON {"step": "document", "total_tasks": 28, "tasks_per_phase": [7, 7, 7, 7], "phase_count": 4, "parallel_groups_identified": 2, "verification_items_added": 3} -->
```
Replace values with actuals. `verification_items_added` = total Added column from the Verification Summary table.
Paste the `comment` from `specs.mjs metrics specs/<feature-name> --step document --set verification_items_added=<N>`, where N is the Added column total of your Verification Summary. It counts the tasks, phases and parallel groups from the files.
**Tell user:**
1. What was created (spec files list)
@@ -230,7 +239,7 @@ Replace values with actuals. `verification_items_added` = total Added column fro
3. Next command: `/plan2code-3-implement-review --web` (quality-gated) or `/plan2code-3-implement --web` (implementation only)
4. Start NEW conversation for implementation
**Phase Overview** — read each `phase-X.md` and present a table: phase name, task count, one-sentence goal. Helps the user plan sessions and identify review gates.
**Phase Overview** — present a table from `status`'s `phases`: phase name, task count (`tasks.total`), one-sentence goal (`goal`, tightened if it runs long; write one yourself when it is null). Helps the user plan sessions and identify review gates.
```
⋅
@@ -556,8 +556,15 @@ enforces it, so never tell someone to keep asking past it.
The person can add folders beside the one the session started in (a shared
library, a design folder), from the footer's folder label. Together they are
the session's **workspace**: context for every skill run in this console
session, each folder addressed by a short `@name`. It outlives dashboard hops;
a new console session starts with the original folder alone.
session, each folder addressed by a short `@name`. It outlives dashboard hops,
and it is remembered: every change is saved to `workspaces.json` beside
`looks.json` (never into the project), keyed by the folder the session runs
in and then by spec. A session with a spec opens on that spec's list, one with
none on the project's; a spec with nothing saved starts as a copy of the
project's list. The dashboard's picker swaps the list as the selection moves,
and a `specDir` you post mid-run takes the current list with it. There is
nothing for you to load: `open` prints the list, and a switch of spec on a
resume reaches you as ordinary workspace changes on your next `wait`.
### What you are told
@@ -767,7 +774,7 @@ that is what the person is there to download. The finish carries no
sees the Trail Footer, and without this their last screen promises a question
that is never coming.
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
and `pathfinder-research` (id = the question's file slug) as each research
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
subagent reports back, or when you resolve a `research` question yourself
(Posting an update → Session meter). Other questions score through their
answers, so there is nothing to post for them.
@@ -820,7 +827,7 @@ know:
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) 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`. |
| 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). |
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
@@ -41,6 +41,7 @@ import {
die,
ensureDir,
fileStamp,
forgetWorkspace,
handOff,
handleFile,
healthOk,
@@ -65,6 +66,7 @@ import {
readLedger,
readWorkspace,
reapHandles,
rememberedWorkspace,
remoteWarning,
removeScratch,
removeSessions,
@@ -73,6 +75,7 @@ import {
SESSION_MAX_AGE_MS,
sessionDir,
sleepSync,
specKey,
staleScratch,
staleSessions,
sweepUploads,
@@ -317,7 +320,7 @@ async function cmdOpen() {
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
} catch {}
const workspace = workspaceOnOpen(dir, worktree);
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
// Month-old sessions and scratch files: listed before the print so the
// agent can see what went, removed after it so the page waits for nothing.
@@ -403,10 +406,11 @@ async function cmdOpen() {
* The workspace as `open` hands it to the agent, and the cursor seeded to
* match: the agent now has the whole list, so no change up to here is owed.
* Read-only on workspace.json, which only the server writes; on a fresh
* session the server has not made it yet, so the original folder stands in.
* session the server has not made it yet, so what was remembered for this
* folder and spec stands in, the same list the server is about to make.
*/
function workspaceOnOpen(dir, worktree) {
const ws = readWorkspace(dir) || initialWorkspace(worktree);
function workspaceOnOpen(dir, worktree, specDir) {
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
try {
writeWorkspaceCursor(dir, ws.version || 0);
@@ -946,6 +950,18 @@ function realNearest(p) {
return path.join(fs.realpathSync(existing), path.relative(existing, p));
}
/* --------------------------------------------------------------- forget */
// Drop the folder list remembered for one spec (Finalize, once the spec is
// archived). The project's own list and every other spec's are untouched.
function cmdForget() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
let spec = specKey(args.spec);
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
const worktree = repoRoots().worktree;
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
}
/* ----------------------------------------------------------------- help */
function cmdHelp() {
@@ -961,7 +977,8 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
first post. --file is optional, and --title defaults to the
project's folder name. Also prints workspace: { folders: [{ name,
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name.
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
@@ -988,6 +1005,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
Copy a cited note attachment into specs/<idea>/attachments/. Prints
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
missing. Paste link as it is.
forget --spec specs/<idea>
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.
status [--session <sid>] [--all]
One session, or every session belonging to this project.
stop --session <sid> | --all
@@ -1206,6 +1227,7 @@ const COMMANDS = {
wait: cmdWait,
chat: cmdChat,
keep: cmdKeep,
forget: cmdForget,
status: cmdStatus,
stop: cmdStop,
help: cmdHelp,
@@ -178,8 +178,8 @@ function lockStale(lock) {
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn) {
const lock = path.join(dir, STATE_LOCK_FILE);
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
const lock = path.join(dir, lockName);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
@@ -188,7 +188,7 @@ export function withStateLock(dir, fn) {
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
@@ -487,8 +487,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks and the pointer to this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
function isScratchName(name) {
return (
@@ -1619,17 +1620,125 @@ export function readWorkspace(dir) {
return readJson(path.join(dir, WORKSPACE_FILE), null);
}
// A fresh workspace: just the original folder, named after itself.
export function initialWorkspace(worktree) {
// A fresh workspace: the original folder, named after itself, plus whatever
// was remembered for this folder and spec (rememberedWorkspace() below).
export function initialWorkspace(worktree, remembered = null) {
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
if (remembered && remembered.original) {
if (remembered.original.name) original.name = remembered.original.name;
if (remembered.original.description) original.description = remembered.original.description;
}
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
id: "f" + (i + 1),
path: f.path,
name: f.name,
description: f.description || "",
...(f.nested ? { nested: true } : {}),
}));
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
}
/* ------------------------------------------------ remembered workspaces */
// The folder list outlives the console session: one file for the person,
// beside looks.json, keyed by the folder a session runs in and then by spec.
// Never under specs/: the paths are this machine's, and the server never
// writes into a project.
//
// { "projects": { "<folded worktree>": {
// "path": "<worktree>",
// "project": { original, folders, at }, // no spec picked
// "specs": { "specs/<name>": { original, folders, at } } } } }
//
// `original` holds the first folder's name and description only (its path is
// always the session's own); `folders` the added ones as { path, name,
// description, nested? }. Two writers, the server on every change and
// `console.mjs forget`, each a read-modify-write of one key.
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
const foldKey = (p) => {
const resolved = path.resolve(String(p || ""));
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
};
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
export function specKey(specDir) {
return String(specDir || "")
.trim()
.replace(/\\/g, "/")
.replace(/^\.\//, "")
.replace(/\/+$/, "");
}
function readStore() {
const saved = readJson(WORKSPACES_FILE, null);
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
}
/**
* What was remembered for this folder and spec: `{ entry, from }`, where
* `from` is "spec" when the spec has its own list, "project" when it falls
* back to the project's (a spec's list starts as a copy of it), and null
* when nothing was ever saved.
*/
export function rememberedWorkspace(worktree, specDir) {
const project = readStore().projects[foldKey(worktree)];
if (!project) return { entry: null, from: null };
const spec = specKey(specDir);
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
}
// The workspace's folders as the store keeps them.
export function rememberable(ws) {
const folders = (ws && ws.folders) || [];
const first = folders.find((f) => f.original) || {};
return {
version: 0,
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
missing: [],
changes: [],
remote: "",
original: { name: first.name || "", description: first.description || "" },
folders: folders
.filter((f) => !f.original)
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
at: nowIso(),
};
}
// Every server and `console.mjs forget` writes the one file, so each
// read-modify-write holds this lock beside it.
const WORKSPACES_LOCK = "workspaces.json.lock";
// Save the list for this folder and spec ("" for the project's own).
export function rememberWorkspace(worktree, specDir, ws) {
ensureDir(path.dirname(WORKSPACES_FILE));
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
}
function saveRemembered(worktree, specDir, ws) {
const store = readStore();
const key = foldKey(worktree);
const project = store.projects[key] || { path: path.resolve(worktree) };
const spec = specKey(specDir);
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
else project.project = rememberable(ws);
store.projects[key] = project;
writeJsonAtomic(WORKSPACES_FILE, store);
}
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
export function forgetWorkspace(worktree, specDir) {
const spec = specKey(specDir);
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
}
function dropRemembered(worktree, spec) {
const store = readStore();
const project = store.projects[foldKey(worktree)];
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
delete project.specs[spec];
writeJsonAtomic(WORKSPACES_FILE, store);
return true;
}
// Single-writer rule: only server.mjs may call this.
export function writeWorkspace(dir, ws) {
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
@@ -2505,6 +2505,9 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
actions stay put. */
.modal.workspace { max-width: 680px; }
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
.workspace .modal-blurb { margin-bottom: 6px; }
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
.workspace-list {
list-style: none; margin: 0; padding: 0;
display: grid; gap: 12px;
@@ -2542,6 +2542,7 @@ function renderDashboard(main) {
const specs = specList();
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
wrap.appendChild(hideUnavailableToggle());
if (!local.launching && !launchScoping) syncWorkspaceScope();
// "Unavailable" is the scan's verdict for the selected spec, not the
// momentary greying while a launch is in flight or the server is away, so
@@ -2963,6 +2964,11 @@ async function launchSkill(entry) {
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected.
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
// dashboard, which would otherwise sync back to the picker's spec.
launchScoping = true;
await syncWorkspaceScope(target ? target.dir : "");
try {
const res = await fetch("/submit", {
method: "POST",
@@ -2973,6 +2979,7 @@ async function launchSkill(entry) {
}),
});
if (res.status === 409) {
launchScoping = false;
pendingResult = true;
banner("Your last pick is still being picked up. One moment.", "info");
return;
@@ -2980,10 +2987,12 @@ async function launchSkill(entry) {
if (!res.ok) throw new Error(String(res.status));
sound("startSkill");
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
launchScoping = false;
pendingResult = true;
save();
render();
} catch {
launchScoping = false;
banner("That did not go through. Nothing was lost; try again.", "warn");
}
}
@@ -5854,6 +5863,32 @@ async function postJson(url, body) {
}
}
/* The workspace follows the dashboard's picker: the folders remembered for
the selected spec, or the project's own under "Start from scratch". The
server swaps the list and remembers every change after it. */
let scopeAsked = null;
// True from a launch's scope sync until its send has gone (or failed).
let launchScoping = false;
async function syncWorkspaceScope(spec) {
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
scopeAsked = want;
const { status, body } = await postJson("/workspace/scope", { spec: want });
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
scopeAsked = null;
if ($("workspace-modal").open) renderWorkspace();
}
// The dialog's "Remembered for" line: whose list this is.
function workspaceScopeText() {
const scope = (wsFrame && wsFrame.scope) || "";
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
const spec = specList().find((s) => s.dir === scope);
const name = spec ? spec.name : scope.split("/").pop();
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
}
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
// The folder whose Remove is waiting on its inline confirm, by id.
@@ -5893,6 +5928,7 @@ function renderWorkspace() {
}
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
$("workspace-scope").textContent = workspaceScopeText();
}
function workspaceRow(f) {
@@ -833,10 +833,28 @@
Click the folder name in the middle of the bottom bar. It shows your
folder's name and branch, such as <strong>shop · main</strong>, and
<strong>shop + 2 folders · main</strong> once you have added some.
The workspace lasts for this console session only: it carries across
steps you start from the dashboard, and a new console session starts
with just the folder you started in.
It carries across steps you start from the dashboard.
</p>
<h4>Remembered for next time</h4>
<ul>
<li>
Every change is saved as you make it, so the next console session in
this folder starts with the same folders.
</li>
<li>
Each spec keeps its own list. The first time you pick a spec on the
dashboard it starts as a copy of the project's list (the one shown
under <strong>Start from scratch</strong>), and after that the two
are separate. Picking a spec loads its list; the line under the
dialog's title says whose list you are looking at.
</li>
<li>
The lists live in <code>workspaces.json</code> in your own
Plan2Code settings folder, beside your look and feel, never in the
project. Finalize offers to forget a spec's list when it archives the
spec.
</li>
</ul>
<h4>Adding a folder</h4>
<ul>
<li>
@@ -1363,9 +1381,10 @@
<h4>What it counts</h4>
<p>
Each step you run here adds points: a plan or a set of documents
weighs more than a single answered question, and a built phase more
still, by how many tasks it completed: a big phase adds more than a
small one. Every two questions you answer add a point too, so a long
weighs more than a quick task, and a built phase more still, by how
many tasks it completed: a big phase adds more than a small one.
Every two questions you answer within one step add a point too
(rounded down, so a single answer adds nothing), so a long
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
points, with what it added. It is a rule of thumb, not a
reading of Plan2Code's real memory: long sessions tend to make it
@@ -2003,6 +2022,7 @@
The folders the agent uses as context this session. It reads the extra ones for
reference and only changes them if you ask.
</p>
<p class="workspace-scope" id="workspace-scope"></p>
<ul class="workspace-list" id="workspace-list"></ul>
<div class="workspace-add">
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
@@ -45,7 +45,10 @@ import {
readLedger,
readOverview,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
remoteWarning,
specKey,
typedCount,
withStateLock,
writeJsonAtomic,
@@ -326,7 +329,9 @@ function workspaceNow() {
return ws;
}
const root = sessionWorktree();
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
const scope = specKey(stateNow?.specDir);
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
@@ -347,13 +352,87 @@ function saveWorkspace(ws) {
// One change: a new version, an entry in the change log the agent is handed,
// the file, and every open page.
function bumpWorkspace(ws, change) {
function bumpWorkspace(ws, change, { remember = true } = {}) {
ws.version = (ws.version || 0) + 1;
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
saveWorkspace(ws);
// Remembered for the next console session too. A folder gone missing or
// found again is not a change of mind, so it is not saved.
if (remember) rememberNow(ws);
pushState();
}
function rememberNow(ws) {
const root = sessionWorktree();
if (!root) return;
try {
rememberWorkspace(root, ws.scope || "", ws);
} catch {}
}
/**
* Point the workspace at another spec ("" for the project's own list) and
* swap in what was remembered there, logging each difference as a change so
* the agent's cursor stays truthful. A spec with nothing saved starts from
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
* list it has and saves it as the spec's (`seed: "current"`, a spec created
* mid-run). Folders keep their ids when their path stays.
*/
function setScope(ws, spec, seed = "project") {
const root = sessionWorktree();
const next = specKey(spec);
if (!root || (ws.scope || "") === next) return false;
const found = rememberedWorkspace(root, next);
ws.scope = next;
if (next && found.from !== "spec" && seed === "current") {
saveWorkspace(ws);
rememberNow(ws);
pushState();
return true;
}
const want = initialWorkspace(root, found.entry).folders;
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
const kept = new Set();
const folders = [];
const changes = [];
for (const w of want) {
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
if (!have) {
folders.push({ ...w, id: "pending" });
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
continue;
}
kept.add(have);
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
if ((have.description || "") !== (w.description || "")) {
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
}
folders.push({ ...have, name: w.name, description: w.description || "" });
}
for (const f of ws.folders) {
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
}
ws.folders = folders.filter((f) => f.id !== "pending");
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
if (!changes.length) {
saveWorkspace(ws);
pushState();
}
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
checkFolders(ws);
return true;
}
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
// learns its spec late) takes the workspace with it.
function followSpecDir(state) {
const spec = specKey(state && state.specDir);
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
}
function isFolder(p) {
try {
return fs.statSync(p).isDirectory();
@@ -370,10 +449,10 @@ function checkFolders(ws) {
const marked = ws.missing.includes(f.id);
if (!there && !marked) {
ws.missing = [...ws.missing, f.id];
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
} else if (there && marked) {
ws.missing = ws.missing.filter((id) => id !== f.id);
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
}
}
}
@@ -402,8 +481,8 @@ function folderIssues(entries) {
}
function workspaceView() {
const { folders, missing, remote } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) };
const { folders, missing, remote, scope } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
}
// Whether child sits strictly under parent.
@@ -492,6 +571,7 @@ function bootWorkspace() {
saveWorkspace(ws);
}
checkFolders(ws);
followSpecDir(stateNow);
}
/**
@@ -1403,6 +1483,24 @@ const server = http.createServer((req, res) => {
});
}
// Which list the workspace is: a spec's, or the project's (`spec` empty).
// The dashboard's picker sends it as the selection moves and before a
// launch, so a skill opens on the list of the spec it was launched for.
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
try {
setScope(workspaceNow(), spec, "project");
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, workspaceView());
});
}
// Only ever returns a path: the page then adds it through /workspace/add.
if (pathname === "/workspace/browse" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
@@ -1561,6 +1659,9 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
pushState();
}
lastStateStamp = stamp;
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-02",
"releaseDate": "2026-10-04",
"mode": "utility"
}
@@ -0,0 +1,247 @@
// Plan2Code skill scripts: shared plumbing.
//
// Every script in a skill's scripts/ directory imports this file. It owns the
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
//
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
// on a handled failure.
// stderr a one-line human diagnostic on failure (the same message + next).
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
// 4 invalid input or a check that failed · 5 refused (would clobber
// or break a rule).
//
// Node 18+ built-ins only, no build step: this ships inside every skill.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
export class CliError extends Error {
constructor(exit, error, message, next) {
super(message);
this.exit = exit;
this.error = error;
this.next = next;
}
}
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
export function fail(exit, error, message, next) {
throw new CliError(exit, error, message, next);
}
export function out(obj) {
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
}
/**
* Parse argv into { _: positionals, <flag>: value }.
* `booleans` names flags that take no value; every other `--flag` takes the
* next argument, and repeats of a flag listed in `lists` collect into an array.
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
* silently changes behavior.
*/
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
const known = new Set([...booleans, ...values, ...lists, "help"]);
const args = { _: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) {
args._.push(a);
continue;
}
let name = a.slice(2);
let value;
const eq = name.indexOf("=");
if (eq !== -1) {
value = name.slice(eq + 1);
name = name.slice(0, eq);
}
if (!known.has(name)) {
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
}
if (name === "help" || booleans.includes(name)) {
args[name] = true;
continue;
}
if (value === undefined) {
if (i + 1 >= argv.length) {
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
}
value = argv[++i];
}
if (lists.includes(name)) (args[name] ||= []).push(value);
else args[name] = value;
}
return args;
}
/**
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
* failure shape plus an exit code, and anything else into exit 1 with the stack
* on stderr. Sets process.exitCode rather than calling process.exit(), so
* stdout is never cut off mid-write.
*/
export async function run(usage, main) {
try {
const argv = process.argv.slice(2);
if (argv.includes("--help") || argv.includes("-h")) {
process.stdout.write(usage.trim() + "\n");
return;
}
await main(argv);
} catch (err) {
if (err instanceof CliError) {
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
process.exitCode = err.exit;
return;
}
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
process.exitCode = EXIT.CRASH;
}
}
/* ------------------------------------------------------------------ time */
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
// is what "today" means to the person reading the date in their files.
export function now() {
const pinned = process.env.PLAN2CODE_NOW;
if (pinned) {
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
const d = new Date(pinned);
if (!Number.isNaN(d.getTime())) return d;
}
return new Date();
}
const pad = (n) => String(n).padStart(2, "0");
/** YYYY-MM-DD */
export function isoDate(d = now()) {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
/** YYYYMMDD */
export function compactDate(d = now()) {
return isoDate(d).replace(/-/g, "");
}
/** YYYY-MM-DD HH:mm */
export function stamp(d = now()) {
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** HHMMSS */
export function clock(d = now()) {
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
}
/* ----------------------------------------------------------------- files */
export function readText(file) {
try {
return fs.readFileSync(file, "utf8");
} catch {
return null;
}
}
export function isDir(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
/** Write a file only when its content changes. Returns true when it wrote. */
export function writeIfChanged(file, content) {
const current = readText(file);
if (current === content) return false;
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
return true;
}
/** Normalise line endings for parsing; keep the original for writing back. */
export function eol(text) {
return text.includes("\r\n") ? "\r\n" : "\n";
}
/**
* phase-N.md per phase number. An exact phase-N.md always wins over a sibling
* such as phase-1-old.md; more than one candidate is reported, never guessed.
* Shared so every script that counts a spec's tasks reads the same files.
*/
export function phaseFiles(dir) {
const files = new Map();
const extra = new Map();
for (const name of fs.readdirSync(dir).sort()) {
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
if (!m) continue;
const n = Number(m[1]);
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
if (!files.has(n)) files.set(n, name);
else if (exact) {
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
files.set(n, name);
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
}
files.extra = extra;
return files;
}
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
export function rel(root, p) {
return path.relative(root, p).split(path.sep).join("/") || ".";
}
/* --------------------------------------------------------- the web console */
// The web console ships beside these scripts in every installed skill
// (references/web-console/), and in this repo it sits at src/web-console/. Its
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
// metrics-bait scan, so the scripts import it rather than keep a second copy.
const CONSOLE_LIB_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
];
let consoleLibPromise;
export function consoleLib() {
consoleLibPromise ||= (async () => {
for (const candidate of CONSOLE_LIB_CANDIDATES) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-lib-missing",
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
);
})();
return consoleLibPromise;
}
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
export function version() {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const text = readText(file);
if (!text) continue;
try {
const v = JSON.parse(text).version;
if (typeof v === "string") return v;
} catch {}
}
return null;
}
@@ -0,0 +1,676 @@
#!/usr/bin/env node
// specs.mjs: where every spec under specs/ stands, read from its files.
//
// The pipeline skills (plan, document, implement, revise-plan, finalize,
// review, handoff) all need the same filesystem facts: which specs exist, what
// a spec's PLAN-DRAFT says, which phases are open, how many tasks are done.
// Those have one correct answer, so this script computes them instead of each
// prompt re-deriving them by hand. It also performs the two mechanical writes
// (a Phase Checklist marker, the archive move), with --dry-run.
//
// Shell listing only matters to people: specs/ is gitignored, so editor search
// tools skip it. This script reads the disk directly and does not care.
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";
const USAGE = `
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
node specs.mjs list [--root <dir>]
Every active spec under specs/ (never specs--completed/), newest first:
state, detail, PLAN-DRAFT files with their **Status:** line, overview,
phase count. Also the names already archived in specs--completed/.
node specs.mjs status <spec> [--root <dir>]
One spec in full: the overview's Phase Checklist, Parallel Execution
Groups, per-phase task counts by marker, task-numbering problems,
completion, the implement phase-selection verdict ("next"), the pending
phases, and consistency checks. <spec> is specs/<name>, <name>, or a path
to its overview.md.
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).
document: total_tasks, tasks_per_phase, phase_count,
parallel_groups_identified computed; pass
--set verification_items_added=N (your Verification Summary's
Added total; the VERIFICATION comments are reported as a check).
finalize: completion_rate_at_audit, tasks_completed, tasks_total; pass
--set verification_failures_found=N
--set documentation_updates_needed=N.
node specs.mjs mark <spec> --phase <N> --to open|in-progress|done [--dry-run]
Set phase N's Phase Checklist marker in overview.md ([ ], [/], [x]).
done also sets the phase file's Status line (**Status:**, **Status**:
or Status:) to Complete (and warns if tasks are unfinished); open on a
Complete phase sets it to In Progress. Warns when the phase file has no
Status line. Refuses a phase with duplicate checklist rows, and refuses
in-progress -> open (started work stays marked).
node specs.mjs archive <spec> [--dry-run]
Move specs/<name>/ to specs--completed/<name>/. Refuses if the target
exists, or if <spec> is not a folder directly under specs/.
Markers: [ ] pending · [/] in progress · [x] complete · [!] blocked · [?] assumed.
Exit: 0 ok · 2 bad arguments · 3 spec not found · 4 cannot parse / check
failed · 5 refused.
`;
/* ------------------------------------------------------------- resolving */
function realOrResolved(p) {
try {
return fs.realpathSync.native(p);
} catch {
return path.resolve(p);
}
}
const samePath = (a, b) => (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
// Read-only commands (status, metrics) accept an archived spec, because
// Finalize reads its own spec after Step 6 moved it. Writes never do.
function resolveSpec(root, arg, { allowArchived = false } = {}) {
if (!arg) fail(EXIT.USAGE, "missing-spec", "Name the spec: specs/<name>, <name>, or its overview.md path.", "Run `specs.mjs list` to see the active specs.");
let p = arg.replace(/\\/g, "/").replace(/\/+$/, "");
if (/\/overview\.md$/i.test(p) || /\/phase-[^/]*\.md$/i.test(p)) p = p.replace(/\/[^/]+$/, "");
const abs = path.isAbsolute(p) ? p : p.includes("/") ? path.join(root, p) : path.join(root, "specs", p);
const relPath = rel(root, abs);
if (!allowArchived && /(^|\/)specs--completed(\/|$)/.test(relPath)) {
fail(EXIT.REFUSED, "archived-spec", `${relPath} is archived; the pipeline only changes active specs under specs/.`, "Pick an active spec from `specs.mjs list`.");
}
// A spec is a folder directly under specs/ (or specs--completed/ for a read).
// Without this, `archive .` would move all of specs/ and `archive ./src` a
// source folder.
const homes = [path.join(root, "specs"), ...(allowArchived ? [path.join(root, "specs--completed")] : [])].map(realOrResolved);
const parent = realOrResolved(path.dirname(path.resolve(abs)));
if (!homes.some((h) => samePath(h, parent))) {
fail(EXIT.REFUSED, "not-a-spec", `${relPath} is not a spec folder: a spec sits directly under specs/${allowArchived ? " (or specs--completed/)" : ""}.`, "Pass specs/<name> or <name>; run `specs.mjs list` to see the active specs.");
}
if (!isDir(abs)) {
fail(EXIT.NOT_FOUND, "spec-not-found", `No spec folder at ${relPath}.`, "Run `specs.mjs list` from the project root (or pass --root) to see the active specs.");
}
return { dir: abs, rel: relPath, name: path.basename(abs) };
}
/* -------------------------------------------------------------- parsing */
const MARKERS = { " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" };
// Task 2.3, a lettered sub-task 3.6a, or a named one such as a testing task 1.T.
const TASK_RE = /^\s*[-*] \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
const CHECKBOX_RE = /^\s*[-*] \[(.)\]/;
// The Status line in any of the forms people write it: **Status:**, **Status**:
// or a plain Status:, optionally as a list item. Groups: everything up to the
// value (kept as written when the value is rewritten), the value, trailing blanks.
const STATUS_RE = /^([ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*)(.+?)([ \t]*)$/m;
function statusOf(text) {
const m = (text || "").match(STATUS_RE);
return m ? m[2] : null;
}
/** A markdown section's lines: from its heading to the next heading of the same or higher level. */
function section(text, headingRe) {
const lines = text.split(/\r?\n/);
const start = lines.findIndex((l) => /^#{1,6}\s/.test(l) && headingRe.test(l));
if (start === -1) return null;
const level = lines[start].match(/^#+/)[0].length;
let end = lines.length;
for (let i = start + 1; i < lines.length; i++) {
const m = lines[i].match(/^(#+)\s/);
if (m && m[1].length <= level) {
end = i;
break;
}
}
return { start, end, lines: lines.slice(start + 1, end) };
}
function plainText(s) {
return s
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/[*_`]/g, "")
.replace(/\s+/g, " ")
.trim();
}
/** Phase Checklist rows: the first "Phase N" on each checkbox line names the phase. */
function parseChecklist(overview) {
const sec = section(overview, /Phase Checklist/i);
if (!sec) return { found: false, phases: [], unparsed: [] };
const phases = [];
const unparsed = [];
sec.lines.forEach((line, i) => {
const m = line.match(CHECKBOX_RE);
if (!m) return;
const text = plainText(line.replace(CHECKBOX_RE, ""));
const num = text.match(/\bPhase\s+(\d+)\b/i);
if (!num) {
unparsed.push({ line: sec.start + 2 + i, text: line.trim() });
return;
}
const after = text.slice(num.index + num[0].length).replace(/^\s*[:\-–—]\s*/, "");
const name = after.split(/\s+[-–—]\s+|\s+\(|\s+_\(|:\s|\s+see\s+phase-/i)[0].replace(/\s*phase-\d+\.md\s*$/i, "").trim();
phases.push({
number: Number(num[1]),
marker: m[1],
state: MARKERS[m[1]] || "unknown",
name: name.replace(/\s*\[Milestone[^\]]*\]\s*$/i, "") || `Phase ${num[1]}`,
line: sec.start + 2 + i,
});
});
return { found: true, phases, unparsed };
}
/** "2, 3", "2-4" and "2–4" (or an em dash) alike: ranges expand, so a group cell never loses a phase. */
function phaseList(cell) {
const outList = [];
for (const part of cell.match(/\d+\s*[-–\u2014]\s*\d+|\d+/g) || []) {
const r = part.match(/^(\d+)\s*[-–\u2014]\s*(\d+)$/);
if (r && Number(r[2]) >= Number(r[1]) && Number(r[2]) - Number(r[1]) < 100) {
for (let n = Number(r[1]); n <= Number(r[2]); n++) outList.push(n);
} else outList.push(...part.match(/\d+/g).map(Number));
}
return [...new Set(outList)];
}
/** Parallel Execution Groups table: real groups only (a named group with 2+ phases). */
function parseGroups(overview) {
const sec = section(overview, /Parallel Execution Groups/i);
if (!sec) return { found: false, groups: [] };
const groups = [];
const seen = new Set();
for (const line of sec.lines) {
if (!/^\s*\|/.test(line) || /^\s*\|[\s:|-]+\|\s*$/.test(line)) continue;
const cells = line.split("|").slice(1, -1).map((c) => c.trim());
if (cells.length < 2 || /^group$/i.test(cells[0])) continue;
const id = plainText(cells[0]);
const phases = phaseList(cells[1]);
// "None", a dash, a single phase, a group its author labelled sequential
// ("A (sequential)"), or a Phases cell written as a chain ("1 → 2") is not
// a parallel group.
if (!id || /^(none|-|–|—)$/i.test(id) || /\bsequential\b/i.test(id) || /→|->|\bthen\b/i.test(cells[1]) || phases.length < 2) continue;
const key = `${id}:${phases.join(",")}`;
if (seen.has(key)) continue;
seen.add(key);
groups.push({ id, phases, reason: plainText(cells[2] || "") });
}
return { found: true, groups };
}
function firstSentence(text) {
const t = plainText(text);
const m = t.match(/^(.+?[.!?])(\s|$)/);
return (m ? m[1] : t).slice(0, 240);
}
function parsePhaseFile(file, number) {
const text = readText(file) || "";
const lines = text.split(/\r?\n/);
const title = (lines.find((l) => /^#\s/.test(l)) || "").replace(/^#\s+/, "").trim();
const status = statusOf(text);
const counts = { pending: 0, "in-progress": 0, complete: 0, blocked: 0, assumed: 0, unknown: 0 };
const tasks = [];
const strayCheckboxes = [];
const unmatchedTasks = [];
let heading = "";
lines.forEach((line, i) => {
const h = line.match(/^#{1,6}\s+(.*)$/);
if (h) heading = plainText(h[1]);
const t = line.match(TASK_RE);
if (t) {
const state = MARKERS[t[1]] || "unknown";
counts[state]++;
const named = !/^\d+$/.test(t[3]);
tasks.push({ id: `${t[2]}.${t[3]}${t[4]}`, phase: Number(t[2]), seq: named ? null : Number(t[3]), named, suffix: t[4], marker: t[1], state, line: i + 1 });
return;
}
// A line that looks like a task but is not counted as one (Task 1.4A,
// "1. [ ] **Task", a non-bold "- [ ] Task 1.3") would make the audit undercount.
if (/^\s*(?:[-*]|\d+\.)\s+\[.\].*\bTask\s+\d+\./i.test(line)) unmatchedTasks.push({ line: i + 1, text: line.trim().slice(0, 120) });
if (CHECKBOX_RE.test(line)) strayCheckboxes.push({ line: i + 1, section: heading, text: line.trim().slice(0, 120) });
});
// Numbering: every task belongs to this phase, the base numbers run 1..n with
// no gaps or repeats, and a lettered task (3.6a) sits after its base (3.6).
// Named tasks (1.T) are outside the numeric sequence.
const numbering = [];
const bases = [];
for (const t of tasks) {
if (t.phase !== number) numbering.push(`Task ${t.id} is in phase-${number}.md but numbered for Phase ${t.phase}`);
if (!t.suffix && !t.named) bases.push(t.seq);
}
const seenIds = new Set();
for (const t of tasks) {
if (seenIds.has(t.id)) numbering.push(`Task ${t.id} appears more than once`);
seenIds.add(t.id);
if (t.suffix && !t.named && !bases.includes(t.seq)) numbering.push(`Task ${t.id} has no base Task ${t.phase}.${t.seq}`);
}
bases.forEach((seq, i) => {
if (seq !== i + 1 && !numbering.some((n) => n.startsWith("Task numbering"))) {
numbering.push(`Task numbering is not sequential: expected ${number}.${i + 1}, found ${number}.${seq}`);
}
});
const overviewSec = section(text, /^#{1,6}\s+Overview\b/i);
const goalText = overviewSec ? overviewSec.lines.join("\n").split(/\n\s*\n/).map((p) => p.trim()).find((p) => p && !/^[-*|>]/.test(p)) : "";
return {
title,
status,
goal: goalText ? firstSentence(goalText) : null,
total: tasks.length,
counts,
open: counts.pending + counts["in-progress"] + counts.blocked + counts.unknown,
// Open work a phase cannot be approved over; blocked tasks may stand ([!] is allowed at sign-off).
unfinished: counts.pending + counts["in-progress"] + counts.unknown,
tasks,
numbering,
strayCheckboxes,
unmatchedTasks,
};
}
function planDrafts(dir) {
return fs
.readdirSync(dir)
.filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n))
.sort()
.map((file) => ({
file,
archived: /-prev\.md$/i.test(file),
status: statusOf(readText(path.join(dir, file))),
}));
}
/* ---------------------------------------------------------------- status */
function specStatus(spec) {
const overviewPath = path.join(spec.dir, "overview.md");
const overview = readText(overviewPath);
const files = phaseFiles(spec.dir);
// An empty overview.md still exists; only a missing one is "no overview".
const hasOverview = overview !== null;
const checklist = hasOverview ? parseChecklist(overview) : { found: false, phases: [], unparsed: [] };
const groups = hasOverview ? parseGroups(overview) : { found: false, groups: [] };
const checks = [];
const check = (level, code, message) => checks.push({ level, code, message });
for (const [n, names] of files.extra) {
check("warn", "duplicate-phase-file", `Phase ${n} has more than one file: using ${files.get(n)}, ignoring ${names.join(", ")}`);
}
const rowsByNumber = new Map();
for (const r of checklist.phases) rowsByNumber.set(r.number, [...(rowsByNumber.get(r.number) || []), r]);
for (const [n, rows] of rowsByNumber) {
if (rows.length > 1) check("error", "duplicate-checklist-row", `Phase ${n} has ${rows.length} rows in the Phase Checklist (overview.md lines ${rows.map((r) => r.line).join(", ")}); the first one is used`);
}
const phases = [];
const numbers = new Set([...checklist.phases.map((p) => p.number), ...files.keys()]);
for (const number of [...numbers].sort((a, b) => a - b)) {
const row = checklist.phases.find((p) => p.number === number) || null;
const file = files.get(number) || null;
const parsed = file ? parsePhaseFile(path.join(spec.dir, file), number) : null;
phases.push({
number,
name: row ? row.name : parsed ? parsed.title.replace(/^Phase\s+\d+\s*[:\-–—]?\s*/i, "") : `Phase ${number}`,
checklist: row ? row.state : null,
marker: row ? row.marker : null,
file,
status: parsed ? parsed.status : null,
goal: parsed ? parsed.goal : null,
tasks: parsed ? { total: parsed.total, open: parsed.open, ...parsed.counts } : null,
blockedTasks: parsed ? parsed.tasks.filter((t) => t.state === "blocked").map((t) => t.id) : [],
assumedTasks: parsed ? parsed.tasks.filter((t) => t.state === "assumed").map((t) => t.id) : [],
openTasks: parsed ? parsed.tasks.filter((t) => ["pending", "in-progress", "blocked", "unknown"].includes(t.state)).map((t) => t.id) : [],
});
if (!row && hasOverview) check("error", "missing-checklist-row", `phase-${number}.md has no row in overview.md's Phase Checklist`);
if (row && !file) check("error", "missing-phase-file", `Phase Checklist lists Phase ${number} but there is no phase-${number}.md`);
if (parsed) {
for (const n of parsed.numbering) check("error", "task-numbering", `phase-${number}.md: ${n}`);
// Prerequisites and criteria are plain bullets by rule; other checkbox
// blocks (a Phase Testing list) are the template's own and are not tasks.
for (const s of parsed.strayCheckboxes.filter((c) => /prerequisite|criteria/i.test(c.section))) {
check("warn", "criteria-checkbox", `phase-${number}.md:${s.line} is a checkbox under "${s.section}"; prerequisites and criteria use plain bullets`);
}
if (parsed.total === 0) check("warn", "no-tasks", `phase-${number}.md has no **Task ${number}.N:** checkbox lines`);
for (const u of parsed.unmatchedTasks) {
check("warn", "uncounted-task", `phase-${number}.md:${u.line} looks like a task but is not counted (a task line is "- [ ] **Task ${number}.N:**"): ${u.text}`);
}
const done = parsed.counts.complete + parsed.counts.assumed;
const rowDone = row && (row.state === "complete" || row.state === "assumed");
// A phase may be approved with blocked [!] tasks left (Implementation
// Mode's self-review allows "[x] or blocked [!]"); only unfinished work is an error.
if (rowDone && parsed.unfinished > 0) {
check("error", "checked-with-open-tasks", `Phase ${number} is [${row.marker}] in overview.md but ${parsed.unfinished} task(s) are not done (${phases.at(-1).openTasks.filter((id) => !phases.at(-1).blockedTasks.includes(id)).join(", ")})`);
} else if (rowDone && parsed.counts.blocked > 0) {
check("info", "approved-with-blocked", `Phase ${number} is [${row.marker}] with ${parsed.counts.blocked} blocked task(s) (${phases.at(-1).blockedTasks.join(", ")})`);
}
if (row && row.state === "pending" && parsed.total > 0 && done > 0) {
// Done tasks under a [ ] phase with work still open is what a re-opened
// phase looks like (revise-plan); with nothing open it is a missed mark.
if (parsed.unfinished > 0) check("info", "partly-done-unchecked", `Phase ${number} is [ ] with ${done} task(s) done and ${parsed.unfinished} open (normal for a re-opened phase)`);
else check("warn", "unchecked-with-done-tasks", `Phase ${number} is [ ] in overview.md but all ${done} unblocked task(s) are done`);
}
if (row && !rowDone && row.state !== "pending" && parsed.total > 0 && parsed.unfinished === 0) {
check("info", "done-not-approved", `Phase ${number}: every task is done but overview.md still shows [${row.marker}] (normal until the user approves the phase)`);
}
}
}
if (!hasOverview) check("error", "no-overview", `${spec.rel} has no overview.md`);
else if (!checklist.found) check("error", "no-checklist", "overview.md has no ## Phase Checklist section");
for (const u of checklist.unparsed) check("warn", "unparsed-checklist-row", `overview.md:${u.line} is a checkbox in the Phase Checklist with no "Phase N" in it: ${u.text}`);
for (const g of groups.groups) {
for (const n of g.phases) if (!numbers.has(n)) check("error", "group-unknown-phase", `Parallel group ${g.id} names Phase ${n}, which does not exist`);
}
// Totals. Completed = [x] plus [?] (assumed complete); [?] is reported on its own too.
// Incomplete = [ ] + [/] (+ unreadable markers); Blocked is its own column.
const totals = { total: 0, complete: 0, assumed: 0, pending: 0, "in-progress": 0, blocked: 0, unknown: 0 };
for (const p of phases) if (p.tasks) for (const k of Object.keys(totals)) totals[k] += p.tasks[k] || 0;
const completed = totals.complete + totals.assumed;
const completion = totals.total ? completed / totals.total : null;
return {
ok: true,
spec: spec.rel,
name: spec.name,
overview: hasOverview ? "overview.md" : null,
planDrafts: planDrafts(spec.dir),
phases,
parallelGroups: groups.groups,
totals: { ...totals, completed, incomplete: totals.pending + totals["in-progress"] + totals.unknown },
completion: completion === null ? null : Number(completion.toFixed(4)),
completionPercent: completion === null ? null : Math.round(completion * 100),
next: nextPhase(phases, groups.groups, checklist.found),
pending: phases
.filter((p) => p.checklist && p.checklist !== "complete" && p.checklist !== "assumed")
.map((p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null, open: p.tasks ? p.tasks.open : null, goal: p.goal })),
checks,
};
}
/**
* Implementation Mode's phase-selection table, applied mechanically.
* 2+ workable phases in the same parallel group, consecutive -> choose (warn if all [/])
* a single [/] -> ask-resume · a single [ ] -> auto-start · nothing workable -> none
*/
function nextPhase(phases, groups, haveChecklist) {
if (!haveChecklist) return { action: "none", reason: "no Phase Checklist in overview.md" };
const ordered = phases.filter((p) => p.checklist);
const isDone = (p) => p.checklist === "complete" || p.checklist === "assumed";
const workable = ordered.filter((p) => p.checklist === "pending" || p.checklist === "in-progress");
if (!workable.length) {
return { action: "none", reason: ordered.length && ordered.every(isDone) ? "every phase is complete" : "no [ ] or [/] phase in the Phase Checklist" };
}
const first = workable[0];
const brief = (p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null });
// A blocked [!] phase ahead of the pick is skipped, but never silently.
const skipped = ordered.slice(0, ordered.indexOf(first)).filter((p) => !isDone(p)).map(brief);
const note = skipped.length ? { skipped, warning: `skipping ${skipped.map((p) => `Phase ${p.number} [${p.state}]`).join(", ")} ahead of it` } : {};
const group = groups.find((g) => g.phases.includes(first.number));
if (group) {
// Consecutive same-group incomplete phases, in checklist order, starting at the first workable one.
const run = [];
for (const p of ordered.slice(ordered.indexOf(first))) {
if (!group.phases.includes(p.number)) break;
if (isDone(p)) continue;
if (p.checklist === "pending" || p.checklist === "in-progress") run.push(p);
else break;
}
if (run.length >= 2) {
const allStarted = run.every((p) => p.checklist === "in-progress");
const warnings = [
...(allStarted ? ["every option is already [/]: another agent may be working on it, so picking one risks duplicated work"] : []),
...(note.warning ? [note.warning] : []),
];
return {
action: "choose",
group: group.id,
options: run.map(brief),
...(note.skipped ? { skipped: note.skipped } : {}),
...(warnings.length ? { warning: warnings.join("; ") } : {}),
};
}
}
return { action: first.checklist === "in-progress" ? "ask-resume" : "auto-start", phase: brief(first), ...note };
}
/* --------------------------------------------------------------- commands */
async function cmdList(args) {
const root = path.resolve(args.root || ".");
const { scanProject } = await consoleLib();
const scan = scanProject(root);
const specs = scan.specs.map((s) => {
const dir = path.join(root, s.dir);
let names = [];
try {
names = fs.readdirSync(dir);
} catch {}
return {
dir: s.dir,
name: s.name,
state: s.state,
detail: s.detail,
touched: s.touched ? new Date(s.touched).toISOString() : null,
planDrafts: planDrafts(dir),
overview: names.includes("overview.md"),
phaseFiles: names.filter((n) => /^phase-\d+\b.*\.md$/i.test(n)).length,
pathfinder: isDir(path.join(dir, "pathfinder")),
};
});
let completed = [];
try {
completed = fs.readdirSync(path.join(root, "specs--completed")).filter((n) => isDir(path.join(root, "specs--completed", n))).sort();
} catch {}
out({
ok: true,
root,
hasAgents: scan.hasAgents,
specsDir: isDir(path.join(root, "specs")),
specs,
completed,
...(specs.length ? {} : { note: "No active specs under specs/." }),
});
}
async function cmdStatus(args) {
const root = path.resolve(args.root || ".");
out(specStatus(resolveSpec(root, args._[1], { allowArchived: true })));
}
function countVerificationAdded(dir) {
let n = 0;
for (const name of fs.readdirSync(dir)) {
if (!/\.md$/i.test(name) || /^PLAN-/i.test(name)) continue;
n += ((readText(path.join(dir, name)) || "").match(/<!--\s*VERIFICATION:\s*Added\b/gi) || []).length;
}
return n;
}
async function cmdMetrics(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1], { allowArchived: true });
const step = args.step;
if (step !== "document" && step !== "finalize") fail(EXIT.USAGE, "bad-step", "--step must be document or finalize.", "Plan's METRICS_JSON is written by hand in its Phase 7.");
const sets = {};
for (const kv of args.set || []) {
const m = kv.match(/^([a-z_]+)=(-?\d+(?:\.\d+)?)$/);
if (!m) fail(EXIT.USAGE, "bad-set", `--set ${kv} is not key=number.`, "Example: --set verification_failures_found=1");
sets[m[1]] = Number(m[2]);
}
// --set supplies the judgment fields only; the computed ones are never overridden.
const SETTABLE = { document: ["verification_items_added"], finalize: ["verification_failures_found", "documentation_updates_needed"] };
for (const k of Object.keys(sets)) {
if (!SETTABLE[step].includes(k)) fail(EXIT.USAGE, "bad-set", `--set ${k} is not a field you supply for --step ${step}.`, `Only ${SETTABLE[step].join(", ")}; the rest is computed from the files.`);
}
const st = specStatus(spec);
const withTasks = st.phases.filter((p) => p.tasks);
let metrics;
let hint;
if (step === "document") {
// verification_items_added is the Added total of the Verification Summary
// you presented, not something the files record, so it comes from --set.
// The <!-- VERIFICATION: Added --> comments are a cross-check only.
if (!("verification_items_added" in sets)) fail(EXIT.USAGE, "missing-set", "document needs --set verification_items_added=N (the Added column total of your Verification Summary).", `The spec has ${countVerificationAdded(spec.dir)} <!-- VERIFICATION: Added --> comment(s), as a cross-check.`);
metrics = {
step: "document",
total_tasks: st.totals.total,
tasks_per_phase: withTasks.map((p) => p.tasks.total),
phase_count: st.phases.length,
parallel_groups_identified: st.parallelGroups.length,
...sets,
};
hint = { verificationCommentsFound: countVerificationAdded(spec.dir) };
} else {
const missing = ["verification_failures_found", "documentation_updates_needed"].filter((k) => !(k in sets));
if (missing.length) fail(EXIT.USAGE, "missing-set", `finalize needs ${missing.map((k) => `--set ${k}=N`).join(" and ")}.`, "Those two counts are your judgment from Steps 2 and 4.");
metrics = {
step: "finalize",
completion_rate_at_audit: st.completion === null ? 0 : Number(st.completion.toFixed(2)),
tasks_completed: st.totals.completed,
tasks_total: st.totals.total,
...sets,
};
}
out({ ok: true, spec: spec.rel, metrics, comment: `<!-- METRICS_JSON ${spacedJson(metrics)} -->`, ...(hint || {}), checks: st.checks.filter((c) => c.level === "error") });
}
// The house style of every METRICS_JSON comment: {"key": value, "list": [1, 2]}.
function spacedJson(obj) {
const v = (x) => (Array.isArray(x) ? `[${x.map(v).join(", ")}]` : x && typeof x === "object" ? spacedJson(x) : JSON.stringify(x));
return `{${Object.entries(obj).map(([k, x]) => `${JSON.stringify(k)}: ${v(x)}`).join(", ")}}`;
}
const TO = { open: " ", "in-progress": "/", done: "x" };
async function cmdMark(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1]);
const number = Number(args.phase);
if (!Number.isInteger(number) || number < 0) fail(EXIT.USAGE, "bad-phase", "--phase needs a phase number.", "Example: --phase 2");
if (!(args.to in TO)) fail(EXIT.USAGE, "bad-to", "--to must be open, in-progress or done.", "open = [ ], in-progress = [/], done = [x]");
const overviewPath = path.join(spec.dir, "overview.md");
const overview = readText(overviewPath);
if (overview === null) fail(EXIT.NOT_FOUND, "no-overview", `${spec.rel} has no overview.md.`, "Run /plan2code-2-document first.");
const checklist = parseChecklist(overview);
const rows = checklist.phases.filter((p) => p.number === number);
const row = rows[0];
if (!row) fail(EXIT.NOT_FOUND, "no-row", `overview.md's Phase Checklist has no row for Phase ${number}.`, "Run `specs.mjs status` to see the phases it lists.");
if (rows.length > 1) fail(EXIT.REFUSED, "duplicate-row", `Phase ${number} has ${rows.length} rows in the Phase Checklist (lines ${rows.map((r) => r.line).join(", ")}); marking one would be a guess.`, "Remove the duplicate row, then rerun.");
const target = TO[args.to];
if (row.marker === "/" && target === " ") {
fail(EXIT.REFUSED, "no-reset", `Phase ${number} is [/]; started work is never reset to [ ].`, "Leave it [/] (a later session resumes it), or mark it done once approved.");
}
const changes = [];
const lines = overview.split(/\r?\n/);
const idx = row.line - 1;
const next = lines[idx].replace(/\[(.)\]/, `[${target}]`);
if (next !== lines[idx]) {
lines[idx] = next;
changes.push({ file: `${spec.rel}/overview.md`, line: row.line, from: `[${row.marker}]`, to: `[${target}]` });
}
// The phase file's Status line follows: done -> Complete; re-opening a Complete
// phase -> In Progress (revise-plan), so the two files never disagree.
let phaseText = null;
let phasePath = null;
let unfinished = [];
const warnings = [];
const file = phaseFiles(spec.dir).get(number);
if (file) {
phasePath = path.join(spec.dir, file);
const text = readText(phasePath) || "";
const parsed = parsePhaseFile(phasePath, number);
unfinished = parsed.tasks.filter((t) => ["pending", "in-progress", "unknown"].includes(t.state)).map((t) => t.id);
const status = statusOf(text);
const want = target === "x" ? "Complete" : target === " " && status && /^complete$/i.test(status) ? "In Progress" : null;
if (status && want && status !== want) {
phaseText = text.replace(STATUS_RE, (_, before, _value, after) => before + want + after);
changes.push({ file: `${spec.rel}/${file}`, field: "Status", from: status, to: want });
}
// done and open keep the Status line in step; with none to find, say so.
if (!status && target !== "/") warnings.push(`${file} has no Status line, so only the Phase Checklist checkbox changed; add a "**Status:** <value>" line under its title.`);
}
if (!args["dry-run"]) {
if (changes.some((c) => c.file.endsWith("overview.md"))) fs.writeFileSync(overviewPath, lines.join(eol(overview)));
if (phaseText !== null) fs.writeFileSync(phasePath, phaseText);
}
const doneEarly = target === "x" && unfinished.length > 0;
if (doneEarly) warnings.unshift(`Phase ${number} was marked done with ${unfinished.length} unfinished task(s): ${unfinished.join(", ")}. Mark only a phase the user approved.`);
out({
ok: true,
spec: spec.rel,
phase: number,
name: row.name,
dryRun: !!args["dry-run"],
changed: changes.length > 0,
changes,
...(warnings.length ? { warning: warnings.join(" ") } : {}),
...(doneEarly ? { unfinished } : {}),
});
}
function listRel(dir, base = dir) {
const outList = [];
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) outList.push(...listRel(p, base));
else outList.push(rel(base, p));
}
return outList.sort();
}
async function cmdArchive(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1]);
const target = path.join(root, "specs--completed", spec.name);
if (fs.existsSync(target)) {
fail(EXIT.REFUSED, "target-exists", `specs--completed/${spec.name}/ already exists; nothing was moved.`, "Ask the user whether to merge by hand or archive under another name.");
}
const files = listRel(spec.dir);
if (!args["dry-run"]) {
fs.mkdirSync(path.dirname(target), { recursive: true });
try {
fs.renameSync(spec.dir, target);
} catch (err) {
// A rename across volumes (or a locked file on Windows) fails; copy then remove.
try {
fs.cpSync(spec.dir, target, { recursive: true, errorOnExist: true, force: false });
} catch (copyErr) {
fail(EXIT.INVALID, "archive-failed", `Could not move or copy ${spec.rel} (${err.code || err.message}; copy: ${copyErr.code || copyErr.message}).`, `Close anything holding files in ${spec.rel} open, check specs--completed/${spec.name} for a partial copy, then rerun.`);
}
try {
fs.rmSync(spec.dir, { recursive: true, force: true });
} catch (rmErr) {
fail(EXIT.INVALID, "source-not-removed", `Copied to specs--completed/${spec.name}/ but could not remove ${spec.rel} (${rmErr.code || rmErr.message}); both copies now exist.`, `Close whatever holds files in ${spec.rel} open, then delete it by hand. The archive is complete.`);
}
}
}
const sourceGone = args["dry-run"] ? null : !fs.existsSync(spec.dir);
const moved = args["dry-run"] ? null : listRel(target);
if (!args["dry-run"] && !(sourceGone && moved.length === files.length)) {
fail(
EXIT.INVALID,
"archive-unverified",
`The move of ${spec.rel} to specs--completed/${spec.name}/ did not verify: ${moved.length} of ${files.length} file(s) at the target, and ${spec.rel} ${sourceGone ? "is gone" : "still exists"}.`,
`Compare ${spec.rel} with specs--completed/${spec.name}/ and finish the move by hand; archive refuses to rerun while the target exists.`
);
}
out({
ok: true,
dryRun: !!args["dry-run"],
from: spec.rel,
to: `specs--completed/${spec.name}`,
files,
...(args["dry-run"] ? {} : { sourceRemoved: sourceGone, filesAtTarget: moved.length, archivedOn: isoDate() }),
});
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "step", "phase", "to"], lists: ["set"] });
const cmd = args._[0];
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, archive: cmdArchive };
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, metrics, mark, archive. Run with --help.");
await commands[cmd](args);
});
@@ -0,0 +1,22 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"mode": "utility"
}
+1 -1
View File
@@ -101,7 +101,7 @@ Only this prompt can obtain phase approval.
When the user replies `approved` to the final sign-off:
1. Run Implementation Mode's `After Approval / Session End` actions.
2. Mark overview.md `[/]` to `[x]` and set the phase status to `Complete`.
2. Mark overview.md `[/]` to `[x]` and set the phase status to `Complete` (`specs.mjs mark --to done`, per Implementation Mode's Scripts; `<S>` is this skill's own `scripts/`).
3. Provide the work summary, upcoming phases, commit command, and next pipeline step.
4. Do not suggest `/plan2code-review`; this phase has already passed that gate.
5. Mention `/plan2code-1b-revise-plan` only when it remains relevant.
@@ -10,6 +10,14 @@ Senior software engineer implementing solutions exactly as specified. Follow spe
The FIRST thing you do, before anything else in this file — before reading a spec, before Phase 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow implement` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-3-implement/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then <D>/console.md and <D>/building.md; progress, every question and the sign-off 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.md → Launches), then the spec.
## Scripts
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-3-implement/scripts/` globally; for Implement + Review, its own skill's `scripts/`). Run them 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" status <spec>`: the Phase Checklist, parallel groups, every phase's task counts by marker, goal, the phase-selection verdict (`next`) and consistency `checks`.
- `node "<S>/specs.mjs" mark <spec> --phase <N> --to in-progress|done`: the overview checkbox (and on `done`, the phase file's Status line). It refuses to reset `[/]` to `[ ]`.
- `node "<S>/commit-msg.mjs" --subject "<subject>" --add-all`: the commit command, ticket taken from the branch.
## Rules
- Follow `./AGENTS.md` if it exists
@@ -25,28 +33,15 @@ The FIRST thing you do, before anything else in this file — before reading a s
## Required Context
⚠️ IMPORTANT: `specs/` is gitignored — NEVER use Glob (silently fails). Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
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/`.
Need implementation spec files to proceed.
**Option 1: User provides an overview.md path** → `specs.mjs status <that path>`.
**IMPORTANT:** Never look in `specs--completed/` (archived only). Only check active spec folders under `specs/`.
**Option 2: Auto-detect** → `specs.mjs list`. Exactly one spec with phases (`phaseFiles` > 0) → `status` it.
**Option 1: User provides overview.md path**
1. Read the overview.md file
2. Find "Phase Checklist" section
3. Identify workable phases: `[ ]` (pending) or `[/]` (in-progress)
4. Check for parallel execution options
5. Apply phase selection logic
6. Read corresponding `phase-X.md` from same directory
7. Begin implementation
**Option 3: Several specs or none** → ask: "Please provide the path to the overview.md file (e.g., `specs/user-authentication/overview.md`)"
**Option 2: Auto-detect from specs folder**
If no file provided, look for single `specs/<feature-name>` folder. If found, read its `overview.md` and follow Option 1.
**Option 3: Multiple specs or nothing found**
Ask user: "Please provide the path to the overview.md file (e.g., `specs/user-authentication/overview.md`)"
Do not proceed without successfully reading overview.md and determining the next phase.
Then read overview.md and act on `next` (Parallel Phase Selection below). Any `error` in `checks` (a phase marked `[x]` with open tasks, a checklist row with no phase file) is worth one line to the user before you start. Do not proceed without a readable overview.md and a `next` verdict.
## Phase Status Tracking
@@ -70,16 +65,16 @@ Never reset `[/]` to `[ ]`. Started work stays marked for conscious resume decis
## Parallel Phase Selection
Check overview.md for "Parallel Execution Groups" section. Find workable phases (`[ ]` or `[/]`).
`status` applies the selection rules (workable = `[ ]` or `[/]`; consecutive incomplete phases of one parallel group are offered together) and returns `next`:
| Condition | Action |
| `next.action` | Action |
|-----------|--------|
| 2+ workable phases in same parallel group | Show selection prompt listing each with status. TIP: run another agent on a different phase simultaneously. If all are `[/]`, warn about duplication. |
| Single `[/]` phase | Prompt: "Phase X is in progress. Resume? (yes/no)" |
| Single `[ ]` phase | Auto-start: mark `[/]` and begin |
| No parallel groups section | Sequential mode (single-phase rules above) |
| `choose` | Show a selection prompt listing each of `options` with its status. TIP: run another agent on a different phase simultaneously. Relay `warning` (all already `[/]`: duplicated work) when present. |
| `ask-resume` | Prompt: "Phase X is in progress. Resume? (yes/no)" Relay `warning` when present. |
| `auto-start` | Mark it `[/]` and begin. Relay `warning` when present. |
| `none` | Nothing to implement: say why (`reason`). Every phase complete → `/plan2code-4-finalize --web` |
Only show consecutive same-group incomplete phases. After selection, mark `[/]`, read `phase-X.md`, begin.
After selection, `mark --to in-progress`, read `phase-X.md`, begin.
## Code Consistency Rules
@@ -103,11 +98,9 @@ Only show consecutive same-group incomplete phases. After selection, mark `[/]`,
### 1. Identify and Claim Phase
Review `overview.md`, find workable phases (`[ ]` or `[/]`). Apply parallel selection logic.
Act on `status`'s `next` (Parallel Phase Selection above).
**Once selected:**
- If `[ ]`: Update to `[/]` in overview.md
- If `[/]`: No change needed
**Once selected:** `specs.mjs mark <spec> --phase <N> --to in-progress` (a no-op when it is already `[/]`).
State: `⚡ [PHASE X: Phase Name] - Marking in-progress and starting`
@@ -168,7 +161,7 @@ See "After Approval / Session End" section below.
| 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): ask if should continue with next. Large (>40): warn at start.
Default: ONE phase per conversation. Small phase (<5 tasks in `status`): ask if should continue with next. Large (>40): warn at start.
## Templates
@@ -205,18 +198,17 @@ Sections: Summary (2-3 sentences), Tasks Completed (Y/Z + blocked list), Test Re
### After Approval / Session End
On user "approved":
1. Mark `[/]` → `[x]` in overview.md, update phase-X.md status to "Complete"
1. `specs.mjs mark <spec> --phase <N> --to done`: overview `[/]` → `[x]` and phase-X.md Status "Complete"
2. Show Planny art with completion message
3. Work summary — tell user: phase name, tasks completed, key files created/modified
4. **Upcoming phases** — read overview.md Phase Checklist, find next 2-3 pending (`[ ]`) phases. For each, peek at its `phase-X.md` for task count and goal. Present a table so the user can assess stopping points and review gates:
4. **Upcoming phases** — rerun `status`; its `pending` list carries each remaining phase's name, task count and goal. Present the next 2-3 as a table so the user can assess stopping points and review gates (tighten a goal to one sentence if it runs long):
| Phase | Tasks | Goal |
|-------|-------|------|
| Phase X: [Name] | Y | [One-sentence goal] |
| Phase X+1: [Name] | Z | [One-sentence goal] |
5. Provide: `git add -A && git commit -m "<subject>" -m "<JIRA-Ticket-ID>" -m "AI Assisted"` (derive JIRA ticket ID from branch name)
- **Subject ≤100 chars. EXACTLY THREE -m flags — no body. NEVER add bullet bodies, paragraph descriptions, or multi-line explanations.** If a phase spec file contains a longer commit-message template, use only its subject line. The diff is the body; the PR is the explanation.
5. Write a one-line subject for the phase, then give the user the `command` from `commit-msg.mjs --subject "<subject>" --add-all`. It enforces the format: subject ≤100 chars and EXACTLY THREE -m flags (subject, ticket, `AI Assisted`), no body. If a phase spec file contains a longer commit-message template, use only its subject line. The diff is the body; the PR is the explanation. On Windows PowerShell 5.1 (no `&&`), give `add` and `commit` as two commands instead. Exit 4 `no-ticket`: ask the user for the ticket and rerun with `--ticket`, or show the command with `<JIRA-Ticket-ID>` for them to fill in.
6. **If more phases:** "NEXT STEP: Start NEW conversation and run: `/plan2code-3-implement --web`"
7. **If final phase:** "NEXT STEP: Start NEW conversation and run: `/plan2code-4-finalize --web`"
8. Mention `/plan2code-1b-revise-plan --web` option
@@ -10,6 +10,14 @@ Critical review specialist -- experienced senior engineer providing independent
The FIRST thing you do, before anything else in this file — before the scope detection: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow review` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md. Scope questions, the findings report and the pick-what-gets-fixed menu all go through it; the report lands on the page as a doc. 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.md → Launches), then Process. Read inside a build session for its review button? Skip this section — building.md's overrides govern, the session is already running. On the console, a `__stop` action is the person ending the session (console.md → Stop requests); 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.md → Finishing).
## Scripts
`<S>` is `scripts/` beside the SKILL.md that loaded this file (`~/.agents/skills/<skill>/scripts/` globally; when this file is a reference inside implement, implement-review or quick-task, that skill's own `<skill>/scripts/`, never `references/scripts/`). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
- `node "<S>/review-scope.mjs" [--base <branch>]`: the branch-review scope from git (Step 1).
- `node "<S>/specs.mjs" list` / `status <spec>`: spec state on disk (Step 2, Session End routing).
- `node "<S>/commit-msg.mjs" --subject "<subject>" --files <path> [--files <path> ...]`: the commit command (one `--files` per path).
## Rules
- Follow `./AGENTS.md` if it exists -- use all rules and conventions. If missing, warn and proceed with caution.
@@ -40,7 +48,7 @@ Three levels -- auto-detected, always respect explicit user override:
**User override:** If user specifies scope, use exactly that. Never silently narrow.
**Doc review:** >70% doc files = editorial critique. >70% code = also verify related docs match.
**Doc review:** >70% doc files = editorial critique. >70% code = also verify related docs match. (`review-scope.mjs` reports this as `mix`: `docs`, `code` or `mixed`; for a Focused scope, count the named files the same way.)
## Process
@@ -54,7 +62,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. **Git fallback** — `git status`, `git diff`, `git log main..HEAD --oneline`, `git diff --name-only main..HEAD`. Nothing? Ask user.
3. **Git fallback** — run `review-scope.mjs`. It 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.
**Classify review type** from context (auto-detect; use `ask_user_question` only if ambiguous):
@@ -69,13 +77,13 @@ Three levels -- auto-detected, always respect explicit user override:
| >70% .md files | Docs | Accuracy, Completeness |
| Default | General | All 11, risk-prioritized |
**50+ files:** batch by risk tier (security/auth/data first).
**50+ files** (`batchByRisk`): batch by risk tier (security/auth/data first).
> 🔬 [Review Mode] [X] files, ~[Y] lines. Type: [type]. Focus: [prioritized dimensions].
### Step 2: Context
1. **Specs?** Read `overview.md` + recent `phase-X.md`.
1. **Specs?** `specs.mjs list` (it reads gitignored `specs/`, which file search skips), then read `overview.md` + recent `phase-X.md`.
2. **AGENTS.md** for conventions.
3. **Tech stack** -- check for deprecations, CVEs, breaking changes.
4. **Classify:** >70% docs = doc review. >70% code = verify docs match.
@@ -167,9 +175,9 @@ Work summary — tell user: scope reviewed, findings count by severity (Critical
Read references/session-end.md
> Fallback: route plan2code artifacts (plan/spec docs/phases) on the reviewed feature's own `specs/<feature>/` state to the earliest unmet pipeline stage whose input exists — `PLAN-*` or `overview.md` without `phase-*.md` → `/plan2code-2-document`; unchecked `- [ ]` phase tasks → `/plan2code-3-implement`; all checked → `/plan2code-4-finalize`; archived → complete, summary only. Verify `specs/` on disk with a terminal `ls`/`Get-ChildItem` — it's gitignored, so search tools miss it and an empty result proves nothing. Non-pipeline artifacts (code/PRs/docs/logs) → summary only. Unresolved Criticals → fixing them (H/A/S) is the next step. Ambiguous or multiple candidate specs → ask one targeted question. Output: "Next (NEW conversation): `/plan2code-<step>` — [why + how you know]", appending ` --web` when the routed step offers the web console; else "Review complete -- [summary]."
> Fallback: route plan2code artifacts (plan/spec docs/phases) on the reviewed feature's own `specs/<feature>/` state to the earliest unmet pipeline stage whose input exists — `PLAN-*` or `overview.md` without `phase-*.md` → `/plan2code-2-document`; unchecked `- [ ]` phase tasks → `/plan2code-3-implement`; all checked → `/plan2code-4-finalize`; archived → complete, summary only. Read the state with `specs.mjs status <spec>` (gitignored `specs/` defeats search tools). Non-pipeline artifacts (code/PRs/docs/logs) → summary only. Unresolved Criticals → fixing them (H/A/S) is the next step. Ambiguous or multiple candidate specs → ask one targeted question. Output: "Next (NEW conversation): `/plan2code-<step>` — [why + how you know]", appending ` --web` when the routed step offers the web console; else "Review complete -- [summary]."
- **Commit** (code changes): `git add [files] && git commit -m "fix: [desc]" -m "<JIRA>" -m "AI Assisted"` -- derive JIRA from branch.
- **Commit** (code changes): the `command` from `commit-msg.mjs --subject "fix: [desc]" --files <file>` repeated once per fixed file (ticket from the branch; exit 4 `no-ticket`: show it with `<JIRA>` for the user to fill in). On Windows PowerShell 5.1 (no `&&`), give `add` and `commit` as two commands.
```
⋅
@@ -5,7 +5,7 @@ Principles to reason from, not a lookup table — adapt; when a case doesn't fit
cleanly, say what you verified and ask.
- **Plan2Code Workflow Pipeline:** `/plan2code-1-plan` → `PLAN-*` files · `/plan2code-2-document` → `overview.md` + `phase-*.md` (the "spec docs") in `specs/<feature>/` · `/plan2code-3-implement` → checks off phase tasks, one phase per run · `/plan2code-4-finalize` → archives to `specs--completed/`.
- **Find specs (any OS/shell):** `specs/` is gitignored, and search tools (Glob/Grep/project search) skip gitignored paths on many platforms — an empty search result is not evidence either way. Check with a terminal listing: `ls specs/<feature>/` (bash/zsh) · `Get-ChildItem specs/<feature>` (PowerShell) · `dir specs\<feature>` (cmd). Feature dir unknown? List `specs/` first. Command errors? Try another shell's form, then read the expected files directly — file reads see gitignored paths. Conclude "no specs" only after a terminal listing or a failed direct read.
- **Find specs (any OS/shell):** `specs/` is gitignored, and search tools (Glob/Grep/project search) skip gitignored paths on many platforms — an empty search result is not evidence either way. Use `node "<S>/specs.mjs" list` (`<S>`: see Review Mode → Scripts) (feature dir unknown, or to see what is archived in `completed`) and `node "<S>/specs.mjs" status <spec>`: they read the disk directly. Its fields map onto the routing below: `planDrafts` with no `overview` · `overview` with no phases · each phase's `tasks.open` · a name in `completed`. If the script cannot run, read the expected files directly — file reads see gitignored paths. Conclude "no specs" only after `list` or a failed direct read.
- **Reconcile three signals:** session context (what this conversation was doing — a fresh session may have none), user intent (what they asked reviewed), the disk check above. Disk wins on state; context wins on intent and on disk silence; no context → intent + disk decide.
- **plan2code artifact reviewed (a plan, the spec docs, phases) — route on the reviewed feature's own `specs/<feature>/` state (another feature's specs prove nothing here), to the earliest unmet stage, suggesting only a step whose input exists:**
- `PLAN-*` without `overview.md` → `/plan2code-2-document`
@@ -556,8 +556,15 @@ enforces it, so never tell someone to keep asking past it.
The person can add folders beside the one the session started in (a shared
library, a design folder), from the footer's folder label. Together they are
the session's **workspace**: context for every skill run in this console
session, each folder addressed by a short `@name`. It outlives dashboard hops;
a new console session starts with the original folder alone.
session, each folder addressed by a short `@name`. It outlives dashboard hops,
and it is remembered: every change is saved to `workspaces.json` beside
`looks.json` (never into the project), keyed by the folder the session runs
in and then by spec. A session with a spec opens on that spec's list, one with
none on the project's; a spec with nothing saved starts as a copy of the
project's list. The dashboard's picker swaps the list as the selection moves,
and a `specDir` you post mid-run takes the current list with it. There is
nothing for you to load: `open` prints the list, and a switch of spec on a
resume reaches you as ordinary workspace changes on your next `wait`.
### What you are told
@@ -767,7 +774,7 @@ that is what the person is there to download. The finish carries no
sees the Trail Footer, and without this their last screen promises a question
that is never coming.
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
and `pathfinder-research` (id = the question's file slug) as each research
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
subagent reports back, or when you resolve a `research` question yourself
(Posting an update → Session meter). Other questions score through their
answers, so there is nothing to post for them.
@@ -820,7 +827,7 @@ know:
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) 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`. |
| 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). |
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
@@ -41,6 +41,7 @@ import {
die,
ensureDir,
fileStamp,
forgetWorkspace,
handOff,
handleFile,
healthOk,
@@ -65,6 +66,7 @@ import {
readLedger,
readWorkspace,
reapHandles,
rememberedWorkspace,
remoteWarning,
removeScratch,
removeSessions,
@@ -73,6 +75,7 @@ import {
SESSION_MAX_AGE_MS,
sessionDir,
sleepSync,
specKey,
staleScratch,
staleSessions,
sweepUploads,
@@ -317,7 +320,7 @@ async function cmdOpen() {
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
} catch {}
const workspace = workspaceOnOpen(dir, worktree);
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
// Month-old sessions and scratch files: listed before the print so the
// agent can see what went, removed after it so the page waits for nothing.
@@ -403,10 +406,11 @@ async function cmdOpen() {
* The workspace as `open` hands it to the agent, and the cursor seeded to
* match: the agent now has the whole list, so no change up to here is owed.
* Read-only on workspace.json, which only the server writes; on a fresh
* session the server has not made it yet, so the original folder stands in.
* session the server has not made it yet, so what was remembered for this
* folder and spec stands in, the same list the server is about to make.
*/
function workspaceOnOpen(dir, worktree) {
const ws = readWorkspace(dir) || initialWorkspace(worktree);
function workspaceOnOpen(dir, worktree, specDir) {
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
try {
writeWorkspaceCursor(dir, ws.version || 0);
@@ -946,6 +950,18 @@ function realNearest(p) {
return path.join(fs.realpathSync(existing), path.relative(existing, p));
}
/* --------------------------------------------------------------- forget */
// Drop the folder list remembered for one spec (Finalize, once the spec is
// archived). The project's own list and every other spec's are untouched.
function cmdForget() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
let spec = specKey(args.spec);
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
const worktree = repoRoots().worktree;
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
}
/* ----------------------------------------------------------------- help */
function cmdHelp() {
@@ -961,7 +977,8 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
first post. --file is optional, and --title defaults to the
project's folder name. Also prints workspace: { folders: [{ name,
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name.
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
@@ -988,6 +1005,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
Copy a cited note attachment into specs/<idea>/attachments/. Prints
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
missing. Paste link as it is.
forget --spec specs/<idea>
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.
status [--session <sid>] [--all]
One session, or every session belonging to this project.
stop --session <sid> | --all
@@ -1206,6 +1227,7 @@ const COMMANDS = {
wait: cmdWait,
chat: cmdChat,
keep: cmdKeep,
forget: cmdForget,
status: cmdStatus,
stop: cmdStop,
help: cmdHelp,
@@ -178,8 +178,8 @@ function lockStale(lock) {
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn) {
const lock = path.join(dir, STATE_LOCK_FILE);
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
const lock = path.join(dir, lockName);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
@@ -188,7 +188,7 @@ export function withStateLock(dir, fn) {
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
@@ -487,8 +487,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks and the pointer to this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
function isScratchName(name) {
return (
@@ -1619,17 +1620,125 @@ export function readWorkspace(dir) {
return readJson(path.join(dir, WORKSPACE_FILE), null);
}
// A fresh workspace: just the original folder, named after itself.
export function initialWorkspace(worktree) {
// A fresh workspace: the original folder, named after itself, plus whatever
// was remembered for this folder and spec (rememberedWorkspace() below).
export function initialWorkspace(worktree, remembered = null) {
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
if (remembered && remembered.original) {
if (remembered.original.name) original.name = remembered.original.name;
if (remembered.original.description) original.description = remembered.original.description;
}
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
id: "f" + (i + 1),
path: f.path,
name: f.name,
description: f.description || "",
...(f.nested ? { nested: true } : {}),
}));
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
}
/* ------------------------------------------------ remembered workspaces */
// The folder list outlives the console session: one file for the person,
// beside looks.json, keyed by the folder a session runs in and then by spec.
// Never under specs/: the paths are this machine's, and the server never
// writes into a project.
//
// { "projects": { "<folded worktree>": {
// "path": "<worktree>",
// "project": { original, folders, at }, // no spec picked
// "specs": { "specs/<name>": { original, folders, at } } } } }
//
// `original` holds the first folder's name and description only (its path is
// always the session's own); `folders` the added ones as { path, name,
// description, nested? }. Two writers, the server on every change and
// `console.mjs forget`, each a read-modify-write of one key.
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
const foldKey = (p) => {
const resolved = path.resolve(String(p || ""));
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
};
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
export function specKey(specDir) {
return String(specDir || "")
.trim()
.replace(/\\/g, "/")
.replace(/^\.\//, "")
.replace(/\/+$/, "");
}
function readStore() {
const saved = readJson(WORKSPACES_FILE, null);
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
}
/**
* What was remembered for this folder and spec: `{ entry, from }`, where
* `from` is "spec" when the spec has its own list, "project" when it falls
* back to the project's (a spec's list starts as a copy of it), and null
* when nothing was ever saved.
*/
export function rememberedWorkspace(worktree, specDir) {
const project = readStore().projects[foldKey(worktree)];
if (!project) return { entry: null, from: null };
const spec = specKey(specDir);
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
}
// The workspace's folders as the store keeps them.
export function rememberable(ws) {
const folders = (ws && ws.folders) || [];
const first = folders.find((f) => f.original) || {};
return {
version: 0,
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
missing: [],
changes: [],
remote: "",
original: { name: first.name || "", description: first.description || "" },
folders: folders
.filter((f) => !f.original)
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
at: nowIso(),
};
}
// Every server and `console.mjs forget` writes the one file, so each
// read-modify-write holds this lock beside it.
const WORKSPACES_LOCK = "workspaces.json.lock";
// Save the list for this folder and spec ("" for the project's own).
export function rememberWorkspace(worktree, specDir, ws) {
ensureDir(path.dirname(WORKSPACES_FILE));
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
}
function saveRemembered(worktree, specDir, ws) {
const store = readStore();
const key = foldKey(worktree);
const project = store.projects[key] || { path: path.resolve(worktree) };
const spec = specKey(specDir);
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
else project.project = rememberable(ws);
store.projects[key] = project;
writeJsonAtomic(WORKSPACES_FILE, store);
}
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
export function forgetWorkspace(worktree, specDir) {
const spec = specKey(specDir);
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
}
function dropRemembered(worktree, spec) {
const store = readStore();
const project = store.projects[foldKey(worktree)];
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
delete project.specs[spec];
writeJsonAtomic(WORKSPACES_FILE, store);
return true;
}
// Single-writer rule: only server.mjs may call this.
export function writeWorkspace(dir, ws) {
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
@@ -2505,6 +2505,9 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
actions stay put. */
.modal.workspace { max-width: 680px; }
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
.workspace .modal-blurb { margin-bottom: 6px; }
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
.workspace-list {
list-style: none; margin: 0; padding: 0;
display: grid; gap: 12px;
@@ -2542,6 +2542,7 @@ function renderDashboard(main) {
const specs = specList();
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
wrap.appendChild(hideUnavailableToggle());
if (!local.launching && !launchScoping) syncWorkspaceScope();
// "Unavailable" is the scan's verdict for the selected spec, not the
// momentary greying while a launch is in flight or the server is away, so
@@ -2963,6 +2964,11 @@ async function launchSkill(entry) {
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected.
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
// dashboard, which would otherwise sync back to the picker's spec.
launchScoping = true;
await syncWorkspaceScope(target ? target.dir : "");
try {
const res = await fetch("/submit", {
method: "POST",
@@ -2973,6 +2979,7 @@ async function launchSkill(entry) {
}),
});
if (res.status === 409) {
launchScoping = false;
pendingResult = true;
banner("Your last pick is still being picked up. One moment.", "info");
return;
@@ -2980,10 +2987,12 @@ async function launchSkill(entry) {
if (!res.ok) throw new Error(String(res.status));
sound("startSkill");
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
launchScoping = false;
pendingResult = true;
save();
render();
} catch {
launchScoping = false;
banner("That did not go through. Nothing was lost; try again.", "warn");
}
}
@@ -5854,6 +5863,32 @@ async function postJson(url, body) {
}
}
/* The workspace follows the dashboard's picker: the folders remembered for
the selected spec, or the project's own under "Start from scratch". The
server swaps the list and remembers every change after it. */
let scopeAsked = null;
// True from a launch's scope sync until its send has gone (or failed).
let launchScoping = false;
async function syncWorkspaceScope(spec) {
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
scopeAsked = want;
const { status, body } = await postJson("/workspace/scope", { spec: want });
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
scopeAsked = null;
if ($("workspace-modal").open) renderWorkspace();
}
// The dialog's "Remembered for" line: whose list this is.
function workspaceScopeText() {
const scope = (wsFrame && wsFrame.scope) || "";
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
const spec = specList().find((s) => s.dir === scope);
const name = spec ? spec.name : scope.split("/").pop();
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
}
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
// The folder whose Remove is waiting on its inline confirm, by id.
@@ -5893,6 +5928,7 @@ function renderWorkspace() {
}
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
$("workspace-scope").textContent = workspaceScopeText();
}
function workspaceRow(f) {
@@ -833,10 +833,28 @@
Click the folder name in the middle of the bottom bar. It shows your
folder's name and branch, such as <strong>shop · main</strong>, and
<strong>shop + 2 folders · main</strong> once you have added some.
The workspace lasts for this console session only: it carries across
steps you start from the dashboard, and a new console session starts
with just the folder you started in.
It carries across steps you start from the dashboard.
</p>
<h4>Remembered for next time</h4>
<ul>
<li>
Every change is saved as you make it, so the next console session in
this folder starts with the same folders.
</li>
<li>
Each spec keeps its own list. The first time you pick a spec on the
dashboard it starts as a copy of the project's list (the one shown
under <strong>Start from scratch</strong>), and after that the two
are separate. Picking a spec loads its list; the line under the
dialog's title says whose list you are looking at.
</li>
<li>
The lists live in <code>workspaces.json</code> in your own
Plan2Code settings folder, beside your look and feel, never in the
project. Finalize offers to forget a spec's list when it archives the
spec.
</li>
</ul>
<h4>Adding a folder</h4>
<ul>
<li>
@@ -1363,9 +1381,10 @@
<h4>What it counts</h4>
<p>
Each step you run here adds points: a plan or a set of documents
weighs more than a single answered question, and a built phase more
still, by how many tasks it completed: a big phase adds more than a
small one. Every two questions you answer add a point too, so a long
weighs more than a quick task, and a built phase more still, by how
many tasks it completed: a big phase adds more than a small one.
Every two questions you answer within one step add a point too
(rounded down, so a single answer adds nothing), so a long
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
points, with what it added. It is a rule of thumb, not a
reading of Plan2Code's real memory: long sessions tend to make it
@@ -2003,6 +2022,7 @@
The folders the agent uses as context this session. It reads the extra ones for
reference and only changes them if you ask.
</p>
<p class="workspace-scope" id="workspace-scope"></p>
<ul class="workspace-list" id="workspace-list"></ul>
<div class="workspace-add">
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
@@ -45,7 +45,10 @@ import {
readLedger,
readOverview,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
remoteWarning,
specKey,
typedCount,
withStateLock,
writeJsonAtomic,
@@ -326,7 +329,9 @@ function workspaceNow() {
return ws;
}
const root = sessionWorktree();
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
const scope = specKey(stateNow?.specDir);
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
@@ -347,13 +352,87 @@ function saveWorkspace(ws) {
// One change: a new version, an entry in the change log the agent is handed,
// the file, and every open page.
function bumpWorkspace(ws, change) {
function bumpWorkspace(ws, change, { remember = true } = {}) {
ws.version = (ws.version || 0) + 1;
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
saveWorkspace(ws);
// Remembered for the next console session too. A folder gone missing or
// found again is not a change of mind, so it is not saved.
if (remember) rememberNow(ws);
pushState();
}
function rememberNow(ws) {
const root = sessionWorktree();
if (!root) return;
try {
rememberWorkspace(root, ws.scope || "", ws);
} catch {}
}
/**
* Point the workspace at another spec ("" for the project's own list) and
* swap in what was remembered there, logging each difference as a change so
* the agent's cursor stays truthful. A spec with nothing saved starts from
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
* list it has and saves it as the spec's (`seed: "current"`, a spec created
* mid-run). Folders keep their ids when their path stays.
*/
function setScope(ws, spec, seed = "project") {
const root = sessionWorktree();
const next = specKey(spec);
if (!root || (ws.scope || "") === next) return false;
const found = rememberedWorkspace(root, next);
ws.scope = next;
if (next && found.from !== "spec" && seed === "current") {
saveWorkspace(ws);
rememberNow(ws);
pushState();
return true;
}
const want = initialWorkspace(root, found.entry).folders;
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
const kept = new Set();
const folders = [];
const changes = [];
for (const w of want) {
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
if (!have) {
folders.push({ ...w, id: "pending" });
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
continue;
}
kept.add(have);
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
if ((have.description || "") !== (w.description || "")) {
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
}
folders.push({ ...have, name: w.name, description: w.description || "" });
}
for (const f of ws.folders) {
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
}
ws.folders = folders.filter((f) => f.id !== "pending");
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
if (!changes.length) {
saveWorkspace(ws);
pushState();
}
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
checkFolders(ws);
return true;
}
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
// learns its spec late) takes the workspace with it.
function followSpecDir(state) {
const spec = specKey(state && state.specDir);
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
}
function isFolder(p) {
try {
return fs.statSync(p).isDirectory();
@@ -370,10 +449,10 @@ function checkFolders(ws) {
const marked = ws.missing.includes(f.id);
if (!there && !marked) {
ws.missing = [...ws.missing, f.id];
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
} else if (there && marked) {
ws.missing = ws.missing.filter((id) => id !== f.id);
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
}
}
}
@@ -402,8 +481,8 @@ function folderIssues(entries) {
}
function workspaceView() {
const { folders, missing, remote } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) };
const { folders, missing, remote, scope } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
}
// Whether child sits strictly under parent.
@@ -492,6 +571,7 @@ function bootWorkspace() {
saveWorkspace(ws);
}
checkFolders(ws);
followSpecDir(stateNow);
}
/**
@@ -1403,6 +1483,24 @@ const server = http.createServer((req, res) => {
});
}
// Which list the workspace is: a spec's, or the project's (`spec` empty).
// The dashboard's picker sends it as the selection moves and before a
// launch, so a skill opens on the list of the spec it was launched for.
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
try {
setScope(workspaceNow(), spec, "project");
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, workspaceView());
});
}
// Only ever returns a path: the page then adds it through /workspace/add.
if (pathname === "/workspace/browse" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
@@ -1561,6 +1659,9 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
pushState();
}
lastStateStamp = stamp;
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-02",
"releaseDate": "2026-10-04",
"mode": "utility"
}
@@ -0,0 +1,120 @@
#!/usr/bin/env node
// commit-msg.mjs: the team's commit message, built from the branch name.
//
// Every Plan2Code skill that suggests a commit uses one format:
//
// <subject>
//
// <JIRA-Ticket-ID>
// AI Assisted
//
// and derives the ticket from a branch named <prefix>/<TICKET-ID>-description,
// where the ticket is an uppercase project key, a hyphen and an integer
// (ABC-10968). This script reads the branch, extracts the ticket and prints
// the exact command, so no prompt re-implements the rule by eye.
import { execFileSync } from "node:child_process";
import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
const USAGE = `
commit-msg.mjs: build the team's commit command from the current branch. JSON on stdout.
node commit-msg.mjs --subject "<subject>" [--add-all | --files <path> ...] [--ticket <ID>]
--subject the one-line description (at most 100 characters). No double
quotes (straight or curly), backticks, $, backslashes or ! in it,
so the command pastes unchanged into bash, zsh and PowerShell.
--add-all prefix the command with "git add -A &&".
--files prefix it with "git add -- <files> &&" (repeat --files per path).
--ticket use this ticket ID instead of reading the branch.
Prints { ok, branch, ticket, subject, message, command, add, commit }. The
commit is three -m flags, exactly: subject, ticket, "AI Assisted". command is
add && commit, one line for bash, zsh and PowerShell 7+. Windows PowerShell 5.1
has no &&: run add (null when nothing is staged) and then commit as two
commands. Nothing is run.
Exit: 0 ok · 2 bad arguments (including a stray argument: one --files per
path) · 3 not a git repository / no branch (detached HEAD) · 4 the branch
carries no ticket ID, --ticket is not KEY-123, the subject breaks a rule, or a
path cannot be quoted safely.
`;
// The ticket is the first <KEY>-<number> path segment start after a "/" (or the
// branch start), ended by "-", "_", "/" or the end of the name.
const TICKET_RE = /(?:^|\/)([A-Z][A-Z0-9]*-\d+)(?=[-_/]|$)/;
function ticketFromBranch(branch) {
const m = String(branch || "").match(TICKET_RE);
return m ? m[1] : null;
}
function git(args) {
try {
return { ok: true, out: execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim() };
} catch {
return { ok: false };
}
}
function currentBranch() {
if (!git(["rev-parse", "--git-dir"]).ok) {
fail(EXIT.NOT_FOUND, "not-a-repo", "This directory is not inside a git repository.", "Run from the project root, or skip the commit suggestion.");
}
// symbolic-ref names the branch even before the first commit, where
// rev-parse --abbrev-ref HEAD fails; it fails only on a detached HEAD.
const ref = git(["symbolic-ref", "--short", "-q", "HEAD"]);
if (!ref.ok || !ref.out) fail(EXIT.NOT_FOUND, "detached-head", "HEAD is detached, so there is no branch name to read a ticket from.", "Ask the user for the ticket ID and pass --ticket <ID>.");
return ref.out;
}
// A path goes into the command as-is when it is plainly safe, in single quotes
// otherwise (literal in bash, zsh and PowerShell alike). Backslashes become
// forward slashes, which git accepts on every platform. A leading @ or - is
// quoted too: unquoted, PowerShell reads @types as a splat and the path
// vanishes. The command's `git add --` means a leading - is never an option.
function quoteFile(f) {
const p = f.replace(/\\/g, "/");
if (/^[\w./:+][\w./:@+-]*$/.test(p)) return p;
// PowerShell treats the curly single quotes as quote characters too.
if (/['\u2018-\u201B]/.test(p)) fail(EXIT.INVALID, "unsafe-path", `The path ${p} contains a single quote, which cannot be quoted the same way in bash and PowerShell.`, "Use --add-all, or leave that file out and stage it by hand.");
return `'${p}'`;
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["add-all"], values: ["subject", "ticket"], lists: ["files"] });
if (args._.length) fail(EXIT.USAGE, "stray-argument", `Unexpected argument(s): ${args._.join(" ")}.`, "Each path needs its own --files (e.g. --files a.js --files b.js); quote a subject with spaces.");
const subject = (args.subject || "").trim();
if (!subject) fail(EXIT.USAGE, "missing-subject", "--subject is required.", 'Example: --subject "Add the export endpoint"');
if (/[\r\n]/.test(subject)) fail(EXIT.INVALID, "multiline-subject", "The subject must be one line.", "The diff is the body; keep the subject to one line.");
if (subject.length > 100) fail(EXIT.INVALID, "subject-too-long", `The subject is ${subject.length} characters; the limit is 100.`, "Shorten it; the diff is the body and the PR is the explanation.");
// Inside "...": PowerShell ends the string at a curly double quote too,
// bash and zsh treat \ as an escape, and ! is history expansion in an
// interactive bash or zsh.
if (/["`$\\!\u201C-\u201F]/.test(subject)) fail(EXIT.INVALID, "unsafe-subject", "The subject contains a double quote (straight or curly), backtick, $, backslash or !, which bash, zsh and PowerShell read differently inside double quotes.", "Rephrase without those characters (single quotes are fine).");
if (args["add-all"] && args.files) fail(EXIT.USAGE, "add-conflict", "Use --add-all or --files, not both.", "Pick one.");
let branch = null;
let ticket = args.ticket ? args.ticket.trim() : null;
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like ABC-10968.");
if (!ticket) {
branch = currentBranch();
ticket = ticketFromBranch(branch);
if (!ticket) {
fail(EXIT.INVALID, "no-ticket", `The branch "${branch}" has no <prefix>/<TICKET-ID>-description ticket in it.`, "Ask the user for the ticket ID, then rerun with --ticket <ID>; or show the command with <JIRA-Ticket-ID> for them to fill in.");
}
}
const add = args["add-all"] ? "git add -A" : args.files ? `git add -- ${args.files.map(quoteFile).join(" ")}` : null;
const commit = `git commit -m "${subject}" -m "${ticket}" -m "AI Assisted"`;
out({
ok: true,
branch,
ticket,
subject,
message: `${subject}\n\n${ticket}\nAI Assisted`,
command: add ? `${add} && ${commit}` : commit,
add,
commit,
});
});
@@ -0,0 +1,247 @@
// Plan2Code skill scripts: shared plumbing.
//
// Every script in a skill's scripts/ directory imports this file. It owns the
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
//
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
// on a handled failure.
// stderr a one-line human diagnostic on failure (the same message + next).
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
// 4 invalid input or a check that failed · 5 refused (would clobber
// or break a rule).
//
// Node 18+ built-ins only, no build step: this ships inside every skill.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
export class CliError extends Error {
constructor(exit, error, message, next) {
super(message);
this.exit = exit;
this.error = error;
this.next = next;
}
}
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
export function fail(exit, error, message, next) {
throw new CliError(exit, error, message, next);
}
export function out(obj) {
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
}
/**
* Parse argv into { _: positionals, <flag>: value }.
* `booleans` names flags that take no value; every other `--flag` takes the
* next argument, and repeats of a flag listed in `lists` collect into an array.
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
* silently changes behavior.
*/
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
const known = new Set([...booleans, ...values, ...lists, "help"]);
const args = { _: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) {
args._.push(a);
continue;
}
let name = a.slice(2);
let value;
const eq = name.indexOf("=");
if (eq !== -1) {
value = name.slice(eq + 1);
name = name.slice(0, eq);
}
if (!known.has(name)) {
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
}
if (name === "help" || booleans.includes(name)) {
args[name] = true;
continue;
}
if (value === undefined) {
if (i + 1 >= argv.length) {
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
}
value = argv[++i];
}
if (lists.includes(name)) (args[name] ||= []).push(value);
else args[name] = value;
}
return args;
}
/**
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
* failure shape plus an exit code, and anything else into exit 1 with the stack
* on stderr. Sets process.exitCode rather than calling process.exit(), so
* stdout is never cut off mid-write.
*/
export async function run(usage, main) {
try {
const argv = process.argv.slice(2);
if (argv.includes("--help") || argv.includes("-h")) {
process.stdout.write(usage.trim() + "\n");
return;
}
await main(argv);
} catch (err) {
if (err instanceof CliError) {
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
process.exitCode = err.exit;
return;
}
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
process.exitCode = EXIT.CRASH;
}
}
/* ------------------------------------------------------------------ time */
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
// is what "today" means to the person reading the date in their files.
export function now() {
const pinned = process.env.PLAN2CODE_NOW;
if (pinned) {
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
const d = new Date(pinned);
if (!Number.isNaN(d.getTime())) return d;
}
return new Date();
}
const pad = (n) => String(n).padStart(2, "0");
/** YYYY-MM-DD */
export function isoDate(d = now()) {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
/** YYYYMMDD */
export function compactDate(d = now()) {
return isoDate(d).replace(/-/g, "");
}
/** YYYY-MM-DD HH:mm */
export function stamp(d = now()) {
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** HHMMSS */
export function clock(d = now()) {
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
}
/* ----------------------------------------------------------------- files */
export function readText(file) {
try {
return fs.readFileSync(file, "utf8");
} catch {
return null;
}
}
export function isDir(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
/** Write a file only when its content changes. Returns true when it wrote. */
export function writeIfChanged(file, content) {
const current = readText(file);
if (current === content) return false;
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
return true;
}
/** Normalise line endings for parsing; keep the original for writing back. */
export function eol(text) {
return text.includes("\r\n") ? "\r\n" : "\n";
}
/**
* phase-N.md per phase number. An exact phase-N.md always wins over a sibling
* such as phase-1-old.md; more than one candidate is reported, never guessed.
* Shared so every script that counts a spec's tasks reads the same files.
*/
export function phaseFiles(dir) {
const files = new Map();
const extra = new Map();
for (const name of fs.readdirSync(dir).sort()) {
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
if (!m) continue;
const n = Number(m[1]);
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
if (!files.has(n)) files.set(n, name);
else if (exact) {
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
files.set(n, name);
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
}
files.extra = extra;
return files;
}
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
export function rel(root, p) {
return path.relative(root, p).split(path.sep).join("/") || ".";
}
/* --------------------------------------------------------- the web console */
// The web console ships beside these scripts in every installed skill
// (references/web-console/), and in this repo it sits at src/web-console/. Its
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
// metrics-bait scan, so the scripts import it rather than keep a second copy.
const CONSOLE_LIB_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
];
let consoleLibPromise;
export function consoleLib() {
consoleLibPromise ||= (async () => {
for (const candidate of CONSOLE_LIB_CANDIDATES) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-lib-missing",
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
);
})();
return consoleLibPromise;
}
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
export function version() {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const text = readText(file);
if (!text) continue;
try {
const v = JSON.parse(text).version;
if (typeof v === "string") return v;
} catch {}
}
return null;
}
@@ -0,0 +1,138 @@
#!/usr/bin/env node
// review-scope.mjs: what a branch review would cover, from git.
//
// Review Mode's scope fallback is a fixed command sequence (status, diff, log,
// name-only against the base branch) followed by arithmetic: how many files,
// how many lines, what share are docs (the >70% rule), whether specs/ is in
// scope, whether the change is big enough to batch by risk. This script runs
// the sequence and does the arithmetic. Choosing the scope and the review type
// from the user's words stays with the agent.
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
const USAGE = `
review-scope.mjs: the branch-review scope from git. JSON on stdout.
node review-scope.mjs [--base <branch>] [--root <dir>]
--base the branch to compare against. Default: main if it exists (local or
origin), else master. The output says which one it used. With
neither (and no --base) it stops with no-base; only a repo with no
commits yet goes on, counting uncommitted changes alone.
Covers commits on this branch since it left the base (base...HEAD), plus
staged, unstaged and untracked changes. Prints the files with their status and
line counts, totals, the share of .md files, the doc/code classification
(docs or code when one side is more than 70% of files, else mixed),
specsInScope, batchByRisk (50+ files) and the commits.
Exit: 0 ok (check "empty") · 2 bad arguments · 3 not a git repository, the
--base branch does not exist, or (no --base) there is no main or master.
`;
function git(root, args, { allowFail = false } = {}) {
try {
// core.quotePath=false: a non-ASCII path comes back as itself, not as an escaped, quoted string.
return execFileSync("git", ["-c", "core.quotePath=false", ...args], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 });
} catch (err) {
if (allowFail) return null;
throw err;
}
}
function refExists(root, ref) {
return git(root, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { allowFail: true }) !== null;
}
function pickBase(root, wanted) {
const candidates = wanted ? [wanted, `origin/${wanted}`] : ["main", "origin/main", "master", "origin/master"];
for (const ref of candidates) if (refExists(root, ref)) return ref;
return null;
}
function parseNumstat(text, into, status) {
for (const line of (text || "").split("\n")) {
if (!line.trim()) continue;
const [a, d, ...rest] = line.split("\t");
let file = rest.join("\t");
// Renames print as "old => new" or "dir/{old => new}/f"; keep the new path.
// A move up a level ("d/{sub => }/f", "{sub => }/f") empties the brace, so
// the doubled or leading slash it leaves behind is dropped.
file = file.replace(/\{[^}]*=> ([^}]*)\}/, "$1").replace(/^.* => /, "").replace(/\/{2,}/g, "/").replace(/^\//, "");
const entry = into.get(file) || { path: file, status: new Set(), added: 0, deleted: 0, binary: false };
entry.status.add(status);
if (a === "-" || d === "-") entry.binary = true;
else {
entry.added += Number(a);
entry.deleted += Number(d);
}
into.set(file, entry);
}
}
// Prose docs only: a requirements.txt or CMakeLists.txt is not documentation.
const DOC_RE = /\.(md|mdx|markdown|rst|adoc)$/i;
run(USAGE, async (argv) => {
const args = parseArgs(argv, { values: ["base", "root"] });
const root = path.resolve(args.root || ".");
const top = git(root, ["rev-parse", "--show-toplevel"], { allowFail: true });
if (!top) fail(EXIT.NOT_FOUND, "not-a-repo", `${root} is not inside a git repository.`, "Ask the user which files to review (Focused scope).");
const repo = top.trim();
const branch = (git(repo, ["rev-parse", "--abbrev-ref", "HEAD"], { allowFail: true }) || "").trim() || null;
const base = pickBase(repo, args.base);
if (args.base && !base) fail(EXIT.NOT_FOUND, "no-base", `No branch named ${args.base} (or origin/${args.base}).`, "Pass an existing --base, or omit it to use main / master.");
// No main or master: counting only uncommitted work would hide every commit
// on the branch, so stop and ask for the trunk. A repo with no commits yet
// has nothing committed to miss, so it goes on.
if (!base && refExists(repo, "HEAD")) {
fail(EXIT.NOT_FOUND, "no-base", "There is no main or master branch (local or origin) to compare this branch with.", "Rerun with --base <trunk> (ask the user which branch is the trunk if unclear).");
}
const files = new Map();
let commits = [];
if (base) {
parseNumstat(git(repo, ["diff", "--numstat", "-M", `${base}...HEAD`], { allowFail: true }), files, "committed");
commits = (git(repo, ["log", "--oneline", "--no-decorate", `${base}..HEAD`], { allowFail: true }) || "").split("\n").filter(Boolean);
}
parseNumstat(git(repo, ["diff", "--numstat", "-M", "--cached"], { allowFail: true }), files, "staged");
parseNumstat(git(repo, ["diff", "--numstat", "-M"], { allowFail: true }), files, "unstaged");
for (const f of (git(repo, ["ls-files", "--others", "--exclude-standard"], { allowFail: true }) || "").split("\n").filter(Boolean)) {
let added = 0;
let binary = false;
try {
const buf = fs.readFileSync(path.join(repo, f));
if (buf.includes(0)) binary = true;
else if (buf.length) added = buf.toString("utf8").split("\n").length - (buf.at(-1) === 10 ? 1 : 0);
} catch {}
files.set(f, { path: f, status: new Set(["untracked"]), added, deleted: 0, binary });
}
const list = [...files.values()]
.map((f) => ({ ...f, status: [...f.status] }))
.sort((a, b) => a.path.localeCompare(b.path));
const docs = list.filter((f) => DOC_RE.test(f.path)).length;
const total = list.length;
const docShare = total ? docs / total : 0;
const lines = list.reduce((n, f) => n + f.added + f.deleted, 0);
out({
ok: true,
repo,
branch,
base,
...(base ? {} : { note: "No commits yet: only uncommitted changes are counted." }),
empty: total === 0,
counts: { files: total, lines, added: list.reduce((n, f) => n + f.added, 0), deleted: list.reduce((n, f) => n + f.deleted, 0), docs, code: total - docs },
docShare: Number(docShare.toFixed(2)),
mix: !total ? "none" : docShare > 0.7 ? "docs" : 1 - docShare > 0.7 ? "code" : "mixed",
// specs/ is gitignored, so git rarely sees it: the conversation is the
// better signal that a spec is under review.
specsInScope: list.some((f) => /^specs\//.test(f.path)),
batchByRisk: total >= 50,
commits,
files: list,
});
});
@@ -0,0 +1,676 @@
#!/usr/bin/env node
// specs.mjs: where every spec under specs/ stands, read from its files.
//
// The pipeline skills (plan, document, implement, revise-plan, finalize,
// review, handoff) all need the same filesystem facts: which specs exist, what
// a spec's PLAN-DRAFT says, which phases are open, how many tasks are done.
// Those have one correct answer, so this script computes them instead of each
// prompt re-deriving them by hand. It also performs the two mechanical writes
// (a Phase Checklist marker, the archive move), with --dry-run.
//
// Shell listing only matters to people: specs/ is gitignored, so editor search
// tools skip it. This script reads the disk directly and does not care.
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";
const USAGE = `
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
node specs.mjs list [--root <dir>]
Every active spec under specs/ (never specs--completed/), newest first:
state, detail, PLAN-DRAFT files with their **Status:** line, overview,
phase count. Also the names already archived in specs--completed/.
node specs.mjs status <spec> [--root <dir>]
One spec in full: the overview's Phase Checklist, Parallel Execution
Groups, per-phase task counts by marker, task-numbering problems,
completion, the implement phase-selection verdict ("next"), the pending
phases, and consistency checks. <spec> is specs/<name>, <name>, or a path
to its overview.md.
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).
document: total_tasks, tasks_per_phase, phase_count,
parallel_groups_identified computed; pass
--set verification_items_added=N (your Verification Summary's
Added total; the VERIFICATION comments are reported as a check).
finalize: completion_rate_at_audit, tasks_completed, tasks_total; pass
--set verification_failures_found=N
--set documentation_updates_needed=N.
node specs.mjs mark <spec> --phase <N> --to open|in-progress|done [--dry-run]
Set phase N's Phase Checklist marker in overview.md ([ ], [/], [x]).
done also sets the phase file's Status line (**Status:**, **Status**:
or Status:) to Complete (and warns if tasks are unfinished); open on a
Complete phase sets it to In Progress. Warns when the phase file has no
Status line. Refuses a phase with duplicate checklist rows, and refuses
in-progress -> open (started work stays marked).
node specs.mjs archive <spec> [--dry-run]
Move specs/<name>/ to specs--completed/<name>/. Refuses if the target
exists, or if <spec> is not a folder directly under specs/.
Markers: [ ] pending · [/] in progress · [x] complete · [!] blocked · [?] assumed.
Exit: 0 ok · 2 bad arguments · 3 spec not found · 4 cannot parse / check
failed · 5 refused.
`;
/* ------------------------------------------------------------- resolving */
function realOrResolved(p) {
try {
return fs.realpathSync.native(p);
} catch {
return path.resolve(p);
}
}
const samePath = (a, b) => (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
// Read-only commands (status, metrics) accept an archived spec, because
// Finalize reads its own spec after Step 6 moved it. Writes never do.
function resolveSpec(root, arg, { allowArchived = false } = {}) {
if (!arg) fail(EXIT.USAGE, "missing-spec", "Name the spec: specs/<name>, <name>, or its overview.md path.", "Run `specs.mjs list` to see the active specs.");
let p = arg.replace(/\\/g, "/").replace(/\/+$/, "");
if (/\/overview\.md$/i.test(p) || /\/phase-[^/]*\.md$/i.test(p)) p = p.replace(/\/[^/]+$/, "");
const abs = path.isAbsolute(p) ? p : p.includes("/") ? path.join(root, p) : path.join(root, "specs", p);
const relPath = rel(root, abs);
if (!allowArchived && /(^|\/)specs--completed(\/|$)/.test(relPath)) {
fail(EXIT.REFUSED, "archived-spec", `${relPath} is archived; the pipeline only changes active specs under specs/.`, "Pick an active spec from `specs.mjs list`.");
}
// A spec is a folder directly under specs/ (or specs--completed/ for a read).
// Without this, `archive .` would move all of specs/ and `archive ./src` a
// source folder.
const homes = [path.join(root, "specs"), ...(allowArchived ? [path.join(root, "specs--completed")] : [])].map(realOrResolved);
const parent = realOrResolved(path.dirname(path.resolve(abs)));
if (!homes.some((h) => samePath(h, parent))) {
fail(EXIT.REFUSED, "not-a-spec", `${relPath} is not a spec folder: a spec sits directly under specs/${allowArchived ? " (or specs--completed/)" : ""}.`, "Pass specs/<name> or <name>; run `specs.mjs list` to see the active specs.");
}
if (!isDir(abs)) {
fail(EXIT.NOT_FOUND, "spec-not-found", `No spec folder at ${relPath}.`, "Run `specs.mjs list` from the project root (or pass --root) to see the active specs.");
}
return { dir: abs, rel: relPath, name: path.basename(abs) };
}
/* -------------------------------------------------------------- parsing */
const MARKERS = { " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" };
// Task 2.3, a lettered sub-task 3.6a, or a named one such as a testing task 1.T.
const TASK_RE = /^\s*[-*] \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
const CHECKBOX_RE = /^\s*[-*] \[(.)\]/;
// The Status line in any of the forms people write it: **Status:**, **Status**:
// or a plain Status:, optionally as a list item. Groups: everything up to the
// value (kept as written when the value is rewritten), the value, trailing blanks.
const STATUS_RE = /^([ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*)(.+?)([ \t]*)$/m;
function statusOf(text) {
const m = (text || "").match(STATUS_RE);
return m ? m[2] : null;
}
/** A markdown section's lines: from its heading to the next heading of the same or higher level. */
function section(text, headingRe) {
const lines = text.split(/\r?\n/);
const start = lines.findIndex((l) => /^#{1,6}\s/.test(l) && headingRe.test(l));
if (start === -1) return null;
const level = lines[start].match(/^#+/)[0].length;
let end = lines.length;
for (let i = start + 1; i < lines.length; i++) {
const m = lines[i].match(/^(#+)\s/);
if (m && m[1].length <= level) {
end = i;
break;
}
}
return { start, end, lines: lines.slice(start + 1, end) };
}
function plainText(s) {
return s
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/[*_`]/g, "")
.replace(/\s+/g, " ")
.trim();
}
/** Phase Checklist rows: the first "Phase N" on each checkbox line names the phase. */
function parseChecklist(overview) {
const sec = section(overview, /Phase Checklist/i);
if (!sec) return { found: false, phases: [], unparsed: [] };
const phases = [];
const unparsed = [];
sec.lines.forEach((line, i) => {
const m = line.match(CHECKBOX_RE);
if (!m) return;
const text = plainText(line.replace(CHECKBOX_RE, ""));
const num = text.match(/\bPhase\s+(\d+)\b/i);
if (!num) {
unparsed.push({ line: sec.start + 2 + i, text: line.trim() });
return;
}
const after = text.slice(num.index + num[0].length).replace(/^\s*[:\-–—]\s*/, "");
const name = after.split(/\s+[-–—]\s+|\s+\(|\s+_\(|:\s|\s+see\s+phase-/i)[0].replace(/\s*phase-\d+\.md\s*$/i, "").trim();
phases.push({
number: Number(num[1]),
marker: m[1],
state: MARKERS[m[1]] || "unknown",
name: name.replace(/\s*\[Milestone[^\]]*\]\s*$/i, "") || `Phase ${num[1]}`,
line: sec.start + 2 + i,
});
});
return { found: true, phases, unparsed };
}
/** "2, 3", "2-4" and "2–4" (or an em dash) alike: ranges expand, so a group cell never loses a phase. */
function phaseList(cell) {
const outList = [];
for (const part of cell.match(/\d+\s*[-–\u2014]\s*\d+|\d+/g) || []) {
const r = part.match(/^(\d+)\s*[-–\u2014]\s*(\d+)$/);
if (r && Number(r[2]) >= Number(r[1]) && Number(r[2]) - Number(r[1]) < 100) {
for (let n = Number(r[1]); n <= Number(r[2]); n++) outList.push(n);
} else outList.push(...part.match(/\d+/g).map(Number));
}
return [...new Set(outList)];
}
/** Parallel Execution Groups table: real groups only (a named group with 2+ phases). */
function parseGroups(overview) {
const sec = section(overview, /Parallel Execution Groups/i);
if (!sec) return { found: false, groups: [] };
const groups = [];
const seen = new Set();
for (const line of sec.lines) {
if (!/^\s*\|/.test(line) || /^\s*\|[\s:|-]+\|\s*$/.test(line)) continue;
const cells = line.split("|").slice(1, -1).map((c) => c.trim());
if (cells.length < 2 || /^group$/i.test(cells[0])) continue;
const id = plainText(cells[0]);
const phases = phaseList(cells[1]);
// "None", a dash, a single phase, a group its author labelled sequential
// ("A (sequential)"), or a Phases cell written as a chain ("1 → 2") is not
// a parallel group.
if (!id || /^(none|-|–|—)$/i.test(id) || /\bsequential\b/i.test(id) || /→|->|\bthen\b/i.test(cells[1]) || phases.length < 2) continue;
const key = `${id}:${phases.join(",")}`;
if (seen.has(key)) continue;
seen.add(key);
groups.push({ id, phases, reason: plainText(cells[2] || "") });
}
return { found: true, groups };
}
function firstSentence(text) {
const t = plainText(text);
const m = t.match(/^(.+?[.!?])(\s|$)/);
return (m ? m[1] : t).slice(0, 240);
}
function parsePhaseFile(file, number) {
const text = readText(file) || "";
const lines = text.split(/\r?\n/);
const title = (lines.find((l) => /^#\s/.test(l)) || "").replace(/^#\s+/, "").trim();
const status = statusOf(text);
const counts = { pending: 0, "in-progress": 0, complete: 0, blocked: 0, assumed: 0, unknown: 0 };
const tasks = [];
const strayCheckboxes = [];
const unmatchedTasks = [];
let heading = "";
lines.forEach((line, i) => {
const h = line.match(/^#{1,6}\s+(.*)$/);
if (h) heading = plainText(h[1]);
const t = line.match(TASK_RE);
if (t) {
const state = MARKERS[t[1]] || "unknown";
counts[state]++;
const named = !/^\d+$/.test(t[3]);
tasks.push({ id: `${t[2]}.${t[3]}${t[4]}`, phase: Number(t[2]), seq: named ? null : Number(t[3]), named, suffix: t[4], marker: t[1], state, line: i + 1 });
return;
}
// A line that looks like a task but is not counted as one (Task 1.4A,
// "1. [ ] **Task", a non-bold "- [ ] Task 1.3") would make the audit undercount.
if (/^\s*(?:[-*]|\d+\.)\s+\[.\].*\bTask\s+\d+\./i.test(line)) unmatchedTasks.push({ line: i + 1, text: line.trim().slice(0, 120) });
if (CHECKBOX_RE.test(line)) strayCheckboxes.push({ line: i + 1, section: heading, text: line.trim().slice(0, 120) });
});
// Numbering: every task belongs to this phase, the base numbers run 1..n with
// no gaps or repeats, and a lettered task (3.6a) sits after its base (3.6).
// Named tasks (1.T) are outside the numeric sequence.
const numbering = [];
const bases = [];
for (const t of tasks) {
if (t.phase !== number) numbering.push(`Task ${t.id} is in phase-${number}.md but numbered for Phase ${t.phase}`);
if (!t.suffix && !t.named) bases.push(t.seq);
}
const seenIds = new Set();
for (const t of tasks) {
if (seenIds.has(t.id)) numbering.push(`Task ${t.id} appears more than once`);
seenIds.add(t.id);
if (t.suffix && !t.named && !bases.includes(t.seq)) numbering.push(`Task ${t.id} has no base Task ${t.phase}.${t.seq}`);
}
bases.forEach((seq, i) => {
if (seq !== i + 1 && !numbering.some((n) => n.startsWith("Task numbering"))) {
numbering.push(`Task numbering is not sequential: expected ${number}.${i + 1}, found ${number}.${seq}`);
}
});
const overviewSec = section(text, /^#{1,6}\s+Overview\b/i);
const goalText = overviewSec ? overviewSec.lines.join("\n").split(/\n\s*\n/).map((p) => p.trim()).find((p) => p && !/^[-*|>]/.test(p)) : "";
return {
title,
status,
goal: goalText ? firstSentence(goalText) : null,
total: tasks.length,
counts,
open: counts.pending + counts["in-progress"] + counts.blocked + counts.unknown,
// Open work a phase cannot be approved over; blocked tasks may stand ([!] is allowed at sign-off).
unfinished: counts.pending + counts["in-progress"] + counts.unknown,
tasks,
numbering,
strayCheckboxes,
unmatchedTasks,
};
}
function planDrafts(dir) {
return fs
.readdirSync(dir)
.filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n))
.sort()
.map((file) => ({
file,
archived: /-prev\.md$/i.test(file),
status: statusOf(readText(path.join(dir, file))),
}));
}
/* ---------------------------------------------------------------- status */
function specStatus(spec) {
const overviewPath = path.join(spec.dir, "overview.md");
const overview = readText(overviewPath);
const files = phaseFiles(spec.dir);
// An empty overview.md still exists; only a missing one is "no overview".
const hasOverview = overview !== null;
const checklist = hasOverview ? parseChecklist(overview) : { found: false, phases: [], unparsed: [] };
const groups = hasOverview ? parseGroups(overview) : { found: false, groups: [] };
const checks = [];
const check = (level, code, message) => checks.push({ level, code, message });
for (const [n, names] of files.extra) {
check("warn", "duplicate-phase-file", `Phase ${n} has more than one file: using ${files.get(n)}, ignoring ${names.join(", ")}`);
}
const rowsByNumber = new Map();
for (const r of checklist.phases) rowsByNumber.set(r.number, [...(rowsByNumber.get(r.number) || []), r]);
for (const [n, rows] of rowsByNumber) {
if (rows.length > 1) check("error", "duplicate-checklist-row", `Phase ${n} has ${rows.length} rows in the Phase Checklist (overview.md lines ${rows.map((r) => r.line).join(", ")}); the first one is used`);
}
const phases = [];
const numbers = new Set([...checklist.phases.map((p) => p.number), ...files.keys()]);
for (const number of [...numbers].sort((a, b) => a - b)) {
const row = checklist.phases.find((p) => p.number === number) || null;
const file = files.get(number) || null;
const parsed = file ? parsePhaseFile(path.join(spec.dir, file), number) : null;
phases.push({
number,
name: row ? row.name : parsed ? parsed.title.replace(/^Phase\s+\d+\s*[:\-–—]?\s*/i, "") : `Phase ${number}`,
checklist: row ? row.state : null,
marker: row ? row.marker : null,
file,
status: parsed ? parsed.status : null,
goal: parsed ? parsed.goal : null,
tasks: parsed ? { total: parsed.total, open: parsed.open, ...parsed.counts } : null,
blockedTasks: parsed ? parsed.tasks.filter((t) => t.state === "blocked").map((t) => t.id) : [],
assumedTasks: parsed ? parsed.tasks.filter((t) => t.state === "assumed").map((t) => t.id) : [],
openTasks: parsed ? parsed.tasks.filter((t) => ["pending", "in-progress", "blocked", "unknown"].includes(t.state)).map((t) => t.id) : [],
});
if (!row && hasOverview) check("error", "missing-checklist-row", `phase-${number}.md has no row in overview.md's Phase Checklist`);
if (row && !file) check("error", "missing-phase-file", `Phase Checklist lists Phase ${number} but there is no phase-${number}.md`);
if (parsed) {
for (const n of parsed.numbering) check("error", "task-numbering", `phase-${number}.md: ${n}`);
// Prerequisites and criteria are plain bullets by rule; other checkbox
// blocks (a Phase Testing list) are the template's own and are not tasks.
for (const s of parsed.strayCheckboxes.filter((c) => /prerequisite|criteria/i.test(c.section))) {
check("warn", "criteria-checkbox", `phase-${number}.md:${s.line} is a checkbox under "${s.section}"; prerequisites and criteria use plain bullets`);
}
if (parsed.total === 0) check("warn", "no-tasks", `phase-${number}.md has no **Task ${number}.N:** checkbox lines`);
for (const u of parsed.unmatchedTasks) {
check("warn", "uncounted-task", `phase-${number}.md:${u.line} looks like a task but is not counted (a task line is "- [ ] **Task ${number}.N:**"): ${u.text}`);
}
const done = parsed.counts.complete + parsed.counts.assumed;
const rowDone = row && (row.state === "complete" || row.state === "assumed");
// A phase may be approved with blocked [!] tasks left (Implementation
// Mode's self-review allows "[x] or blocked [!]"); only unfinished work is an error.
if (rowDone && parsed.unfinished > 0) {
check("error", "checked-with-open-tasks", `Phase ${number} is [${row.marker}] in overview.md but ${parsed.unfinished} task(s) are not done (${phases.at(-1).openTasks.filter((id) => !phases.at(-1).blockedTasks.includes(id)).join(", ")})`);
} else if (rowDone && parsed.counts.blocked > 0) {
check("info", "approved-with-blocked", `Phase ${number} is [${row.marker}] with ${parsed.counts.blocked} blocked task(s) (${phases.at(-1).blockedTasks.join(", ")})`);
}
if (row && row.state === "pending" && parsed.total > 0 && done > 0) {
// Done tasks under a [ ] phase with work still open is what a re-opened
// phase looks like (revise-plan); with nothing open it is a missed mark.
if (parsed.unfinished > 0) check("info", "partly-done-unchecked", `Phase ${number} is [ ] with ${done} task(s) done and ${parsed.unfinished} open (normal for a re-opened phase)`);
else check("warn", "unchecked-with-done-tasks", `Phase ${number} is [ ] in overview.md but all ${done} unblocked task(s) are done`);
}
if (row && !rowDone && row.state !== "pending" && parsed.total > 0 && parsed.unfinished === 0) {
check("info", "done-not-approved", `Phase ${number}: every task is done but overview.md still shows [${row.marker}] (normal until the user approves the phase)`);
}
}
}
if (!hasOverview) check("error", "no-overview", `${spec.rel} has no overview.md`);
else if (!checklist.found) check("error", "no-checklist", "overview.md has no ## Phase Checklist section");
for (const u of checklist.unparsed) check("warn", "unparsed-checklist-row", `overview.md:${u.line} is a checkbox in the Phase Checklist with no "Phase N" in it: ${u.text}`);
for (const g of groups.groups) {
for (const n of g.phases) if (!numbers.has(n)) check("error", "group-unknown-phase", `Parallel group ${g.id} names Phase ${n}, which does not exist`);
}
// Totals. Completed = [x] plus [?] (assumed complete); [?] is reported on its own too.
// Incomplete = [ ] + [/] (+ unreadable markers); Blocked is its own column.
const totals = { total: 0, complete: 0, assumed: 0, pending: 0, "in-progress": 0, blocked: 0, unknown: 0 };
for (const p of phases) if (p.tasks) for (const k of Object.keys(totals)) totals[k] += p.tasks[k] || 0;
const completed = totals.complete + totals.assumed;
const completion = totals.total ? completed / totals.total : null;
return {
ok: true,
spec: spec.rel,
name: spec.name,
overview: hasOverview ? "overview.md" : null,
planDrafts: planDrafts(spec.dir),
phases,
parallelGroups: groups.groups,
totals: { ...totals, completed, incomplete: totals.pending + totals["in-progress"] + totals.unknown },
completion: completion === null ? null : Number(completion.toFixed(4)),
completionPercent: completion === null ? null : Math.round(completion * 100),
next: nextPhase(phases, groups.groups, checklist.found),
pending: phases
.filter((p) => p.checklist && p.checklist !== "complete" && p.checklist !== "assumed")
.map((p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null, open: p.tasks ? p.tasks.open : null, goal: p.goal })),
checks,
};
}
/**
* Implementation Mode's phase-selection table, applied mechanically.
* 2+ workable phases in the same parallel group, consecutive -> choose (warn if all [/])
* a single [/] -> ask-resume · a single [ ] -> auto-start · nothing workable -> none
*/
function nextPhase(phases, groups, haveChecklist) {
if (!haveChecklist) return { action: "none", reason: "no Phase Checklist in overview.md" };
const ordered = phases.filter((p) => p.checklist);
const isDone = (p) => p.checklist === "complete" || p.checklist === "assumed";
const workable = ordered.filter((p) => p.checklist === "pending" || p.checklist === "in-progress");
if (!workable.length) {
return { action: "none", reason: ordered.length && ordered.every(isDone) ? "every phase is complete" : "no [ ] or [/] phase in the Phase Checklist" };
}
const first = workable[0];
const brief = (p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null });
// A blocked [!] phase ahead of the pick is skipped, but never silently.
const skipped = ordered.slice(0, ordered.indexOf(first)).filter((p) => !isDone(p)).map(brief);
const note = skipped.length ? { skipped, warning: `skipping ${skipped.map((p) => `Phase ${p.number} [${p.state}]`).join(", ")} ahead of it` } : {};
const group = groups.find((g) => g.phases.includes(first.number));
if (group) {
// Consecutive same-group incomplete phases, in checklist order, starting at the first workable one.
const run = [];
for (const p of ordered.slice(ordered.indexOf(first))) {
if (!group.phases.includes(p.number)) break;
if (isDone(p)) continue;
if (p.checklist === "pending" || p.checklist === "in-progress") run.push(p);
else break;
}
if (run.length >= 2) {
const allStarted = run.every((p) => p.checklist === "in-progress");
const warnings = [
...(allStarted ? ["every option is already [/]: another agent may be working on it, so picking one risks duplicated work"] : []),
...(note.warning ? [note.warning] : []),
];
return {
action: "choose",
group: group.id,
options: run.map(brief),
...(note.skipped ? { skipped: note.skipped } : {}),
...(warnings.length ? { warning: warnings.join("; ") } : {}),
};
}
}
return { action: first.checklist === "in-progress" ? "ask-resume" : "auto-start", phase: brief(first), ...note };
}
/* --------------------------------------------------------------- commands */
async function cmdList(args) {
const root = path.resolve(args.root || ".");
const { scanProject } = await consoleLib();
const scan = scanProject(root);
const specs = scan.specs.map((s) => {
const dir = path.join(root, s.dir);
let names = [];
try {
names = fs.readdirSync(dir);
} catch {}
return {
dir: s.dir,
name: s.name,
state: s.state,
detail: s.detail,
touched: s.touched ? new Date(s.touched).toISOString() : null,
planDrafts: planDrafts(dir),
overview: names.includes("overview.md"),
phaseFiles: names.filter((n) => /^phase-\d+\b.*\.md$/i.test(n)).length,
pathfinder: isDir(path.join(dir, "pathfinder")),
};
});
let completed = [];
try {
completed = fs.readdirSync(path.join(root, "specs--completed")).filter((n) => isDir(path.join(root, "specs--completed", n))).sort();
} catch {}
out({
ok: true,
root,
hasAgents: scan.hasAgents,
specsDir: isDir(path.join(root, "specs")),
specs,
completed,
...(specs.length ? {} : { note: "No active specs under specs/." }),
});
}
async function cmdStatus(args) {
const root = path.resolve(args.root || ".");
out(specStatus(resolveSpec(root, args._[1], { allowArchived: true })));
}
function countVerificationAdded(dir) {
let n = 0;
for (const name of fs.readdirSync(dir)) {
if (!/\.md$/i.test(name) || /^PLAN-/i.test(name)) continue;
n += ((readText(path.join(dir, name)) || "").match(/<!--\s*VERIFICATION:\s*Added\b/gi) || []).length;
}
return n;
}
async function cmdMetrics(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1], { allowArchived: true });
const step = args.step;
if (step !== "document" && step !== "finalize") fail(EXIT.USAGE, "bad-step", "--step must be document or finalize.", "Plan's METRICS_JSON is written by hand in its Phase 7.");
const sets = {};
for (const kv of args.set || []) {
const m = kv.match(/^([a-z_]+)=(-?\d+(?:\.\d+)?)$/);
if (!m) fail(EXIT.USAGE, "bad-set", `--set ${kv} is not key=number.`, "Example: --set verification_failures_found=1");
sets[m[1]] = Number(m[2]);
}
// --set supplies the judgment fields only; the computed ones are never overridden.
const SETTABLE = { document: ["verification_items_added"], finalize: ["verification_failures_found", "documentation_updates_needed"] };
for (const k of Object.keys(sets)) {
if (!SETTABLE[step].includes(k)) fail(EXIT.USAGE, "bad-set", `--set ${k} is not a field you supply for --step ${step}.`, `Only ${SETTABLE[step].join(", ")}; the rest is computed from the files.`);
}
const st = specStatus(spec);
const withTasks = st.phases.filter((p) => p.tasks);
let metrics;
let hint;
if (step === "document") {
// verification_items_added is the Added total of the Verification Summary
// you presented, not something the files record, so it comes from --set.
// The <!-- VERIFICATION: Added --> comments are a cross-check only.
if (!("verification_items_added" in sets)) fail(EXIT.USAGE, "missing-set", "document needs --set verification_items_added=N (the Added column total of your Verification Summary).", `The spec has ${countVerificationAdded(spec.dir)} <!-- VERIFICATION: Added --> comment(s), as a cross-check.`);
metrics = {
step: "document",
total_tasks: st.totals.total,
tasks_per_phase: withTasks.map((p) => p.tasks.total),
phase_count: st.phases.length,
parallel_groups_identified: st.parallelGroups.length,
...sets,
};
hint = { verificationCommentsFound: countVerificationAdded(spec.dir) };
} else {
const missing = ["verification_failures_found", "documentation_updates_needed"].filter((k) => !(k in sets));
if (missing.length) fail(EXIT.USAGE, "missing-set", `finalize needs ${missing.map((k) => `--set ${k}=N`).join(" and ")}.`, "Those two counts are your judgment from Steps 2 and 4.");
metrics = {
step: "finalize",
completion_rate_at_audit: st.completion === null ? 0 : Number(st.completion.toFixed(2)),
tasks_completed: st.totals.completed,
tasks_total: st.totals.total,
...sets,
};
}
out({ ok: true, spec: spec.rel, metrics, comment: `<!-- METRICS_JSON ${spacedJson(metrics)} -->`, ...(hint || {}), checks: st.checks.filter((c) => c.level === "error") });
}
// The house style of every METRICS_JSON comment: {"key": value, "list": [1, 2]}.
function spacedJson(obj) {
const v = (x) => (Array.isArray(x) ? `[${x.map(v).join(", ")}]` : x && typeof x === "object" ? spacedJson(x) : JSON.stringify(x));
return `{${Object.entries(obj).map(([k, x]) => `${JSON.stringify(k)}: ${v(x)}`).join(", ")}}`;
}
const TO = { open: " ", "in-progress": "/", done: "x" };
async function cmdMark(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1]);
const number = Number(args.phase);
if (!Number.isInteger(number) || number < 0) fail(EXIT.USAGE, "bad-phase", "--phase needs a phase number.", "Example: --phase 2");
if (!(args.to in TO)) fail(EXIT.USAGE, "bad-to", "--to must be open, in-progress or done.", "open = [ ], in-progress = [/], done = [x]");
const overviewPath = path.join(spec.dir, "overview.md");
const overview = readText(overviewPath);
if (overview === null) fail(EXIT.NOT_FOUND, "no-overview", `${spec.rel} has no overview.md.`, "Run /plan2code-2-document first.");
const checklist = parseChecklist(overview);
const rows = checklist.phases.filter((p) => p.number === number);
const row = rows[0];
if (!row) fail(EXIT.NOT_FOUND, "no-row", `overview.md's Phase Checklist has no row for Phase ${number}.`, "Run `specs.mjs status` to see the phases it lists.");
if (rows.length > 1) fail(EXIT.REFUSED, "duplicate-row", `Phase ${number} has ${rows.length} rows in the Phase Checklist (lines ${rows.map((r) => r.line).join(", ")}); marking one would be a guess.`, "Remove the duplicate row, then rerun.");
const target = TO[args.to];
if (row.marker === "/" && target === " ") {
fail(EXIT.REFUSED, "no-reset", `Phase ${number} is [/]; started work is never reset to [ ].`, "Leave it [/] (a later session resumes it), or mark it done once approved.");
}
const changes = [];
const lines = overview.split(/\r?\n/);
const idx = row.line - 1;
const next = lines[idx].replace(/\[(.)\]/, `[${target}]`);
if (next !== lines[idx]) {
lines[idx] = next;
changes.push({ file: `${spec.rel}/overview.md`, line: row.line, from: `[${row.marker}]`, to: `[${target}]` });
}
// The phase file's Status line follows: done -> Complete; re-opening a Complete
// phase -> In Progress (revise-plan), so the two files never disagree.
let phaseText = null;
let phasePath = null;
let unfinished = [];
const warnings = [];
const file = phaseFiles(spec.dir).get(number);
if (file) {
phasePath = path.join(spec.dir, file);
const text = readText(phasePath) || "";
const parsed = parsePhaseFile(phasePath, number);
unfinished = parsed.tasks.filter((t) => ["pending", "in-progress", "unknown"].includes(t.state)).map((t) => t.id);
const status = statusOf(text);
const want = target === "x" ? "Complete" : target === " " && status && /^complete$/i.test(status) ? "In Progress" : null;
if (status && want && status !== want) {
phaseText = text.replace(STATUS_RE, (_, before, _value, after) => before + want + after);
changes.push({ file: `${spec.rel}/${file}`, field: "Status", from: status, to: want });
}
// done and open keep the Status line in step; with none to find, say so.
if (!status && target !== "/") warnings.push(`${file} has no Status line, so only the Phase Checklist checkbox changed; add a "**Status:** <value>" line under its title.`);
}
if (!args["dry-run"]) {
if (changes.some((c) => c.file.endsWith("overview.md"))) fs.writeFileSync(overviewPath, lines.join(eol(overview)));
if (phaseText !== null) fs.writeFileSync(phasePath, phaseText);
}
const doneEarly = target === "x" && unfinished.length > 0;
if (doneEarly) warnings.unshift(`Phase ${number} was marked done with ${unfinished.length} unfinished task(s): ${unfinished.join(", ")}. Mark only a phase the user approved.`);
out({
ok: true,
spec: spec.rel,
phase: number,
name: row.name,
dryRun: !!args["dry-run"],
changed: changes.length > 0,
changes,
...(warnings.length ? { warning: warnings.join(" ") } : {}),
...(doneEarly ? { unfinished } : {}),
});
}
function listRel(dir, base = dir) {
const outList = [];
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) outList.push(...listRel(p, base));
else outList.push(rel(base, p));
}
return outList.sort();
}
async function cmdArchive(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1]);
const target = path.join(root, "specs--completed", spec.name);
if (fs.existsSync(target)) {
fail(EXIT.REFUSED, "target-exists", `specs--completed/${spec.name}/ already exists; nothing was moved.`, "Ask the user whether to merge by hand or archive under another name.");
}
const files = listRel(spec.dir);
if (!args["dry-run"]) {
fs.mkdirSync(path.dirname(target), { recursive: true });
try {
fs.renameSync(spec.dir, target);
} catch (err) {
// A rename across volumes (or a locked file on Windows) fails; copy then remove.
try {
fs.cpSync(spec.dir, target, { recursive: true, errorOnExist: true, force: false });
} catch (copyErr) {
fail(EXIT.INVALID, "archive-failed", `Could not move or copy ${spec.rel} (${err.code || err.message}; copy: ${copyErr.code || copyErr.message}).`, `Close anything holding files in ${spec.rel} open, check specs--completed/${spec.name} for a partial copy, then rerun.`);
}
try {
fs.rmSync(spec.dir, { recursive: true, force: true });
} catch (rmErr) {
fail(EXIT.INVALID, "source-not-removed", `Copied to specs--completed/${spec.name}/ but could not remove ${spec.rel} (${rmErr.code || rmErr.message}); both copies now exist.`, `Close whatever holds files in ${spec.rel} open, then delete it by hand. The archive is complete.`);
}
}
}
const sourceGone = args["dry-run"] ? null : !fs.existsSync(spec.dir);
const moved = args["dry-run"] ? null : listRel(target);
if (!args["dry-run"] && !(sourceGone && moved.length === files.length)) {
fail(
EXIT.INVALID,
"archive-unverified",
`The move of ${spec.rel} to specs--completed/${spec.name}/ did not verify: ${moved.length} of ${files.length} file(s) at the target, and ${spec.rel} ${sourceGone ? "is gone" : "still exists"}.`,
`Compare ${spec.rel} with specs--completed/${spec.name}/ and finish the move by hand; archive refuses to rerun while the target exists.`
);
}
out({
ok: true,
dryRun: !!args["dry-run"],
from: spec.rel,
to: `specs--completed/${spec.name}`,
files,
...(args["dry-run"] ? {} : { sourceRemoved: sourceGone, filesAtTarget: moved.length, archivedOn: isoDate() }),
});
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "step", "phase", "to"], lists: ["set"] });
const cmd = args._[0];
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, archive: cmdArchive };
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, metrics, mark, archive. Run with --help.");
await commands[cmd](args);
});
@@ -0,0 +1,22 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"mode": "utility"
}
+26 -34
View File
@@ -16,6 +16,14 @@ Senior software engineer implementing solutions exactly as specified. Follow spe
The FIRST thing you do, before anything else in this file — before reading a spec, before Phase 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow implement` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-3-implement/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then <D>/console.md and <D>/building.md; progress, every question and the sign-off 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.md → Launches), then the spec.
## Scripts
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-3-implement/scripts/` globally; for Implement + Review, its own skill's `scripts/`). Run them 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" status <spec>`: the Phase Checklist, parallel groups, every phase's task counts by marker, goal, the phase-selection verdict (`next`) and consistency `checks`.
- `node "<S>/specs.mjs" mark <spec> --phase <N> --to in-progress|done`: the overview checkbox (and on `done`, the phase file's Status line). It refuses to reset `[/]` to `[ ]`.
- `node "<S>/commit-msg.mjs" --subject "<subject>" --add-all`: the commit command, ticket taken from the branch.
## Rules
- Follow `./AGENTS.md` if it exists
@@ -31,28 +39,15 @@ The FIRST thing you do, before anything else in this file — before reading a s
## Required Context
⚠️ IMPORTANT: `specs/` is gitignored — NEVER use Glob (silently fails). Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
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/`.
Need implementation spec files to proceed.
**Option 1: User provides an overview.md path** → `specs.mjs status <that path>`.
**IMPORTANT:** Never look in `specs--completed/` (archived only). Only check active spec folders under `specs/`.
**Option 2: Auto-detect** → `specs.mjs list`. Exactly one spec with phases (`phaseFiles` > 0) → `status` it.
**Option 1: User provides overview.md path**
1. Read the overview.md file
2. Find "Phase Checklist" section
3. Identify workable phases: `[ ]` (pending) or `[/]` (in-progress)
4. Check for parallel execution options
5. Apply phase selection logic
6. Read corresponding `phase-X.md` from same directory
7. Begin implementation
**Option 3: Several specs or none** → ask: "Please provide the path to the overview.md file (e.g., `specs/user-authentication/overview.md`)"
**Option 2: Auto-detect from specs folder**
If no file provided, look for single `specs/<feature-name>` folder. If found, read its `overview.md` and follow Option 1.
**Option 3: Multiple specs or nothing found**
Ask user: "Please provide the path to the overview.md file (e.g., `specs/user-authentication/overview.md`)"
Do not proceed without successfully reading overview.md and determining the next phase.
Then read overview.md and act on `next` (Parallel Phase Selection below). Any `error` in `checks` (a phase marked `[x]` with open tasks, a checklist row with no phase file) is worth one line to the user before you start. Do not proceed without a readable overview.md and a `next` verdict.
## Phase Status Tracking
@@ -76,16 +71,16 @@ Never reset `[/]` to `[ ]`. Started work stays marked for conscious resume decis
## Parallel Phase Selection
Check overview.md for "Parallel Execution Groups" section. Find workable phases (`[ ]` or `[/]`).
`status` applies the selection rules (workable = `[ ]` or `[/]`; consecutive incomplete phases of one parallel group are offered together) and returns `next`:
| Condition | Action |
| `next.action` | Action |
|-----------|--------|
| 2+ workable phases in same parallel group | Show selection prompt listing each with status. TIP: run another agent on a different phase simultaneously. If all are `[/]`, warn about duplication. |
| Single `[/]` phase | Prompt: "Phase X is in progress. Resume? (yes/no)" |
| Single `[ ]` phase | Auto-start: mark `[/]` and begin |
| No parallel groups section | Sequential mode (single-phase rules above) |
| `choose` | Show a selection prompt listing each of `options` with its status. TIP: run another agent on a different phase simultaneously. Relay `warning` (all already `[/]`: duplicated work) when present. |
| `ask-resume` | Prompt: "Phase X is in progress. Resume? (yes/no)" Relay `warning` when present. |
| `auto-start` | Mark it `[/]` and begin. Relay `warning` when present. |
| `none` | Nothing to implement: say why (`reason`). Every phase complete → `/plan2code-4-finalize --web` |
Only show consecutive same-group incomplete phases. After selection, mark `[/]`, read `phase-X.md`, begin.
After selection, `mark --to in-progress`, read `phase-X.md`, begin.
## Code Consistency Rules
@@ -109,11 +104,9 @@ Only show consecutive same-group incomplete phases. After selection, mark `[/]`,
### 1. Identify and Claim Phase
Review `overview.md`, find workable phases (`[ ]` or `[/]`). Apply parallel selection logic.
Act on `status`'s `next` (Parallel Phase Selection above).
**Once selected:**
- If `[ ]`: Update to `[/]` in overview.md
- If `[/]`: No change needed
**Once selected:** `specs.mjs mark <spec> --phase <N> --to in-progress` (a no-op when it is already `[/]`).
State: `⚡ [PHASE X: Phase Name] - Marking in-progress and starting`
@@ -174,7 +167,7 @@ See "After Approval / Session End" section below.
| 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): ask if should continue with next. Large (>40): warn at start.
Default: ONE phase per conversation. Small phase (<5 tasks in `status`): ask if should continue with next. Large (>40): warn at start.
## Templates
@@ -211,18 +204,17 @@ Sections: Summary (2-3 sentences), Tasks Completed (Y/Z + blocked list), Test Re
### After Approval / Session End
On user "approved":
1. Mark `[/]` → `[x]` in overview.md, update phase-X.md status to "Complete"
1. `specs.mjs mark <spec> --phase <N> --to done`: overview `[/]` → `[x]` and phase-X.md Status "Complete"
2. Show Planny art with completion message
3. Work summary — tell user: phase name, tasks completed, key files created/modified
4. **Upcoming phases** — read overview.md Phase Checklist, find next 2-3 pending (`[ ]`) phases. For each, peek at its `phase-X.md` for task count and goal. Present a table so the user can assess stopping points and review gates:
4. **Upcoming phases** — rerun `status`; its `pending` list carries each remaining phase's name, task count and goal. Present the next 2-3 as a table so the user can assess stopping points and review gates (tighten a goal to one sentence if it runs long):
| Phase | Tasks | Goal |
|-------|-------|------|
| Phase X: [Name] | Y | [One-sentence goal] |
| Phase X+1: [Name] | Z | [One-sentence goal] |
5. Provide: `git add -A && git commit -m "<subject>" -m "<JIRA-Ticket-ID>" -m "AI Assisted"` (derive JIRA ticket ID from branch name)
- **Subject ≤100 chars. EXACTLY THREE -m flags — no body. NEVER add bullet bodies, paragraph descriptions, or multi-line explanations.** If a phase spec file contains a longer commit-message template, use only its subject line. The diff is the body; the PR is the explanation.
5. Write a one-line subject for the phase, then give the user the `command` from `commit-msg.mjs --subject "<subject>" --add-all`. It enforces the format: subject ≤100 chars and EXACTLY THREE -m flags (subject, ticket, `AI Assisted`), no body. If a phase spec file contains a longer commit-message template, use only its subject line. The diff is the body; the PR is the explanation. On Windows PowerShell 5.1 (no `&&`), give `add` and `commit` as two commands instead. Exit 4 `no-ticket`: ask the user for the ticket and rerun with `--ticket`, or show the command with `<JIRA-Ticket-ID>` for them to fill in.
6. **If more phases:** "NEXT STEP: Start NEW conversation and run: `/plan2code-3-implement --web`"
7. **If final phase:** "NEXT STEP: Start NEW conversation and run: `/plan2code-4-finalize --web`"
8. Mention `/plan2code-1b-revise-plan --web` option
@@ -10,6 +10,14 @@ Critical review specialist -- experienced senior engineer providing independent
The FIRST thing you do, before anything else in this file — before the scope detection: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow review` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md. Scope questions, the findings report and the pick-what-gets-fixed menu all go through it; the report lands on the page as a doc. 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.md → Launches), then Process. Read inside a build session for its review button? Skip this section — building.md's overrides govern, the session is already running. On the console, a `__stop` action is the person ending the session (console.md → Stop requests); 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.md → Finishing).
## Scripts
`<S>` is `scripts/` beside the SKILL.md that loaded this file (`~/.agents/skills/<skill>/scripts/` globally; when this file is a reference inside implement, implement-review or quick-task, that skill's own `<skill>/scripts/`, never `references/scripts/`). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
- `node "<S>/review-scope.mjs" [--base <branch>]`: the branch-review scope from git (Step 1).
- `node "<S>/specs.mjs" list` / `status <spec>`: spec state on disk (Step 2, Session End routing).
- `node "<S>/commit-msg.mjs" --subject "<subject>" --files <path> [--files <path> ...]`: the commit command (one `--files` per path).
## Rules
- Follow `./AGENTS.md` if it exists -- use all rules and conventions. If missing, warn and proceed with caution.
@@ -40,7 +48,7 @@ Three levels -- auto-detected, always respect explicit user override:
**User override:** If user specifies scope, use exactly that. Never silently narrow.
**Doc review:** >70% doc files = editorial critique. >70% code = also verify related docs match.
**Doc review:** >70% doc files = editorial critique. >70% code = also verify related docs match. (`review-scope.mjs` reports this as `mix`: `docs`, `code` or `mixed`; for a Focused scope, count the named files the same way.)
## Process
@@ -54,7 +62,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. **Git fallback** — `git status`, `git diff`, `git log main..HEAD --oneline`, `git diff --name-only main..HEAD`. Nothing? Ask user.
3. **Git fallback** — run `review-scope.mjs`. It 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.
**Classify review type** from context (auto-detect; use `ask_user_question` only if ambiguous):
@@ -69,13 +77,13 @@ Three levels -- auto-detected, always respect explicit user override:
| >70% .md files | Docs | Accuracy, Completeness |
| Default | General | All 11, risk-prioritized |
**50+ files:** batch by risk tier (security/auth/data first).
**50+ files** (`batchByRisk`): batch by risk tier (security/auth/data first).
> 🔬 [Review Mode] [X] files, ~[Y] lines. Type: [type]. Focus: [prioritized dimensions].
### Step 2: Context
1. **Specs?** Read `overview.md` + recent `phase-X.md`.
1. **Specs?** `specs.mjs list` (it reads gitignored `specs/`, which file search skips), then read `overview.md` + recent `phase-X.md`.
2. **AGENTS.md** for conventions.
3. **Tech stack** -- check for deprecations, CVEs, breaking changes.
4. **Classify:** >70% docs = doc review. >70% code = verify docs match.
@@ -167,9 +175,9 @@ Work summary — tell user: scope reviewed, findings count by severity (Critical
Read references/session-end.md
> Fallback: route plan2code artifacts (plan/spec docs/phases) on the reviewed feature's own `specs/<feature>/` state to the earliest unmet pipeline stage whose input exists — `PLAN-*` or `overview.md` without `phase-*.md` → `/plan2code-2-document`; unchecked `- [ ]` phase tasks → `/plan2code-3-implement`; all checked → `/plan2code-4-finalize`; archived → complete, summary only. Verify `specs/` on disk with a terminal `ls`/`Get-ChildItem` — it's gitignored, so search tools miss it and an empty result proves nothing. Non-pipeline artifacts (code/PRs/docs/logs) → summary only. Unresolved Criticals → fixing them (H/A/S) is the next step. Ambiguous or multiple candidate specs → ask one targeted question. Output: "Next (NEW conversation): `/plan2code-<step>` — [why + how you know]", appending ` --web` when the routed step offers the web console; else "Review complete -- [summary]."
> Fallback: route plan2code artifacts (plan/spec docs/phases) on the reviewed feature's own `specs/<feature>/` state to the earliest unmet pipeline stage whose input exists — `PLAN-*` or `overview.md` without `phase-*.md` → `/plan2code-2-document`; unchecked `- [ ]` phase tasks → `/plan2code-3-implement`; all checked → `/plan2code-4-finalize`; archived → complete, summary only. Read the state with `specs.mjs status <spec>` (gitignored `specs/` defeats search tools). Non-pipeline artifacts (code/PRs/docs/logs) → summary only. Unresolved Criticals → fixing them (H/A/S) is the next step. Ambiguous or multiple candidate specs → ask one targeted question. Output: "Next (NEW conversation): `/plan2code-<step>` — [why + how you know]", appending ` --web` when the routed step offers the web console; else "Review complete -- [summary]."
- **Commit** (code changes): `git add [files] && git commit -m "fix: [desc]" -m "<JIRA>" -m "AI Assisted"` -- derive JIRA from branch.
- **Commit** (code changes): the `command` from `commit-msg.mjs --subject "fix: [desc]" --files <file>` repeated once per fixed file (ticket from the branch; exit 4 `no-ticket`: show it with `<JIRA>` for the user to fill in). On Windows PowerShell 5.1 (no `&&`), give `add` and `commit` as two commands.
```
⋅
@@ -5,7 +5,7 @@ Principles to reason from, not a lookup table — adapt; when a case doesn't fit
cleanly, say what you verified and ask.
- **Plan2Code Workflow Pipeline:** `/plan2code-1-plan` → `PLAN-*` files · `/plan2code-2-document` → `overview.md` + `phase-*.md` (the "spec docs") in `specs/<feature>/` · `/plan2code-3-implement` → checks off phase tasks, one phase per run · `/plan2code-4-finalize` → archives to `specs--completed/`.
- **Find specs (any OS/shell):** `specs/` is gitignored, and search tools (Glob/Grep/project search) skip gitignored paths on many platforms — an empty search result is not evidence either way. Check with a terminal listing: `ls specs/<feature>/` (bash/zsh) · `Get-ChildItem specs/<feature>` (PowerShell) · `dir specs\<feature>` (cmd). Feature dir unknown? List `specs/` first. Command errors? Try another shell's form, then read the expected files directly — file reads see gitignored paths. Conclude "no specs" only after a terminal listing or a failed direct read.
- **Find specs (any OS/shell):** `specs/` is gitignored, and search tools (Glob/Grep/project search) skip gitignored paths on many platforms — an empty search result is not evidence either way. Use `node "<S>/specs.mjs" list` (`<S>`: see Review Mode → Scripts) (feature dir unknown, or to see what is archived in `completed`) and `node "<S>/specs.mjs" status <spec>`: they read the disk directly. Its fields map onto the routing below: `planDrafts` with no `overview` · `overview` with no phases · each phase's `tasks.open` · a name in `completed`. If the script cannot run, read the expected files directly — file reads see gitignored paths. Conclude "no specs" only after `list` or a failed direct read.
- **Reconcile three signals:** session context (what this conversation was doing — a fresh session may have none), user intent (what they asked reviewed), the disk check above. Disk wins on state; context wins on intent and on disk silence; no context → intent + disk decide.
- **plan2code artifact reviewed (a plan, the spec docs, phases) — route on the reviewed feature's own `specs/<feature>/` state (another feature's specs prove nothing here), to the earliest unmet stage, suggesting only a step whose input exists:**
- `PLAN-*` without `overview.md` → `/plan2code-2-document`
@@ -556,8 +556,15 @@ enforces it, so never tell someone to keep asking past it.
The person can add folders beside the one the session started in (a shared
library, a design folder), from the footer's folder label. Together they are
the session's **workspace**: context for every skill run in this console
session, each folder addressed by a short `@name`. It outlives dashboard hops;
a new console session starts with the original folder alone.
session, each folder addressed by a short `@name`. It outlives dashboard hops,
and it is remembered: every change is saved to `workspaces.json` beside
`looks.json` (never into the project), keyed by the folder the session runs
in and then by spec. A session with a spec opens on that spec's list, one with
none on the project's; a spec with nothing saved starts as a copy of the
project's list. The dashboard's picker swaps the list as the selection moves,
and a `specDir` you post mid-run takes the current list with it. There is
nothing for you to load: `open` prints the list, and a switch of spec on a
resume reaches you as ordinary workspace changes on your next `wait`.
### What you are told
@@ -767,7 +774,7 @@ that is what the person is there to download. The finish carries no
sees the Trail Footer, and without this their last screen promises a question
that is never coming.
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
and `pathfinder-research` (id = the question's file slug) as each research
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
subagent reports back, or when you resolve a `research` question yourself
(Posting an update → Session meter). Other questions score through their
answers, so there is nothing to post for them.
@@ -820,7 +827,7 @@ know:
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) 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`. |
| 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). |
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
@@ -41,6 +41,7 @@ import {
die,
ensureDir,
fileStamp,
forgetWorkspace,
handOff,
handleFile,
healthOk,
@@ -65,6 +66,7 @@ import {
readLedger,
readWorkspace,
reapHandles,
rememberedWorkspace,
remoteWarning,
removeScratch,
removeSessions,
@@ -73,6 +75,7 @@ import {
SESSION_MAX_AGE_MS,
sessionDir,
sleepSync,
specKey,
staleScratch,
staleSessions,
sweepUploads,
@@ -317,7 +320,7 @@ async function cmdOpen() {
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
} catch {}
const workspace = workspaceOnOpen(dir, worktree);
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
// Month-old sessions and scratch files: listed before the print so the
// agent can see what went, removed after it so the page waits for nothing.
@@ -403,10 +406,11 @@ async function cmdOpen() {
* The workspace as `open` hands it to the agent, and the cursor seeded to
* match: the agent now has the whole list, so no change up to here is owed.
* Read-only on workspace.json, which only the server writes; on a fresh
* session the server has not made it yet, so the original folder stands in.
* session the server has not made it yet, so what was remembered for this
* folder and spec stands in, the same list the server is about to make.
*/
function workspaceOnOpen(dir, worktree) {
const ws = readWorkspace(dir) || initialWorkspace(worktree);
function workspaceOnOpen(dir, worktree, specDir) {
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
try {
writeWorkspaceCursor(dir, ws.version || 0);
@@ -946,6 +950,18 @@ function realNearest(p) {
return path.join(fs.realpathSync(existing), path.relative(existing, p));
}
/* --------------------------------------------------------------- forget */
// Drop the folder list remembered for one spec (Finalize, once the spec is
// archived). The project's own list and every other spec's are untouched.
function cmdForget() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
let spec = specKey(args.spec);
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
const worktree = repoRoots().worktree;
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
}
/* ----------------------------------------------------------------- help */
function cmdHelp() {
@@ -961,7 +977,8 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
first post. --file is optional, and --title defaults to the
project's folder name. Also prints workspace: { folders: [{ name,
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name.
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
@@ -988,6 +1005,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
Copy a cited note attachment into specs/<idea>/attachments/. Prints
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
missing. Paste link as it is.
forget --spec specs/<idea>
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.
status [--session <sid>] [--all]
One session, or every session belonging to this project.
stop --session <sid> | --all
@@ -1206,6 +1227,7 @@ const COMMANDS = {
wait: cmdWait,
chat: cmdChat,
keep: cmdKeep,
forget: cmdForget,
status: cmdStatus,
stop: cmdStop,
help: cmdHelp,
@@ -178,8 +178,8 @@ function lockStale(lock) {
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn) {
const lock = path.join(dir, STATE_LOCK_FILE);
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
const lock = path.join(dir, lockName);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
@@ -188,7 +188,7 @@ export function withStateLock(dir, fn) {
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
@@ -487,8 +487,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks and the pointer to this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
function isScratchName(name) {
return (
@@ -1619,17 +1620,125 @@ export function readWorkspace(dir) {
return readJson(path.join(dir, WORKSPACE_FILE), null);
}
// A fresh workspace: just the original folder, named after itself.
export function initialWorkspace(worktree) {
// A fresh workspace: the original folder, named after itself, plus whatever
// was remembered for this folder and spec (rememberedWorkspace() below).
export function initialWorkspace(worktree, remembered = null) {
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
if (remembered && remembered.original) {
if (remembered.original.name) original.name = remembered.original.name;
if (remembered.original.description) original.description = remembered.original.description;
}
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
id: "f" + (i + 1),
path: f.path,
name: f.name,
description: f.description || "",
...(f.nested ? { nested: true } : {}),
}));
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
}
/* ------------------------------------------------ remembered workspaces */
// The folder list outlives the console session: one file for the person,
// beside looks.json, keyed by the folder a session runs in and then by spec.
// Never under specs/: the paths are this machine's, and the server never
// writes into a project.
//
// { "projects": { "<folded worktree>": {
// "path": "<worktree>",
// "project": { original, folders, at }, // no spec picked
// "specs": { "specs/<name>": { original, folders, at } } } } }
//
// `original` holds the first folder's name and description only (its path is
// always the session's own); `folders` the added ones as { path, name,
// description, nested? }. Two writers, the server on every change and
// `console.mjs forget`, each a read-modify-write of one key.
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
const foldKey = (p) => {
const resolved = path.resolve(String(p || ""));
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
};
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
export function specKey(specDir) {
return String(specDir || "")
.trim()
.replace(/\\/g, "/")
.replace(/^\.\//, "")
.replace(/\/+$/, "");
}
function readStore() {
const saved = readJson(WORKSPACES_FILE, null);
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
}
/**
* What was remembered for this folder and spec: `{ entry, from }`, where
* `from` is "spec" when the spec has its own list, "project" when it falls
* back to the project's (a spec's list starts as a copy of it), and null
* when nothing was ever saved.
*/
export function rememberedWorkspace(worktree, specDir) {
const project = readStore().projects[foldKey(worktree)];
if (!project) return { entry: null, from: null };
const spec = specKey(specDir);
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
}
// The workspace's folders as the store keeps them.
export function rememberable(ws) {
const folders = (ws && ws.folders) || [];
const first = folders.find((f) => f.original) || {};
return {
version: 0,
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
missing: [],
changes: [],
remote: "",
original: { name: first.name || "", description: first.description || "" },
folders: folders
.filter((f) => !f.original)
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
at: nowIso(),
};
}
// Every server and `console.mjs forget` writes the one file, so each
// read-modify-write holds this lock beside it.
const WORKSPACES_LOCK = "workspaces.json.lock";
// Save the list for this folder and spec ("" for the project's own).
export function rememberWorkspace(worktree, specDir, ws) {
ensureDir(path.dirname(WORKSPACES_FILE));
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
}
function saveRemembered(worktree, specDir, ws) {
const store = readStore();
const key = foldKey(worktree);
const project = store.projects[key] || { path: path.resolve(worktree) };
const spec = specKey(specDir);
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
else project.project = rememberable(ws);
store.projects[key] = project;
writeJsonAtomic(WORKSPACES_FILE, store);
}
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
export function forgetWorkspace(worktree, specDir) {
const spec = specKey(specDir);
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
}
function dropRemembered(worktree, spec) {
const store = readStore();
const project = store.projects[foldKey(worktree)];
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
delete project.specs[spec];
writeJsonAtomic(WORKSPACES_FILE, store);
return true;
}
// Single-writer rule: only server.mjs may call this.
export function writeWorkspace(dir, ws) {
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
@@ -2505,6 +2505,9 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
actions stay put. */
.modal.workspace { max-width: 680px; }
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
.workspace .modal-blurb { margin-bottom: 6px; }
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
.workspace-list {
list-style: none; margin: 0; padding: 0;
display: grid; gap: 12px;
@@ -2542,6 +2542,7 @@ function renderDashboard(main) {
const specs = specList();
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
wrap.appendChild(hideUnavailableToggle());
if (!local.launching && !launchScoping) syncWorkspaceScope();
// "Unavailable" is the scan's verdict for the selected spec, not the
// momentary greying while a launch is in flight or the server is away, so
@@ -2963,6 +2964,11 @@ async function launchSkill(entry) {
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected.
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
// dashboard, which would otherwise sync back to the picker's spec.
launchScoping = true;
await syncWorkspaceScope(target ? target.dir : "");
try {
const res = await fetch("/submit", {
method: "POST",
@@ -2973,6 +2979,7 @@ async function launchSkill(entry) {
}),
});
if (res.status === 409) {
launchScoping = false;
pendingResult = true;
banner("Your last pick is still being picked up. One moment.", "info");
return;
@@ -2980,10 +2987,12 @@ async function launchSkill(entry) {
if (!res.ok) throw new Error(String(res.status));
sound("startSkill");
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
launchScoping = false;
pendingResult = true;
save();
render();
} catch {
launchScoping = false;
banner("That did not go through. Nothing was lost; try again.", "warn");
}
}
@@ -5854,6 +5863,32 @@ async function postJson(url, body) {
}
}
/* The workspace follows the dashboard's picker: the folders remembered for
the selected spec, or the project's own under "Start from scratch". The
server swaps the list and remembers every change after it. */
let scopeAsked = null;
// True from a launch's scope sync until its send has gone (or failed).
let launchScoping = false;
async function syncWorkspaceScope(spec) {
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
scopeAsked = want;
const { status, body } = await postJson("/workspace/scope", { spec: want });
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
scopeAsked = null;
if ($("workspace-modal").open) renderWorkspace();
}
// The dialog's "Remembered for" line: whose list this is.
function workspaceScopeText() {
const scope = (wsFrame && wsFrame.scope) || "";
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
const spec = specList().find((s) => s.dir === scope);
const name = spec ? spec.name : scope.split("/").pop();
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
}
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
// The folder whose Remove is waiting on its inline confirm, by id.
@@ -5893,6 +5928,7 @@ function renderWorkspace() {
}
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
$("workspace-scope").textContent = workspaceScopeText();
}
function workspaceRow(f) {
@@ -833,10 +833,28 @@
Click the folder name in the middle of the bottom bar. It shows your
folder's name and branch, such as <strong>shop · main</strong>, and
<strong>shop + 2 folders · main</strong> once you have added some.
The workspace lasts for this console session only: it carries across
steps you start from the dashboard, and a new console session starts
with just the folder you started in.
It carries across steps you start from the dashboard.
</p>
<h4>Remembered for next time</h4>
<ul>
<li>
Every change is saved as you make it, so the next console session in
this folder starts with the same folders.
</li>
<li>
Each spec keeps its own list. The first time you pick a spec on the
dashboard it starts as a copy of the project's list (the one shown
under <strong>Start from scratch</strong>), and after that the two
are separate. Picking a spec loads its list; the line under the
dialog's title says whose list you are looking at.
</li>
<li>
The lists live in <code>workspaces.json</code> in your own
Plan2Code settings folder, beside your look and feel, never in the
project. Finalize offers to forget a spec's list when it archives the
spec.
</li>
</ul>
<h4>Adding a folder</h4>
<ul>
<li>
@@ -1363,9 +1381,10 @@
<h4>What it counts</h4>
<p>
Each step you run here adds points: a plan or a set of documents
weighs more than a single answered question, and a built phase more
still, by how many tasks it completed: a big phase adds more than a
small one. Every two questions you answer add a point too, so a long
weighs more than a quick task, and a built phase more still, by how
many tasks it completed: a big phase adds more than a small one.
Every two questions you answer within one step add a point too
(rounded down, so a single answer adds nothing), so a long
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
points, with what it added. It is a rule of thumb, not a
reading of Plan2Code's real memory: long sessions tend to make it
@@ -2003,6 +2022,7 @@
The folders the agent uses as context this session. It reads the extra ones for
reference and only changes them if you ask.
</p>
<p class="workspace-scope" id="workspace-scope"></p>
<ul class="workspace-list" id="workspace-list"></ul>
<div class="workspace-add">
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
@@ -45,7 +45,10 @@ import {
readLedger,
readOverview,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
remoteWarning,
specKey,
typedCount,
withStateLock,
writeJsonAtomic,
@@ -326,7 +329,9 @@ function workspaceNow() {
return ws;
}
const root = sessionWorktree();
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
const scope = specKey(stateNow?.specDir);
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
@@ -347,13 +352,87 @@ function saveWorkspace(ws) {
// One change: a new version, an entry in the change log the agent is handed,
// the file, and every open page.
function bumpWorkspace(ws, change) {
function bumpWorkspace(ws, change, { remember = true } = {}) {
ws.version = (ws.version || 0) + 1;
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
saveWorkspace(ws);
// Remembered for the next console session too. A folder gone missing or
// found again is not a change of mind, so it is not saved.
if (remember) rememberNow(ws);
pushState();
}
function rememberNow(ws) {
const root = sessionWorktree();
if (!root) return;
try {
rememberWorkspace(root, ws.scope || "", ws);
} catch {}
}
/**
* Point the workspace at another spec ("" for the project's own list) and
* swap in what was remembered there, logging each difference as a change so
* the agent's cursor stays truthful. A spec with nothing saved starts from
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
* list it has and saves it as the spec's (`seed: "current"`, a spec created
* mid-run). Folders keep their ids when their path stays.
*/
function setScope(ws, spec, seed = "project") {
const root = sessionWorktree();
const next = specKey(spec);
if (!root || (ws.scope || "") === next) return false;
const found = rememberedWorkspace(root, next);
ws.scope = next;
if (next && found.from !== "spec" && seed === "current") {
saveWorkspace(ws);
rememberNow(ws);
pushState();
return true;
}
const want = initialWorkspace(root, found.entry).folders;
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
const kept = new Set();
const folders = [];
const changes = [];
for (const w of want) {
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
if (!have) {
folders.push({ ...w, id: "pending" });
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
continue;
}
kept.add(have);
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
if ((have.description || "") !== (w.description || "")) {
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
}
folders.push({ ...have, name: w.name, description: w.description || "" });
}
for (const f of ws.folders) {
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
}
ws.folders = folders.filter((f) => f.id !== "pending");
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
if (!changes.length) {
saveWorkspace(ws);
pushState();
}
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
checkFolders(ws);
return true;
}
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
// learns its spec late) takes the workspace with it.
function followSpecDir(state) {
const spec = specKey(state && state.specDir);
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
}
function isFolder(p) {
try {
return fs.statSync(p).isDirectory();
@@ -370,10 +449,10 @@ function checkFolders(ws) {
const marked = ws.missing.includes(f.id);
if (!there && !marked) {
ws.missing = [...ws.missing, f.id];
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
} else if (there && marked) {
ws.missing = ws.missing.filter((id) => id !== f.id);
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
}
}
}
@@ -402,8 +481,8 @@ function folderIssues(entries) {
}
function workspaceView() {
const { folders, missing, remote } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) };
const { folders, missing, remote, scope } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
}
// Whether child sits strictly under parent.
@@ -492,6 +571,7 @@ function bootWorkspace() {
saveWorkspace(ws);
}
checkFolders(ws);
followSpecDir(stateNow);
}
/**
@@ -1403,6 +1483,24 @@ const server = http.createServer((req, res) => {
});
}
// Which list the workspace is: a spec's, or the project's (`spec` empty).
// The dashboard's picker sends it as the selection moves and before a
// launch, so a skill opens on the list of the spec it was launched for.
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
try {
setScope(workspaceNow(), spec, "project");
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, workspaceView());
});
}
// Only ever returns a path: the page then adds it through /workspace/add.
if (pathname === "/workspace/browse" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
@@ -1561,6 +1659,9 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
pushState();
}
lastStateStamp = stamp;
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-02",
"releaseDate": "2026-10-04",
"mode": "utility"
}
@@ -0,0 +1,120 @@
#!/usr/bin/env node
// commit-msg.mjs: the team's commit message, built from the branch name.
//
// Every Plan2Code skill that suggests a commit uses one format:
//
// <subject>
//
// <JIRA-Ticket-ID>
// AI Assisted
//
// and derives the ticket from a branch named <prefix>/<TICKET-ID>-description,
// where the ticket is an uppercase project key, a hyphen and an integer
// (ABC-10968). This script reads the branch, extracts the ticket and prints
// the exact command, so no prompt re-implements the rule by eye.
import { execFileSync } from "node:child_process";
import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
const USAGE = `
commit-msg.mjs: build the team's commit command from the current branch. JSON on stdout.
node commit-msg.mjs --subject "<subject>" [--add-all | --files <path> ...] [--ticket <ID>]
--subject the one-line description (at most 100 characters). No double
quotes (straight or curly), backticks, $, backslashes or ! in it,
so the command pastes unchanged into bash, zsh and PowerShell.
--add-all prefix the command with "git add -A &&".
--files prefix it with "git add -- <files> &&" (repeat --files per path).
--ticket use this ticket ID instead of reading the branch.
Prints { ok, branch, ticket, subject, message, command, add, commit }. The
commit is three -m flags, exactly: subject, ticket, "AI Assisted". command is
add && commit, one line for bash, zsh and PowerShell 7+. Windows PowerShell 5.1
has no &&: run add (null when nothing is staged) and then commit as two
commands. Nothing is run.
Exit: 0 ok · 2 bad arguments (including a stray argument: one --files per
path) · 3 not a git repository / no branch (detached HEAD) · 4 the branch
carries no ticket ID, --ticket is not KEY-123, the subject breaks a rule, or a
path cannot be quoted safely.
`;
// The ticket is the first <KEY>-<number> path segment start after a "/" (or the
// branch start), ended by "-", "_", "/" or the end of the name.
const TICKET_RE = /(?:^|\/)([A-Z][A-Z0-9]*-\d+)(?=[-_/]|$)/;
function ticketFromBranch(branch) {
const m = String(branch || "").match(TICKET_RE);
return m ? m[1] : null;
}
function git(args) {
try {
return { ok: true, out: execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim() };
} catch {
return { ok: false };
}
}
function currentBranch() {
if (!git(["rev-parse", "--git-dir"]).ok) {
fail(EXIT.NOT_FOUND, "not-a-repo", "This directory is not inside a git repository.", "Run from the project root, or skip the commit suggestion.");
}
// symbolic-ref names the branch even before the first commit, where
// rev-parse --abbrev-ref HEAD fails; it fails only on a detached HEAD.
const ref = git(["symbolic-ref", "--short", "-q", "HEAD"]);
if (!ref.ok || !ref.out) fail(EXIT.NOT_FOUND, "detached-head", "HEAD is detached, so there is no branch name to read a ticket from.", "Ask the user for the ticket ID and pass --ticket <ID>.");
return ref.out;
}
// A path goes into the command as-is when it is plainly safe, in single quotes
// otherwise (literal in bash, zsh and PowerShell alike). Backslashes become
// forward slashes, which git accepts on every platform. A leading @ or - is
// quoted too: unquoted, PowerShell reads @types as a splat and the path
// vanishes. The command's `git add --` means a leading - is never an option.
function quoteFile(f) {
const p = f.replace(/\\/g, "/");
if (/^[\w./:+][\w./:@+-]*$/.test(p)) return p;
// PowerShell treats the curly single quotes as quote characters too.
if (/['\u2018-\u201B]/.test(p)) fail(EXIT.INVALID, "unsafe-path", `The path ${p} contains a single quote, which cannot be quoted the same way in bash and PowerShell.`, "Use --add-all, or leave that file out and stage it by hand.");
return `'${p}'`;
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["add-all"], values: ["subject", "ticket"], lists: ["files"] });
if (args._.length) fail(EXIT.USAGE, "stray-argument", `Unexpected argument(s): ${args._.join(" ")}.`, "Each path needs its own --files (e.g. --files a.js --files b.js); quote a subject with spaces.");
const subject = (args.subject || "").trim();
if (!subject) fail(EXIT.USAGE, "missing-subject", "--subject is required.", 'Example: --subject "Add the export endpoint"');
if (/[\r\n]/.test(subject)) fail(EXIT.INVALID, "multiline-subject", "The subject must be one line.", "The diff is the body; keep the subject to one line.");
if (subject.length > 100) fail(EXIT.INVALID, "subject-too-long", `The subject is ${subject.length} characters; the limit is 100.`, "Shorten it; the diff is the body and the PR is the explanation.");
// Inside "...": PowerShell ends the string at a curly double quote too,
// bash and zsh treat \ as an escape, and ! is history expansion in an
// interactive bash or zsh.
if (/["`$\\!\u201C-\u201F]/.test(subject)) fail(EXIT.INVALID, "unsafe-subject", "The subject contains a double quote (straight or curly), backtick, $, backslash or !, which bash, zsh and PowerShell read differently inside double quotes.", "Rephrase without those characters (single quotes are fine).");
if (args["add-all"] && args.files) fail(EXIT.USAGE, "add-conflict", "Use --add-all or --files, not both.", "Pick one.");
let branch = null;
let ticket = args.ticket ? args.ticket.trim() : null;
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like ABC-10968.");
if (!ticket) {
branch = currentBranch();
ticket = ticketFromBranch(branch);
if (!ticket) {
fail(EXIT.INVALID, "no-ticket", `The branch "${branch}" has no <prefix>/<TICKET-ID>-description ticket in it.`, "Ask the user for the ticket ID, then rerun with --ticket <ID>; or show the command with <JIRA-Ticket-ID> for them to fill in.");
}
}
const add = args["add-all"] ? "git add -A" : args.files ? `git add -- ${args.files.map(quoteFile).join(" ")}` : null;
const commit = `git commit -m "${subject}" -m "${ticket}" -m "AI Assisted"`;
out({
ok: true,
branch,
ticket,
subject,
message: `${subject}\n\n${ticket}\nAI Assisted`,
command: add ? `${add} && ${commit}` : commit,
add,
commit,
});
});
@@ -0,0 +1,247 @@
// Plan2Code skill scripts: shared plumbing.
//
// Every script in a skill's scripts/ directory imports this file. It owns the
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
//
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
// on a handled failure.
// stderr a one-line human diagnostic on failure (the same message + next).
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
// 4 invalid input or a check that failed · 5 refused (would clobber
// or break a rule).
//
// Node 18+ built-ins only, no build step: this ships inside every skill.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
export class CliError extends Error {
constructor(exit, error, message, next) {
super(message);
this.exit = exit;
this.error = error;
this.next = next;
}
}
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
export function fail(exit, error, message, next) {
throw new CliError(exit, error, message, next);
}
export function out(obj) {
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
}
/**
* Parse argv into { _: positionals, <flag>: value }.
* `booleans` names flags that take no value; every other `--flag` takes the
* next argument, and repeats of a flag listed in `lists` collect into an array.
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
* silently changes behavior.
*/
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
const known = new Set([...booleans, ...values, ...lists, "help"]);
const args = { _: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) {
args._.push(a);
continue;
}
let name = a.slice(2);
let value;
const eq = name.indexOf("=");
if (eq !== -1) {
value = name.slice(eq + 1);
name = name.slice(0, eq);
}
if (!known.has(name)) {
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
}
if (name === "help" || booleans.includes(name)) {
args[name] = true;
continue;
}
if (value === undefined) {
if (i + 1 >= argv.length) {
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
}
value = argv[++i];
}
if (lists.includes(name)) (args[name] ||= []).push(value);
else args[name] = value;
}
return args;
}
/**
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
* failure shape plus an exit code, and anything else into exit 1 with the stack
* on stderr. Sets process.exitCode rather than calling process.exit(), so
* stdout is never cut off mid-write.
*/
export async function run(usage, main) {
try {
const argv = process.argv.slice(2);
if (argv.includes("--help") || argv.includes("-h")) {
process.stdout.write(usage.trim() + "\n");
return;
}
await main(argv);
} catch (err) {
if (err instanceof CliError) {
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
process.exitCode = err.exit;
return;
}
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
process.exitCode = EXIT.CRASH;
}
}
/* ------------------------------------------------------------------ time */
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
// is what "today" means to the person reading the date in their files.
export function now() {
const pinned = process.env.PLAN2CODE_NOW;
if (pinned) {
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
const d = new Date(pinned);
if (!Number.isNaN(d.getTime())) return d;
}
return new Date();
}
const pad = (n) => String(n).padStart(2, "0");
/** YYYY-MM-DD */
export function isoDate(d = now()) {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
/** YYYYMMDD */
export function compactDate(d = now()) {
return isoDate(d).replace(/-/g, "");
}
/** YYYY-MM-DD HH:mm */
export function stamp(d = now()) {
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** HHMMSS */
export function clock(d = now()) {
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
}
/* ----------------------------------------------------------------- files */
export function readText(file) {
try {
return fs.readFileSync(file, "utf8");
} catch {
return null;
}
}
export function isDir(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
/** Write a file only when its content changes. Returns true when it wrote. */
export function writeIfChanged(file, content) {
const current = readText(file);
if (current === content) return false;
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
return true;
}
/** Normalise line endings for parsing; keep the original for writing back. */
export function eol(text) {
return text.includes("\r\n") ? "\r\n" : "\n";
}
/**
* phase-N.md per phase number. An exact phase-N.md always wins over a sibling
* such as phase-1-old.md; more than one candidate is reported, never guessed.
* Shared so every script that counts a spec's tasks reads the same files.
*/
export function phaseFiles(dir) {
const files = new Map();
const extra = new Map();
for (const name of fs.readdirSync(dir).sort()) {
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
if (!m) continue;
const n = Number(m[1]);
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
if (!files.has(n)) files.set(n, name);
else if (exact) {
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
files.set(n, name);
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
}
files.extra = extra;
return files;
}
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
export function rel(root, p) {
return path.relative(root, p).split(path.sep).join("/") || ".";
}
/* --------------------------------------------------------- the web console */
// The web console ships beside these scripts in every installed skill
// (references/web-console/), and in this repo it sits at src/web-console/. Its
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
// metrics-bait scan, so the scripts import it rather than keep a second copy.
const CONSOLE_LIB_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
];
let consoleLibPromise;
export function consoleLib() {
consoleLibPromise ||= (async () => {
for (const candidate of CONSOLE_LIB_CANDIDATES) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-lib-missing",
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
);
})();
return consoleLibPromise;
}
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
export function version() {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const text = readText(file);
if (!text) continue;
try {
const v = JSON.parse(text).version;
if (typeof v === "string") return v;
} catch {}
}
return null;
}
@@ -0,0 +1,138 @@
#!/usr/bin/env node
// review-scope.mjs: what a branch review would cover, from git.
//
// Review Mode's scope fallback is a fixed command sequence (status, diff, log,
// name-only against the base branch) followed by arithmetic: how many files,
// how many lines, what share are docs (the >70% rule), whether specs/ is in
// scope, whether the change is big enough to batch by risk. This script runs
// the sequence and does the arithmetic. Choosing the scope and the review type
// from the user's words stays with the agent.
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
const USAGE = `
review-scope.mjs: the branch-review scope from git. JSON on stdout.
node review-scope.mjs [--base <branch>] [--root <dir>]
--base the branch to compare against. Default: main if it exists (local or
origin), else master. The output says which one it used. With
neither (and no --base) it stops with no-base; only a repo with no
commits yet goes on, counting uncommitted changes alone.
Covers commits on this branch since it left the base (base...HEAD), plus
staged, unstaged and untracked changes. Prints the files with their status and
line counts, totals, the share of .md files, the doc/code classification
(docs or code when one side is more than 70% of files, else mixed),
specsInScope, batchByRisk (50+ files) and the commits.
Exit: 0 ok (check "empty") · 2 bad arguments · 3 not a git repository, the
--base branch does not exist, or (no --base) there is no main or master.
`;
function git(root, args, { allowFail = false } = {}) {
try {
// core.quotePath=false: a non-ASCII path comes back as itself, not as an escaped, quoted string.
return execFileSync("git", ["-c", "core.quotePath=false", ...args], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 });
} catch (err) {
if (allowFail) return null;
throw err;
}
}
function refExists(root, ref) {
return git(root, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { allowFail: true }) !== null;
}
function pickBase(root, wanted) {
const candidates = wanted ? [wanted, `origin/${wanted}`] : ["main", "origin/main", "master", "origin/master"];
for (const ref of candidates) if (refExists(root, ref)) return ref;
return null;
}
function parseNumstat(text, into, status) {
for (const line of (text || "").split("\n")) {
if (!line.trim()) continue;
const [a, d, ...rest] = line.split("\t");
let file = rest.join("\t");
// Renames print as "old => new" or "dir/{old => new}/f"; keep the new path.
// A move up a level ("d/{sub => }/f", "{sub => }/f") empties the brace, so
// the doubled or leading slash it leaves behind is dropped.
file = file.replace(/\{[^}]*=> ([^}]*)\}/, "$1").replace(/^.* => /, "").replace(/\/{2,}/g, "/").replace(/^\//, "");
const entry = into.get(file) || { path: file, status: new Set(), added: 0, deleted: 0, binary: false };
entry.status.add(status);
if (a === "-" || d === "-") entry.binary = true;
else {
entry.added += Number(a);
entry.deleted += Number(d);
}
into.set(file, entry);
}
}
// Prose docs only: a requirements.txt or CMakeLists.txt is not documentation.
const DOC_RE = /\.(md|mdx|markdown|rst|adoc)$/i;
run(USAGE, async (argv) => {
const args = parseArgs(argv, { values: ["base", "root"] });
const root = path.resolve(args.root || ".");
const top = git(root, ["rev-parse", "--show-toplevel"], { allowFail: true });
if (!top) fail(EXIT.NOT_FOUND, "not-a-repo", `${root} is not inside a git repository.`, "Ask the user which files to review (Focused scope).");
const repo = top.trim();
const branch = (git(repo, ["rev-parse", "--abbrev-ref", "HEAD"], { allowFail: true }) || "").trim() || null;
const base = pickBase(repo, args.base);
if (args.base && !base) fail(EXIT.NOT_FOUND, "no-base", `No branch named ${args.base} (or origin/${args.base}).`, "Pass an existing --base, or omit it to use main / master.");
// No main or master: counting only uncommitted work would hide every commit
// on the branch, so stop and ask for the trunk. A repo with no commits yet
// has nothing committed to miss, so it goes on.
if (!base && refExists(repo, "HEAD")) {
fail(EXIT.NOT_FOUND, "no-base", "There is no main or master branch (local or origin) to compare this branch with.", "Rerun with --base <trunk> (ask the user which branch is the trunk if unclear).");
}
const files = new Map();
let commits = [];
if (base) {
parseNumstat(git(repo, ["diff", "--numstat", "-M", `${base}...HEAD`], { allowFail: true }), files, "committed");
commits = (git(repo, ["log", "--oneline", "--no-decorate", `${base}..HEAD`], { allowFail: true }) || "").split("\n").filter(Boolean);
}
parseNumstat(git(repo, ["diff", "--numstat", "-M", "--cached"], { allowFail: true }), files, "staged");
parseNumstat(git(repo, ["diff", "--numstat", "-M"], { allowFail: true }), files, "unstaged");
for (const f of (git(repo, ["ls-files", "--others", "--exclude-standard"], { allowFail: true }) || "").split("\n").filter(Boolean)) {
let added = 0;
let binary = false;
try {
const buf = fs.readFileSync(path.join(repo, f));
if (buf.includes(0)) binary = true;
else if (buf.length) added = buf.toString("utf8").split("\n").length - (buf.at(-1) === 10 ? 1 : 0);
} catch {}
files.set(f, { path: f, status: new Set(["untracked"]), added, deleted: 0, binary });
}
const list = [...files.values()]
.map((f) => ({ ...f, status: [...f.status] }))
.sort((a, b) => a.path.localeCompare(b.path));
const docs = list.filter((f) => DOC_RE.test(f.path)).length;
const total = list.length;
const docShare = total ? docs / total : 0;
const lines = list.reduce((n, f) => n + f.added + f.deleted, 0);
out({
ok: true,
repo,
branch,
base,
...(base ? {} : { note: "No commits yet: only uncommitted changes are counted." }),
empty: total === 0,
counts: { files: total, lines, added: list.reduce((n, f) => n + f.added, 0), deleted: list.reduce((n, f) => n + f.deleted, 0), docs, code: total - docs },
docShare: Number(docShare.toFixed(2)),
mix: !total ? "none" : docShare > 0.7 ? "docs" : 1 - docShare > 0.7 ? "code" : "mixed",
// specs/ is gitignored, so git rarely sees it: the conversation is the
// better signal that a spec is under review.
specsInScope: list.some((f) => /^specs\//.test(f.path)),
batchByRisk: total >= 50,
commits,
files: list,
});
});
@@ -0,0 +1,676 @@
#!/usr/bin/env node
// specs.mjs: where every spec under specs/ stands, read from its files.
//
// The pipeline skills (plan, document, implement, revise-plan, finalize,
// review, handoff) all need the same filesystem facts: which specs exist, what
// a spec's PLAN-DRAFT says, which phases are open, how many tasks are done.
// Those have one correct answer, so this script computes them instead of each
// prompt re-deriving them by hand. It also performs the two mechanical writes
// (a Phase Checklist marker, the archive move), with --dry-run.
//
// Shell listing only matters to people: specs/ is gitignored, so editor search
// tools skip it. This script reads the disk directly and does not care.
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";
const USAGE = `
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
node specs.mjs list [--root <dir>]
Every active spec under specs/ (never specs--completed/), newest first:
state, detail, PLAN-DRAFT files with their **Status:** line, overview,
phase count. Also the names already archived in specs--completed/.
node specs.mjs status <spec> [--root <dir>]
One spec in full: the overview's Phase Checklist, Parallel Execution
Groups, per-phase task counts by marker, task-numbering problems,
completion, the implement phase-selection verdict ("next"), the pending
phases, and consistency checks. <spec> is specs/<name>, <name>, or a path
to its overview.md.
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).
document: total_tasks, tasks_per_phase, phase_count,
parallel_groups_identified computed; pass
--set verification_items_added=N (your Verification Summary's
Added total; the VERIFICATION comments are reported as a check).
finalize: completion_rate_at_audit, tasks_completed, tasks_total; pass
--set verification_failures_found=N
--set documentation_updates_needed=N.
node specs.mjs mark <spec> --phase <N> --to open|in-progress|done [--dry-run]
Set phase N's Phase Checklist marker in overview.md ([ ], [/], [x]).
done also sets the phase file's Status line (**Status:**, **Status**:
or Status:) to Complete (and warns if tasks are unfinished); open on a
Complete phase sets it to In Progress. Warns when the phase file has no
Status line. Refuses a phase with duplicate checklist rows, and refuses
in-progress -> open (started work stays marked).
node specs.mjs archive <spec> [--dry-run]
Move specs/<name>/ to specs--completed/<name>/. Refuses if the target
exists, or if <spec> is not a folder directly under specs/.
Markers: [ ] pending · [/] in progress · [x] complete · [!] blocked · [?] assumed.
Exit: 0 ok · 2 bad arguments · 3 spec not found · 4 cannot parse / check
failed · 5 refused.
`;
/* ------------------------------------------------------------- resolving */
function realOrResolved(p) {
try {
return fs.realpathSync.native(p);
} catch {
return path.resolve(p);
}
}
const samePath = (a, b) => (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
// Read-only commands (status, metrics) accept an archived spec, because
// Finalize reads its own spec after Step 6 moved it. Writes never do.
function resolveSpec(root, arg, { allowArchived = false } = {}) {
if (!arg) fail(EXIT.USAGE, "missing-spec", "Name the spec: specs/<name>, <name>, or its overview.md path.", "Run `specs.mjs list` to see the active specs.");
let p = arg.replace(/\\/g, "/").replace(/\/+$/, "");
if (/\/overview\.md$/i.test(p) || /\/phase-[^/]*\.md$/i.test(p)) p = p.replace(/\/[^/]+$/, "");
const abs = path.isAbsolute(p) ? p : p.includes("/") ? path.join(root, p) : path.join(root, "specs", p);
const relPath = rel(root, abs);
if (!allowArchived && /(^|\/)specs--completed(\/|$)/.test(relPath)) {
fail(EXIT.REFUSED, "archived-spec", `${relPath} is archived; the pipeline only changes active specs under specs/.`, "Pick an active spec from `specs.mjs list`.");
}
// A spec is a folder directly under specs/ (or specs--completed/ for a read).
// Without this, `archive .` would move all of specs/ and `archive ./src` a
// source folder.
const homes = [path.join(root, "specs"), ...(allowArchived ? [path.join(root, "specs--completed")] : [])].map(realOrResolved);
const parent = realOrResolved(path.dirname(path.resolve(abs)));
if (!homes.some((h) => samePath(h, parent))) {
fail(EXIT.REFUSED, "not-a-spec", `${relPath} is not a spec folder: a spec sits directly under specs/${allowArchived ? " (or specs--completed/)" : ""}.`, "Pass specs/<name> or <name>; run `specs.mjs list` to see the active specs.");
}
if (!isDir(abs)) {
fail(EXIT.NOT_FOUND, "spec-not-found", `No spec folder at ${relPath}.`, "Run `specs.mjs list` from the project root (or pass --root) to see the active specs.");
}
return { dir: abs, rel: relPath, name: path.basename(abs) };
}
/* -------------------------------------------------------------- parsing */
const MARKERS = { " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" };
// Task 2.3, a lettered sub-task 3.6a, or a named one such as a testing task 1.T.
const TASK_RE = /^\s*[-*] \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
const CHECKBOX_RE = /^\s*[-*] \[(.)\]/;
// The Status line in any of the forms people write it: **Status:**, **Status**:
// or a plain Status:, optionally as a list item. Groups: everything up to the
// value (kept as written when the value is rewritten), the value, trailing blanks.
const STATUS_RE = /^([ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*)(.+?)([ \t]*)$/m;
function statusOf(text) {
const m = (text || "").match(STATUS_RE);
return m ? m[2] : null;
}
/** A markdown section's lines: from its heading to the next heading of the same or higher level. */
function section(text, headingRe) {
const lines = text.split(/\r?\n/);
const start = lines.findIndex((l) => /^#{1,6}\s/.test(l) && headingRe.test(l));
if (start === -1) return null;
const level = lines[start].match(/^#+/)[0].length;
let end = lines.length;
for (let i = start + 1; i < lines.length; i++) {
const m = lines[i].match(/^(#+)\s/);
if (m && m[1].length <= level) {
end = i;
break;
}
}
return { start, end, lines: lines.slice(start + 1, end) };
}
function plainText(s) {
return s
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/[*_`]/g, "")
.replace(/\s+/g, " ")
.trim();
}
/** Phase Checklist rows: the first "Phase N" on each checkbox line names the phase. */
function parseChecklist(overview) {
const sec = section(overview, /Phase Checklist/i);
if (!sec) return { found: false, phases: [], unparsed: [] };
const phases = [];
const unparsed = [];
sec.lines.forEach((line, i) => {
const m = line.match(CHECKBOX_RE);
if (!m) return;
const text = plainText(line.replace(CHECKBOX_RE, ""));
const num = text.match(/\bPhase\s+(\d+)\b/i);
if (!num) {
unparsed.push({ line: sec.start + 2 + i, text: line.trim() });
return;
}
const after = text.slice(num.index + num[0].length).replace(/^\s*[:\-–—]\s*/, "");
const name = after.split(/\s+[-–—]\s+|\s+\(|\s+_\(|:\s|\s+see\s+phase-/i)[0].replace(/\s*phase-\d+\.md\s*$/i, "").trim();
phases.push({
number: Number(num[1]),
marker: m[1],
state: MARKERS[m[1]] || "unknown",
name: name.replace(/\s*\[Milestone[^\]]*\]\s*$/i, "") || `Phase ${num[1]}`,
line: sec.start + 2 + i,
});
});
return { found: true, phases, unparsed };
}
/** "2, 3", "2-4" and "2–4" (or an em dash) alike: ranges expand, so a group cell never loses a phase. */
function phaseList(cell) {
const outList = [];
for (const part of cell.match(/\d+\s*[-–\u2014]\s*\d+|\d+/g) || []) {
const r = part.match(/^(\d+)\s*[-–\u2014]\s*(\d+)$/);
if (r && Number(r[2]) >= Number(r[1]) && Number(r[2]) - Number(r[1]) < 100) {
for (let n = Number(r[1]); n <= Number(r[2]); n++) outList.push(n);
} else outList.push(...part.match(/\d+/g).map(Number));
}
return [...new Set(outList)];
}
/** Parallel Execution Groups table: real groups only (a named group with 2+ phases). */
function parseGroups(overview) {
const sec = section(overview, /Parallel Execution Groups/i);
if (!sec) return { found: false, groups: [] };
const groups = [];
const seen = new Set();
for (const line of sec.lines) {
if (!/^\s*\|/.test(line) || /^\s*\|[\s:|-]+\|\s*$/.test(line)) continue;
const cells = line.split("|").slice(1, -1).map((c) => c.trim());
if (cells.length < 2 || /^group$/i.test(cells[0])) continue;
const id = plainText(cells[0]);
const phases = phaseList(cells[1]);
// "None", a dash, a single phase, a group its author labelled sequential
// ("A (sequential)"), or a Phases cell written as a chain ("1 → 2") is not
// a parallel group.
if (!id || /^(none|-|–|—)$/i.test(id) || /\bsequential\b/i.test(id) || /→|->|\bthen\b/i.test(cells[1]) || phases.length < 2) continue;
const key = `${id}:${phases.join(",")}`;
if (seen.has(key)) continue;
seen.add(key);
groups.push({ id, phases, reason: plainText(cells[2] || "") });
}
return { found: true, groups };
}
function firstSentence(text) {
const t = plainText(text);
const m = t.match(/^(.+?[.!?])(\s|$)/);
return (m ? m[1] : t).slice(0, 240);
}
function parsePhaseFile(file, number) {
const text = readText(file) || "";
const lines = text.split(/\r?\n/);
const title = (lines.find((l) => /^#\s/.test(l)) || "").replace(/^#\s+/, "").trim();
const status = statusOf(text);
const counts = { pending: 0, "in-progress": 0, complete: 0, blocked: 0, assumed: 0, unknown: 0 };
const tasks = [];
const strayCheckboxes = [];
const unmatchedTasks = [];
let heading = "";
lines.forEach((line, i) => {
const h = line.match(/^#{1,6}\s+(.*)$/);
if (h) heading = plainText(h[1]);
const t = line.match(TASK_RE);
if (t) {
const state = MARKERS[t[1]] || "unknown";
counts[state]++;
const named = !/^\d+$/.test(t[3]);
tasks.push({ id: `${t[2]}.${t[3]}${t[4]}`, phase: Number(t[2]), seq: named ? null : Number(t[3]), named, suffix: t[4], marker: t[1], state, line: i + 1 });
return;
}
// A line that looks like a task but is not counted as one (Task 1.4A,
// "1. [ ] **Task", a non-bold "- [ ] Task 1.3") would make the audit undercount.
if (/^\s*(?:[-*]|\d+\.)\s+\[.\].*\bTask\s+\d+\./i.test(line)) unmatchedTasks.push({ line: i + 1, text: line.trim().slice(0, 120) });
if (CHECKBOX_RE.test(line)) strayCheckboxes.push({ line: i + 1, section: heading, text: line.trim().slice(0, 120) });
});
// Numbering: every task belongs to this phase, the base numbers run 1..n with
// no gaps or repeats, and a lettered task (3.6a) sits after its base (3.6).
// Named tasks (1.T) are outside the numeric sequence.
const numbering = [];
const bases = [];
for (const t of tasks) {
if (t.phase !== number) numbering.push(`Task ${t.id} is in phase-${number}.md but numbered for Phase ${t.phase}`);
if (!t.suffix && !t.named) bases.push(t.seq);
}
const seenIds = new Set();
for (const t of tasks) {
if (seenIds.has(t.id)) numbering.push(`Task ${t.id} appears more than once`);
seenIds.add(t.id);
if (t.suffix && !t.named && !bases.includes(t.seq)) numbering.push(`Task ${t.id} has no base Task ${t.phase}.${t.seq}`);
}
bases.forEach((seq, i) => {
if (seq !== i + 1 && !numbering.some((n) => n.startsWith("Task numbering"))) {
numbering.push(`Task numbering is not sequential: expected ${number}.${i + 1}, found ${number}.${seq}`);
}
});
const overviewSec = section(text, /^#{1,6}\s+Overview\b/i);
const goalText = overviewSec ? overviewSec.lines.join("\n").split(/\n\s*\n/).map((p) => p.trim()).find((p) => p && !/^[-*|>]/.test(p)) : "";
return {
title,
status,
goal: goalText ? firstSentence(goalText) : null,
total: tasks.length,
counts,
open: counts.pending + counts["in-progress"] + counts.blocked + counts.unknown,
// Open work a phase cannot be approved over; blocked tasks may stand ([!] is allowed at sign-off).
unfinished: counts.pending + counts["in-progress"] + counts.unknown,
tasks,
numbering,
strayCheckboxes,
unmatchedTasks,
};
}
function planDrafts(dir) {
return fs
.readdirSync(dir)
.filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n))
.sort()
.map((file) => ({
file,
archived: /-prev\.md$/i.test(file),
status: statusOf(readText(path.join(dir, file))),
}));
}
/* ---------------------------------------------------------------- status */
function specStatus(spec) {
const overviewPath = path.join(spec.dir, "overview.md");
const overview = readText(overviewPath);
const files = phaseFiles(spec.dir);
// An empty overview.md still exists; only a missing one is "no overview".
const hasOverview = overview !== null;
const checklist = hasOverview ? parseChecklist(overview) : { found: false, phases: [], unparsed: [] };
const groups = hasOverview ? parseGroups(overview) : { found: false, groups: [] };
const checks = [];
const check = (level, code, message) => checks.push({ level, code, message });
for (const [n, names] of files.extra) {
check("warn", "duplicate-phase-file", `Phase ${n} has more than one file: using ${files.get(n)}, ignoring ${names.join(", ")}`);
}
const rowsByNumber = new Map();
for (const r of checklist.phases) rowsByNumber.set(r.number, [...(rowsByNumber.get(r.number) || []), r]);
for (const [n, rows] of rowsByNumber) {
if (rows.length > 1) check("error", "duplicate-checklist-row", `Phase ${n} has ${rows.length} rows in the Phase Checklist (overview.md lines ${rows.map((r) => r.line).join(", ")}); the first one is used`);
}
const phases = [];
const numbers = new Set([...checklist.phases.map((p) => p.number), ...files.keys()]);
for (const number of [...numbers].sort((a, b) => a - b)) {
const row = checklist.phases.find((p) => p.number === number) || null;
const file = files.get(number) || null;
const parsed = file ? parsePhaseFile(path.join(spec.dir, file), number) : null;
phases.push({
number,
name: row ? row.name : parsed ? parsed.title.replace(/^Phase\s+\d+\s*[:\-–—]?\s*/i, "") : `Phase ${number}`,
checklist: row ? row.state : null,
marker: row ? row.marker : null,
file,
status: parsed ? parsed.status : null,
goal: parsed ? parsed.goal : null,
tasks: parsed ? { total: parsed.total, open: parsed.open, ...parsed.counts } : null,
blockedTasks: parsed ? parsed.tasks.filter((t) => t.state === "blocked").map((t) => t.id) : [],
assumedTasks: parsed ? parsed.tasks.filter((t) => t.state === "assumed").map((t) => t.id) : [],
openTasks: parsed ? parsed.tasks.filter((t) => ["pending", "in-progress", "blocked", "unknown"].includes(t.state)).map((t) => t.id) : [],
});
if (!row && hasOverview) check("error", "missing-checklist-row", `phase-${number}.md has no row in overview.md's Phase Checklist`);
if (row && !file) check("error", "missing-phase-file", `Phase Checklist lists Phase ${number} but there is no phase-${number}.md`);
if (parsed) {
for (const n of parsed.numbering) check("error", "task-numbering", `phase-${number}.md: ${n}`);
// Prerequisites and criteria are plain bullets by rule; other checkbox
// blocks (a Phase Testing list) are the template's own and are not tasks.
for (const s of parsed.strayCheckboxes.filter((c) => /prerequisite|criteria/i.test(c.section))) {
check("warn", "criteria-checkbox", `phase-${number}.md:${s.line} is a checkbox under "${s.section}"; prerequisites and criteria use plain bullets`);
}
if (parsed.total === 0) check("warn", "no-tasks", `phase-${number}.md has no **Task ${number}.N:** checkbox lines`);
for (const u of parsed.unmatchedTasks) {
check("warn", "uncounted-task", `phase-${number}.md:${u.line} looks like a task but is not counted (a task line is "- [ ] **Task ${number}.N:**"): ${u.text}`);
}
const done = parsed.counts.complete + parsed.counts.assumed;
const rowDone = row && (row.state === "complete" || row.state === "assumed");
// A phase may be approved with blocked [!] tasks left (Implementation
// Mode's self-review allows "[x] or blocked [!]"); only unfinished work is an error.
if (rowDone && parsed.unfinished > 0) {
check("error", "checked-with-open-tasks", `Phase ${number} is [${row.marker}] in overview.md but ${parsed.unfinished} task(s) are not done (${phases.at(-1).openTasks.filter((id) => !phases.at(-1).blockedTasks.includes(id)).join(", ")})`);
} else if (rowDone && parsed.counts.blocked > 0) {
check("info", "approved-with-blocked", `Phase ${number} is [${row.marker}] with ${parsed.counts.blocked} blocked task(s) (${phases.at(-1).blockedTasks.join(", ")})`);
}
if (row && row.state === "pending" && parsed.total > 0 && done > 0) {
// Done tasks under a [ ] phase with work still open is what a re-opened
// phase looks like (revise-plan); with nothing open it is a missed mark.
if (parsed.unfinished > 0) check("info", "partly-done-unchecked", `Phase ${number} is [ ] with ${done} task(s) done and ${parsed.unfinished} open (normal for a re-opened phase)`);
else check("warn", "unchecked-with-done-tasks", `Phase ${number} is [ ] in overview.md but all ${done} unblocked task(s) are done`);
}
if (row && !rowDone && row.state !== "pending" && parsed.total > 0 && parsed.unfinished === 0) {
check("info", "done-not-approved", `Phase ${number}: every task is done but overview.md still shows [${row.marker}] (normal until the user approves the phase)`);
}
}
}
if (!hasOverview) check("error", "no-overview", `${spec.rel} has no overview.md`);
else if (!checklist.found) check("error", "no-checklist", "overview.md has no ## Phase Checklist section");
for (const u of checklist.unparsed) check("warn", "unparsed-checklist-row", `overview.md:${u.line} is a checkbox in the Phase Checklist with no "Phase N" in it: ${u.text}`);
for (const g of groups.groups) {
for (const n of g.phases) if (!numbers.has(n)) check("error", "group-unknown-phase", `Parallel group ${g.id} names Phase ${n}, which does not exist`);
}
// Totals. Completed = [x] plus [?] (assumed complete); [?] is reported on its own too.
// Incomplete = [ ] + [/] (+ unreadable markers); Blocked is its own column.
const totals = { total: 0, complete: 0, assumed: 0, pending: 0, "in-progress": 0, blocked: 0, unknown: 0 };
for (const p of phases) if (p.tasks) for (const k of Object.keys(totals)) totals[k] += p.tasks[k] || 0;
const completed = totals.complete + totals.assumed;
const completion = totals.total ? completed / totals.total : null;
return {
ok: true,
spec: spec.rel,
name: spec.name,
overview: hasOverview ? "overview.md" : null,
planDrafts: planDrafts(spec.dir),
phases,
parallelGroups: groups.groups,
totals: { ...totals, completed, incomplete: totals.pending + totals["in-progress"] + totals.unknown },
completion: completion === null ? null : Number(completion.toFixed(4)),
completionPercent: completion === null ? null : Math.round(completion * 100),
next: nextPhase(phases, groups.groups, checklist.found),
pending: phases
.filter((p) => p.checklist && p.checklist !== "complete" && p.checklist !== "assumed")
.map((p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null, open: p.tasks ? p.tasks.open : null, goal: p.goal })),
checks,
};
}
/**
* Implementation Mode's phase-selection table, applied mechanically.
* 2+ workable phases in the same parallel group, consecutive -> choose (warn if all [/])
* a single [/] -> ask-resume · a single [ ] -> auto-start · nothing workable -> none
*/
function nextPhase(phases, groups, haveChecklist) {
if (!haveChecklist) return { action: "none", reason: "no Phase Checklist in overview.md" };
const ordered = phases.filter((p) => p.checklist);
const isDone = (p) => p.checklist === "complete" || p.checklist === "assumed";
const workable = ordered.filter((p) => p.checklist === "pending" || p.checklist === "in-progress");
if (!workable.length) {
return { action: "none", reason: ordered.length && ordered.every(isDone) ? "every phase is complete" : "no [ ] or [/] phase in the Phase Checklist" };
}
const first = workable[0];
const brief = (p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null });
// A blocked [!] phase ahead of the pick is skipped, but never silently.
const skipped = ordered.slice(0, ordered.indexOf(first)).filter((p) => !isDone(p)).map(brief);
const note = skipped.length ? { skipped, warning: `skipping ${skipped.map((p) => `Phase ${p.number} [${p.state}]`).join(", ")} ahead of it` } : {};
const group = groups.find((g) => g.phases.includes(first.number));
if (group) {
// Consecutive same-group incomplete phases, in checklist order, starting at the first workable one.
const run = [];
for (const p of ordered.slice(ordered.indexOf(first))) {
if (!group.phases.includes(p.number)) break;
if (isDone(p)) continue;
if (p.checklist === "pending" || p.checklist === "in-progress") run.push(p);
else break;
}
if (run.length >= 2) {
const allStarted = run.every((p) => p.checklist === "in-progress");
const warnings = [
...(allStarted ? ["every option is already [/]: another agent may be working on it, so picking one risks duplicated work"] : []),
...(note.warning ? [note.warning] : []),
];
return {
action: "choose",
group: group.id,
options: run.map(brief),
...(note.skipped ? { skipped: note.skipped } : {}),
...(warnings.length ? { warning: warnings.join("; ") } : {}),
};
}
}
return { action: first.checklist === "in-progress" ? "ask-resume" : "auto-start", phase: brief(first), ...note };
}
/* --------------------------------------------------------------- commands */
async function cmdList(args) {
const root = path.resolve(args.root || ".");
const { scanProject } = await consoleLib();
const scan = scanProject(root);
const specs = scan.specs.map((s) => {
const dir = path.join(root, s.dir);
let names = [];
try {
names = fs.readdirSync(dir);
} catch {}
return {
dir: s.dir,
name: s.name,
state: s.state,
detail: s.detail,
touched: s.touched ? new Date(s.touched).toISOString() : null,
planDrafts: planDrafts(dir),
overview: names.includes("overview.md"),
phaseFiles: names.filter((n) => /^phase-\d+\b.*\.md$/i.test(n)).length,
pathfinder: isDir(path.join(dir, "pathfinder")),
};
});
let completed = [];
try {
completed = fs.readdirSync(path.join(root, "specs--completed")).filter((n) => isDir(path.join(root, "specs--completed", n))).sort();
} catch {}
out({
ok: true,
root,
hasAgents: scan.hasAgents,
specsDir: isDir(path.join(root, "specs")),
specs,
completed,
...(specs.length ? {} : { note: "No active specs under specs/." }),
});
}
async function cmdStatus(args) {
const root = path.resolve(args.root || ".");
out(specStatus(resolveSpec(root, args._[1], { allowArchived: true })));
}
function countVerificationAdded(dir) {
let n = 0;
for (const name of fs.readdirSync(dir)) {
if (!/\.md$/i.test(name) || /^PLAN-/i.test(name)) continue;
n += ((readText(path.join(dir, name)) || "").match(/<!--\s*VERIFICATION:\s*Added\b/gi) || []).length;
}
return n;
}
async function cmdMetrics(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1], { allowArchived: true });
const step = args.step;
if (step !== "document" && step !== "finalize") fail(EXIT.USAGE, "bad-step", "--step must be document or finalize.", "Plan's METRICS_JSON is written by hand in its Phase 7.");
const sets = {};
for (const kv of args.set || []) {
const m = kv.match(/^([a-z_]+)=(-?\d+(?:\.\d+)?)$/);
if (!m) fail(EXIT.USAGE, "bad-set", `--set ${kv} is not key=number.`, "Example: --set verification_failures_found=1");
sets[m[1]] = Number(m[2]);
}
// --set supplies the judgment fields only; the computed ones are never overridden.
const SETTABLE = { document: ["verification_items_added"], finalize: ["verification_failures_found", "documentation_updates_needed"] };
for (const k of Object.keys(sets)) {
if (!SETTABLE[step].includes(k)) fail(EXIT.USAGE, "bad-set", `--set ${k} is not a field you supply for --step ${step}.`, `Only ${SETTABLE[step].join(", ")}; the rest is computed from the files.`);
}
const st = specStatus(spec);
const withTasks = st.phases.filter((p) => p.tasks);
let metrics;
let hint;
if (step === "document") {
// verification_items_added is the Added total of the Verification Summary
// you presented, not something the files record, so it comes from --set.
// The <!-- VERIFICATION: Added --> comments are a cross-check only.
if (!("verification_items_added" in sets)) fail(EXIT.USAGE, "missing-set", "document needs --set verification_items_added=N (the Added column total of your Verification Summary).", `The spec has ${countVerificationAdded(spec.dir)} <!-- VERIFICATION: Added --> comment(s), as a cross-check.`);
metrics = {
step: "document",
total_tasks: st.totals.total,
tasks_per_phase: withTasks.map((p) => p.tasks.total),
phase_count: st.phases.length,
parallel_groups_identified: st.parallelGroups.length,
...sets,
};
hint = { verificationCommentsFound: countVerificationAdded(spec.dir) };
} else {
const missing = ["verification_failures_found", "documentation_updates_needed"].filter((k) => !(k in sets));
if (missing.length) fail(EXIT.USAGE, "missing-set", `finalize needs ${missing.map((k) => `--set ${k}=N`).join(" and ")}.`, "Those two counts are your judgment from Steps 2 and 4.");
metrics = {
step: "finalize",
completion_rate_at_audit: st.completion === null ? 0 : Number(st.completion.toFixed(2)),
tasks_completed: st.totals.completed,
tasks_total: st.totals.total,
...sets,
};
}
out({ ok: true, spec: spec.rel, metrics, comment: `<!-- METRICS_JSON ${spacedJson(metrics)} -->`, ...(hint || {}), checks: st.checks.filter((c) => c.level === "error") });
}
// The house style of every METRICS_JSON comment: {"key": value, "list": [1, 2]}.
function spacedJson(obj) {
const v = (x) => (Array.isArray(x) ? `[${x.map(v).join(", ")}]` : x && typeof x === "object" ? spacedJson(x) : JSON.stringify(x));
return `{${Object.entries(obj).map(([k, x]) => `${JSON.stringify(k)}: ${v(x)}`).join(", ")}}`;
}
const TO = { open: " ", "in-progress": "/", done: "x" };
async function cmdMark(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1]);
const number = Number(args.phase);
if (!Number.isInteger(number) || number < 0) fail(EXIT.USAGE, "bad-phase", "--phase needs a phase number.", "Example: --phase 2");
if (!(args.to in TO)) fail(EXIT.USAGE, "bad-to", "--to must be open, in-progress or done.", "open = [ ], in-progress = [/], done = [x]");
const overviewPath = path.join(spec.dir, "overview.md");
const overview = readText(overviewPath);
if (overview === null) fail(EXIT.NOT_FOUND, "no-overview", `${spec.rel} has no overview.md.`, "Run /plan2code-2-document first.");
const checklist = parseChecklist(overview);
const rows = checklist.phases.filter((p) => p.number === number);
const row = rows[0];
if (!row) fail(EXIT.NOT_FOUND, "no-row", `overview.md's Phase Checklist has no row for Phase ${number}.`, "Run `specs.mjs status` to see the phases it lists.");
if (rows.length > 1) fail(EXIT.REFUSED, "duplicate-row", `Phase ${number} has ${rows.length} rows in the Phase Checklist (lines ${rows.map((r) => r.line).join(", ")}); marking one would be a guess.`, "Remove the duplicate row, then rerun.");
const target = TO[args.to];
if (row.marker === "/" && target === " ") {
fail(EXIT.REFUSED, "no-reset", `Phase ${number} is [/]; started work is never reset to [ ].`, "Leave it [/] (a later session resumes it), or mark it done once approved.");
}
const changes = [];
const lines = overview.split(/\r?\n/);
const idx = row.line - 1;
const next = lines[idx].replace(/\[(.)\]/, `[${target}]`);
if (next !== lines[idx]) {
lines[idx] = next;
changes.push({ file: `${spec.rel}/overview.md`, line: row.line, from: `[${row.marker}]`, to: `[${target}]` });
}
// The phase file's Status line follows: done -> Complete; re-opening a Complete
// phase -> In Progress (revise-plan), so the two files never disagree.
let phaseText = null;
let phasePath = null;
let unfinished = [];
const warnings = [];
const file = phaseFiles(spec.dir).get(number);
if (file) {
phasePath = path.join(spec.dir, file);
const text = readText(phasePath) || "";
const parsed = parsePhaseFile(phasePath, number);
unfinished = parsed.tasks.filter((t) => ["pending", "in-progress", "unknown"].includes(t.state)).map((t) => t.id);
const status = statusOf(text);
const want = target === "x" ? "Complete" : target === " " && status && /^complete$/i.test(status) ? "In Progress" : null;
if (status && want && status !== want) {
phaseText = text.replace(STATUS_RE, (_, before, _value, after) => before + want + after);
changes.push({ file: `${spec.rel}/${file}`, field: "Status", from: status, to: want });
}
// done and open keep the Status line in step; with none to find, say so.
if (!status && target !== "/") warnings.push(`${file} has no Status line, so only the Phase Checklist checkbox changed; add a "**Status:** <value>" line under its title.`);
}
if (!args["dry-run"]) {
if (changes.some((c) => c.file.endsWith("overview.md"))) fs.writeFileSync(overviewPath, lines.join(eol(overview)));
if (phaseText !== null) fs.writeFileSync(phasePath, phaseText);
}
const doneEarly = target === "x" && unfinished.length > 0;
if (doneEarly) warnings.unshift(`Phase ${number} was marked done with ${unfinished.length} unfinished task(s): ${unfinished.join(", ")}. Mark only a phase the user approved.`);
out({
ok: true,
spec: spec.rel,
phase: number,
name: row.name,
dryRun: !!args["dry-run"],
changed: changes.length > 0,
changes,
...(warnings.length ? { warning: warnings.join(" ") } : {}),
...(doneEarly ? { unfinished } : {}),
});
}
function listRel(dir, base = dir) {
const outList = [];
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) outList.push(...listRel(p, base));
else outList.push(rel(base, p));
}
return outList.sort();
}
async function cmdArchive(args) {
const root = path.resolve(args.root || ".");
const spec = resolveSpec(root, args._[1]);
const target = path.join(root, "specs--completed", spec.name);
if (fs.existsSync(target)) {
fail(EXIT.REFUSED, "target-exists", `specs--completed/${spec.name}/ already exists; nothing was moved.`, "Ask the user whether to merge by hand or archive under another name.");
}
const files = listRel(spec.dir);
if (!args["dry-run"]) {
fs.mkdirSync(path.dirname(target), { recursive: true });
try {
fs.renameSync(spec.dir, target);
} catch (err) {
// A rename across volumes (or a locked file on Windows) fails; copy then remove.
try {
fs.cpSync(spec.dir, target, { recursive: true, errorOnExist: true, force: false });
} catch (copyErr) {
fail(EXIT.INVALID, "archive-failed", `Could not move or copy ${spec.rel} (${err.code || err.message}; copy: ${copyErr.code || copyErr.message}).`, `Close anything holding files in ${spec.rel} open, check specs--completed/${spec.name} for a partial copy, then rerun.`);
}
try {
fs.rmSync(spec.dir, { recursive: true, force: true });
} catch (rmErr) {
fail(EXIT.INVALID, "source-not-removed", `Copied to specs--completed/${spec.name}/ but could not remove ${spec.rel} (${rmErr.code || rmErr.message}); both copies now exist.`, `Close whatever holds files in ${spec.rel} open, then delete it by hand. The archive is complete.`);
}
}
}
const sourceGone = args["dry-run"] ? null : !fs.existsSync(spec.dir);
const moved = args["dry-run"] ? null : listRel(target);
if (!args["dry-run"] && !(sourceGone && moved.length === files.length)) {
fail(
EXIT.INVALID,
"archive-unverified",
`The move of ${spec.rel} to specs--completed/${spec.name}/ did not verify: ${moved.length} of ${files.length} file(s) at the target, and ${spec.rel} ${sourceGone ? "is gone" : "still exists"}.`,
`Compare ${spec.rel} with specs--completed/${spec.name}/ and finish the move by hand; archive refuses to rerun while the target exists.`
);
}
out({
ok: true,
dryRun: !!args["dry-run"],
from: spec.rel,
to: `specs--completed/${spec.name}`,
files,
...(args["dry-run"] ? {} : { sourceRemoved: sourceGone, filesAtTarget: moved.length, archivedOn: isoDate() }),
});
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "step", "phase", "to"], lists: ["set"] });
const cmd = args._[0];
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, archive: cmdArchive };
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, metrics, mark, archive. Run with --help.");
await commands[cmd](args);
});
@@ -0,0 +1,22 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"mode": "utility"
}
+26 -28
View File
@@ -16,6 +16,16 @@ QA engineer and technical lead performing rigorous final validation. Verify spec
The FIRST thing you do, before anything else in this file — before the Required Context check, before Step 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow finalize` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec specs/<feature-name>` if known, else post `specDir` later), then <D>/console.md → Finalize; the audit options, the doc-update approval and every cleanup confirmation go through it. Switchable anytime. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console.md → Launches), then the Required Context check.
## Scripts
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-4-finalize/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` / `status <spec>`: specs on disk; one spec's phases, task counts by marker, completion and `checks`. `status` also reads an archived spec.
- `node "<S>/specs.mjs" archive <spec> [--dry-run]`: the Step 6 move, verified.
- `node "<S>/specs.mjs" metrics <spec> --step finalize --set ...`: Step 7's METRICS_JSON line.
- `node "<S>/feedback-payload.mjs"`: Step 6.5 (see its reference).
- `node "<S>/commit-msg.mjs" --subject "<subject>"`: the commit command, ticket from the branch.
## Rules
- Follow `./AGENTS.md` if it exists
@@ -30,11 +40,7 @@ The FIRST thing you do, before anything else in this file — before the Require
### Required Context
⚠️ IMPORTANT: `specs/` is gitignored — NEVER use Glob (silently fails). Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
Need all implementation spec files. Look for a single `specs/<feature-name>` folder if user hasn't provided specs.
**NEVER look in `specs--completed/`** - that contains archived specs only.
Need all implementation spec files. If the user hasn't named the spec, run `specs.mjs list` (it reads gitignored `specs/` directly, where Glob silently finds nothing, and never offers `specs--completed/`, which holds archives only). Exactly one active spec → use it.
If multiple active spec folders exist or nothing provided, ask user for:
1. The entire `specs/<feature-name>/` directory: `overview.md` and all `phase-X.md` files
@@ -57,17 +63,16 @@ Complete steps in order. Report progress after each.
**Objective:** Verify all tasks across all phases completed.
1. Open each `phase-X.md` file
2. Count only `**Task X.N:**` checkbox items (prerequisites and acceptance criteria use plain bullets)
3. Verify each task status:
1. Run `specs.mjs status <spec>`. It counts only `**Task X.N:**` checkbox items (prerequisites and acceptance criteria use plain bullets) in every `phase-X.md`, by marker:
| Status | Meaning | Action |
|--------|---------|--------|
| `[x]` | Completed | Verify implementation exists |
| `[ ]` | Not started | Flag INCOMPLETE |
| `[!]` | Blocked | Document blocker |
| Marker | Meaning | Counts as | Action |
|--------|---------|-----------|--------|
| `[x]` | Completed | Completed | Verify implementation exists |
| `[?]` | Assumed complete | Completed | List it: it was never verified |
| `[ ]` / `[/]` | Not started / started | Incomplete | Flag INCOMPLETE |
| `[!]` | Blocked | Incomplete | Document blocker |
3. Create audit table:
2. Build the audit table from each phase's `tasks` (Completed = `complete` + `assumed`; Incomplete = `pending` + `in-progress`; each phase's `openTasks`, `blockedTasks` and `assumedTasks` name them; the Total row is `totals`):
```markdown
## Task Completion Audit
@@ -77,7 +82,7 @@ Complete steps in order. Report progress after each.
| **Total** | **X** | **X** | **X** | **X** |
```
4. Calculate: `(Completed / Total) * 100`
3. Completion is `completionPercent` (Completed / Total). Report any `error` in `checks` too (e.g. a phase marked `[x]` in overview.md with open tasks).
#### If incomplete tasks exist:
@@ -245,13 +250,9 @@ Ask: "Submit this feedback + run metrics to the maintainer via GitHub? (optional
**Confirm with user before moving files.**
1. Create: `specs--completed/<feature-name>/`
2. Move all contents of `specs/<feature-name>/`:
- `overview.md` (with completion summary)
- All `phase-X.md` files
- `PLAN-DRAFT.md`, `PLAN-CONVERSATION-*.md`, `pathfinder/` (if present)
3. Remove temporary scratch files not part of the final spec record
4. Verify original directory empty and can be removed
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.
---
@@ -282,7 +283,7 @@ Read references/community-feedback-submission.md
<!-- METRICS_JSON {"step": "finalize", "completion_rate_at_audit": 0.95, "tasks_completed": 19, "tasks_total": 20, "verification_failures_found": 1, "documentation_updates_needed": 2} -->
Replace METRICS_JSON values with actuals. `completion_rate_at_audit` = Y/Z as decimal (e.g., 19/20 = 0.95).
Paste the `comment` from `specs.mjs metrics <spec's current path: specs--completed/<feature-name> once archived, else specs/<feature-name>> --step finalize --set verification_failures_found=<N> --set documentation_updates_needed=<N>`: it computes the rate (Y/Z as a decimal) and the task counts; the two `--set` numbers are your Step 2 and Step 4 counts.
### Finalization Steps Completed
- [x] Step 1: Task Completion Audit
@@ -322,7 +323,7 @@ Replace METRICS_JSON values with actuals. `completion_rate_at_audit` = Y/Z as de
| Completion | Action |
|-----------|--------|
| **>75%** | Finalize with notice. List incomplete items. Note remaining tasks for follow-up cycle. |
| **≥75%** | Finalize with notice. List incomplete items. Note remaining tasks for follow-up cycle. |
| **<75%** | Recommend returning to implementation. List incomplete phases with task counts. Options: 1) Return via `/plan2code-3-implement --web` 2) Proceed with partial finalization. |
## Abort Handling
@@ -348,10 +349,7 @@ If you discovered undocumented commands, dependency quirks, gotchas (>5min cost)
(Step 7 already delivered the completion summary — don't repeat it.)
Suggested commit (only if README, CHANGELOG, or other tracked docs were updated):
```
git commit -m "chore: finalize and archive <feature-name>" -m "<JIRA-Ticket-ID>" -m "AI Assisted"
```
Suggested commit (only if README, CHANGELOG, or other tracked docs were updated): the `command` from `commit-msg.mjs --subject "chore: finalize and archive <feature-name>"` (exit 4 `no-ticket`: show it with `<JIRA-Ticket-ID>` for the user to fill in).
Returning context: Feature complete. Specs archived to `specs--completed/<feature-name>/`.
@@ -2,52 +2,39 @@
> Loaded by `src/plan2code-4-finalize.md` STEP 6.5. This file has no character limit (see `AGENTS-architecture.md` Reference Files).
## 1. Generate a fresh `run_id`
Everything in the payload is read from files, so a script builds it: the metrics from the `METRICS_JSON` comments the pipeline already wrote, the task counts from the phase files, your Step 5 answers from overview.md's `## User Feedback` table, the installed version, and a sha256 prefix of each prompt. Your part is the two judgment counts, the preview, and the user's approval.
Compute your own current timestamp and a freshly generated random 4-character hex string — do not reuse the example value shown below or anywhere in this spec. Format: `run-<YYYYMMDD>-<HHMMSS>-<4-hex-chars>` (e.g. `run-20260715-143000-a1b2`).
## 1. Build the payload
## 2. Assemble the payload
Step 6 has already archived the spec, so point at the archive:
Read `PLAN-DRAFT-*.md`, `phase-*.md`, and `overview.md` in `specs--completed/<feature-name>/` (STEP 6 has already archived them there) and reason over their content to gather:
- `step1`: `final_confidence`, `confidence_breakdown` (`{requirements, feasibility, integration, risk}`), `clarification_rounds`, `tech_stack_revision_rounds`, `verification_gaps_found`, `functional_requirements_count`, `non_functional_requirements_count`, `risk_count`, `phase_count`
- `step2`: `total_tasks`, `phase_count`, `parallel_groups_identified`, `requirement_coverage_percent`, `verification_items_added`
- `step3`: `task_completion_rate`, `tasks_completed`, `tasks_total`, `blocker_count`
- `step4`: `completion_rate_at_audit`, `verification_failures_found`, `documentation_updates_needed`, `archival_succeeded` (safe to read now that Step 6 has run)
- `plan2code_version` — from `version.json`
- `prompt_versions_short` — first 12 characters of each of the 8 prompt file names' content (`plan`, `revise_plan`, `document`, `implement`, `finalize`, `init`, `init_update`, `quick_task`). You do not have `sha256File()` available — note these as best-effort/approximate if you cannot compute a real hash, or omit the field entirely if you cannot.
**Never include** `project.name` or any bulky arrays (e.g. `tasks_per_phase`).
Include the feedback collected at Step 5 as `user_feedback`: `overall_rating`, `rating_reason`, `what_went_well`, `what_went_poorly`.
Assemble the full nested JSON object matching this schema exactly:
```json
{
"schema_version": "1.0",
"run_id": "run-<YYYYMMDD>-<HHMMSS>-<4-hex>",
"plan2code_version": "<from version.json>",
"prompt_versions_short": { "plan": "...", "revise_plan": "...", "document": "...", "implement": "...", "finalize": "...", "init": "...", "init_update": "...", "quick_task": "..." },
"step1": { "final_confidence": 0, "confidence_breakdown": { "requirements": 0, "feasibility": 0, "integration": 0, "risk": 0 }, "clarification_rounds": 0, "tech_stack_revision_rounds": 0, "verification_gaps_found": 0, "functional_requirements_count": 0, "non_functional_requirements_count": 0, "risk_count": 0, "phase_count": 0 },
"step2": { "total_tasks": 0, "phase_count": 0, "parallel_groups_identified": 0, "requirement_coverage_percent": 0, "verification_items_added": 0 },
"step3": { "task_completion_rate": 0, "tasks_completed": 0, "tasks_total": 0, "blocker_count": 0 },
"step4": { "completion_rate_at_audit": 0, "verification_failures_found": 0, "documentation_updates_needed": 0, "archival_succeeded": true },
"user_feedback": { "overall_rating": 0, "rating_reason": "...", "what_went_well": "...", "what_went_poorly": "..." }
}
```
node "<S>/feedback-payload.mjs" build specs--completed/<feature-name> --set verification_failures_found=<N> --set documentation_updates_needed=<N>
```
## 3. Render the GitHub Issue
If Step 6 did not archive (the archive target already existed), the spec is still in `specs/`: pass `specs/<feature-name>` instead. A bare `<feature-name>` that exists in both folders stops with exit 5 `ambiguous-spec` rather than guessing, because `specs--completed/<feature-name>` would be the older run.
- **Title:** `` `[Feedback] v<plan2code_version> — rating <N>/10` `` (e.g. `[Feedback] v1.15.3 — rating 8/10`)
- **Body:** a short human-readable markdown summary (version, rating, headline numbers such as completion rate and confidence), followed by the full payload as `<!-- METRICS_JSON {...} -->` (same HTML-comment convention used in Step 7's own summary block)
- **Label:** `community-feedback`
The two counts are the ones Step 7's METRICS_JSON carries (your Step 2 and Step 4 findings). It prints:
Estimate the combined URL-encoded size of `title` + `body` + `labels`. If it exceeds roughly 8KB, warn the user and offer to truncate the longest free-text `user_feedback` field(s) — starting with `rating_reason`, then `what_went_well`/`what_went_poorly` — before proceeding. This size limit only affects the browser/print fallback tiers (below), not the `gh` CLI tier.
| Field | Use |
|---|---|
| `title`, `body`, `label` | The exact issue to preview. The body ends with the full payload as `<!-- METRICS_JSON {...} -->` |
| `payload` | The schema-1.0 object: a fresh `run_id`, `plan2code_version`, `prompt_versions_short` (12-character sha256 prefixes), `step1`-`step4`, `user_feedback`. It never includes `project.name` or bulky arrays |
| `notes` | Missing METRICS_JSON blocks (that step is `null`, which the ingest side reads as not present). Mention them in one line |
| `oversize`, `urlBytes`, `next` | The prefilled browser URL is over ~8 KB. Offer to shorten the free-text answers; on yes, rebuild with `--truncate` (trims `rating_reason` first, then `what_went_well` / `what_went_poorly`). Tier 1 (`gh`) has no limit, so declining is fine only when `gh` is installed and signed in (`gh auth status`): if `gh` fails, `submit` stops with exit 4 `oversize` instead of falling back to the browser |
| `dir` | Where `payload.json` and `body.md` were written; `submit` needs it |
## 4. Preview and approval gate
| Exit | Meaning | Do |
|---|---|---|
| 2 `missing-set` | A judgment count is missing | Pass both `--set` values |
| 3 `no-feedback` | overview.md has no `## User Feedback` table | Nothing to submit: skip to Step 7 |
| 3 `spec-not-found` | Wrong name or not archived | Check `specs--completed/` |
| 4 `bad-rating` | The Rating row is not 1-10 | Fix the row, rebuild |
| 5 `ambiguous-spec` | A bare name exists in both `specs/` and `specs--completed/` | Pass the exact path: `specs/<feature-name>` if Step 6 did not archive this run |
Display the exact rendered title, full body (including the `METRICS_JSON` block), and label(s) to the user, mirroring the Step 4 Documentation Review pattern:
## 2. Preview and approval gate
Display the exact `title`, the full `body` (including the `METRICS_JSON` block), and the label to the user, mirroring the Step 4 Documentation Review pattern:
```
⋅
@@ -61,12 +48,25 @@ Display the exact rendered title, full body (including the `METRICS_JSON` block)
Do NOT proceed to submission without an explicit "approve" reply. A "skip" or any non-approval reply cancels this sub-step entirely and proceeds to Step 7 with no submission.
## 5. Tiered submission
## 3. Submit
On approval, attempt each tier in order until one succeeds:
On approval only:
1. **Tier 1 (primary):** Attempt `gh issue create --repo jparkerweb/plan2code --title "<title>" --body "<body>" --label community-feedback` via your shell tool. If it succeeds, report the created issue URL to the user and stop.
2. **Tier 2 (secondary):** If `gh` is not installed or not authenticated (command fails), construct the URL `https://github.com/jparkerweb/plan2code/issues/new?title=<url-encoded title>&body=<url-encoded body>&labels=community-feedback` and attempt to open it in the user's default browser using the OS-appropriate command (`start "<url>"` on Windows, `open "<url>"` on macOS, `xdg-open "<url>"` on Linux). Tell the user they still need to click "Submit issue" themselves since they must be logged in.
3. **Tier 3 (tertiary):** If no browser can be opened (e.g. no shell tool access, headless/remote session), print the same URL from Tier 2 to the terminal/chat: "Please open this URL in your browser and click 'Submit issue' to share your feedback: `<url>`".
```
node "<S>/feedback-payload.mjs" submit --from <dir>
```
After any tier succeeds (or the user manually confirms Tier 3 submission), proceed to Step 7 as normal.
It tries each tier in order and reports the one that worked:
| `tier` | What happened | Tell the user |
|---|---|---|
| 1 | `gh issue create` succeeded | The issue URL (`issue`) |
| 2 | `gh` missing or not signed in (`ghError`); the system was asked to open the prefilled new-issue page | If it opened, they still need to click **Submit new issue**, signed in to GitHub. If nothing opened (a remote or headless session), give them `url` as in tier 3 |
| 3 | No browser could be opened (headless or remote session) | "Please open this URL in your browser and click 'Submit new issue' to share your feedback:" plus `url` |
| Exit | Meaning | Do |
|---|---|---|
| 3 `no-payload` | `--from` has no `payload.json` / `body.md` | Pass the `dir` that `build` printed |
| 4 `oversize` | `gh` failed (`message` says why) and the URL is over ~8 KB, too long for tiers 2 and 3, so neither ran | Offer to shorten the free-text answers: on yes, rebuild with `--truncate` and submit again. Or have the user install `gh` and run `gh auth login`, then submit again |
`--dry-run` shows the tiers without running them, plus `urlBytes` and `oversize` (when `oversize` is true, only tier 1 can submit). After any tier succeeds (or the user confirms a tier 3 submission), proceed to Step 7 as normal.
@@ -556,8 +556,15 @@ enforces it, so never tell someone to keep asking past it.
The person can add folders beside the one the session started in (a shared
library, a design folder), from the footer's folder label. Together they are
the session's **workspace**: context for every skill run in this console
session, each folder addressed by a short `@name`. It outlives dashboard hops;
a new console session starts with the original folder alone.
session, each folder addressed by a short `@name`. It outlives dashboard hops,
and it is remembered: every change is saved to `workspaces.json` beside
`looks.json` (never into the project), keyed by the folder the session runs
in and then by spec. A session with a spec opens on that spec's list, one with
none on the project's; a spec with nothing saved starts as a copy of the
project's list. The dashboard's picker swaps the list as the selection moves,
and a `specDir` you post mid-run takes the current list with it. There is
nothing for you to load: `open` prints the list, and a switch of spec on a
resume reaches you as ordinary workspace changes on your next `wait`.
### What you are told
@@ -767,7 +774,7 @@ that is what the person is there to download. The finish carries no
sees the Trail Footer, and without this their last screen promises a question
that is never coming.
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
and `pathfinder-research` (id = the question's file slug) as each research
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
subagent reports back, or when you resolve a `research` question yourself
(Posting an update → Session meter). Other questions score through their
answers, so there is nothing to post for them.
@@ -820,7 +827,7 @@ know:
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) 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`. |
| 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). |
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
@@ -41,6 +41,7 @@ import {
die,
ensureDir,
fileStamp,
forgetWorkspace,
handOff,
handleFile,
healthOk,
@@ -65,6 +66,7 @@ import {
readLedger,
readWorkspace,
reapHandles,
rememberedWorkspace,
remoteWarning,
removeScratch,
removeSessions,
@@ -73,6 +75,7 @@ import {
SESSION_MAX_AGE_MS,
sessionDir,
sleepSync,
specKey,
staleScratch,
staleSessions,
sweepUploads,
@@ -317,7 +320,7 @@ async function cmdOpen() {
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
} catch {}
const workspace = workspaceOnOpen(dir, worktree);
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
// Month-old sessions and scratch files: listed before the print so the
// agent can see what went, removed after it so the page waits for nothing.
@@ -403,10 +406,11 @@ async function cmdOpen() {
* The workspace as `open` hands it to the agent, and the cursor seeded to
* match: the agent now has the whole list, so no change up to here is owed.
* Read-only on workspace.json, which only the server writes; on a fresh
* session the server has not made it yet, so the original folder stands in.
* session the server has not made it yet, so what was remembered for this
* folder and spec stands in, the same list the server is about to make.
*/
function workspaceOnOpen(dir, worktree) {
const ws = readWorkspace(dir) || initialWorkspace(worktree);
function workspaceOnOpen(dir, worktree, specDir) {
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
try {
writeWorkspaceCursor(dir, ws.version || 0);
@@ -946,6 +950,18 @@ function realNearest(p) {
return path.join(fs.realpathSync(existing), path.relative(existing, p));
}
/* --------------------------------------------------------------- forget */
// Drop the folder list remembered for one spec (Finalize, once the spec is
// archived). The project's own list and every other spec's are untouched.
function cmdForget() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
let spec = specKey(args.spec);
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
const worktree = repoRoots().worktree;
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
}
/* ----------------------------------------------------------------- help */
function cmdHelp() {
@@ -961,7 +977,8 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
first post. --file is optional, and --title defaults to the
project's folder name. Also prints workspace: { folders: [{ name,
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name.
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
@@ -988,6 +1005,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
Copy a cited note attachment into specs/<idea>/attachments/. Prints
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
missing. Paste link as it is.
forget --spec specs/<idea>
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.
status [--session <sid>] [--all]
One session, or every session belonging to this project.
stop --session <sid> | --all
@@ -1206,6 +1227,7 @@ const COMMANDS = {
wait: cmdWait,
chat: cmdChat,
keep: cmdKeep,
forget: cmdForget,
status: cmdStatus,
stop: cmdStop,
help: cmdHelp,
@@ -178,8 +178,8 @@ function lockStale(lock) {
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn) {
const lock = path.join(dir, STATE_LOCK_FILE);
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
const lock = path.join(dir, lockName);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
@@ -188,7 +188,7 @@ export function withStateLock(dir, fn) {
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
@@ -487,8 +487,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks and the pointer to this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
function isScratchName(name) {
return (
@@ -1619,17 +1620,125 @@ export function readWorkspace(dir) {
return readJson(path.join(dir, WORKSPACE_FILE), null);
}
// A fresh workspace: just the original folder, named after itself.
export function initialWorkspace(worktree) {
// A fresh workspace: the original folder, named after itself, plus whatever
// was remembered for this folder and spec (rememberedWorkspace() below).
export function initialWorkspace(worktree, remembered = null) {
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
if (remembered && remembered.original) {
if (remembered.original.name) original.name = remembered.original.name;
if (remembered.original.description) original.description = remembered.original.description;
}
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
id: "f" + (i + 1),
path: f.path,
name: f.name,
description: f.description || "",
...(f.nested ? { nested: true } : {}),
}));
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
}
/* ------------------------------------------------ remembered workspaces */
// The folder list outlives the console session: one file for the person,
// beside looks.json, keyed by the folder a session runs in and then by spec.
// Never under specs/: the paths are this machine's, and the server never
// writes into a project.
//
// { "projects": { "<folded worktree>": {
// "path": "<worktree>",
// "project": { original, folders, at }, // no spec picked
// "specs": { "specs/<name>": { original, folders, at } } } } }
//
// `original` holds the first folder's name and description only (its path is
// always the session's own); `folders` the added ones as { path, name,
// description, nested? }. Two writers, the server on every change and
// `console.mjs forget`, each a read-modify-write of one key.
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
const foldKey = (p) => {
const resolved = path.resolve(String(p || ""));
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
};
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
export function specKey(specDir) {
return String(specDir || "")
.trim()
.replace(/\\/g, "/")
.replace(/^\.\//, "")
.replace(/\/+$/, "");
}
function readStore() {
const saved = readJson(WORKSPACES_FILE, null);
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
}
/**
* What was remembered for this folder and spec: `{ entry, from }`, where
* `from` is "spec" when the spec has its own list, "project" when it falls
* back to the project's (a spec's list starts as a copy of it), and null
* when nothing was ever saved.
*/
export function rememberedWorkspace(worktree, specDir) {
const project = readStore().projects[foldKey(worktree)];
if (!project) return { entry: null, from: null };
const spec = specKey(specDir);
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
}
// The workspace's folders as the store keeps them.
export function rememberable(ws) {
const folders = (ws && ws.folders) || [];
const first = folders.find((f) => f.original) || {};
return {
version: 0,
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
missing: [],
changes: [],
remote: "",
original: { name: first.name || "", description: first.description || "" },
folders: folders
.filter((f) => !f.original)
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
at: nowIso(),
};
}
// Every server and `console.mjs forget` writes the one file, so each
// read-modify-write holds this lock beside it.
const WORKSPACES_LOCK = "workspaces.json.lock";
// Save the list for this folder and spec ("" for the project's own).
export function rememberWorkspace(worktree, specDir, ws) {
ensureDir(path.dirname(WORKSPACES_FILE));
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
}
function saveRemembered(worktree, specDir, ws) {
const store = readStore();
const key = foldKey(worktree);
const project = store.projects[key] || { path: path.resolve(worktree) };
const spec = specKey(specDir);
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
else project.project = rememberable(ws);
store.projects[key] = project;
writeJsonAtomic(WORKSPACES_FILE, store);
}
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
export function forgetWorkspace(worktree, specDir) {
const spec = specKey(specDir);
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
}
function dropRemembered(worktree, spec) {
const store = readStore();
const project = store.projects[foldKey(worktree)];
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
delete project.specs[spec];
writeJsonAtomic(WORKSPACES_FILE, store);
return true;
}
// Single-writer rule: only server.mjs may call this.
export function writeWorkspace(dir, ws) {
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
@@ -2505,6 +2505,9 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
actions stay put. */
.modal.workspace { max-width: 680px; }
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
.workspace .modal-blurb { margin-bottom: 6px; }
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
.workspace-list {
list-style: none; margin: 0; padding: 0;
display: grid; gap: 12px;
@@ -2542,6 +2542,7 @@ function renderDashboard(main) {
const specs = specList();
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
wrap.appendChild(hideUnavailableToggle());
if (!local.launching && !launchScoping) syncWorkspaceScope();
// "Unavailable" is the scan's verdict for the selected spec, not the
// momentary greying while a launch is in flight or the server is away, so
@@ -2963,6 +2964,11 @@ async function launchSkill(entry) {
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected.
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
// dashboard, which would otherwise sync back to the picker's spec.
launchScoping = true;
await syncWorkspaceScope(target ? target.dir : "");
try {
const res = await fetch("/submit", {
method: "POST",
@@ -2973,6 +2979,7 @@ async function launchSkill(entry) {
}),
});
if (res.status === 409) {
launchScoping = false;
pendingResult = true;
banner("Your last pick is still being picked up. One moment.", "info");
return;
@@ -2980,10 +2987,12 @@ async function launchSkill(entry) {
if (!res.ok) throw new Error(String(res.status));
sound("startSkill");
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
launchScoping = false;
pendingResult = true;
save();
render();
} catch {
launchScoping = false;
banner("That did not go through. Nothing was lost; try again.", "warn");
}
}
@@ -5854,6 +5863,32 @@ async function postJson(url, body) {
}
}
/* The workspace follows the dashboard's picker: the folders remembered for
the selected spec, or the project's own under "Start from scratch". The
server swaps the list and remembers every change after it. */
let scopeAsked = null;
// True from a launch's scope sync until its send has gone (or failed).
let launchScoping = false;
async function syncWorkspaceScope(spec) {
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
scopeAsked = want;
const { status, body } = await postJson("/workspace/scope", { spec: want });
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
scopeAsked = null;
if ($("workspace-modal").open) renderWorkspace();
}
// The dialog's "Remembered for" line: whose list this is.
function workspaceScopeText() {
const scope = (wsFrame && wsFrame.scope) || "";
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
const spec = specList().find((s) => s.dir === scope);
const name = spec ? spec.name : scope.split("/").pop();
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
}
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
// The folder whose Remove is waiting on its inline confirm, by id.
@@ -5893,6 +5928,7 @@ function renderWorkspace() {
}
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
$("workspace-scope").textContent = workspaceScopeText();
}
function workspaceRow(f) {
@@ -833,10 +833,28 @@
Click the folder name in the middle of the bottom bar. It shows your
folder's name and branch, such as <strong>shop · main</strong>, and
<strong>shop + 2 folders · main</strong> once you have added some.
The workspace lasts for this console session only: it carries across
steps you start from the dashboard, and a new console session starts
with just the folder you started in.
It carries across steps you start from the dashboard.
</p>
<h4>Remembered for next time</h4>
<ul>
<li>
Every change is saved as you make it, so the next console session in
this folder starts with the same folders.
</li>
<li>
Each spec keeps its own list. The first time you pick a spec on the
dashboard it starts as a copy of the project's list (the one shown
under <strong>Start from scratch</strong>), and after that the two
are separate. Picking a spec loads its list; the line under the
dialog's title says whose list you are looking at.
</li>
<li>
The lists live in <code>workspaces.json</code> in your own
Plan2Code settings folder, beside your look and feel, never in the
project. Finalize offers to forget a spec's list when it archives the
spec.
</li>
</ul>
<h4>Adding a folder</h4>
<ul>
<li>
@@ -1363,9 +1381,10 @@
<h4>What it counts</h4>
<p>
Each step you run here adds points: a plan or a set of documents
weighs more than a single answered question, and a built phase more
still, by how many tasks it completed: a big phase adds more than a
small one. Every two questions you answer add a point too, so a long
weighs more than a quick task, and a built phase more still, by how
many tasks it completed: a big phase adds more than a small one.
Every two questions you answer within one step add a point too
(rounded down, so a single answer adds nothing), so a long
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
points, with what it added. It is a rule of thumb, not a
reading of Plan2Code's real memory: long sessions tend to make it
@@ -2003,6 +2022,7 @@
The folders the agent uses as context this session. It reads the extra ones for
reference and only changes them if you ask.
</p>
<p class="workspace-scope" id="workspace-scope"></p>
<ul class="workspace-list" id="workspace-list"></ul>
<div class="workspace-add">
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
@@ -45,7 +45,10 @@ import {
readLedger,
readOverview,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
remoteWarning,
specKey,
typedCount,
withStateLock,
writeJsonAtomic,
@@ -326,7 +329,9 @@ function workspaceNow() {
return ws;
}
const root = sessionWorktree();
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
const scope = specKey(stateNow?.specDir);
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
@@ -347,13 +352,87 @@ function saveWorkspace(ws) {
// One change: a new version, an entry in the change log the agent is handed,
// the file, and every open page.
function bumpWorkspace(ws, change) {
function bumpWorkspace(ws, change, { remember = true } = {}) {
ws.version = (ws.version || 0) + 1;
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
saveWorkspace(ws);
// Remembered for the next console session too. A folder gone missing or
// found again is not a change of mind, so it is not saved.
if (remember) rememberNow(ws);
pushState();
}
function rememberNow(ws) {
const root = sessionWorktree();
if (!root) return;
try {
rememberWorkspace(root, ws.scope || "", ws);
} catch {}
}
/**
* Point the workspace at another spec ("" for the project's own list) and
* swap in what was remembered there, logging each difference as a change so
* the agent's cursor stays truthful. A spec with nothing saved starts from
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
* list it has and saves it as the spec's (`seed: "current"`, a spec created
* mid-run). Folders keep their ids when their path stays.
*/
function setScope(ws, spec, seed = "project") {
const root = sessionWorktree();
const next = specKey(spec);
if (!root || (ws.scope || "") === next) return false;
const found = rememberedWorkspace(root, next);
ws.scope = next;
if (next && found.from !== "spec" && seed === "current") {
saveWorkspace(ws);
rememberNow(ws);
pushState();
return true;
}
const want = initialWorkspace(root, found.entry).folders;
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
const kept = new Set();
const folders = [];
const changes = [];
for (const w of want) {
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
if (!have) {
folders.push({ ...w, id: "pending" });
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
continue;
}
kept.add(have);
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
if ((have.description || "") !== (w.description || "")) {
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
}
folders.push({ ...have, name: w.name, description: w.description || "" });
}
for (const f of ws.folders) {
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
}
ws.folders = folders.filter((f) => f.id !== "pending");
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
if (!changes.length) {
saveWorkspace(ws);
pushState();
}
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
checkFolders(ws);
return true;
}
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
// learns its spec late) takes the workspace with it.
function followSpecDir(state) {
const spec = specKey(state && state.specDir);
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
}
function isFolder(p) {
try {
return fs.statSync(p).isDirectory();
@@ -370,10 +449,10 @@ function checkFolders(ws) {
const marked = ws.missing.includes(f.id);
if (!there && !marked) {
ws.missing = [...ws.missing, f.id];
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
} else if (there && marked) {
ws.missing = ws.missing.filter((id) => id !== f.id);
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path });
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
}
}
}
@@ -402,8 +481,8 @@ function folderIssues(entries) {
}
function workspaceView() {
const { folders, missing, remote } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) };
const { folders, missing, remote, scope } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
}
// Whether child sits strictly under parent.
@@ -492,6 +571,7 @@ function bootWorkspace() {
saveWorkspace(ws);
}
checkFolders(ws);
followSpecDir(stateNow);
}
/**
@@ -1403,6 +1483,24 @@ const server = http.createServer((req, res) => {
});
}
// Which list the workspace is: a spec's, or the project's (`spec` empty).
// The dashboard's picker sends it as the selection moves and before a
// launch, so a skill opens on the list of the spec it was launched for.
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
try {
setScope(workspaceNow(), spec, "project");
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, workspaceView());
});
}
// Only ever returns a path: the page then adds it through /workspace/add.
if (pathname === "/workspace/browse" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
@@ -1561,6 +1659,9 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
pushState();
}
lastStateStamp = stamp;
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-02",
"releaseDate": "2026-10-04",
"mode": "utility"
}
@@ -0,0 +1,120 @@
#!/usr/bin/env node
// commit-msg.mjs: the team's commit message, built from the branch name.
//
// Every Plan2Code skill that suggests a commit uses one format:
//
// <subject>
//
// <JIRA-Ticket-ID>
// AI Assisted
//
// and derives the ticket from a branch named <prefix>/<TICKET-ID>-description,
// where the ticket is an uppercase project key, a hyphen and an integer
// (ABC-10968). This script reads the branch, extracts the ticket and prints
// the exact command, so no prompt re-implements the rule by eye.
import { execFileSync } from "node:child_process";
import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
const USAGE = `
commit-msg.mjs: build the team's commit command from the current branch. JSON on stdout.
node commit-msg.mjs --subject "<subject>" [--add-all | --files <path> ...] [--ticket <ID>]
--subject the one-line description (at most 100 characters). No double
quotes (straight or curly), backticks, $, backslashes or ! in it,
so the command pastes unchanged into bash, zsh and PowerShell.
--add-all prefix the command with "git add -A &&".
--files prefix it with "git add -- <files> &&" (repeat --files per path).
--ticket use this ticket ID instead of reading the branch.
Prints { ok, branch, ticket, subject, message, command, add, commit }. The
commit is three -m flags, exactly: subject, ticket, "AI Assisted". command is
add && commit, one line for bash, zsh and PowerShell 7+. Windows PowerShell 5.1
has no &&: run add (null when nothing is staged) and then commit as two
commands. Nothing is run.
Exit: 0 ok · 2 bad arguments (including a stray argument: one --files per
path) · 3 not a git repository / no branch (detached HEAD) · 4 the branch
carries no ticket ID, --ticket is not KEY-123, the subject breaks a rule, or a
path cannot be quoted safely.
`;
// The ticket is the first <KEY>-<number> path segment start after a "/" (or the
// branch start), ended by "-", "_", "/" or the end of the name.
const TICKET_RE = /(?:^|\/)([A-Z][A-Z0-9]*-\d+)(?=[-_/]|$)/;
function ticketFromBranch(branch) {
const m = String(branch || "").match(TICKET_RE);
return m ? m[1] : null;
}
function git(args) {
try {
return { ok: true, out: execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim() };
} catch {
return { ok: false };
}
}
function currentBranch() {
if (!git(["rev-parse", "--git-dir"]).ok) {
fail(EXIT.NOT_FOUND, "not-a-repo", "This directory is not inside a git repository.", "Run from the project root, or skip the commit suggestion.");
}
// symbolic-ref names the branch even before the first commit, where
// rev-parse --abbrev-ref HEAD fails; it fails only on a detached HEAD.
const ref = git(["symbolic-ref", "--short", "-q", "HEAD"]);
if (!ref.ok || !ref.out) fail(EXIT.NOT_FOUND, "detached-head", "HEAD is detached, so there is no branch name to read a ticket from.", "Ask the user for the ticket ID and pass --ticket <ID>.");
return ref.out;
}
// A path goes into the command as-is when it is plainly safe, in single quotes
// otherwise (literal in bash, zsh and PowerShell alike). Backslashes become
// forward slashes, which git accepts on every platform. A leading @ or - is
// quoted too: unquoted, PowerShell reads @types as a splat and the path
// vanishes. The command's `git add --` means a leading - is never an option.
function quoteFile(f) {
const p = f.replace(/\\/g, "/");
if (/^[\w./:+][\w./:@+-]*$/.test(p)) return p;
// PowerShell treats the curly single quotes as quote characters too.
if (/['\u2018-\u201B]/.test(p)) fail(EXIT.INVALID, "unsafe-path", `The path ${p} contains a single quote, which cannot be quoted the same way in bash and PowerShell.`, "Use --add-all, or leave that file out and stage it by hand.");
return `'${p}'`;
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["add-all"], values: ["subject", "ticket"], lists: ["files"] });
if (args._.length) fail(EXIT.USAGE, "stray-argument", `Unexpected argument(s): ${args._.join(" ")}.`, "Each path needs its own --files (e.g. --files a.js --files b.js); quote a subject with spaces.");
const subject = (args.subject || "").trim();
if (!subject) fail(EXIT.USAGE, "missing-subject", "--subject is required.", 'Example: --subject "Add the export endpoint"');
if (/[\r\n]/.test(subject)) fail(EXIT.INVALID, "multiline-subject", "The subject must be one line.", "The diff is the body; keep the subject to one line.");
if (subject.length > 100) fail(EXIT.INVALID, "subject-too-long", `The subject is ${subject.length} characters; the limit is 100.`, "Shorten it; the diff is the body and the PR is the explanation.");
// Inside "...": PowerShell ends the string at a curly double quote too,
// bash and zsh treat \ as an escape, and ! is history expansion in an
// interactive bash or zsh.
if (/["`$\\!\u201C-\u201F]/.test(subject)) fail(EXIT.INVALID, "unsafe-subject", "The subject contains a double quote (straight or curly), backtick, $, backslash or !, which bash, zsh and PowerShell read differently inside double quotes.", "Rephrase without those characters (single quotes are fine).");
if (args["add-all"] && args.files) fail(EXIT.USAGE, "add-conflict", "Use --add-all or --files, not both.", "Pick one.");
let branch = null;
let ticket = args.ticket ? args.ticket.trim() : null;
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like ABC-10968.");
if (!ticket) {
branch = currentBranch();
ticket = ticketFromBranch(branch);
if (!ticket) {
fail(EXIT.INVALID, "no-ticket", `The branch "${branch}" has no <prefix>/<TICKET-ID>-description ticket in it.`, "Ask the user for the ticket ID, then rerun with --ticket <ID>; or show the command with <JIRA-Ticket-ID> for them to fill in.");
}
}
const add = args["add-all"] ? "git add -A" : args.files ? `git add -- ${args.files.map(quoteFile).join(" ")}` : null;
const commit = `git commit -m "${subject}" -m "${ticket}" -m "AI Assisted"`;
out({
ok: true,
branch,
ticket,
subject,
message: `${subject}\n\n${ticket}\nAI Assisted`,
command: add ? `${add} && ${commit}` : commit,
add,
commit,
});
});
@@ -0,0 +1,247 @@
// Plan2Code skill scripts: shared plumbing.
//
// Every script in a skill's scripts/ directory imports this file. It owns the
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
//
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
// on a handled failure.
// stderr a one-line human diagnostic on failure (the same message + next).
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
// 4 invalid input or a check that failed · 5 refused (would clobber
// or break a rule).
//
// Node 18+ built-ins only, no build step: this ships inside every skill.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
export class CliError extends Error {
constructor(exit, error, message, next) {
super(message);
this.exit = exit;
this.error = error;
this.next = next;
}
}
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
export function fail(exit, error, message, next) {
throw new CliError(exit, error, message, next);
}
export function out(obj) {
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
}
/**
* Parse argv into { _: positionals, <flag>: value }.
* `booleans` names flags that take no value; every other `--flag` takes the
* next argument, and repeats of a flag listed in `lists` collect into an array.
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
* silently changes behavior.
*/
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
const known = new Set([...booleans, ...values, ...lists, "help"]);
const args = { _: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith("--")) {
args._.push(a);
continue;
}
let name = a.slice(2);
let value;
const eq = name.indexOf("=");
if (eq !== -1) {
value = name.slice(eq + 1);
name = name.slice(0, eq);
}
if (!known.has(name)) {
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
}
if (name === "help" || booleans.includes(name)) {
args[name] = true;
continue;
}
if (value === undefined) {
if (i + 1 >= argv.length) {
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
}
value = argv[++i];
}
if (lists.includes(name)) (args[name] ||= []).push(value);
else args[name] = value;
}
return args;
}
/**
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
* failure shape plus an exit code, and anything else into exit 1 with the stack
* on stderr. Sets process.exitCode rather than calling process.exit(), so
* stdout is never cut off mid-write.
*/
export async function run(usage, main) {
try {
const argv = process.argv.slice(2);
if (argv.includes("--help") || argv.includes("-h")) {
process.stdout.write(usage.trim() + "\n");
return;
}
await main(argv);
} catch (err) {
if (err instanceof CliError) {
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
process.exitCode = err.exit;
return;
}
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
process.exitCode = EXIT.CRASH;
}
}
/* ------------------------------------------------------------------ time */
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
// is what "today" means to the person reading the date in their files.
export function now() {
const pinned = process.env.PLAN2CODE_NOW;
if (pinned) {
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
const d = new Date(pinned);
if (!Number.isNaN(d.getTime())) return d;
}
return new Date();
}
const pad = (n) => String(n).padStart(2, "0");
/** YYYY-MM-DD */
export function isoDate(d = now()) {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
/** YYYYMMDD */
export function compactDate(d = now()) {
return isoDate(d).replace(/-/g, "");
}
/** YYYY-MM-DD HH:mm */
export function stamp(d = now()) {
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** HHMMSS */
export function clock(d = now()) {
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
}
/* ----------------------------------------------------------------- files */
export function readText(file) {
try {
return fs.readFileSync(file, "utf8");
} catch {
return null;
}
}
export function isDir(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
/** Write a file only when its content changes. Returns true when it wrote. */
export function writeIfChanged(file, content) {
const current = readText(file);
if (current === content) return false;
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
return true;
}
/** Normalise line endings for parsing; keep the original for writing back. */
export function eol(text) {
return text.includes("\r\n") ? "\r\n" : "\n";
}
/**
* phase-N.md per phase number. An exact phase-N.md always wins over a sibling
* such as phase-1-old.md; more than one candidate is reported, never guessed.
* Shared so every script that counts a spec's tasks reads the same files.
*/
export function phaseFiles(dir) {
const files = new Map();
const extra = new Map();
for (const name of fs.readdirSync(dir).sort()) {
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
if (!m) continue;
const n = Number(m[1]);
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
if (!files.has(n)) files.set(n, name);
else if (exact) {
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
files.set(n, name);
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
}
files.extra = extra;
return files;
}
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
export function rel(root, p) {
return path.relative(root, p).split(path.sep).join("/") || ".";
}
/* --------------------------------------------------------- the web console */
// The web console ships beside these scripts in every installed skill
// (references/web-console/), and in this repo it sits at src/web-console/. Its
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
// metrics-bait scan, so the scripts import it rather than keep a second copy.
const CONSOLE_LIB_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
];
let consoleLibPromise;
export function consoleLib() {
consoleLibPromise ||= (async () => {
for (const candidate of CONSOLE_LIB_CANDIDATES) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-lib-missing",
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
);
})();
return consoleLibPromise;
}
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
export function version() {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const text = readText(file);
if (!text) continue;
try {
const v = JSON.parse(text).version;
if (typeof v === "string") return v;
} catch {}
}
return null;
}
Loaded 100 of 243 files, more files were not shown because too many files have changed in this diff. Show more