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

@@ -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,379 @@
#!/usr/bin/env node
// feedback-payload.mjs: Finalize STEP 6.5, the community feedback submission.
//
// The payload is fixed data: metrics read from the METRICS_JSON comments the
// pipeline already wrote, task counts read from the phase files, the user's
// Step 5 answers read from overview.md's ## User Feedback table, the installed
// version, and a sha256 prefix of each prompt. None of it needs judgment, and
// the hashes cannot be computed by reading. The submission is a fixed tier
// sequence (gh, then the browser, then a printed URL). Both live here; the
// agent previews and asks for approval in between.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import crypto from "node:crypto";
import { execFileSync, spawn } from "node:child_process";
import { EXIT, HERE, fail, out, parseArgs, run, readText, isDir, rel, compactDate, clock, version, phaseFiles } from "./common.mjs";
const USAGE = `
feedback-payload.mjs: build and submit the community feedback payload. JSON on stdout.
node feedback-payload.mjs build <spec> --set verification_failures_found=N
--set documentation_updates_needed=N [--truncate] [--root <dir>] [--out <dir>]
<spec> is the archived spec (specs--completed/<name>, specs/<name> when
Step 6 did not archive, or <name>). Reads
its PLAN-DRAFT, overview.md and phase files, and the ## User Feedback
table Step 5 appended. Writes payload.json and body.md to --out (default:
a new folder in the OS temp dir) and prints the title, body, label, the
browser URL and its size. --truncate shortens the free-text answers
(rating_reason first, then what_went_well / what_went_poorly) until the
URL fits 8 KB.
node feedback-payload.mjs submit --from <dir> [--dry-run]
Only after the user approved the preview. Tier 1: gh issue create.
Tier 2: open the prefilled new-issue page in the browser (the user still
clicks Submit). Tier 3: print the URL. Reports the tier that worked.
Tiers 2 and 3 are skipped when the URL is over 8 KB (exit 4 oversize).
Exit: 0 ok · 2 bad arguments · 3 spec, feedback table or payload not found ·
4 the payload would be invalid (e.g. no rating), or gh failed and the URL is
too long for the other tiers · 5 a bare <name> exists in both specs/ and
specs--completed/ (pass the exact path).
`;
const REPO = "jparkerweb/plan2code";
const LABEL = "community-feedback";
const URL_LIMIT = 8192;
// Prompt keys the metrics pipeline cohorts on, and the skill each comes from.
const PROMPTS = {
plan: "plan2code-1-plan",
revise_plan: "plan2code-1b-revise-plan",
document: "plan2code-2-document",
implement: "plan2code-3-implement",
finalize: "plan2code-4-finalize",
init: "plan2code-init",
init_update: "plan2code-init-update",
quick_task: "plan2code-quick-task",
};
/**
* The prompt's source text: an installed skill's SKILL.md minus the generated
* frontmatter (the installer writes header + "\n\n" + source), or the repo's
* src/<name>.md. Hashing either gives the same sha256 the metrics collector
* computes from src/.
*/
function promptSource(name) {
const skillMd = path.join(HERE, "..", "..", name, "SKILL.md");
const text = readText(skillMd);
if (text !== null) {
const m = text.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n\r?\n/);
return m ? text.slice(m[0].length) : text;
}
for (const candidate of [path.join(HERE, "..", "..", "..", "src", `${name}.md`), path.join(HERE, "..", "..", "src", `${name}.md`)]) {
const t = readText(candidate);
if (t !== null) return t;
}
return null;
}
function promptVersions() {
const outV = {};
for (const [key, name] of Object.entries(PROMPTS)) {
const src = promptSource(name);
outV[key] = src === null ? "sha256:missing" : crypto.createHash("sha256").update(src, "utf8").digest("hex").slice(0, 12);
}
return outV;
}
function metricsBlocks(text) {
const blocks = [];
for (const m of (text || "").matchAll(/<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/g)) {
try {
blocks.push(JSON.parse(m[1]));
} catch {}
}
return blocks;
}
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
function parseFeedbackTable(overview) {
const sec = overview.match(/^## +User Feedback\s*$([\s\S]*?)(?=^## |(?![\s\S]))/m);
if (!sec) return null;
const fields = {};
for (const line of sec[1].split(/\r?\n/)) {
if (!/^\s*\|/.test(line) || /^\s*\|[\s:|-]+\|\s*$/.test(line)) continue;
// Split on pipes that are not escaped (values escape theirs as \|).
const cells = line.trim().replace(/^\||\|$/g, "").split(/(?<!\\)\|/).map((c) => c.trim().replace(/\\\|/g, "|"));
if (cells.length >= 2 && !/^field$/i.test(cells[0])) fields[cells[0].toLowerCase()] = cells.slice(1).join("|").trim();
}
return fields;
}
function phaseTasks(dir) {
const c = { total: 0, complete: 0, assumed: 0, blocked: 0 };
// The same files specs.mjs reads: a stale sibling like phase-1-old.md is not counted.
for (const n of phaseFiles(dir).values()) {
for (const line of (readText(path.join(dir, n)) || "").split(/\r?\n/)) {
// The same task line specs.mjs counts: 2.3, 3.6a, or a named 1.T.
const m = line.match(/^\s*[-*] \[(.)\]\s+\*\*Task\s+\d+\.(?:\d+|[A-Za-z]+)[a-z]*\b/);
if (!m) continue;
c.total++;
if (/[xX]/.test(m[1])) c.complete++;
else if (m[1] === "?") c.assumed++;
else if (m[1] === "!") c.blocked++;
}
}
return c;
}
function locateSpec(root, arg) {
if (!arg) fail(EXIT.USAGE, "missing-spec", "Name the archived spec.", "Example: build specs--completed/user-auth");
const p = arg.replace(/\\/g, "/").replace(/\/+$/, "");
const candidates = p.includes("/") ? [path.resolve(root, p)] : [path.join(root, "specs--completed", p), path.join(root, "specs", p)];
// A bare name in both places means Step 6 did not archive (the target
// existed): specs--completed/<name> is an older run, so guessing would read
// the wrong spec.
if (candidates.length > 1 && candidates.every(isDir)) fail(EXIT.REFUSED, "ambiguous-spec", `Both specs/${p} and specs--completed/${p} exist.`, `Pass the exact path: specs/${p} when Step 6 did not archive this run, specs--completed/${p} when it did.`);
const dir = candidates.find(isDir);
if (!dir) fail(EXIT.NOT_FOUND, "spec-not-found", `No spec folder at ${candidates.map((c) => rel(root, c)).join(" or ")}.`, "Step 6 archives to specs--completed/<name>/; check the name.");
return dir;
}
function urlFor(title, body) {
return `https://github.com/${REPO}/issues/new?title=${encodeURIComponent(title)}&body=${encodeURIComponent(body)}&labels=${LABEL}`;
}
function render(payload) {
const f = payload.user_feedback;
const title = `[Feedback] v${payload.plan2code_version} - rating ${f.overall_rating}/10`;
const pct = (v) => (v === null || v === undefined ? "n/a" : `${Math.round(v * 100)}%`);
// The person's words are shown as text, never markup: a "<!--" in them must
// not open a comment ahead of the payload's.
const shown = (s) => String(s).replace(/</g, "&lt;");
// Inside the comment, < and > are written as \u003c / \u003e: still valid JSON
// that parses back to the same text, but a "-->" in an answer can no longer
// end the comment (or the ingest regex) early.
const json = JSON.stringify(payload).replace(/</g, "\\u003c").replace(/>/g, "\\u003e");
const s1 = payload.step1 || {};
const s2 = payload.step2 || {};
const body = [
"## Plan2Code run feedback",
"",
`- **Version:** ${payload.plan2code_version}`,
`- **Rating:** ${f.overall_rating}/10`,
`- **Planning confidence:** ${s1.final_confidence ?? "n/a"}`,
`- **Tasks completed:** ${payload.step3.tasks_completed ?? "n/a"} of ${payload.step3.tasks_total ?? "n/a"} (${pct(payload.step3.task_completion_rate)})`,
`- **Phases:** ${s2.phase_count ?? s1.phase_count ?? "n/a"}`,
"",
`**Reason:** ${shown(f.rating_reason)}`,
"",
`**Went well:** ${shown(f.what_went_well)}`,
"",
`**Went poorly:** ${shown(f.what_went_poorly)}`,
"",
`<!-- METRICS_JSON ${json} -->`,
"",
].join("\n");
return { title, body };
}
function sizeOf(title, body) {
return Buffer.byteLength(urlFor(title, body), "utf8");
}
async function cmdBuild(args) {
const root = path.resolve(args.root || ".");
const dir = locateSpec(root, args._[1]);
const sets = {};
for (const kv of args.set || []) {
const m = kv.match(/^([a-z_]+)=(\d+)$/);
if (!m) fail(EXIT.USAGE, "bad-set", `--set ${kv} is not key=integer.`, "Example: --set verification_failures_found=1");
if (!["verification_failures_found", "documentation_updates_needed"].includes(m[1])) fail(EXIT.USAGE, "bad-set", `--set ${m[1]} is not a field you supply.`, "Only verification_failures_found and documentation_updates_needed; the rest is read from the files.");
sets[m[1]] = Number(m[2]);
}
const overview = readText(path.join(dir, "overview.md"));
if (overview === null) fail(EXIT.NOT_FOUND, "no-overview", `${rel(root, dir)} has no overview.md.`, "The payload reads overview.md; check the archive.");
const feedback = parseFeedbackTable(overview);
if (!feedback) fail(EXIT.NOT_FOUND, "no-feedback", "overview.md has no ## User Feedback table.", "Step 5 appends it; with no feedback there is nothing to submit, so skip Step 6.5.");
// As lenient as the metrics collector: field names any case, "8/10" reads as 8.
const rating = parseInt(feedback.rating, 10);
if (!Number.isInteger(rating) || rating < 1 || rating > 10) fail(EXIT.INVALID, "bad-rating", `The User Feedback Rating "${feedback.rating ?? ""}" is not a whole number from 1 to 10.`, "Fix the Rating row in overview.md, then rebuild.");
const drafts = fs.readdirSync(dir).filter((n) => /^PLAN-DRAFT-.*\.md$/i.test(n) && !/-prev\.md$/i.test(n)).sort();
const draft = drafts.length ? readText(path.join(dir, drafts.at(-1))) : null;
const plan = metricsBlocks(draft).find((b) => !b.step || b.step === "plan") || null;
const overviewBlocks = metricsBlocks(overview);
const doc = overviewBlocks.find((b) => b.step === "document") || null;
const fin = overviewBlocks.find((b) => b.step === "finalize") || null;
const tasks = phaseTasks(dir);
const done = tasks.complete + tasks.assumed;
const rate = tasks.total ? Number((done / tasks.total).toFixed(2)) : null;
const bd = plan && plan.confidence_breakdown && typeof plan.confidence_breakdown === "object" ? plan.confidence_breakdown : null;
const pick = (k) => (k in sets ? sets[k] : fin ? num(fin[k]) : null);
const missing = ["verification_failures_found", "documentation_updates_needed"].filter((k) => pick(k) === null);
if (missing.length) fail(EXIT.USAGE, "missing-set", `Pass ${missing.map((k) => `--set ${k}=N`).join(" and ")} (your Step 2 and Step 4 counts).`, "They are the same numbers Step 7's METRICS_JSON carries.");
const name = path.basename(dir);
const payload = {
schema_version: "1.0",
run_id: `run-${compactDate()}-${clock()}-${crypto.randomBytes(2).toString("hex")}`,
plan2code_version: version() || "unknown",
prompt_versions_short: promptVersions(),
// A step with no METRICS_JSON block is null, which the ingest side reads as
// "not present"; an object of nulls would be counted as present.
step1: plan
? {
final_confidence: num(plan.confidence ?? plan.final_confidence),
confidence_breakdown: bd ? { requirements: num(bd.requirements), feasibility: num(bd.feasibility), integration: num(bd.integration), risk: num(bd.risk) } : null,
clarification_rounds: num(plan.clarification_rounds),
tech_stack_revision_rounds: num(plan.tech_stack_revision_rounds),
verification_gaps_found: num(plan.verification_gaps_found),
functional_requirements_count: num(plan.functional_requirements_count),
non_functional_requirements_count: num(plan.non_functional_requirements_count),
risk_count: num(plan.risk_count),
phase_count: num(plan.phase_count),
}
: null,
step2: doc
? {
total_tasks: num(doc.total_tasks),
phase_count: num(doc.phase_count),
parallel_groups_identified: num(doc.parallel_groups_identified),
requirement_coverage_percent: num(doc.requirement_coverage_percent),
verification_items_added: num(doc.verification_items_added),
}
: null,
step3: { task_completion_rate: rate, tasks_completed: done, tasks_total: tasks.total, blocker_count: tasks.blocked },
step4: {
completion_rate_at_audit: fin ? num(fin.completion_rate_at_audit) ?? rate : rate,
verification_failures_found: pick("verification_failures_found"),
documentation_updates_needed: pick("documentation_updates_needed"),
archival_succeeded: /specs--completed$/.test(path.dirname(dir)) && !isDir(path.join(root, "specs", name)),
},
user_feedback: {
overall_rating: rating,
rating_reason: feedback.reason || "",
what_went_well: feedback["went well"] || "",
what_went_poorly: feedback["went poorly"] || "",
},
};
let { title, body } = render(payload);
const truncated = [];
if (args.truncate) {
// Each field keeps at least 40 characters of its own text. Every pass cuts
// from the field's ORIGINAL text, so the loop always shortens and ends.
for (const field of ["rating_reason", "what_went_well", "what_went_poorly"]) {
const original = payload.user_feedback[field];
let keep = original.length;
while (sizeOf(title, body) > URL_LIMIT && keep > 40) {
keep = Math.max(40, Math.floor(keep * 0.8));
// Never cut between the two halves of a surrogate pair (an emoji): a
// lone half makes encodeURIComponent throw.
let end = keep;
if (/[\uD800-\uDBFF]/.test(original[end - 1] || "")) end--;
payload.user_feedback[field] = original.slice(0, end).trimEnd() + "...";
({ title, body } = render(payload));
if (!truncated.includes(field)) truncated.push(field);
}
}
}
const outDir = path.resolve(args.out || fs.mkdtempSync(path.join(os.tmpdir(), "plan2code-feedback-")));
fs.mkdirSync(outDir, { recursive: true });
fs.writeFileSync(path.join(outDir, "payload.json"), JSON.stringify({ title, label: LABEL, payload }, null, 2));
fs.writeFileSync(path.join(outDir, "body.md"), body);
const url = urlFor(title, body);
const bytes = Buffer.byteLength(url, "utf8");
out({
ok: true,
dir: outDir,
title,
label: LABEL,
body,
payload,
url,
urlBytes: bytes,
oversize: bytes > URL_LIMIT,
...(truncated.length ? { truncated } : {}),
...(bytes > URL_LIMIT && !args.truncate ? { next: "The browser and print tiers cap URLs near 8 KB: offer to shorten the free-text answers, then rebuild with --truncate. gh (tier 1) has no limit, but if gh fails, submit stops with exit 4 oversize instead of opening a cut-off page." } : {}),
notes: [
...(plan ? [] : ["No plan METRICS_JSON in the PLAN-DRAFT: step1 is null (not present)."]),
...(doc ? [] : ["No document METRICS_JSON in overview.md: step2 is null (not present)."]),
],
});
}
function tryGh(dir, title) {
try {
const url = execFileSync("gh", ["issue", "create", "--repo", REPO, "--title", title, "--body-file", path.join(dir, "body.md"), "--label", LABEL], {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
timeout: 60000,
}).trim();
return { ok: true, url: url.split(/\s+/).find((s) => s.startsWith("https://")) || url };
} catch (err) {
return { ok: false, why: String((err.stderr || err.message || "").toString().trim().split("\n")[0] || "gh failed") };
}
}
function openBrowser(url) {
// No shell in between: a URL full of & and % survives intact.
const [cmd, argv] =
process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] :
process.platform === "darwin" ? ["open", [url]] :
["xdg-open", [url]];
return new Promise((resolve) => {
try {
const child = spawn(cmd, argv, { stdio: "ignore", detached: true });
child.on("error", () => resolve(false));
child.on("spawn", () => {
child.unref();
resolve(true);
});
} catch {
resolve(false);
}
});
}
async function cmdSubmit(args) {
if (!args.from) fail(EXIT.USAGE, "missing-from", "--from <dir> is required (the dir `build` printed).", "Run build first.");
const dir = path.resolve(args.from);
const saved = readText(path.join(dir, "payload.json"));
const body = readText(path.join(dir, "body.md"));
if (saved === null || body === null) fail(EXIT.NOT_FOUND, "no-payload", `${dir} has no payload.json / body.md.`, "Run build first and pass the dir it printed.");
const { title } = JSON.parse(saved);
const url = urlFor(title, body);
const urlBytes = Buffer.byteLength(url, "utf8");
const oversize = urlBytes > URL_LIMIT;
if (args["dry-run"]) {
out({ ok: true, dryRun: true, urlBytes, oversize, tiers: [`gh issue create --repo ${REPO} --title "${title}" --body-file ${path.join(dir, "body.md")} --label ${LABEL}`, `open in browser: ${url.slice(0, 120)}...`, "print the URL"], ...(oversize ? { note: "The URL is over 8 KB: only tier 1 (gh) can submit this payload; tiers 2 and 3 would be skipped." } : {}) });
return;
}
const gh = tryGh(dir, title);
if (gh.ok) {
out({ ok: true, tier: 1, issue: gh.url, message: `Feedback submitted: ${gh.url}` });
return;
}
// The browser and print tiers cap URLs near 8 KB: an oversize URL would open
// a page with the body cut off (or none at all), so do not offer it.
if (oversize) fail(EXIT.INVALID, "oversize", `gh failed (${gh.why}) and the prefilled URL is ${urlBytes} bytes, over the ${URL_LIMIT}-byte limit of the browser and print tiers.`, "Offer to shorten the free-text answers and rebuild with --truncate, then submit again; or install gh and sign in (gh auth login) so tier 1 can submit it as is.");
if (await openBrowser(url)) {
// A launched opener is not proof a browser appeared (a headless or remote
// session has none), so the URL always rides along.
out({ ok: true, tier: 2, ghError: gh.why, url, message: "Asked the system to open the prefilled issue in the browser. If a page opened, the user still has to click Submit new issue (signed in to GitHub). If nothing opened, give them the url to open by hand (tier 3)." });
return;
}
out({ ok: true, tier: 3, ghError: gh.why, url, message: "Please open this URL in your browser and click 'Submit new issue' to share your feedback." });
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["dry-run", "truncate"], values: ["root", "out", "from"], lists: ["set"] });
const cmd = args._[0];
if (cmd === "build") return cmdBuild(args);
if (cmd === "submit") return cmdSubmit(args);
fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: build, submit. Run with --help.");
});
@@ -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"
}