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 c0ea70e838
commit 6a66440095
243 files changed
+23698 -1607

No files matched your search

@@ -0,0 +1,224 @@
#!/usr/bin/env node
// agent-files.mjs: find other AI agents' config files and point them at AGENTS.md.
//
// Init and Init Update both end with the same step: detect CLAUDE.md, GEMINI.md,
// .cursorrules, the Copilot instructions and the Cursor / Windsurf rule folders,
// and (only for the ones the user confirms) replace each with a short pointer
// to AGENTS.md. Which files exist, how long they are, the relative path back to
// AGENTS.md and the replacement text are all fixed, so they live here.
import fs from "node:fs";
import path from "node:path";
import { EXIT, fail, out, parseArgs, run, readText, isDir } from "./common.mjs";
const USAGE = `
agent-files.mjs: detect AI agent config files and replace them with AGENTS.md pointers. JSON on stdout.
node agent-files.mjs detect [--root <dir>]
Every config file present, with its line count, whether it has custom
content (more than 10 lines) and the pointer it would get.
node agent-files.mjs apply <id> [<id> ...] [--root <dir>] [--dry-run]
node agent-files.mjs apply --all [--root <dir>] [--dry-run]
Replace the confirmed entries (ids from detect: CLAUDE.md, GEMINI.md,
.cursorrules, .github/copilot-instructions.md, .cursor/rules,
.windsurf/rules). A rules folder loses its .md files (and .mdc, for Cursor) and gets one
reference.md. Only run this for entries the user confirmed.
An entry that is AGENTS.md itself through a symlink or hard link
(detect: linkedToAgents) is refused by id and skipped by --all
("skipped-linked"). A symlink to any other file is removed and replaced,
never written through.
Exit: 0 ok · 2 bad arguments · 3 AGENTS.md missing or an id not present ·
5 refused (an entry linked to AGENTS.md).
`;
// id, title, where the pointer goes, and the relative path back to AGENTS.md.
const TARGETS = [
{ id: "CLAUDE.md", title: "CLAUDE.md", file: "CLAUDE.md", ref: "./AGENTS.md" },
{ id: "GEMINI.md", title: "GEMINI.md", file: "GEMINI.md", ref: "./AGENTS.md" },
{ id: ".cursorrules", title: ".cursorrules", file: ".cursorrules", ref: "./AGENTS.md" },
{ id: ".github/copilot-instructions.md", title: "Copilot Instructions", file: ".github/copilot-instructions.md", ref: "../AGENTS.md" },
{ id: ".cursor/rules", title: "Project Rules", dir: ".cursor/rules", ref: "../../AGENTS.md" },
{ id: ".windsurf/rules", title: "Project Rules", dir: ".windsurf/rules", ref: "../../AGENTS.md" },
];
const CUSTOM_LINES = 10;
// CLAUDE.md gets its own template: Claude Code auto-loads it, so it carries the
// directive that makes AGENTS.md the mandatory first read.
function claudeTemplate() {
return [
"# CLAUDE.md",
"",
"**CRITICAL — MANDATORY FIRST STEP: You MUST read [AGENTS.md](./AGENTS.md) before responding to ANY user message, including simple questions. Do NOT skip this step regardless of how trivial the request appears. No exceptions.**",
"",
"See AGENTS.md for complete project documentation including:",
"- Development commands and setup",
"- Architecture overview",
"- Environment variables",
"- Testing patterns",
"- Deployment guides",
"- Keeping this file current / Failure log",
"- Section details in .agents-docs/",
"",
"This file exists for Claude Code auto-loading. All AI coding agents should reference AGENTS.md.",
"",
].join("\n");
}
function referenceTemplate(title, ref) {
return [
`# ${title}`,
"",
`See [AGENTS.md](${ref}) for complete project documentation including:`,
"- Development commands and setup",
"- Architecture overview",
"- Environment variables",
"- Testing patterns",
"- Deployment guides",
"- Keeping this file current / Failure log",
"- Section details in .agents-docs/",
"",
].join("\n");
}
function templateFor(t) {
return t.id === "CLAUDE.md" ? claudeTemplate() : referenceTemplate(t.title, t.ref);
}
// A CRLF checkout of a pointer file is still the pointer.
function lf(text) {
return text === null ? null : text.replace(/\r\n/g, "\n");
}
const samePath = (a, b) => (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
// True when p is AGENTS.md itself: a symlink resolving to it, or a hard link to
// the same inode. Writing a pointer through either would replace AGENTS.md.
// Some platforms report ino 0 for every file, so 0 never counts as a match.
function isAgentsFile(p, agents) {
try {
if (samePath(fs.realpathSync.native(p), fs.realpathSync.native(agents))) return true;
const a = fs.statSync(p, { bigint: true });
const b = fs.statSync(agents, { bigint: true });
return a.ino !== 0n && a.ino === b.ino && a.dev === b.dev;
} catch {
return false;
}
}
function lineCount(text) {
if (!text) return 0;
return text.replace(/\r?\n$/, "").split(/\r?\n/).length;
}
function detect(root) {
const agents = path.join(root, "AGENTS.md");
const found = [];
for (const t of TARGETS) {
if (t.file) {
const text = readText(path.join(root, t.file));
if (text === null) continue;
const lines = lineCount(text);
found.push({
id: t.id,
title: t.title,
files: [{ path: t.file, lines }],
lines,
custom: lines > CUSTOM_LINES,
alreadyPointer: lf(text) === templateFor(t),
linkedToAgents: isAgentsFile(path.join(root, t.file), agents),
writes: t.file,
pointsTo: t.ref,
});
} else {
const dir = path.join(root, t.dir);
if (!isDir(dir)) continue;
// Cursor's own rule files are .mdc; leaving them would keep a second source of rules.
const exts = t.id === ".cursor/rules" ? [".md", ".mdc"] : [".md"];
const mds = fs.readdirSync(dir).filter((n) => exts.some((e) => n.toLowerCase().endsWith(e)) && !isDir(path.join(dir, n))).sort();
if (!mds.length) continue;
const files = mds.map((n) => ({ path: `${t.dir}/${n}`, lines: lineCount(readText(path.join(dir, n))) }));
const lines = files.reduce((n, f) => n + f.lines, 0);
found.push({
id: t.id,
title: t.title,
files,
lines,
custom: files.some((f) => f.lines > CUSTOM_LINES),
alreadyPointer: mds.length === 1 && mds[0] === "reference.md" && lf(readText(path.join(dir, "reference.md"))) === templateFor(t),
linkedToAgents: mds.some((n) => isAgentsFile(path.join(dir, n), agents)),
writes: `${t.dir}/reference.md`,
deletes: files.map((f) => f.path).filter((p) => !p.endsWith("/reference.md")),
pointsTo: t.ref,
});
}
}
return found;
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { booleans: ["dry-run", "all"], values: ["root"] });
const cmd = args._[0];
const root = path.resolve(args.root || ".");
const hasAgents = fs.existsSync(path.join(root, "AGENTS.md"));
if (cmd === "detect") {
const found = detect(root);
out({
ok: true,
root,
hasAgents,
found,
warnings: found.filter((f) => f.custom && !f.alreadyPointer && !f.linkedToAgents).map((f) => `${f.id} has custom content that will be replaced (${f.lines} lines).`),
...(found.length ? {} : { note: "No AI agent config files found: skip this step silently." }),
});
return;
}
if (cmd !== "apply") fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: detect, apply. Run with --help.");
if (!hasAgents) fail(EXIT.NOT_FOUND, "no-agents-md", "AGENTS.md does not exist, so there is nothing to point these files at.", "Create AGENTS.md first.");
const ids = args._.slice(1);
if (!args.all && !ids.length) fail(EXIT.USAGE, "nothing-selected", "Name the entries to replace, or pass --all.", "Use the ids `detect` printed, for the entries the user confirmed.");
const found = detect(root);
const chosen = args.all ? found : ids.map((id) => {
const hit = found.find((f) => f.id === id.replace(/\\/g, "/").replace(/\/$/, ""));
if (!hit) fail(EXIT.NOT_FOUND, "not-present", `"${id}" is not one of the detected entries (${found.map((f) => f.id).join(", ") || "none"}).`, "Run `detect` and use its ids.");
return hit;
});
// Checked before anything is written, so a refusal leaves every file as it was.
const linked = chosen.find((c) => c.linkedToAgents);
if (linked && !args.all) {
fail(EXIT.REFUSED, "linked-to-agents", `${linked.id} is AGENTS.md itself (via a symlink or hard link); replacing it would overwrite AGENTS.md with the pointer.`, `Leave ${linked.id} as it is: it already serves AGENTS.md. Rerun apply without it.`);
}
const actions = [];
for (const entry of chosen) {
if (entry.linkedToAgents) {
actions.push({ action: "skipped-linked", path: entry.writes });
continue;
}
const t = TARGETS.find((x) => x.id === entry.id);
const content = templateFor(t);
for (const del of entry.deletes || []) {
actions.push({ action: "delete", path: del });
if (!args["dry-run"]) fs.rmSync(path.join(root, del), { force: true });
}
const target = path.join(root, entry.writes);
const changed = lf(readText(target)) !== content;
actions.push({ action: changed ? "write" : "unchanged", path: entry.writes });
if (changed && !args["dry-run"]) {
fs.mkdirSync(path.dirname(target), { recursive: true });
// A symlink (or a hard link) to some other file is replaced, not written
// through, so the file it shares content with is left alone.
let st = null;
try {
st = fs.lstatSync(target);
} catch {}
if (st && (st.isSymbolicLink() || st.nlink > 1)) fs.rmSync(target, { force: true });
fs.writeFileSync(target, content);
}
}
out({ ok: true, root, dryRun: !!args["dry-run"], updated: chosen.filter((c) => !c.linkedToAgents).map((c) => c.id), actions });
});
@@ -0,0 +1,157 @@
#!/usr/bin/env node
// agents-md.mjs: the shape of a project's AGENTS.md, read from disk.
//
// Init and Init Update both start by establishing facts about AGENTS.md: does
// it exist, how long is it, which sections does it have, is it a single file
// or an index over .agents-docs/, which section files exist, which links are
// broken, which section files nothing links to. All of that is mechanical;
// what to write about it is not.
import fs from "node:fs";
import path from "node:path";
import { EXIT, fail, out, parseArgs, run, readText, isDir } from "./common.mjs";
const USAGE = `
agents-md.mjs: inspect AGENTS.md and .agents-docs/. JSON on stdout.
node agents-md.mjs inspect [--root <dir>]
exists, line count against the 500-line budget, structure
(progressive or single-file), every ## section with its line count and
its Details link, the always-inline sections, .agents-docs/ files with
their breadcrumb check, broken links, orphan section files (no link from
AGENTS.md).
node agents-md.mjs filename "<Section Name>"
The detail file for a section: AGENTS-<kebab-case>.md, its link line
and its two header lines.
Exit: 0 ok (check "exists") · 2 bad arguments.
`;
const LIMIT = 500;
const ALWAYS_INLINE = ["Project Overview", "How to Use This File", "Keeping this file current", "Failure log"];
const BREADCRUMB = "> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.";
function kebab(name) {
return name
.normalize("NFKD")
.replace(/[̀-ͯ]/g, "")
.toLowerCase()
.replace(/&/g, " and ")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}
function lineCount(text) {
return text ? text.replace(/\r?\n$/, "").split(/\r?\n/).length : 0;
}
function sectionsOf(text) {
const lines = text.split(/\r?\n/);
const outList = [];
let inFence = false;
lines.forEach((l, i) => {
if (/^\s*(```|~~~)/.test(l)) inFence = !inFence;
if (inFence) return;
const m = l.match(/^## +(.+?)\s*$/);
if (m) outList.push({ name: m[1].trim(), line: i + 1 });
});
outList.forEach((s, i) => {
const end = i + 1 < outList.length ? outList[i + 1].line - 1 : lines.length;
const body = lines.slice(s.line, end).join("\n");
s.lines = end - s.line + 1;
const link = body.match(/\]\((\.\/)?\.agents-docs\/([^)\s#]+)/);
s.details = link ? `.agents-docs/${link[2]}` : null;
});
return outList;
}
function inspect(root) {
const file = path.join(root, "AGENTS.md");
const text = readText(file);
const docsDir = path.join(root, ".agents-docs");
const hasDocs = isDir(docsDir);
const docFiles = hasDocs
? fs.readdirSync(docsDir).filter((n) => n.toLowerCase().endsWith(".md")).sort().map((n) => {
const t = readText(path.join(docsDir, n)) || "";
const lines = t.split(/\r?\n/);
const h1 = lines.find((l) => /^# /.test(l));
return {
path: `.agents-docs/${n}`,
lines: lineCount(t),
title: h1 ? h1.replace(/^# +/, "").trim() : null,
breadcrumb: lines.slice(0, 6).some((l) => l.trim() === BREADCRUMB || /^> Part of \[AGENTS\.md\]\(\.\.\/AGENTS\.md\)/.test(l.trim())),
namedLikeConvention: /^AGENTS-[a-z0-9]+(-[a-z0-9]+)*\.md$/.test(n),
};
})
: [];
if (text === null) {
return { ok: true, root, exists: false, hasAgentsDocs: hasDocs, agentsDocs: docFiles, otherFiles: ["CLAUDE.md", "README.md", "PROJECT.md", "GEMINI.md", ".cursorrules", ".github/copilot-instructions.md"].filter((f) => fs.existsSync(path.join(root, f))) };
}
const sections = sectionsOf(text);
const linked = new Set();
for (const m of text.matchAll(/\]\((?:\.\/)?(\.agents-docs\/[^)\s#]+)/g)) linked.add(m[1]);
const broken = [...linked].filter((l) => !fs.existsSync(path.join(root, l)));
// A section file nothing in AGENTS.md links to is an orphan, unless another
// section file links to it: that one is reached indirectly, and deleting it
// would break a link, so it is reported apart and never offered for removal.
const fromDocs = new Set();
for (const d of docFiles) {
const t = readText(path.join(root, d.path)) || "";
for (const m of t.matchAll(/\]\((?:\.\/)?([^)\s#]+\.md)/g)) {
const target = path.posix.normalize(path.posix.join(".agents-docs", m[1]));
if (target !== d.path) fromDocs.add(target);
}
}
const unlinked = docFiles.map((d) => d.path).filter((p) => !linked.has(p));
const orphans = unlinked.filter((p) => !fromDocs.has(p));
const indirect = unlinked.filter((p) => fromDocs.has(p));
const inline = ALWAYS_INLINE.map((name) => {
const s = sections.find((x) => x.name.toLowerCase() === name.toLowerCase());
return { name, present: !!s, splitOut: !!(s && s.details) };
});
const count = lineCount(text);
return {
ok: true,
root,
exists: true,
lines: count,
budget: `${count}/${LIMIT}`,
nearLimit: count > LIMIT * 0.9,
overLimit: count > LIMIT,
structure: hasDocs ? "progressive" : "single-file",
sections,
alwaysInline: inline,
hasAgentsDocs: hasDocs,
agentsDocs: docFiles,
brokenLinks: broken,
orphans,
indirect,
problems: [
...broken.map((b) => `AGENTS.md links to ${b}, which does not exist`),
...orphans.map((o) => `${o} has no link from AGENTS.md (orphan: offer to remove it)`),
...inline.filter((s) => s.splitOut).map((s) => `${s.name} must stay inline in AGENTS.md but links out to a section file`),
...docFiles.filter((d) => !d.breadcrumb).map((d) => `${d.path} lacks the "> Part of [AGENTS.md](../AGENTS.md)" breadcrumb`),
...docFiles.filter((d) => !d.namedLikeConvention).map((d) => `${d.path} is not named AGENTS-<kebab-case>.md`),
],
};
}
run(USAGE, async (argv) => {
const args = parseArgs(argv, { values: ["root"] });
const cmd = args._[0];
if (cmd === "inspect") {
out(inspect(path.resolve(args.root || ".")));
return;
}
if (cmd === "filename") {
const name = args._.slice(1).join(" ").trim();
if (!name) fail(EXIT.USAGE, "missing-name", "Give the section name.", 'Example: filename "Development Commands"');
const slug = kebab(name);
if (!slug) fail(EXIT.USAGE, "bad-name", `"${name}" has no letters or digits to name a file from.`, "Use the section's heading text.");
const file = `.agents-docs/AGENTS-${slug}.md`;
out({ ok: true, section: name, file, link: `Details: [${name}](./${file})`, header: [`# ${name}`, BREADCRUMB] });
return;
}
fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: inspect, filename. Run with --help.");
});
@@ -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
// (PCWEB-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 PCWEB-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,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"
}