Harden the shared console install, launcher, Loop staging, spec state and prompts

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-08 13:48:28 -08:00
1 parent 120c259d9c
commit 3ee96834bf
130 files changed
+5988 -1434

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
// Fails when the console opening paragraph of a skill drifts from the shared one.
//
// Eighteen skills open with the same "web console or terminal?" paragraph. Only
// the workflow name, the notes file and a few skill-specific clauses may differ;
// the shared sentences below must read the same in every one, so a fix to one
// skill's opening cannot silently skip the others. Matching ignores case and
// punctuation (dashes, colons, commas, brackets), never the words.
// Usage: node scripts/check-console-openings.mjs [srcDir] (defaults to ./src)
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
// Shared sentences. `{w}` is the workflow name. A sentence a skill states in its
// own words on purpose is listed in EXEMPT with the reason.
export const SHARED = [
{ id: "first", text: "The FIRST thing you do, before anything else in this file" },
{ id: "ask", text: "**web console** (browser page, suggested) or **terminal**?" },
{ id: "run", text: 'run `node "<D>/console.mjs" open --workflow {w}` before reading' },
{ id: "dir", text: "<D>: references/web-console/ beside this SKILL.md" },
{ id: "dirfile", text: "or the dir in ~/.plan2code/console/console-dir" },
{ id: "read", text: "then read <D>/console.md" },
{ id: "switch", text: "Switchable anytime." },
{ id: "web", text: "If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag." },
{ id: "dash", text: "Launched by the dashboard? Its session is already open: resume it (console-launches.md)" },
];
export const EXEMPT = {
// Implement + Review defers to Implementation Mode's own Interface question.
"plan2code-3-implement-review": { ask: "defers to Implementation Mode's Interface question", run: "the question is Implementation Mode's" , switch: "Implementation Mode's Interface section says it" },
// Git runs an instruction in the argument in the terminal at once and has its own hand-off lines.
"plan2code-git": { dash: "also resumes from Commit it now and the Changelog hand-off", first: "opens with the run-at-once rule for an argument" },
};
export function normalize(text) {
return text
.toLowerCase()
.replace(/[\u2014\u2013:;,()\[\]]/g, " ")
.replace(/\s+/g, " ")
.trim();
}
// The paragraph (one line) holding the `open --workflow` command, or null.
export function openingOf(markdown) {
return markdown.split("\n").find((l) => l.includes('console.mjs" open --workflow')) ?? null;
}
export function workflowOf(skill) {
return skill.replace(/^plan2code-/, "").replace(/^\d+b?-/, "");
}
// Returns one message per drift found under srcDir.
export function check(srcDir) {
const problems = [];
const notesDir = path.join(srcDir, "web-console", "notes");
const files = fs
.readdirSync(srcDir)
.filter((f) => /^plan2code-.+\.md$/.test(f))
.sort();
let seen = 0;
for (const file of files) {
const skill = file.replace(/\.md$/, "");
const opening = openingOf(fs.readFileSync(path.join(srcDir, file), "utf8"));
if (!opening) continue; // the dashboard opens its own way
seen++;
const w = workflowOf(skill);
const norm = normalize(opening);
const exempt = EXEMPT[skill] ?? {};
for (const s of SHARED) {
if (exempt[s.id]) continue;
if (!norm.includes(normalize(s.text.replace("{w}", w)))) problems.push(`${file}: shared sentence "${s.id}" differs or is missing (expected: ${s.text.replace("{w}", w)})`);
}
const flows = [...opening.matchAll(/--workflow ([a-z-]+)/g)].map((m) => m[1]);
if (!flows.includes(w) && !exempt.run) problems.push(`${file}: opens --workflow ${flows.join(", ")} instead of ${w}`);
const note = opening.match(/<D>\/notes\/([a-z-]+)\.md/);
if (!note) problems.push(`${file}: names no <D>/notes/<workflow>.md file`);
else if (!fs.existsSync(path.join(notesDir, `${note[1]}.md`))) problems.push(`${file}: notes file ${note[1]}.md is not in src/web-console/notes/`);
}
if (seen !== 18) problems.push(`expected 18 skills with a console opening, found ${seen}`);
return problems;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const problems = check(process.argv[2] ? path.resolve(process.argv[2]) : path.join(root, "src"));
if (problems.length) {
for (const p of problems) console.error(` FAIL ${p}`);
process.exit(1);
}
console.log("All 18 console openings share their sentences.");
}
+39
View File
@@ -0,0 +1,39 @@
// Fails when a file in .agents-docs/ is larger than the size limit, so a doc
// never grows into one nobody reads whole again. Split it by area instead and
// link the pieces from its index (see AGENTS-architecture.md).
// Usage: node scripts/check-doc-size.mjs [docsDir] [limitBytes]
// The limit is the largest area file (about 54 KB) plus headroom.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
export const DEFAULT_LIMIT = 60000;
// One entry per file over the limit: { file, bytes }.
export function oversize(dir, limit = DEFAULT_LIMIT) {
return fs.readdirSync(dir)
.filter((f) => f.endsWith(".md"))
.map((f) => ({ file: f, bytes: fs.statSync(path.join(dir, f)).size }))
.filter((e) => e.bytes > limit)
.sort((a, b) => a.file.localeCompare(b.file));
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const here = path.dirname(fileURLToPath(import.meta.url));
const dir = process.argv[2] ? path.resolve(process.argv[2]) : path.join(here, "..", ".agents-docs");
const limit = process.argv[3] ? Number(process.argv[3]) : DEFAULT_LIMIT;
if (!Number.isFinite(limit) || limit <= 0) {
console.error(`Bad size limit: ${process.argv[3]}`);
process.exit(2);
}
const big = oversize(dir, limit);
if (big.length) {
console.error(
`Over the ${limit}-byte limit (split each by area and link the pieces from its index):\n` +
big.map((e) => ` ${e.file}: ${e.bytes} bytes`).join("\n"),
);
process.exit(1);
}
console.log(`Every file in .agents-docs/ is within ${limit} bytes.`);
}
+69
View File
@@ -0,0 +1,69 @@
// Fails when a built prompt names an agent product's tool by its product name.
//
// Prompts are read by many agents, and each one calls the same tool something
// else. Prompt text says what to do ("ask with the question tool", "list the
// folder") and never what one product's tool is called. This reads every
// Markdown file in the built skills/ tree, so run it after
// `node install.js --build-skills`.
// Usage: node scripts/check-prompt-wording.mjs [skillsDir] (defaults to ./skills)
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
// Case-sensitive on purpose: "glob" and "grep" in lower case are ordinary words
// and command names, "Glob" and "Grep" as tool names are what this catches.
export const BANNED = [
"AskUserQuestion",
"Glob",
"Grep",
"TodoWrite",
"WebFetch",
"WebSearch",
"NotebookEdit",
"Read tool",
"Write tool",
"Edit tool",
"Bash tool",
"ask_user_question",
];
const PATTERN = new RegExp(`(?<![A-Za-z0-9_])(${BANNED.join("|")})(?![A-Za-z0-9_])`);
function* markdownFiles(dir) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) yield* markdownFiles(full);
else if (entry.name.endsWith(".md")) yield full;
}
}
// Returns [{ file, line, name }] for every banned name found under dir.
export function findBanned(dir) {
const hits = [];
for (const file of markdownFiles(dir)) {
fs.readFileSync(file, "utf8")
.split("\n")
.forEach((text, i) => {
const m = PATTERN.exec(text);
if (m) hits.push({ file: path.relative(dir, file).split(path.sep).join("/"), line: i + 1, name: m[1] });
});
}
return hits;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const dir = process.argv[2] ? path.resolve(process.argv[2]) : path.join(root, "skills");
if (!fs.existsSync(dir)) {
console.error(` FAIL ${dir} does not exist. Run: node install.js --build-skills`);
process.exit(1);
}
const hits = findBanned(dir);
if (hits.length) {
for (const h of hits) console.error(` FAIL ${h.file}:${h.line} names a product tool: ${h.name}`);
console.error(" Say what to do in neutral words (\"the question tool\", \"list the folder\").");
process.exit(1);
}
console.log("Built prompts name no product tool.");
}
+27
View File
@@ -0,0 +1,27 @@
// Refuse a commit that stages a file named `nul`.
//
// On Windows a stray `> nul` in a Git Bash or Unix-style command (where nul is
// not the null device) writes a real file called `nul`, which Windows tools
// then cannot open, move or delete, and which breaks a checkout there. The
// repo used to hide it with a `nul` line in .gitignore; this pre-commit check
// (run from .husky/pre-commit) refuses it instead, so one never lands.
//
// node scripts/check-staged-nul.mjs exit 1 and name them when any staged
// path is nul (or nul.<ext>)
import { execFileSync } from "node:child_process";
import { pathToFileURL } from "node:url";
/** The paths whose file name is the Windows device name nul, with or without an extension. */
export function nulPaths(paths) {
return paths.filter((p) => /^nul(\.[^/\\]*)?$/i.test(p.split(/[/\\]/).pop()));
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const staged = execFileSync("git", ["diff", "--cached", "--name-only", "--diff-filter=ACR", "-z"], { encoding: "utf8" }).split("\0").filter(Boolean);
const bad = nulPaths(staged);
if (bad.length) {
process.stderr.write(`pre-commit: refusing to commit a file named nul (a Windows device name): ${bad.join(", ")}\nUnstage and delete it: git rm --cached -- <path>, then remove the file.\n`);
process.exit(1);
}
}
+37
View File
@@ -0,0 +1,37 @@
// Fails when a scripts/test-*.mjs file is in neither list of scripts/test-lanes.json,
// is in both, or is named there but missing on disk. Prints the names and exits 1.
// Usage: node scripts/check-test-lanes.mjs [scriptsDir] (the folder defaults to this one)
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
export function checkLanes(dir) {
const lanes = JSON.parse(fs.readFileSync(path.join(dir, "test-lanes.json"), "utf8"));
const fast = lanes.fast || [];
const skip = lanes.skipFast || [];
const onDisk = fs.readdirSync(dir).filter((f) => /^test-.*\.mjs$/.test(f));
const listed = new Set([...fast, ...skip]);
const all = [...fast, ...skip];
return {
duplicates: [...new Set(all.filter((f, i) => all.indexOf(f) !== i && !(fast.includes(f) && skip.includes(f))))].sort(),
unlisted: onDisk.filter((f) => !listed.has(f)).sort(),
both: fast.filter((f) => skip.includes(f)).sort(),
missing: [...listed].filter((f) => !onDisk.includes(f)).sort(),
};
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const dir = process.argv[2] ? path.resolve(process.argv[2]) : path.dirname(fileURLToPath(import.meta.url));
const { unlisted, both, missing, duplicates } = checkLanes(dir);
const out = [];
if (unlisted.length) out.push(`In neither list of test-lanes.json (add each to fast or skipFast): ${unlisted.join(", ")}`);
if (both.length) out.push(`In both lists: ${both.join(", ")}`);
if (duplicates.length) out.push(`Listed twice in one list: ${duplicates.join(", ")}`);
if (missing.length) out.push(`Named in test-lanes.json but not on disk: ${missing.join(", ")}`);
if (out.length) {
console.error(out.join("\n"));
process.exit(1);
}
console.log("test-lanes.json lists every scripts/test-*.mjs once.");
}
+138
View File
@@ -0,0 +1,138 @@
// Writes one version into every file that carries it, so a release never leaves one behind:
// version.json (and its releaseDate), the root package.json, README's "Version X.Y.Z" line, and
// under plan2code-app/: package.json, package-lock.json (two lines), src-tauri/tauri.conf.json,
// src-tauri/Cargo.toml, fake-agent/Cargo.toml and Cargo.lock (the plan2code-app and fake-agent
// entries). It never touches CHANGELOG.md: write its heading by hand, then run this.
// `check-versions.mjs` is the reader of the same places and stays the judge.
//
// node scripts/set-version.mjs <x.y.z> [--date YYYY-MM-DD] [--root <dir>]
//
// The release date defaults to today (local time). Every carrier is read and checked before any is
// written, so a file that has no version leaves the tree as it was. Exit 0 when written, 1 when a
// carrier could not be edited, 2 for bad arguments.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const SEMVER = /^\d+\.\d+\.\d+$/;
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const validDate = (d) => {
if (!DATE.test(d)) return false;
const at = new Date(`${d}T00:00:00Z`);
return !Number.isNaN(at.getTime()) && at.toISOString().slice(0, 10) === d;
};
// Replace the first match of `pattern` (its first group is kept, then the new value, then its
// last group). A text edit, never a JSON round trip, so each file's formatting stays as it was.
function swap(text, pattern, value, what) {
if (!pattern.test(text)) throw new Error(`no ${what} found`);
return text.replace(pattern, (_, before, _old, after = "") => `${before}${value}${after}`);
}
const JSON_VERSION = /^(\s*"version"\s*:\s*")([^"]*)(")/m;
const CARGO_VERSION = /^(\s*version\s*=\s*")([^"]*)(")/m;
// A JSON file's top-level version, checked by parsing the result.
function jsonVersion(text, version, what) {
const out = swap(text, JSON_VERSION, version, `${what} "version"`);
if (JSON.parse(out).version !== version) throw new Error(`the first "version" in ${what} is not the top-level one`);
return out;
}
const lockEntry = (name) => new RegExp(`(^name = "${name}"\\r?\\nversion = ")([^"]*)(")`, "m");
/** Each carrier: its path under the root and how to rewrite its text. */
const CARRIERS = [
{ file: "version.json", edit: (t, v, d) => swap(jsonVersion(t, v, "version.json"), /^(\s*"releaseDate"\s*:\s*")([^"]*)(")/m, d, "releaseDate") },
{ file: "package.json", edit: (t, v) => jsonVersion(t, v, "package.json") },
{ file: "README.md", edit: (t, v) => swap(t, /^(Version )(\d+\.\d+\.\d+)(\b)/m, v, '"Version X.Y.Z" line') },
{ file: "plan2code-app/package.json", edit: (t, v) => jsonVersion(t, v, "package.json") },
{ file: "plan2code-app/src-tauri/tauri.conf.json", edit: (t, v) => jsonVersion(t, v, "tauri.conf.json") },
{
file: "plan2code-app/package-lock.json",
edit: (t, v) => {
// The top-level version, then the one inside packages[""].
let out = jsonVersion(t, v, "package-lock.json");
const at = out.indexOf('"packages"');
if (at < 0) throw new Error('no "packages" block found');
const head = out.slice(0, at);
const tail = swap(out.slice(at), JSON_VERSION, v, 'packages[""] "version"');
out = head + tail;
if (JSON.parse(out).packages?.[""]?.version !== v) throw new Error('packages[""].version was not updated');
return out;
},
},
{ file: "plan2code-app/src-tauri/Cargo.toml", edit: (t, v) => swap(t, CARGO_VERSION, v, "version line") },
{ file: "plan2code-app/fake-agent/Cargo.toml", edit: (t, v) => swap(t, CARGO_VERSION, v, "version line") },
{
file: "plan2code-app/Cargo.lock",
edit: (t, v) => swap(swap(t, lockEntry("plan2code-app"), v, "plan2code-app entry"), lockEntry("fake-agent"), v, "fake-agent entry"),
},
];
function today() {
const d = new Date();
const pad = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
/**
* Write `version` into every carrier under `root`. Returns `{ ok, written: [file], problems: [string] }`;
* nothing is written unless every carrier edits cleanly.
*/
export function setVersion(root, version, date = today()) {
const problems = [];
const staged = [];
for (const { file, edit } of CARRIERS) {
const full = path.join(root, file);
try {
const before = fs.readFileSync(full, "utf8");
staged.push({ file, full, before, after: edit(before, version, date) });
} catch (error) {
problems.push(`${file}: ${error.code === "ENOENT" ? "file is missing" : error.message}`);
}
}
if (problems.length) return { ok: false, written: [], problems };
const written = [];
try {
for (const { file, full, before, after } of staged) {
if (after !== before) fs.writeFileSync(full, after);
written.push(file);
}
} catch (error) {
// A write failed part way (permissions, a locked file): put back what was already written.
for (const { file, full, before } of staged) if (written.includes(file)) fs.writeFileSync(full, before);
return { ok: false, written: [], problems: [`write failed (${error.code || error.message}); restored the files already written`] };
}
return { ok: true, written, problems };
}
export const CARRIER_FILES = CARRIERS.map((c) => c.file);
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const args = process.argv.slice(2);
const take = (flag) => {
const at = args.indexOf(flag);
if (at < 0) return undefined;
const [, value] = args.splice(at, 2);
return value ?? "";
};
const date = take("--date");
const rootArg = take("--root");
const [version, ...extra] = args;
const usage = "Usage: node scripts/set-version.mjs <x.y.z> [--date YYYY-MM-DD] [--root <dir>]";
if (!version || extra.length || !SEMVER.test(version) || (date !== undefined && !validDate(date)) || rootArg === "") {
console.error(usage);
process.exit(2);
}
const { ok, written, problems } = setVersion(rootArg ? path.resolve(rootArg) : ROOT, version, date);
if (!ok) {
for (const problem of problems) console.error(`CANNOT SET: ${problem}`);
console.error("Nothing was written.");
process.exit(1);
}
for (const file of written) console.log(`${version.padEnd(10)} ${file}`);
console.log(`Wrote ${version} to ${written.length} files. CHANGELOG.md is yours to edit; then run: node scripts/check-versions.mjs`);
}
+77
View File
@@ -0,0 +1,77 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { check, normalize, workflowOf } from "./check-console-openings.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const SRC = path.join(path.dirname(HERE), "src");
// A copy of the real prompts and notes names, small enough to edit per test.
function copySrc() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-openings-"));
for (const f of fs.readdirSync(SRC)) if (/^plan2code.*\.md$/.test(f)) fs.copyFileSync(path.join(SRC, f), path.join(dir, f));
fs.mkdirSync(path.join(dir, "web-console", "notes"), { recursive: true });
for (const f of fs.readdirSync(path.join(SRC, "web-console", "notes"))) fs.writeFileSync(path.join(dir, "web-console", "notes", f), "");
return dir;
}
function edit(dir, file, from, to) {
const p = path.join(dir, file);
const t = fs.readFileSync(p, "utf8");
assert.ok(t.includes(from), `fixture text missing in ${file}: ${from}`);
fs.writeFileSync(p, t.replace(from, to));
}
test("the real prompts pass", () => {
assert.deepEqual(check(SRC), []);
});
test("a drifted shared sentence is named with its skill", () => {
const dir = copySrc();
edit(dir, "plan2code-review.md", "Switchable anytime.", "You can switch whenever.");
const problems = check(dir);
assert.equal(problems.length, 1);
assert.match(problems[0], /plan2code-review\.md: shared sentence "switch"/);
});
test("punctuation and case alone do not count as drift", () => {
const dir = copySrc();
edit(dir, "plan2code-test.md", "Switchable anytime.", "switchable anytime.");
edit(dir, "plan2code-test.md", "Its session is already open: resume it", "Its session is already open \u2014 resume it");
assert.deepEqual(check(dir), []);
});
test("a wrong workflow name or a missing notes file is reported", () => {
const dir = copySrc();
edit(dir, "plan2code-xray.md", "--workflow xray", "--workflow diagnose");
edit(dir, "plan2code-changelog.md", "<D>/notes/changelog.md", "<D>/notes/nope.md");
const problems = check(dir).join("\n");
assert.match(problems, /plan2code-xray\.md.*shared sentence "run"/);
assert.match(problems, /plan2code-xray\.md: opens --workflow diagnose instead of xray/);
assert.match(problems, /plan2code-changelog\.md: notes file nope\.md is not in src\/web-console\/notes/);
});
test("a skill that loses its opening is caught by the count", () => {
const dir = copySrc();
fs.rmSync(path.join(dir, "plan2code-pr-prep.md"));
assert.match(check(dir).join("\n"), /expected 18 skills with a console opening, found 17/);
});
test("helpers", () => {
assert.equal(normalize("A \u2014 B: (C), D"), "a b c d");
assert.equal(workflowOf("plan2code-1b-revise-plan"), "revise-plan");
assert.equal(workflowOf("plan2code-3-implement-review"), "implement-review");
assert.equal(workflowOf("plan2code-pr-prep"), "pr-prep");
});
test("the CLI exits 1 on drift", () => {
const dir = copySrc();
edit(dir, "plan2code-git.md", "Switchable anytime.", "Whenever.");
const r = spawnSync(process.execPath, [path.join(HERE, "check-console-openings.mjs"), dir], { encoding: "utf8" });
assert.equal(r.status, 1);
assert.match(r.stderr, /plan2code-git\.md/);
});
+54
View File
@@ -0,0 +1,54 @@
import { test, after } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { oversize, DEFAULT_LIMIT } from "./check-doc-size.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const script = path.join(here, "check-doc-size.mjs");
const made = [];
after(() => {
for (const d of made) fs.rmSync(d, { recursive: true, force: true });
});
function fixture(sizes) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "docsize-"));
made.push(dir);
for (const [name, n] of Object.entries(sizes)) fs.writeFileSync(path.join(dir, name), "x".repeat(n));
return dir;
}
const run = (...args) => spawnSync(process.execPath, [script, ...args], { encoding: "utf8" });
test("files within the limit pass, and a file exactly at it passes", () => {
const dir = fixture({ "a.md": 10, "b.md": 100 });
const r = run(dir, "100");
assert.equal(r.status, 0, r.stderr);
});
test("a file over the limit fails and is named with its size", () => {
const dir = fixture({ "a.md": 10, "big.md": 101 });
const r = run(dir, "100");
assert.equal(r.status, 1);
assert.match(r.stderr, /big\.md: 101 bytes/);
assert.doesNotMatch(r.stderr, /a\.md/);
});
test("only .md files count", () => {
const dir = fixture({ "a.md": 10, "notes.txt": 5000 });
assert.deepEqual(oversize(dir, 100), []);
});
test("a bad limit is refused", () => {
const dir = fixture({ "a.md": 1 });
assert.equal(run(dir, "nope").status, 2);
});
test("every file in .agents-docs/ is within the default limit", () => {
const r = run();
assert.equal(r.status, 0, r.stderr);
assert.equal(DEFAULT_LIMIT, 60000);
});
+51
View File
@@ -0,0 +1,51 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { BANNED, findBanned } from "./check-prompt-wording.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.dirname(HERE);
function fixture(files) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-wording-"));
for (const [name, text] of Object.entries(files)) {
const full = path.join(dir, name);
fs.mkdirSync(path.dirname(full), { recursive: true });
fs.writeFileSync(full, text);
}
return dir;
}
test("a clean tree has no hits", () => {
const dir = fixture({ "a/SKILL.md": "Ask with the question tool. Run `glob` or grep in a shell.\n" });
assert.deepEqual(findBanned(dir), []);
});
test("every banned name is found, with its file and line", () => {
for (const name of BANNED) {
const dir = fixture({ "x/references/r.md": `fine\nuse ${name} here\n` });
assert.deepEqual(findBanned(dir), [{ file: "x/references/r.md", line: 2, name }], name);
}
});
test("a longer word that contains a banned name is not a hit", () => {
const dir = fixture({ "a.md": "Globals and Grepping and AskUserQuestionnaire\n" });
assert.deepEqual(findBanned(dir), []);
});
test("the CLI exits 1 on a hit and 0 on a clean tree", () => {
const bad = fixture({ "a.md": "never use Glob\n" });
const r = spawnSync(process.execPath, [path.join(HERE, "check-prompt-wording.mjs"), bad], { encoding: "utf8" });
assert.equal(r.status, 1);
assert.match(r.stderr, /a\.md:1 names a product tool: Glob/);
const ok = fixture({ "a.md": "list the folder\n" });
assert.equal(spawnSync(process.execPath, [path.join(HERE, "check-prompt-wording.mjs"), ok]).status, 0);
});
test("the built skills tree names no product tool", { skip: !fs.existsSync(path.join(ROOT, "skills")) }, () => {
assert.deepEqual(findBanned(path.join(ROOT, "skills")), []);
});
+57
View File
@@ -0,0 +1,57 @@
import { test, after } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const script = path.join(path.dirname(fileURLToPath(import.meta.url)), "check-test-lanes.mjs");
const made = [];
after(() => {
for (const d of made) fs.rmSync(d, { recursive: true, force: true });
});
function fixture(files, lanes) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "lanes-"));
made.push(dir);
for (const f of files) fs.writeFileSync(path.join(dir, f), "");
fs.writeFileSync(path.join(dir, "test-lanes.json"), JSON.stringify(lanes));
return dir;
}
const run = (dir) => spawnSync(process.execPath, [script, dir], { encoding: "utf8" });
test("a complete fixture passes", () => {
const dir = fixture(["test-a.mjs", "test-b.mjs"], { fast: ["test-a.mjs"], skipFast: ["test-b.mjs"] });
const r = run(dir);
assert.equal(r.status, 0, r.stderr);
});
test("an unlisted file fails and is named", () => {
const dir = fixture(["test-a.mjs", "test-b.mjs"], { fast: ["test-a.mjs"], skipFast: [] });
const r = run(dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /test-b\.mjs/);
});
test("a doubly listed file fails and is named", () => {
const dir = fixture(["test-a.mjs"], { fast: ["test-a.mjs"], skipFast: ["test-a.mjs"] });
const r = run(dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /In both lists: test-a\.mjs/);
});
test("a dangling name fails and is named", () => {
const dir = fixture(["test-a.mjs"], { fast: ["test-a.mjs"], skipFast: ["test-gone.mjs"] });
const r = run(dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /not on disk: test-gone\.mjs/);
});
test("a name repeated inside one list fails and is named", () => {
const dir = fixture(["test-a.mjs"], { fast: ["test-a.mjs", "test-a.mjs"], skipFast: [] });
const r = run(dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /Listed twice in one list: test-a.mjs/);
});
+187
View File
@@ -0,0 +1,187 @@
// Tests for the shared console: each skill's forwarding stub (src/web-console-stub/console.mjs)
// and what the build leaves in skills/.
// Run with: node --test scripts/test-console-stub.mjs
//
// The stubs run from the built skills/ tree against a scratch PLAN2CODE_CONSOLE_HOME holding a
// fake shared copy, so nothing here starts a console server or touches ~/.plan2code.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createRequire } from "node:module";
import { spawnSync } from "node:child_process";
import { pathToFileURL } from "node:url";
import { ROOT, SKILLS } from "./skill-script-helpers.mjs";
const require = createRequire(import.meta.url);
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-stub-"));
process.env.HOME = HOME;
process.env.USERPROFILE = HOME;
const { SOURCE_PROMPTS, generateSkillName, CONSOLE_SHARED_DIR } = require(path.join(ROOT, "install.js"));
test.after(() => fs.rmSync(HOME, { recursive: true, force: true }));
const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version;
const MESSAGE = "The Plan2Code console is missing or out of date. Run: plan2code update";
const consoleSkills = SOURCE_PROMPTS.filter((p) => (p.additionalReferences || []).some((r) => r.source === "web-console")).map(
(p) => ({ name: generateSkillName(p), target: p.additionalReferences.find((r) => r.source === "web-console").target })
);
// A stand-in shared console: prints the arguments it was given and the exit code asked for.
function fakeConsole({ version = VERSION, pointer = true, entry = true } = {}) {
const home = fs.mkdtempSync(path.join(HOME, "home-"));
const dir = path.join(home, version);
fs.mkdirSync(dir, { recursive: true });
if (entry) {
fs.writeFileSync(
path.join(dir, "console.mjs"),
'console.log(JSON.stringify({ args: process.argv.slice(2), home: process.env.PLAN2CODE_CONSOLE_HOME }));\nprocess.exitCode = Number(process.env.FAKE_EXIT || 0);\n'
);
}
fs.writeFileSync(path.join(dir, "version.txt"), version + "\n");
if (pointer) fs.writeFileSync(path.join(home, "console-dir"), dir + "\n");
return { home, dir };
}
function runStub(skill, home, args = [], env = {}) {
const stub = path.join(SKILLS, skill.name, "references", skill.target, "console.mjs");
return spawnSync(process.execPath, [stub, ...args], {
encoding: "utf8",
env: { ...process.env, PLAN2CODE_CONSOLE_HOME: home, ...env },
});
}
test("every skill that lists the console carries a stub", () => {
assert.ok(consoleSkills.length >= 19, `expected the 19 skills, found ${consoleSkills.length}`);
for (const skill of consoleSkills) {
const stub = path.join(SKILLS, skill.name, "references", skill.target, "console.mjs");
assert.ok(fs.existsSync(stub), `${skill.name} has no stub`);
const text = fs.readFileSync(stub, "utf8");
assert.ok(text.includes(`const VERSION = "${VERSION}";`), `${skill.name}: the version is not baked in`);
assert.ok(!text.includes("__PLAN2CODE_VERSION__"), `${skill.name}: the version token is left in`);
}
});
test("every stub forwards its arguments and exit code to the shared copy", () => {
const { home } = fakeConsole();
for (const skill of consoleSkills) {
const args = ["open", "--workflow", skill.name, "--spec", "specs/x y"];
const ok = runStub(skill, home, args);
assert.equal(ok.status, 0, `${skill.name}: ${ok.stderr}`);
assert.deepEqual(JSON.parse(ok.stdout).args, args, `${skill.name}: arguments`);
const coded = runStub(skill, home, ["wait"], { FAKE_EXIT: "30" });
assert.equal(coded.status, 30, `${skill.name}: the shared copy's exit code`);
assert.equal(coded.stderr, "", `${skill.name}: nothing is added on stderr`);
}
});
test("a missing or stale shared copy prints the one plain line and exits 5, naming no path", () => {
const cases = {
"no console-dir at all": () => fs.mkdtempSync(path.join(HOME, "empty-")),
"a pointer to a folder that is gone": () => {
const { home, dir } = fakeConsole();
fs.rmSync(dir, { recursive: true, force: true });
return home;
},
"a pointer to a source checkout with no version.txt": () => {
const home = fs.mkdtempSync(path.join(HOME, "source-pointer-"));
const source = fs.mkdtempSync(path.join(HOME, "source-"));
fs.writeFileSync(path.join(source, "console.mjs"), "");
fs.writeFileSync(path.join(home, "console-dir"), `${source}\n`);
return home;
},
"a copy of another version": () => fakeConsole({ version: "0.0.1" }).home,
"a copy with no console.mjs": () => fakeConsole({ entry: false }).home,
"an empty pointer": () => {
const home = fs.mkdtempSync(path.join(HOME, "empty-pointer-"));
fs.writeFileSync(path.join(home, "console-dir"), "\n");
return home;
},
};
for (const [what, make] of Object.entries(cases)) {
const home = make();
for (const skill of consoleSkills) {
const r = runStub(skill, home, ["open"]);
assert.equal(r.status, 5, `${what} (${skill.name}): exit code`);
assert.equal(r.stdout, "", `${what} (${skill.name}): stdout`);
assert.equal(r.stderr, MESSAGE + "\n", `${what} (${skill.name}): the line`);
assert.ok(!r.stderr.includes(home) && !/[\\/]/.test(r.stderr), `${what} (${skill.name}): names no path`);
}
}
});
test("a stub finds its own version folder even when console-dir names a console that is not this version", () => {
const { home } = fakeConsole({ pointer: false });
const elsewhere = fs.mkdtempSync(path.join(HOME, "elsewhere-"));
fs.writeFileSync(path.join(home, "console-dir"), `${elsewhere}\n`);
const res = runStub(consoleSkills[0], home, ["status"]);
assert.equal(res.status, 0, res.stderr);
assert.deepEqual(JSON.parse(res.stdout).args, ["status"]);
});
test("a stub finds the copy through console-dir under PLAN2CODE_CONSOLE_HOME and passes the home on", () => {
const { home } = fakeConsole();
const skill = consoleSkills[0];
const r = runStub(skill, home, ["status"], { PLAN2CODE_CONSOLE_HOME: home });
assert.equal(r.status, 0, r.stderr);
assert.equal(JSON.parse(r.stdout).home, home);
});
test("no built skill holds the large console files; the shared copy keeps every game, sound and vendor file", () => {
const forbidden = new Set(["public", "activities", "vendor"]);
const found = [];
const walk = (dir, rel) => {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const next = path.join(rel, e.name);
if (e.isDirectory()) {
if (forbidden.has(e.name)) found.push(next);
walk(path.join(dir, e.name), next);
} else if (/\.(mp3|png|svg)$/.test(e.name) || /^(server|routes|files|sessions)\.mjs$/.test(e.name)) found.push(next);
}
};
for (const entry of fs.readdirSync(SKILLS, { withFileTypes: true })) {
if (!entry.isDirectory() || entry.name === CONSOLE_SHARED_DIR) continue;
walk(path.join(SKILLS, entry.name), entry.name);
}
assert.deepEqual(found, [], "console files left inside a skill");
const shared = path.join(SKILLS, CONSOLE_SHARED_DIR, VERSION);
assert.equal(fs.readFileSync(path.join(shared, "version.txt"), "utf8").trim(), VERSION);
const src = path.join(ROOT, "src", "web-console");
const sourceFiles = [];
const collect = (dir, rel) => {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const next = rel ? `${rel}/${e.name}` : e.name;
if (e.isDirectory()) collect(path.join(dir, e.name), next);
else sourceFiles.push(next);
}
};
collect(src, "");
for (const rel of sourceFiles) {
const built = path.join(shared, ...rel.split("/"));
assert.ok(fs.existsSync(built), `the shared console lacks ${rel}`);
assert.ok(fs.readFileSync(built).equals(fs.readFileSync(path.join(src, ...rel.split("/")))), `${rel} differs from src/`);
}
assert.ok(fs.existsSync(path.join(shared, "public", "vendor", "codemirror.esm.js")), "codemirror ships");
assert.ok(fs.readdirSync(path.join(shared, "public")).filter((f) => f.endsWith(".mp3")).length >= 3, "every sound ships");
});
test("the shared copy ships a module for every game listed in public/activities.js", async () => {
const { ACTIVITIES } = await import(pathToFileURL(path.join(ROOT, "src", "web-console", "public", "activities.js")).href);
assert.ok(ACTIVITIES.length >= 13, `expected the thirteen games, found ${ACTIVITIES.length}`);
const shared = path.join(SKILLS, CONSOLE_SHARED_DIR, VERSION, "public");
for (const game of ACTIVITIES) {
assert.ok(fs.existsSync(path.join(shared, ...game.module.split("/").filter(Boolean))), `${game.id}: ${game.module} is not in the shared console`);
}
});
test("a skill keeps the markdown the agent reads by path, and notes/", () => {
for (const skill of consoleSkills) {
const dir = path.join(SKILLS, skill.name, "references", skill.target);
for (const file of ["console.md", "building.md", "console-finish.md"]) assert.ok(fs.existsSync(path.join(dir, file)), `${skill.name}: ${file}`);
assert.ok(fs.existsSync(path.join(dir, "notes", "implement.md")), `${skill.name}: notes/implement.md`);
}
});
+15
View File
@@ -0,0 +1,15 @@
// Runs the fast test lane: the files listed under `fast` in scripts/test-lanes.json,
// through node-test.mjs so its cap of one file per spare core applies.
// Usage: node scripts/test-fast.mjs (or: npm run test:fast)
import { spawnSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const lanes = JSON.parse(fs.readFileSync(path.join(here, "test-lanes.json"), "utf8"));
const files = lanes.fast.map((name) => path.join(here, name));
const r = spawnSync(process.execPath, [path.join(here, "node-test.mjs"), ...files], { cwd: process.cwd(), stdio: "inherit" });
process.exit(r.status ?? 1);
+36
View File
@@ -12,7 +12,9 @@ import path from "node:path";
import { execFileSync } from "node:child_process";
import { tmp, write, gitInit, gitIn, copyFixture, slashed, fixtureCleanup } from "./skill-script-helpers.mjs";
import {
GIT_TIMEOUT_MS,
countPending,
git,
gitFloor,
parseRemoteUrl,
parseStatusV2,
@@ -409,3 +411,37 @@ test("snapshot: a 300-branch repo reads in under 5 seconds", () => {
assert.equal(s.branches.length, 301);
assert.ok(took < 5000, `took ${took} ms`);
});
// A git that never returns (a stuck credential helper, hook or network drive)
// used to hold the console server's only thread for good. The alias stands in
// for one: real git, running a command that just sleeps.
test("git() gives up on a hanging git: 10 seconds by default, or the caller's limit", () => {
const repo = tmp("git-hang");
const hang = (ms) => ["-c", `alias.hang=!node -e "setTimeout(() => {}, ${ms})"`, "hang"];
assert.equal(GIT_TIMEOUT_MS, 10000);
let t = Date.now();
const quick = git(hang(30000), repo, { timeout: 500 });
assert.equal(quick.ok, false);
assert.match(quick.err, /did not finish within 0\.5s/);
assert.ok(Date.now() - t < 8000, "the caller's limit applies");
t = Date.now();
const byDefault = git(hang(14000), repo);
const took = Date.now() - t;
assert.equal(byDefault.ok, false);
assert.match(byDefault.err, /did not finish within 10s/);
assert.ok(took >= 9000 && took < 13500, `the default limit applies (took ${took}ms)`);
});
// A repository whose status fails (here a corrupt index; a status past git()'s
// time limit fails the same way) has an unknown tree: snapshot says so
// instead of drawing an empty, clean-looking board.
test("snapshot reports an error, not a clean tree, when git status fails in a repository", () => {
const { repo } = repoWithCommit("status-fails");
fs.writeFileSync(path.join(repo, ".git", "index"), "not an index");
const snap = snapshot(repo);
assert.equal(snap.repo, true);
assert.ok(snap.error, "the failure is reported");
assert.equal(snap.changes, undefined, "no change list is drawn from an empty status");
});
+105
View File
@@ -500,3 +500,108 @@ test("app declined: the no is remembered next to the pieces, and needs a record
installer.recordInstalled("launcher");
assert.deepEqual(installer.readInstallRecord().skipped, ["app"], "other writes keep the decline");
});
test("shared console install: the new version is placed, old versions go, and every other entry is left byte-identical", () => {
const SHARED = path.join(ROOT, "skills", installer.CONSOLE_SHARED_DIR, VERSION, "console.mjs");
if (!fs.existsSync(SHARED)) spawnSync(process.execPath, [INSTALL, "--build-skills"], { stdio: "ignore" });
const home = installer.consoleHomeDir();
assert.equal(home, path.join(HOME, ".plan2code", "console"), "the default home is under the temp HOME");
fs.rmSync(home, { recursive: true, force: true });
const put = (rel, body) => {
const p = path.join(home, ...rel.split("/"));
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, body);
return p;
};
put("2.9.9/console.mjs", "old");
put("2.9.9/public/core.js", "old");
put("10.0.0/console.mjs", "an older or newer version folder goes too");
put(`${VERSION}/stale.txt`, "a leftover inside the folder being replaced");
const kept = {
"sessions/20261108-101010-aaaaaa/state.json": '{"a":1}',
"sessions/20261108-101010-aaaaaa/shots/x.png": "png",
"looks.json": '{"theme":"dark"}',
"workspaces.json": "{}",
"subagents.json": "[]",
"runtime/x.json": "{}",
"notes.txt": "not ours",
"3.0/keep.txt": "not a version folder",
};
for (const [rel, body] of Object.entries(kept)) put(rel, body);
const lines = [];
const log = console.log;
console.log = (...a) => lines.push(a.join(" "));
let ok;
try {
ok = installer.installSharedConsole({ quiet: false });
} finally {
console.log = log;
}
assert.equal(ok, true);
assert.equal(fs.existsSync(path.join(home, "2.9.9")), false, "an old version folder is gone");
assert.equal(fs.existsSync(path.join(home, "10.0.0")), false, "every other version folder is gone");
assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs")), "the new version is present");
assert.equal(fs.readFileSync(path.join(home, VERSION, "version.txt"), "utf8").trim(), VERSION);
assert.equal(fs.existsSync(path.join(home, VERSION, "stale.txt")), false, "the folder is replaced, not merged");
assert.equal(fs.readFileSync(path.join(home, "console-dir"), "utf8").trim(), path.join(home, VERSION));
for (const [rel, body] of Object.entries(kept)) {
assert.equal(fs.readFileSync(path.join(home, ...rel.split("/")), "utf8"), body, rel + " is untouched");
}
assert.ok(lines.some((line) => line.includes("Removed old console 2.9.9")), lines.join("\n"));
// A second run changes nothing it should not.
assert.equal(installer.installSharedConsole({ quiet: true }), true);
assert.equal(fs.readFileSync(path.join(home, "looks.json"), "utf8"), kept["looks.json"]);
assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs")));
});
test("shared console install: sweep false keeps old versions until sweepOldConsoles runs", () => {
const SHARED = path.join(ROOT, "skills", installer.CONSOLE_SHARED_DIR, VERSION, "console.mjs");
if (!fs.existsSync(SHARED)) spawnSync(process.execPath, [INSTALL, "--build-skills"], { stdio: "ignore" });
const home = installer.consoleHomeDir();
fs.rmSync(home, { recursive: true, force: true });
fs.mkdirSync(path.join(home, "2.9.9"), { recursive: true });
fs.writeFileSync(path.join(home, "2.9.9", "console.mjs"), "old");
fs.writeFileSync(path.join(home, "2.9.9", "version.txt"), "2.9.9\n");
assert.equal(installer.installSharedConsole({ quiet: true, sweep: false }), true);
assert.ok(fs.existsSync(path.join(home, "2.9.9", "console.mjs")), "a failed skills add leaves the old version for the old stubs");
assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs")), "the new version is placed");
installer.sweepOldConsoles({ quiet: true });
assert.equal(fs.existsSync(path.join(home, "2.9.9")), false, "swept once skills add worked");
assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs")), "the current version stays");
});
test("shared console install: a missing build fails plainly and removes nothing", () => {
const home = installer.consoleHomeDir();
fs.mkdirSync(home, { recursive: true });
fs.writeFileSync(path.join(home, "looks.json"), "{}");
const errors = [];
const error = console.error;
console.error = (...a) => errors.push(a.join(" "));
try {
// An empty folder stands in for a build that did not happen; the real build is never touched.
const empty = fs.mkdtempSync(path.join(HOME, "no-build-"));
assert.equal(installer.installSharedConsole({ quiet: true, source: empty }), false);
} finally {
console.error = error;
}
assert.ok(errors.join("\n").includes("Could not install the shared console"));
assert.ok(fs.existsSync(path.join(home, "looks.json")), "what was there stays");
});
test("the skills CLI is pinned to one exact version, and every doc line that runs it names that version", () => {
const source = fs.readFileSync(INSTALL, "utf8");
const pinned = source.match(/const SKILLS_CLI_VERSION = '(\d+\.\d+\.\d+)';/);
assert.ok(pinned, "install.js pins SKILLS_CLI_VERSION to an exact x.y.z");
assert.ok(source.includes("npx --yes skills@${SKILLS_CLI_VERSION}"), "SKILLS_CLI runs the pinned version");
assert.ok(!/npx (--yes )?skills( |')/.test(source), "no unpinned `npx skills` in install.js");
for (const doc of ["README.md", ".agents-docs/AGENTS-development-commands.md"]) {
const text = fs.readFileSync(path.join(ROOT, doc), "utf8");
assert.ok(!/npx (--yes )?skills (add|list|remove|--version)/.test(text), `${doc} has an unpinned \`npx skills\` command`);
for (const m of text.matchAll(/npx (?:--yes )?skills@(\d+\.\d+\.\d+)/g)) {
assert.equal(m[1], pinned[1], `${doc} names skills@${m[1]}, install.js pins ${pinned[1]}`);
}
}
});
+122
View File
@@ -0,0 +1,122 @@
{
"fast": [
"test-agent-lookup.mjs",
"test-agents-file.mjs",
"test-app-meter.mjs",
"test-browser-helper.mjs",
"test-check-console-openings.mjs",
"test-check-doc-size.mjs",
"test-check-prompt-wording.mjs",
"test-check-test-lanes.mjs",
"test-check-versions.mjs",
"test-getting-started.mjs",
"test-git-repo.mjs",
"test-install-update.mjs",
"test-line-endings.mjs",
"test-script-changelog.mjs",
"test-script-coverage.mjs",
"test-script-finalize.mjs",
"test-script-git.mjs",
"test-script-pathfinder.mjs",
"test-script-pr-prep.mjs",
"test-script-run-check.mjs",
"test-script-test-commands.mjs",
"test-script-test-map.mjs",
"test-script-test-match.mjs",
"test-script-xray.mjs",
"test-set-version.mjs",
"test-skill-scripts.mjs",
"test-skill-test-runs.mjs",
"test-us-english.mjs",
"test-web-console-agents-doc.mjs",
"test-web-console-git-board.mjs",
"test-web-console-send-state.mjs",
"test-web-console-shape.mjs",
"test-web-console-skills.mjs",
"test-web-console-spec-states.mjs",
"test-web-console-state.mjs",
"test-web-console-strengths.mjs",
"test-web-console-tones.mjs"
],
"skipFast": [
"test-console-stub.mjs",
"test-console-wire-budgets.mjs",
"test-fast.mjs",
"test-launcher.mjs",
"test-standalone-check.mjs",
"test-web-console-activities-bounce-cars.mjs",
"test-web-console-activities-bounce-game.mjs",
"test-web-console-activities-bounce.mjs",
"test-web-console-activities-flock.mjs",
"test-web-console-activities-ghoul-arms.mjs",
"test-web-console-activities-ghoul-banister.mjs",
"test-web-console-activities-ghoul-bog.mjs",
"test-web-console-activities-ghoul-bones.mjs",
"test-web-console-activities-ghoul-bonestair.mjs",
"test-web-console-activities-ghoul-bossintro.mjs",
"test-web-console-activities-ghoul-carnival.mjs",
"test-web-console-activities-ghoul-cart.mjs",
"test-web-console-activities-ghoul-chapel.mjs",
"test-web-console-activities-ghoul-dice.mjs",
"test-web-console-activities-ghoul-ending.mjs",
"test-web-console-activities-ghoul-eye.mjs",
"test-web-console-activities-ghoul-frozen.mjs",
"test-web-console-activities-ghoul-gameover.mjs",
"test-web-console-activities-ghoul-graveyard.mjs",
"test-web-console-activities-ghoul-grounds.mjs",
"test-web-console-activities-ghoul-gurney.mjs",
"test-web-console-activities-ghoul-hearse.mjs",
"test-web-console-activities-ghoul-heart.mjs",
"test-web-console-activities-ghoul-intro.mjs",
"test-web-console-activities-ghoul-lantern.mjs",
"test-web-console-activities-ghoul-marrow.mjs",
"test-web-console-activities-ghoul-mat.mjs",
"test-web-console-activities-ghoul-mine.mjs",
"test-web-console-activities-ghoul-mower.mjs",
"test-web-console-activities-ghoul-pew.mjs",
"test-web-console-activities-ghoul-retry.mjs",
"test-web-console-activities-ghoul-ride.mjs",
"test-web-console-activities-ghoul-sanatorium.mjs",
"test-web-console-activities-ghoul-sled.mjs",
"test-web-console-activities-ghoul-story.mjs",
"test-web-console-activities-ghoul-tray.mjs",
"test-web-console-activities-ghoul-village.mjs",
"test-web-console-activities-ghoul-wagon.mjs",
"test-web-console-activities-ghoul.mjs",
"test-web-console-activities-rapids.mjs",
"test-web-console-activities.mjs",
"test-web-console-chat-stress.mjs",
"test-web-console-chat.mjs",
"test-web-console-concurrency.mjs",
"test-web-console-embed.mjs",
"test-web-console-git.mjs",
"test-web-console-handoffs.mjs",
"test-web-console-hardening.mjs",
"test-web-console-in-app.mjs",
"test-web-console-lifecycle.mjs",
"test-web-console-logic.mjs",
"test-web-console-loop.mjs",
"test-web-console-notepad.mjs",
"test-web-console-page-activities.mjs",
"test-web-console-page-ask.mjs",
"test-web-console-page-cards.mjs",
"test-web-console-page-dashboard.mjs",
"test-web-console-page-git.mjs",
"test-web-console-page-help.mjs",
"test-web-console-page-loop.mjs",
"test-web-console-page-notepad.mjs",
"test-web-console-page-prefs.mjs",
"test-web-console-page-send.mjs",
"test-web-console-page-session.mjs",
"test-web-console-page-setup.mjs",
"test-web-console-page-workspace.mjs",
"test-web-console-pointers.mjs",
"test-web-console-qa.mjs",
"test-web-console-server.mjs",
"test-web-console-session.mjs",
"test-web-console-source.mjs",
"test-web-console-speed.mjs",
"test-web-console-subagents.mjs",
"test-web-console-workspace.mjs"
]
}
+68 -15
View File
@@ -140,7 +140,7 @@ function writeCache(box, latest, ageMs = 0) {
test("launcher: Claude Code gets the prompt first, then bypassPermissions and the forwarded args", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
const result = box.run(["--verbose"]);
const result = box.run(["--bypass-permissions", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions", "--verbose"]);
assert.match(result.stdout, new RegExp(`Claude Code ${NOTICE}`));
@@ -149,7 +149,7 @@ test("launcher: Claude Code gets the prompt first, then bypassPermissions and th
test("launcher: Devin keeps its args ahead of the -- and the prompt", (t) => {
const box = sandbox(["devin"]);
t.after(box.cleanup);
const result = box.run(["--verbose"]);
const result = box.run(["--bypass-permissions", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("devin"), ["--permission-mode", "bypass", "--verbose", "--", "/plan2code"]);
});
@@ -157,7 +157,7 @@ test("launcher: Devin keeps its args ahead of the -- and the prompt", (t) => {
test("launcher: Codex gets the bypass flag, the forwarded args, then the $plan2code prompt", (t) => {
const box = sandbox(["codex"]);
t.after(box.cleanup);
const result = box.run(["--verbose"]);
const result = box.run(["--bypass-permissions", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("codex"), ["--dangerously-bypass-approvals-and-sandbox", "--verbose", "$plan2code"]);
});
@@ -177,6 +177,59 @@ test("launcher: --keep-permissions keeps every built-in's permission prompts, an
}
});
test("launcher: with no terminal and no flag every built-in keeps its permission prompts", (t) => {
const box = sandbox(["claude", "devin", "codex"]);
t.after(box.cleanup);
const expected = {
claude: ["/plan2code", "--verbose"],
devin: ["--verbose", "--", "/plan2code"],
codex: ["--verbose", "$plan2code"],
};
for (const [cli, args] of Object.entries(expected)) {
const result = box.run(["--cli", cli, "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf(cli), args, cli);
assert.doesNotMatch(result.stdout, /off\?/, cli);
}
});
test("launcher: --bypass-permissions turns every built-in's prompts off with no terminal, and is never forwarded", (t) => {
const box = sandbox(["claude", "devin", "codex"]);
t.after(box.cleanup);
const expected = {
claude: ["/plan2code", "--permission-mode", "bypassPermissions", "--verbose"],
devin: ["--permission-mode", "bypass", "--verbose", "--", "/plan2code"],
codex: ["--dangerously-bypass-approvals-and-sandbox", "--verbose", "$plan2code"],
};
for (const [cli, args] of Object.entries(expected)) {
const result = box.run(["--cli", cli, "--bypass-permissions", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf(cli), args, cli);
}
// --keep-permissions wins when both are given.
assert.equal(box.run(["--cli", "claude", "--bypass-permissions", "--keep-permissions"]).status, 0);
assert.deepEqual(box.argsOf("claude"), ["/plan2code"]);
});
test("launcher: the keyboard question names what the flag drops, and Codex's names its sandbox", () => {
const { bypassQuestion } = require(LAUNCHER);
const claude = bypassQuestion({ id: "claude", label: "Claude Code", bypassArgs: ["--permission-mode", "bypassPermissions"] });
assert.equal(claude.heading, "Turn Claude Code's permission prompts off?");
assert.equal(claude.prompt, "Turn permission prompts off?");
assert.match(claude.detail, /without asking \(--permission-mode bypassPermissions\)/);
assert.doesNotMatch(claude.detail, /sandbox/);
assert.equal(claude.hint, "Type n to keep the permission prompts, or press Enter to turn them off.");
const codex = bypassQuestion({ id: "codex", label: "Codex", bypassArgs: ["--dangerously-bypass-approvals-and-sandbox"] });
assert.equal(codex.heading, "Turn Codex's approval prompts and its sandbox off?");
assert.equal(codex.prompt, "Turn approval prompts and its sandbox off?");
assert.match(codex.detail, /outside its sandbox \(--dangerously-bypass-approvals-and-sandbox\)/);
assert.equal(codex.hint, "Type n to keep the approval prompts and its sandbox, or press Enter to turn them off.");
// A custom agent gets the plain wording, with its own arguments.
const goose = bypassQuestion({ id: "goose", label: "Goose", bypassArgs: ["--bypass"] });
assert.equal(goose.heading, "Turn Goose's permission prompts off?");
assert.match(goose.detail, /\(--bypass\)/);
});
test("launcher: --cli codex picks Codex when it is installed beside another CLI", (t) => {
const box = sandbox(["claude", "codex"]);
t.after(box.cleanup);
@@ -200,7 +253,7 @@ test("launcher: Codex takes a forwarded --model ahead of the $plan2code prompt,
const result = box.run(["--cli", "codex", "--model", "x"]);
assert.equal(result.status, 0, result.stderr);
assert.doesNotMatch(result.stdout, new RegExp(NOTICE));
assert.deepEqual(box.argsOf("codex"), ["--dangerously-bypass-approvals-and-sandbox", "--model", "x", "$plan2code"]);
assert.deepEqual(box.argsOf("codex"), ["--model", "x", "$plan2code"]);
});
test("launcher: Codex's -m counts as a model already chosen", (t) => {
@@ -209,7 +262,7 @@ test("launcher: Codex's -m counts as a model already chosen", (t) => {
const result = box.run(["--cli", "codex", "-m", "x"]);
assert.equal(result.status, 0, result.stderr);
assert.doesNotMatch(result.stdout, new RegExp(NOTICE));
assert.deepEqual(box.argsOf("codex"), ["--dangerously-bypass-approvals-and-sandbox", "-m", "x", "$plan2code"]);
assert.deepEqual(box.argsOf("codex"), ["-m", "x", "$plan2code"]);
});
test("launcher: hasModelFlag reads -m as a model only for Codex", () => {
@@ -241,7 +294,7 @@ test("launcher: a forwarded --model skips the model notice", (t) => {
const result = box.run(args);
assert.equal(result.status, 0, result.stderr);
assert.doesNotMatch(result.stdout, new RegExp(NOTICE));
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions", ...args]);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", ...args]);
}
});
@@ -270,7 +323,7 @@ test("launcher: --cli picks the CLI and is never forwarded; the pick is merged i
for (const args of [["--cli", "devin"], ["--cli=DEVIN"]]) {
const result = box.run(args);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("devin"), ["--permission-mode", "bypass", "--", "/plan2code"]);
assert.deepEqual(box.argsOf("devin"), ["--", "/plan2code"]);
}
assert.equal(box.argsOf("claude"), null);
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), { lastFolder: box.home, lastCli: "devin" });
@@ -393,7 +446,7 @@ test("launcher: a forwarded argument with a space and a cmd metacharacter arrive
t.after(box.cleanup);
const result = box.run(["--append-system-prompt", "a b&c"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions", "--append-system-prompt", "a b&c"]);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--append-system-prompt", "a b&c"]);
});
test("launcher: the CLI's non-zero exit code is passed through", (t) => {
@@ -533,7 +586,7 @@ test("launcher: a piped run prints no escape codes, with or without NO_COLOR", (
// The desktop app hand-off. The stand-in app is found through PLAN2CODE_APP; "no display" is
// only something a Linux run can ask for, since Windows and macOS always count as having one.
const NO_DISPLAY = { DISPLAY: "", WAYLAND_DISPLAY: "" };
const CLASSIC_ARGS = ["/plan2code", "--permission-mode", "bypassPermissions"];
const CLASSIC_ARGS = ["/plan2code"];
test("launcher app: with no app installed the agent starts exactly as before", (t) => {
const box = sandbox(["claude"]);
@@ -759,13 +812,13 @@ test("launcher agents: --cli <custom id> starts it with args, the model through
const box = sandbox(["claude", "goose"]);
t.after(box.cleanup);
writeAgents(box, goose());
const result = box.run(["--cli", "goose", "--model", "m1", "--verbose"]);
const result = box.run(["--cli", "goose", "--bypass-permissions", "--model", "m1", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("goose"), ["--yes", "/plan2code", "--model", "m1", "--bypass", "--verbose"]);
assert.equal(box.argsOf("claude"), null);
assert.equal(JSON.parse(fs.readFileSync(box.stateFile, "utf8")).lastCli, "goose");
// No model chosen and no models flag: the model arguments are left out.
assert.equal(box.run(["--cli=goose"]).status, 0);
assert.equal(box.run(["--cli=goose", "--bypass-permissions"]).status, 0);
assert.deepEqual(box.argsOf("goose"), ["--yes", "/plan2code", "--bypass"]);
// --keep-permissions leaves bypassArgs out.
assert.equal(box.run(["--cli=goose", "--keep-permissions"]).status, 0);
@@ -903,7 +956,7 @@ const leadRun = (id) => builtin(id).install[OS_KEY][0].run;
test("launcher list: the menu and launch come from the sandboxed agents.json + agent-lookup.mjs", (t) => {
const box = sandbox(["claude", "devin", "codex"], { installed: "0.0.0" });
t.after(box.cleanup);
const result = box.run(["--cli", "devin", "--verbose"]);
const result = box.run(["--cli", "devin", "--bypass-permissions", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("devin"), ["--permission-mode", "bypass", "--verbose", "--", "/plan2code"]);
// The menu's order and shape come from the list: --cli errors list the same ids.
@@ -916,9 +969,9 @@ test("launcher list: a forwarded --model fills {model} in place; Codex's -m forw
const box = sandbox(["claude", "codex"], { installed: "0.0.0" });
t.after(box.cleanup);
assert.equal(box.run(["--cli", "claude", "--model", "opus"]).status, 0);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions", "--model", "opus"]);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--model", "opus"]);
assert.equal(box.run(["--cli", "codex", "-m", "x"]).status, 0);
assert.deepEqual(box.argsOf("codex"), ["--dangerously-bypass-approvals-and-sandbox", "-m", "x", "$plan2code"]);
assert.deepEqual(box.argsOf("codex"), ["-m", "x", "$plan2code"]);
});
test("launcher list: the last-used notice names the gone agent and the pick, on a terminal only", () => {
@@ -940,7 +993,7 @@ test("launcher list: a missing agent-lookup.mjs falls back to the built-in list"
t.after(box.cleanup);
const result = box.run([]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions"]);
assert.deepEqual(box.argsOf("claude"), ["/plan2code"]);
});
test("launcher list: with no agent and no terminal it prints this OS's install steps and exits 127", (t) => {
+26
View File
@@ -84,3 +84,29 @@ test("--hook fixes the file a Write or Edit names, and nothing outside the repo"
for (const input of ["", "not json", "{}"]) assert.equal(run(dir, ["--hook"], input).status, 0, `never fails the tool call (${JSON.stringify(input)})`);
});
test("the pre-commit hook refuses a staged file named nul, and .gitignore no longer hides one", async () => {
const { nulPaths } = await import("./check-staged-nul.mjs");
assert.deepEqual(nulPaths(["nul", "src/NUL", "docs/nul.txt", "null.md", "src/nullable.js", "annul", "a/b/Nul.log"]), ["nul", "src/NUL", "docs/nul.txt", "a/b/Nul.log"]);
assert.match(fs.readFileSync(path.join(HERE, "..", ".husky", "pre-commit"), "utf8"), /^node scripts\/check-staged-nul\.mjs$/m);
assert.ok(!/^nul$/m.test(fs.readFileSync(path.join(HERE, "..", ".gitignore"), "utf8")), "the check replaces the ignore line");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-nul-"));
try {
const g = (...a) => execFileSync("git", ["-C", dir, ...a], { encoding: "utf8", stdio: "pipe" });
g("init", "-q");
fs.writeFileSync(path.join(dir, "ok.txt"), "ok\n");
g("add", "ok.txt");
const check = () => spawnSync(process.execPath, [path.join(HERE, "check-staged-nul.mjs")], { cwd: dir, encoding: "utf8" });
assert.equal(check().status, 0, "an ordinary file passes");
// Staged through the index, with no file on disk: Windows cannot create
// one, and git there refuses the path unless protectNTFS is off.
const blob = execFileSync("git", ["-C", dir, "hash-object", "-w", "--stdin"], { input: "", encoding: "utf8" }).trim();
g("-c", "core.protectNTFS=false", "update-index", "--add", "--cacheinfo", `100644,${blob},sub/nul.txt`);
const refused = check();
assert.equal(refused.status, 1);
assert.match(refused.stderr, /refusing to commit a file named nul.*sub\/nul\.txt/);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
+12
View File
@@ -1043,3 +1043,15 @@ test("the git prompt never instructs a forbidden command, stays under 20,000 cha
assert.ok(prompt.includes(name), `the prompt names ${name}`);
}
});
test("commit-msg has no add-everything option: --add-all is refused, and no prompt, reference or script names it", () => {
const r = runScript("plan2code-git", "commit-msg.mjs", ["--subject", "Fix", "--add-all"]);
assert.equal(r.code, 2, r.stdout);
assert.equal(r.json.error, "unknown-flag");
// Every source a skill ships (prompts, references, scripts and the console)
// and the desktop app, whose Loop runs the script too.
const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : /\.(md|mjs|js|rs)$/.test(e.name) ? [path.join(dir, e.name)] : []));
const sources = [...walk(path.join(ROOT, "src")), ...walk(path.join(ROOT, "plan2code-app", "src-tauri", "src"))];
const found = sources.filter((f) => !/[\\/]public[\\/]vendor[\\/]/.test(f) && fs.readFileSync(f, "utf8").includes("--add-all"));
assert.deepEqual(found.map((f) => path.relative(ROOT, f)), [], "--add-all is retired: stage the work's own files with --files");
});
+174 -16
View File
@@ -25,7 +25,7 @@ const MAP = `${B}
# Map: audit-export
*Decisions live in \`questions/\` — one file each. This file is just the index.*
*Decisions live in \`questions/\`, one file each. This file is just the index.*
**Status:** Working
**Updated:** 2026-08-01
@@ -43,7 +43,7 @@ A locked plan for exporting audit events.
<!-- Rebuilt from questions/ every session. -->
- [x] [Codebase context](./questions/00-codebase-context.md) — Node and Postgres; a long gist
- [x] [Codebase context](./questions/00-codebase-context.md): Node and Postgres; a long gist
that wraps onto a second line. *(2026-08-01)*
- [ ] [Export format](./questions/01-export-format.md)
- [ ] [Row-count
@@ -89,11 +89,11 @@ test("pathfinder reconcile: files win, dates backfill, stale claims reset, rows
assert.deepEqual(r.json.refire.map((x) => x.nn), ["02"], "research with no Research complete line is re-fired");
assert.equal(r.json.refire[0].partialEvidence, true);
const map = read(root, `${pf}/map.md`);
assert.match(map, /- \[x\] \[Codebase context\]\(\.\/questions\/00-codebase-context\.md\) — Node and Postgres; a long gist\n that wraps onto a second line\. \*\(2026-08-01\)\*/, "an unchanged row keeps its own wrapped text");
assert.match(map, /- \[x\] \[Export format\]\(\.\/questions\/01-export-format\.md\) — CSV with a BOM\. \*\(2026-08-02\)\*/);
assert.match(map, /- \[x\] \[Codebase context\]\(\.\/questions\/00-codebase-context\.md\): Node and Postgres; a long gist\n that wraps onto a second line\. \*\(2026-08-01\)\*/, "an unchanged row keeps its own wrapped text");
assert.match(map, /- \[x\] \[Export format\]\(\.\/questions\/01-export-format\.md\): CSV with a BOM\. \*\(2026-08-02\)\*/);
assert.match(map, /- \[ \] \[Row-count\n ceiling\]\(\.\/questions\/02-row-count-ceiling\.md\)/, "a wrapped link is still one row");
assert.match(map, /- \[!\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\) — Blocked by 02/);
assert.match(map, /- \[-\] \[SIEM push\]\(\.\/questions\/05-siem-push\.md\) — out of scope, see below/);
assert.match(map, /- \[!\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\): Blocked by 02/);
assert.match(map, /- \[-\] \[SIEM push\]\(\.\/questions\/05-siem-push\.md\): out of scope, see below/);
assert.ok(!map.includes("09-gone"), "a row with no file is dropped");
assert.match(map, /<!-- Rebuilt from questions\/ every session\. -->/);
const q1 = read(root, `${pf}/questions/01-export-format.md`);
@@ -132,13 +132,13 @@ test("pathfinder frontier, claim, resolve, rule-out", () => {
assert.equal(res.code, 0, res.stderr);
assert.deepEqual(res.json.unblocked, [{ nn: "04", name: "Delivery channel" }]);
const map = read(root, `${pf}/map.md`);
assert.match(map, /- \[x\] \[Row-count ceiling\]\(\.\/questions\/02-row-count-ceiling\.md\) — 2M rows at the 99th percentile\. \*\(2026-08-03\)\*/);
assert.match(map, /- \[x\] \[Row-count ceiling\]\(\.\/questions\/02-row-count-ceiling\.md\): 2M rows at the 99th percentile\. \*\(2026-08-03\)\*/);
assert.match(map, /- \[ \] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\)\n/, "the Blocked by tail goes with the [!] marker");
assert.match(map, /^\*\*Updated:\*\* 2026-08-03$/m);
const ro = P("rule-out", "audit-export", "03", "--reason", "testing is owned elsewhere");
assert.equal(ro.code, 0, ro.stderr);
assert.match(read(root, `${pf}/questions/03-testing-posture.md`), /State: out-of-scope[\s\S]*## Question\n\nOut of scope: testing is owned elsewhere/);
assert.match(read(root, `${pf}/map.md`), /## Out of scope\n\n- Redesign of the schema\.\n- \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\) — testing is owned elsewhere/);
assert.match(read(root, `${pf}/map.md`), /## Out of scope\n\n- Redesign of the schema\.\n- \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\): testing is owned elsewhere/);
assert.equal(P("rule-out", "audit-export", "04").code, 2, "--reason is required");
assert.equal(P("rule-out", "audit-export", "00", "--reason", "x").code, 5, "a resolved decision is not ruled out");
});
@@ -156,7 +156,7 @@ test("pathfinder trail: exact footer for forms A, B and C", () => {
" ● done · ◉ here · ○ open · ⊘ blocked · ⊝ out of scope · ⚑ destination · ~1 fog",
" 1 Codebase context ✔ · 2 Export format ✔ · 3 Row-count ceiling · 4 Testing posture ◀ here",
" 5 Delivery channel (blocked:3) · 6 SIEM push (out of scope)",
" Confidence: not yet — Feasibility still needs work.",
" Confidence: not yet, Feasibility still needs work.",
"",
"WAITING ON YOU · answer here, in this conversation:",
"Q1 Types · Q2 Cadence",
@@ -266,7 +266,7 @@ test("pathfinder brief-data: range filtering, frontier notes, plain sections", (
assert.deepEqual(full.waiting, [{ name: "Delivery channel", waitingOn: ["Row-count ceiling"] }]);
assert.deepEqual(full.fog, ["How far back an export may reach."]);
assert.deepEqual(full.ruledOut, ["Redesign of the schema."]);
assert.equal(full.confidence, "Confidence: not yet — Feasibility still needs work.");
assert.equal(full.confidence, "Confidence: not yet, Feasibility still needs work.");
const since = P("brief-data", "audit-export", "--range", "since:2026-08-02").json;
assert.deepEqual(since.decided.map((d) => d.name), ["Export format"]);
assert.deepEqual(P("brief-data", "audit-export", "--range", "2026-08-01..2026-08-01").json.decided.map((d) => d.name), ["Codebase context"]);
@@ -304,7 +304,7 @@ test("pathfinder reconcile: an unrepairable file is skipped and named, nothing h
test("pathfinder reconcile: rows stay in place among grouping lines, a re-opened row loses its gist, stray claims clear", () => {
const { root, pf } = mapFixture();
const mp = path.join(root, pf, "map.md");
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- [ ] [Export format]", "### Group two\n\n- [x] [Export format]").replace("- [ ] [Export format](./questions/01-export-format.md)", "- [x] [Export format](./questions/01-export-format.md) — old gist *(2026-07-01)*"));
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- [ ] [Export format]", "### Group two\n\n- [x] [Export format]").replace("- [ ] [Export format](./questions/01-export-format.md)", "- [x] [Export format](./questions/01-export-format.md): old gist *(2026-07-01)*"));
fs.writeFileSync(path.join(root, pf, "questions/01-export-format.md"), q("Export format", { claimed: "2026-08-02 10:00" }));
const r = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["reconcile", "audit-export", "--root", root]);
assert.ok(r.json.repairs.some((x) => x.nn === "01" && x.repair === "stray-claim-cleared"));
@@ -366,10 +366,10 @@ test("pathfinder brief-data: calendar dates only, no future since, no NNs or lin
assert.equal(P("brief-data", "audit-export", "--range", "since:2026-13-99").json.error, "bad-date");
assert.equal(P("brief-data", "audit-export", "--range", "since:2026-09-01").code, 2);
const mp = path.join(root, pf, "map.md");
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- Redesign of the schema.", "- [SIEM push](./questions/05-siem-push.md) — not ours.\n- Nothing yet."));
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- Redesign of the schema.", "- [SIEM push](./questions/05-siem-push.md): not ours.\n- Nothing yet."));
fs.writeFileSync(path.join(root, pf, "questions/04-delivery-channel.md"), q("Delivery channel", { blocked: "09" }));
const j = P("brief-data", "audit-export", "--range", "full").json;
assert.deepEqual(j.ruledOut, ["SIEM push — not ours."]);
assert.deepEqual(j.ruledOut, ["SIEM push: not ours."]);
assert.deepEqual(j.waiting.find((w) => w.name === "Delivery channel").waitingOn, ["a question that no longer exists"]);
});
@@ -445,15 +445,15 @@ test("pathfinder: an author's sub-bullet under a row survives resolve, rule-out
.replace("- [ ] [Delivery channel](./questions/04-delivery-channel.md)", "- [ ] [Delivery channel](./questions/04-delivery-channel.md)\n - note: depends on the volume\n and wraps"));
P("reconcile", "audit-export");
let map = read(root, `${pf}/map.md`);
assert.match(map, /- \[!\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\) — Blocked by 02\n - note: depends on the volume\n and wraps\n/, "kept under a regenerated [!] row");
assert.match(map, /- \[!\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\): Blocked by 02\n - note: depends on the volume\n and wraps\n/, "kept under a regenerated [!] row");
P("claim", "audit-export", "03");
fs.appendFileSync(path.join(root, pf, "questions/03-testing-posture.md"), "\n## Answer\n\nUnit.\n\n**Gist:** Unit tests only.\n");
assert.equal(P("resolve", "audit-export", "03").code, 0);
map = read(root, `${pf}/map.md`);
assert.match(map, /- \[x\] \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\) — Unit tests only\. \*\(2026-08-03\)\*\n - note: ask Dana first\n/, "kept on resolve");
assert.match(map, /- \[x\] \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\): Unit tests only\. \*\(2026-08-03\)\*\n - note: ask Dana first\n/, "kept on resolve");
assert.equal(P("rule-out", "audit-export", "04", "--reason", "not ours").code, 0);
map = read(root, `${pf}/map.md`);
assert.match(map, /- \[-\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\) — out of scope, see below\n - note: depends on the volume\n and wraps\n/, "kept on rule-out");
assert.match(map, /- \[-\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\): out of scope, see below\n - note: depends on the volume\n and wraps\n/, "kept on rule-out");
assert.deepEqual(P("frontier", "audit-export").json.drift, []);
});
@@ -540,3 +540,161 @@ test("pathfinder lint: the chart.md map template lints clean", () => {
assert.equal(l.code, 0, JSON.stringify(l.json.problems));
assert.deepEqual([l.json.errors, l.json.warnings], [0, 0], JSON.stringify(l.json.problems));
});
/* ============================================== separators, init and add */
// U+2014, built from its code so this file carries none: maps written before
// the ": " separator used it between a row's link and its tail.
const EM = String.fromCharCode(0x2014);
test("pathfinder: a map written the old way (em dash tails) still reads, and nothing the script writes has an em dash", () => {
const { root, pf } = mapFixture();
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
const mp = path.join(root, pf, "map.md");
const oldRow00 = `- [x] [Codebase context](./questions/00-codebase-context.md) ${EM} Node and Postgres; a long gist\n that wraps onto a second line. *(2026-08-01)*`;
const oldRow04 = `- [!] [Delivery channel](./questions/04-delivery-channel.md) ${EM} Blocked by 02`;
const OLD = MAP
.replace(", one file each", ` ${EM} one file each`)
.replace(/- \[x\] \[Codebase context\][^\n]*\n[^\n]*\n/, `${oldRow00}\n`)
.replace("- [ ] [Testing posture](./questions/03-testing-posture.md)", `- [x] [Testing posture](./questions/03-testing-posture.md) ${EM} an old gist *(2026-07-01)*`)
.replace("- [ ] [Delivery channel](./questions/04-delivery-channel.md)", `${oldRow04}\n- [-] [SIEM push](./questions/05-siem-push.md) ${EM} out of scope, see below`)
.replace("- [ ] [Gone question](./questions/09-gone.md)\n", "")
.replace("- Redesign of the schema.", `- [SIEM push](./questions/05-siem-push.md) ${EM} not ours.\n- Nothing yet.`);
fs.writeFileSync(mp, OLD);
// Every old row is found by its checkbox and link: drift is about markers only.
const before = P("frontier", "audit-export").json;
assert.ok(!before.drift.some((d) => /no map row|no question file|appears/.test(d)), JSON.stringify(before.drift));
const r = P("reconcile", "audit-export");
assert.equal(r.code, 0, r.stderr);
let map = read(root, `${pf}/map.md`);
assert.ok(map.includes(`${oldRow00}\n`), "an unchanged row keeps the author's words, old separator and all");
assert.ok(map.includes(`${oldRow04}\n`), "a [!] row that stays [!] is kept as written");
assert.match(map, /- \[x\] \[Export format\]\(\.\/questions\/01-export-format\.md\): CSV with a BOM\. \*\(2026-08-02\)\*\n/, "a row turning [x] is written with the new separator");
assert.match(map, /- \[ \] \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\)\n/, "a re-opened row drops its old em dash tail");
assert.deepEqual(P("frontier", "audit-export").json.drift, []);
assert.equal(P("reconcile", "audit-export").json.mapWritten, false, "stable on an old map");
fs.appendFileSync(path.join(root, pf, "questions/02-row-count-ceiling.md"), "\n## Answer\n\nFacts.\n\n**Gist:** 2M rows.\n");
assert.equal(P("resolve", "audit-export", "02").code, 0);
assert.equal(P("rule-out", "audit-export", "03", "--reason", "owned elsewhere").code, 0);
map = read(root, `${pf}/map.md`);
assert.match(map, /- \[ \] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\)\n/, "the old Blocked by tail goes with the [!] marker");
assert.match(map, /- \[-\] \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\): out of scope, see below\n/);
assert.match(map, /- \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\): owned elsewhere\n/);
const oldLines = new Set(OLD.split("\n"));
const written = map.split("\n").filter((l) => !oldLines.has(l));
assert.ok(written.length > 0);
assert.deepEqual(written.filter((l) => l.includes(EM)), [], "no line the script wrote carries an em dash");
const brief = P("brief-data", "audit-export", "--range", "full").json;
assert.deepEqual(brief.ruledOut, [`SIEM push ${EM} not ours.`, "Testing posture: owned elsewhere"], "old and new out-of-scope lines both read; the placeholder is skipped");
assert.ok(!brief.confidence.includes(EM), brief.confidence);
const trail = P("trail", "audit-export", "--form", "A", "--text").stdout;
assert.ok(!trail.includes(EM), trail);
const src = fs.readFileSync(path.join(SKILLS, "plan2code-0-pathfinder", "scripts", "pathfinder.mjs"), "utf8");
assert.ok(!src.includes(EM), "pathfinder.mjs holds no em dash; a reader of old maps spells it \\u2014");
});
test("pathfinder gate: the PLAN-DRAFT status line is byte-exact with the one specs.mjs reads", () => {
const { root } = mapFixture();
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
P("reconcile", "audit-export");
const line = P("gate", "audit-export").json.planDraftStatus;
const m = /^\*\*Status:\*\* (.+)$/.exec(line || "");
assert.ok(m, `gate prints the **Status:** line: ${line}`);
const status = m[1];
assert.match(status, /^[\x20-\x7e]+$/, "plain ASCII: an en dash or a smart character breaks the match");
const specs = fs.readFileSync(path.join(ROOT, "src", "skill-scripts", "specs.mjs"), "utf8");
const decl = /const DRAFT_STATUSES = \[([^\]]*)\]/.exec(specs);
assert.ok(decl, "specs.mjs still declares DRAFT_STATUSES");
const statuses = [...decl[1].matchAll(/"([^"\\]*)"/g)].map((x) => x[1]);
assert.ok(statuses.includes(status), `"${status}" is not in specs.mjs DRAFT_STATUSES: ${JSON.stringify(statuses)}`);
assert.ok(fs.readFileSync(path.join(ROOT, "src", "plan2code-1-plan.md"), "utf8").includes(`Status "${status}": Resume at Phase 4`), "Plan resumes from the same string");
assert.ok(fs.readFileSync(path.join(SKILLS, "plan2code-0-pathfinder", "references", "handoff.md"), "utf8").includes(line), "handoff.md quotes the same line");
});
test("pathfinder init and add: the map and every question type from the templates, lint-clean, with their refusals", () => {
const root = tmp("pfi");
const pf = "specs/audit-export/pathfinder";
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
const INIT = ["--destination", "A locked plan for exporting audit events as one file.", "--scores", "10,8,12,9", "--fog", "How far back an export may reach."];
assert.equal(P("init", "Audit_Export", ...INIT).json.error, "bad-idea-name");
assert.equal(P("add", "audit-export", "--name", "Export format", "--question", "Which format?").json.error, "reserved-00", "00 is the codebase context");
// Chart Step 3: the codebase context, written before there is a map.
const c = P("add", "audit-export", "--name", "Codebase context", "--type", "legwork-afk", "--question", "What does the codebase provide?");
assert.equal(c.code, 0, c.stderr);
assert.deepEqual([c.json.nn, c.json.file, c.json.mapRow, c.json.nextNN], ["00", `${pf}/questions/00-codebase-context.md`, null, "01"]);
assert.match(c.json.next, /init/);
assert.equal(read(root, `${pf}/questions/00-codebase-context.md`), [B, "", "# Codebase context", "", "Type: legwork · AFK", "State: open", "Blocked by: none", "Claimed: none", "Resolved: none", "Locked: no", "", "## Question", "", "What does the codebase provide?", "", "## Evidence", ""].join("\n"));
// Chart Step 5: init.
assert.equal(P("init", "audit-export", "--scores", "1,1,1,1", "--fog", "x").code, 2, "--destination is required");
assert.equal(P("init", "audit-export", "--destination", "d", "--scores", "10,8,30,9", "--fog", "x").json.error, "bad-scores");
assert.equal(P("init", "audit-export", "--destination", "d", "--scores", "10,8,12,9").json.error, "no-fog", "no fog is the off-ramp, not a map");
assert.equal(P("init", "audit-export", "--destination", "d", "--scores", "10,8,12,9", "--fog", "[ ] decide x").json.error, "checkbox", "init refuses a checkbox as add does");
assert.equal(P("init", "audit-export", "--destination", "d", "--scores", "10,8,12,9", "--fog", "x", "--rule", "TASK_COMPLETE").json.error, "loop-token", "init refuses a loop token as add does");
const dry = P("init", "audit-export", ...INIT, "--dry-run");
assert.deepEqual([dry.code, dry.json.mapWritten, fs.existsSync(path.join(root, pf, "map.md"))], [0, false, false], "--dry-run writes nothing");
const i = P("init", "audit-export", ...INIT, "--rule", "Dana reviews compliance text.", "--out", "Schema redesign: the write path is untouched.");
assert.equal(i.code, 0, i.stderr);
assert.deepEqual([i.json.status, i.json.agentsAbsent, i.json.indexed], ["Charting", true, [{ nn: "00", name: "Codebase context", marker: "[ ]" }]]);
let map = read(root, `${pf}/map.md`);
assert.ok(map.startsWith(`${B}\n\n# Map: audit-export\n`), map);
assert.match(map, /^\*\*Status:\*\* Charting\n\*\*Updated:\*\* 2026-08-03\n\*\*Confidence:\*\* Requirements-clarity 10\/25 · Feasibility-technical 8\/25 · Integration-points 12\/25 · Risk-assessment 9\/25\n/m);
assert.match(map, /## Destination\n\nA locked plan for exporting audit events as one file\.\n/);
assert.match(map, /<!-- Standing[\s\S]*?-->\n\n- \*\*Backend:\*\* local\n- `AGENTS\.md` is absent\.\n- One question _file_ at a time;[\s\S]*\n- Dana reviews compliance text\.\n\n## Glossary/, "Backend first, then AGENTS.md as found on disk, the standing rules, then --rule");
assert.match(map, /## Question Checklist\n\n<!--[\s\S]*?-->\n\n- \[ \] \[Codebase context\]\(\.\/questions\/00-codebase-context\.md\)\n\n## Not yet specified/, "a question written before the map is indexed");
assert.match(map, /-->\n\n- How far back an export may reach\.\n\n## Out of scope\n\n<!--[\s\S]*?-->\n\n- Schema redesign: the write path is untouched\.\n$/);
assert.ok(!map.includes(EM), "init writes no em dash");
assert.equal(P("init", "audit-export", ...INIT).json.error, "map-exists", "never overwrites a map");
// Chart Step 6: one question of each type, in dependency order.
const types = [["Export format", "grill", "grill · HITL"], ["Row-count ceiling", "research", "research · AFK"], ["Delivery sketch", "sketch", "sketch · HITL"], ["Ask legal", "legwork-hitl", "legwork · HITL"], ["Load figures", "legwork · AFK", "legwork · AFK"]];
const extra = { "Row-count ceiling": ["--evidence", "audit_events is partitioned monthly.", "--recommended", "Cap at 2M rows."], "Delivery sketch": ["--blocked-by", "2", "--locked"] };
types.forEach(([name, flag, type], n) => {
const a = P("add", "audit-export", "--name", name, "--type", flag, "--question", `What about ${name}?`, ...(extra[name] || []));
assert.equal(a.code, 0, a.stderr);
assert.deepEqual([a.json.nn, a.json.type, a.json.mapWritten, a.json.nextNN], [`0${n + 1}`, type, true, `0${n + 2}`], name);
});
assert.equal(read(root, `${pf}/questions/02-row-count-ceiling.md`).split("## Question\n")[1], "\nWhat about Row-count ceiling?\n\nRecommended answer to react to: Cap at 2M rows.\n\n## Evidence\n\n- audit_events is partitioned monthly.\n");
assert.match(read(root, `${pf}/questions/03-delivery-sketch.md`), /Type: sketch · HITL\nState: open\nBlocked by: 02\nClaimed: none\nResolved: none\nLocked: yes\n/);
map = read(root, `${pf}/map.md`);
assert.match(map, /- \[ \] \[Codebase context\]\(\.\/questions\/00-codebase-context\.md\)\n- \[ \] \[Export format\]\(\.\/questions\/01-export-format\.md\)\n- \[ \] \[Row-count ceiling\]\(\.\/questions\/02-row-count-ceiling\.md\)\n- \[!\] \[Delivery sketch\]\(\.\/questions\/03-delivery-sketch\.md\): Blocked by 02\n- \[ \] \[Ask legal\]\(\.\/questions\/04-ask-legal\.md\)\n- \[ \] \[Load figures\]\(\.\/questions\/05-load-figures\.md\)\n\n## Not yet specified/);
assert.match(map, /^\*\*Next NN:\*\* 06$/m);
// Refusals, and a dry run that writes nothing.
const refused = (args, code, error, why) => {
const x = P("add", "audit-export", ...args);
assert.deepEqual([x.code, x.json.error], [code, error], why);
};
refused(["--name", "export FORMAT", "--question", "Again?"], 5, "duplicate", "one file per decision");
refused(["--name", "Codebase context", "--slug", "codebase-context-two", "--question", "Again?"], 5, "duplicate", "the same name under another file name");
const bare = tmp("pfr");
write(bare, "specs/odd/pathfinder/questions/01-first.md", q("First"));
const late = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["add", "odd", "--name", "Codebase context", "--question", "What?", "--root", bare]);
assert.deepEqual([late.code, late.json.error], [5, "reserved-name"], "codebase-context is 00 only");
refused(["--name", "Odd", "--type", "legwork", "--question", "Which?"], 2, "bad-type", "legwork names its mode");
refused(["--name", "Odd", "--question", "Which?", "--blocked-by", "09"], 3, "no-blocker", "a blocker must exist");
refused(["--name", "Odd", "--question", "Which?\n- [ ] a checkbox"], 5, "checkbox", "plain bullets only");
refused(["--name", "Odd", "--question", "Done. TASK_COMPLETE"], 5, "loop-token", "loop tokens never land under specs/");
refused(["--name", "Odd"], 2, "missing-question", "--question is required");
refused(["--name", "Odd", "--slug", "Not Kebab", "--question", "Which?"], 2, "bad-slug", "the file name is kebab-case");
const mapBefore = read(root, `${pf}/map.md`);
const d = P("add", "audit-export", "--name", "Retention", "--question", "How long?", "--dry-run");
assert.deepEqual([d.code, d.json.nn, d.json.dryRun, d.json.mapWritten], [0, "06", true, false]);
assert.ok(!fs.existsSync(path.join(root, pf, "questions/06-retention.md")), "add --dry-run writes no file");
assert.equal(read(root, `${pf}/map.md`), mapBefore, "nor the map");
// Chart Step 7: the index already agrees with the files, and lint accepts all of it.
const r = P("reconcile", "audit-export");
assert.deepEqual([r.json.repairs, r.json.mapChanges, r.json.mapWritten], [[], [], false], JSON.stringify(r.json));
const l = P("lint", "audit-export");
assert.equal(l.code, 0, JSON.stringify(l.json.problems));
assert.deepEqual([l.json.errors, l.json.warnings], [0, 0], JSON.stringify(l.json.problems));
});
test("pathfinder --help lists init and add", () => {
const h = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["--help"]);
assert.equal(h.code, 0);
assert.match(h.stdout, /node pathfinder\.mjs init <map>/);
assert.match(h.stdout, /node pathfinder\.mjs add <map>/);
});
+154
View File
@@ -0,0 +1,154 @@
// Tests for scripts/set-version.mjs, the one writer of the version carriers.
// Run with: node --test scripts/test-set-version.mjs
//
// Every run works on a scratch copy of the carriers (plus CHANGELOG.md, which check-versions reads
// and the script leaves to a person), never on the real tree.
import test, { after } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { checkVersions } from "./check-versions.mjs";
import { CARRIER_FILES } from "./set-version.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(here, "..");
const SET = path.join(here, "set-version.mjs");
const made = [];
after(() => {
for (const d of made) fs.rmSync(d, { recursive: true, force: true });
});
function scratch() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "setver-"));
made.push(dir);
for (const file of [...CARRIER_FILES, "CHANGELOG.md"]) {
const to = path.join(dir, file);
fs.mkdirSync(path.dirname(to), { recursive: true });
fs.copyFileSync(path.join(ROOT, file), to);
}
return dir;
}
const read = (dir, file) => fs.readFileSync(path.join(dir, file), "utf8");
const run = (...args) => spawnSync(process.execPath, [SET, ...args], { encoding: "utf8" });
// A person writes the changelog heading; the script never does.
function writeHeading(dir, version) {
const file = path.join(dir, "CHANGELOG.md");
fs.writeFileSync(file, fs.readFileSync(file, "utf8").replace(/^##\s+v?\d+\.\d+\.\d+/m, `## v${version}`));
}
const changedLines = (a, b) => {
const x = a.split("\n");
const y = b.split("\n");
assert.equal(x.length, y.length, "the line count does not change");
return x.filter((line, i) => line !== y[i]).length;
};
test("it names all the carriers, and the tree's own versions agree before the test starts", () => {
assert.equal(CARRIER_FILES.length, 9);
assert.ok(checkVersions(ROOT).ok, checkVersions(ROOT).problems.join("\n"));
});
test("after it runs, check-versions passes on the scratch copy", () => {
const dir = scratch();
const before = Object.fromEntries(CARRIER_FILES.map((f) => [f, read(dir, f)]));
const r = run("9.8.7", "--date", "2030-01-02", "--root", dir);
assert.equal(r.status, 0, r.stderr);
writeHeading(dir, "9.8.7");
const check = checkVersions(dir);
assert.deepEqual(check.problems, []);
assert.ok(check.versions.every((v) => v.version === "9.8.7"));
assert.match(read(dir, "version.json"), /"releaseDate": "2030-01-02"/);
assert.match(read(dir, "README.md"), /^Version 9\.8\.7\b/m);
// Only the version lines changed: the carriers keep their formatting.
const expected = {
"version.json": 2, "package.json": 1, "README.md": 1, "plan2code-app/package.json": 1,
"plan2code-app/src-tauri/tauri.conf.json": 1, "plan2code-app/package-lock.json": 2,
"plan2code-app/src-tauri/Cargo.toml": 1, "plan2code-app/fake-agent/Cargo.toml": 1, "plan2code-app/Cargo.lock": 2,
};
for (const f of CARRIER_FILES) assert.equal(changedLines(before[f], read(dir, f)), expected[f], f);
});
test("a second run for another version replaces the first, and the date defaults to today", () => {
const dir = scratch();
assert.equal(run("1.2.3", "--root", dir).status, 0);
assert.equal(run("1.2.4", "--root", dir).status, 0);
writeHeading(dir, "1.2.4");
assert.deepEqual(checkVersions(dir).problems, []);
const { releaseDate } = JSON.parse(read(dir, "version.json"));
const d = new Date();
const today = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
assert.equal(releaseDate, today);
});
test("a Cargo.lock with CRLF line endings is still edited, and keeps them", () => {
const dir = scratch();
const lock = path.join(dir, "plan2code-app/Cargo.lock");
fs.writeFileSync(lock, fs.readFileSync(lock, "utf8").replace(/\n/g, "\r\n"));
assert.equal(run("4.5.6", "--root", dir).status, 0);
writeHeading(dir, "4.5.6");
assert.deepEqual(checkVersions(dir).problems, []);
assert.ok(read(dir, "plan2code-app/Cargo.lock").includes("\r\n"));
});
test("it never touches CHANGELOG.md", () => {
const dir = scratch();
const before = read(dir, "CHANGELOG.md");
assert.equal(run("7.7.7", "--root", dir).status, 0);
assert.equal(read(dir, "CHANGELOG.md"), before);
});
test("a missing carrier fails, names it, and writes nothing", () => {
const dir = scratch();
fs.rmSync(path.join(dir, "plan2code-app/fake-agent/Cargo.toml"));
const before = Object.fromEntries(CARRIER_FILES.filter((f) => !f.includes("fake-agent/")).map((f) => [f, read(dir, f)]));
const r = run("6.6.6", "--root", dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /fake-agent\/Cargo\.toml: file is missing/);
assert.match(r.stderr, /Nothing was written/);
for (const [f, text] of Object.entries(before)) assert.equal(read(dir, f), text, `${f} is unchanged`);
});
test("a carrier with no version in it fails and writes nothing", () => {
const dir = scratch();
fs.writeFileSync(path.join(dir, "README.md"), "# Plan2Code\n\nNo version line here.\n");
const r = run("6.6.6", "--root", dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /README\.md: no "Version X\.Y\.Z" line found/);
assert.match(read(dir, "version.json"), /"version": "[^"]+"/);
assert.ok(!read(dir, "version.json").includes("6.6.6"));
});
test("bad arguments exit 2 and write nothing", () => {
const dir = scratch();
for (const args of [[], ["3.0"], ["v3.0.1"], ["3.0.1-beta"], ["3.0.1", "extra"], ["3.0.1", "--date", "yesterday"], ["3.0.1", "--root"]]) {
const r = run(...args, ...(args.includes("--root") ? [] : ["--root", dir]));
assert.equal(r.status, 2, `${args.join(" ")}: ${r.stderr}`);
assert.match(r.stderr, /Usage: node scripts\/set-version\.mjs/);
}
assert.ok(!read(dir, "version.json").includes("3.0.1"));
});
test("an impossible date is refused", () => {
const dir = scratch();
const r = run("3.0.1", "--date", "2030-99-99", "--root", dir);
assert.equal(r.status, 2);
assert.equal(run("3.0.1", "--date", "2030-02-30", "--root", dir).status, 2);
assert.equal(run("3.0.1", "--date", "2028-02-29", "--root", dir).status, 0);
});
test("a write that fails part way puts back the files already written", () => {
const dir = scratch();
const last = path.join(dir, "plan2code-app/Cargo.lock");
fs.chmodSync(last, 0o444);
const before = Object.fromEntries(CARRIER_FILES.map((f) => [f, read(dir, f)]));
const r = run("5.5.5", "--root", dir);
fs.chmodSync(last, 0o644);
if (r.status === 0) return; // running as a user who can write a read-only file: nothing to test
assert.equal(r.status, 1);
assert.match(r.stderr, /restored the files already written/);
for (const f of CARRIER_FILES) assert.equal(read(dir, f), before[f], `${f} is back as it was`);
});
+125 -7
View File
@@ -9,17 +9,21 @@ import path from "node:path";
import { spawnSync } from "node:child_process";
import { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
// skills/ also holds _console, the shared console build: not a skill.
const skillNames = () => fs.readdirSync(SKILLS).filter((name) => !name.startsWith("_"));
/* ================================================================ install */
test("npm test runs every scripts/test-*.mjs file, and names none that is missing", () => {
const command = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).scripts.test;
const listed = [...command.matchAll(/scripts\/(test-[\w-]+\.mjs)/g)].map((m) => m[1]).sort();
const onDisk = fs.readdirSync(path.join(ROOT, "scripts")).filter((f) => /^test-[\w-]+\.mjs$/.test(f)).sort();
// test-fast.mjs runs the fast lane (npm run test:fast); it is a runner, not a test file.
const onDisk = fs.readdirSync(path.join(ROOT, "scripts")).filter((f) => /^test-[\w-]+\.mjs$/.test(f) && f !== "test-fast.mjs").sort();
assert.deepEqual(listed, onDisk);
});
test("every skill with scripts ships common.mjs and version.json; dashboard ships none", () => {
const withScripts = fs.readdirSync(SKILLS).filter((s) => fs.existsSync(path.join(SKILLS, s, "scripts")));
const withScripts = skillNames().filter((s) => fs.existsSync(path.join(SKILLS, s, "scripts")));
assert.ok(withScripts.length >= 11, `expected most skills to carry scripts, got ${withScripts.join(", ")}`);
for (const s of withScripts) {
for (const f of ["common.mjs", "version.json"]) assert.ok(fs.existsSync(path.join(SKILLS, s, "scripts", f)), `${s}/scripts/${f}`);
@@ -41,7 +45,7 @@ test("the Handoff skill writes through the console's handoff new, with no folder
});
test("every script a SKILL.md (or a reference it ships) runs exists beside it, and answers --help", () => {
for (const skill of fs.readdirSync(SKILLS)) {
for (const skill of skillNames()) {
const dir = path.join(SKILLS, skill);
const texts = [];
const walk = (d) => {
@@ -78,7 +82,7 @@ test("scripts are self-contained: built-ins and siblings only", () => {
}
// A sibling import ships with its importer: every skill that carries a
// script also carries each ./x.mjs it imports.
for (const skill of fs.readdirSync(SKILLS)) {
for (const skill of skillNames()) {
const dir = path.join(SKILLS, skill, "scripts");
if (!fs.existsSync(dir)) continue;
for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".mjs"))) {
@@ -159,6 +163,58 @@ test("specs list: a diagnosis Quick Task marked Fixed is a fixed bug", () => {
assert.equal(bug.detail, "bug fixed");
});
// The seven cases where the dashboard scan and specs.mjs once disagreed
// (recorded in the hardening spec's Phase 5 notes; the same cases are in
// test-web-console-spec-states.mjs). Each is a spec folder and the
// [state, detail, finalizeReady] both must now report.
const DESYNC_CHECKLIST = (...marks) => `# Overview\n\n## Phase Checklist\n\n${marks.map((m, i) => `- [${m}] [Phase ${i + 1}: Step ${i + 1}](./phase-${i + 1}.md)`).join("\n")}\n`;
const DESYNC_PHASE = (n, lines) => `# Phase ${n}: Step ${n}\n\n**Status:** In Progress\n\n## Tasks\n\n${lines.join("\n")}\n\n## Acceptance Criteria\n\n- It works\n`;
const DESYNC_CASES = {
"blocked-reasoned": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two", " > BLOCKED: needs admin access. User action: create the app."]) },
want: ["building", "1 of 2 tasks done, 1 blocked", true],
},
"unknown-marker": {
files: { "overview.md": DESYNC_CHECKLIST("/"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [~] **Task 1.2:** Two"]) },
want: ["building", "1 of 2 tasks done", false],
},
"row-without-file": {
files: { "overview.md": DESYNC_CHECKLIST("x", " "), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [x] **Task 1.2:** Two"]) },
want: ["building", "2 of 2 tasks done, Phase 2 not written up", false],
},
"phase-without-tasks": {
files: { "overview.md": DESYNC_CHECKLIST("x", " "), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-2.md": DESYNC_PHASE(2, ["To be written."]) },
want: ["building", "1 of 1 tasks done, Phase 2 not written up", false],
},
"stale-duplicate": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-1-old.md": DESYNC_PHASE(1, ["- [ ] **Task 1.1:** One", "- [ ] **Task 1.2:** Two"]) },
want: ["built", "all tasks done", false],
},
"not-a-phase-file": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-notes.md": "# Notes\n\n- [ ] Ask about colors\n" },
want: ["built", "all tasks done", false],
},
"blocked-bare": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two"]) },
want: ["building", "1 of 2 tasks done, 1 blocked", false],
},
};
test("specs: list and status agree with the dashboard scan on the seven desync cases", () => {
const root = tmp("desync");
for (const [name, c] of Object.entries(DESYNC_CASES)) for (const [file, text] of Object.entries(c.files)) write(root, `specs/${name}/${file}`, text);
const S = (...a) => runScript("plan2code-3-implement", "specs.mjs", [...a, "--root", root]);
const list = S("list");
assert.equal(list.code, 0, list.stderr);
for (const [name, c] of Object.entries(DESYNC_CASES)) {
const row = list.json.specs.find((s) => s.name === name);
const st = S("status", name);
assert.equal(st.code, 0, st.stderr);
assert.deepEqual([row.state, row.detail, Boolean(row.finalizeReady)], c.want, `${name}: specs.mjs list (the dashboard scan)`);
assert.deepEqual([st.json.state, st.json.stateDetail, st.json.finalizeReady], c.want, `${name}: specs.mjs status`);
}
});
test("specs status: checklist formats, groups, task markers, numbering, totals, checks", () => {
const root = specFixture();
const r = runScript("plan2code-3-implement", "specs.mjs", ["status", "specs/lunch-vote/overview.md", "--root", root]);
@@ -310,6 +366,7 @@ test("specs mark: transitions, the no-reset rule, dry-run and idempotence", () =
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[ \] \*\*Phase 3/, "dry-run writes nothing");
assert.equal(S("mark", "lunch-vote", "--phase", "3", "--to", "in-progress").code, 0);
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[\/\] \*\*Phase 3 — Web UI\*\* — see/, "only the marker changes");
assert.match(read(root, "specs/lunch-vote/phase-3.md"), /^\*\*Status:\*\* In Progress$/m, "in-progress writes the phase file's Status line too");
assert.equal(S("mark", "lunch-vote", "--phase", "3", "--to", "in-progress").json.changed, false);
const reset = S("mark", "lunch-vote", "--phase", "3", "--to", "open");
assert.equal(reset.code, 5);
@@ -366,11 +423,11 @@ test("commit-msg: the two -m flags on any branch, subject rules", () => {
g("add", "-A");
g("commit", "-q", "-m", "init");
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
const ok = C("--subject", "Add the export endpoint", "--add-all");
const ok = C("--subject", "Add the export endpoint", "--files", "src/export.js");
assert.equal(ok.code, 0, ok.stderr);
assert.equal(ok.json.ticket, undefined);
assert.equal(ok.json.branch, undefined);
assert.equal(ok.json.command, 'git add -A && git commit -m "Add the export endpoint" -m "AI Assisted"');
assert.equal(ok.json.command, 'git add -- src/export.js && git commit -m "Add the export endpoint" -m "AI Assisted"');
assert.equal(ok.json.message, "Add the export endpoint\n\nAI Assisted");
assert.equal(C("--subject", "x".repeat(101)).code, 4);
assert.equal(C("--subject", 'say "hi"').code, 4);
@@ -438,6 +495,22 @@ test("agent-files: detect, apply only what was chosen, rules folders, idempotent
/* ============================================================== agents-md.mjs */
test("agents-md: Init's first run warns once that a gitignored specs--completed/ is not backed up", () => {
const root = tmp("notices");
const I = () => runScript("plan2code-init", "agents-md.mjs", ["inspect", "--root", root]).json;
assert.deepEqual(I().notices, [], "no .gitignore, nothing to say");
for (const line of ["specs--completed/", "/specs--completed", "specs*"]) {
write(root, ".gitignore", `node_modules\nspecs/\n${line}\n`);
assert.deepEqual(I().notices.map((n) => n.code), ["specs-not-backed-up"], line);
}
assert.match(I().notices[0].message, /not backed up/);
write(root, ".gitignore", "node_modules\nspecs/\n");
assert.deepEqual(I().notices, [], "only specs/ ignored: archives are committed");
write(root, ".gitignore", "specs--completed/\n");
write(root, "AGENTS.md", "# AGENTS.md\n\n## Project Overview\n\nA thing.\n");
assert.equal(I().notices, undefined, "once AGENTS.md exists (Init Update), it is not said again");
});
test("agents-md: structure, budget, orphans, broken links, inline rules", () => {
const root = tmp("agentsmd");
write(root, "AGENTS.md", [
@@ -581,6 +654,35 @@ test("specs check: a well-formed spec passes", () => {
assert.deepEqual(r.json.problems, []);
});
test("specs check: the format rules warn on an unmarked spec and fail one carrying the format marker", () => {
const root = cleanSpec(specFixture());
write(
root,
"specs/clean/phase-1.md",
phase(1, "x", [["x", "1.1"], ["!", "1.2"], ["!", "1.3"], [" ", "1.4"], [" ", "1.5"]])
.replace("**Status:** x\n", "")
.replace("**Task 1.3:** Do 1.3", "**Task 1.3:** Do 1.3\n > BLOCKED: needs admin. User action: grant it.")
.replace("**Task 1.4:** Do 1.4", "**Task 1.4:** Change `src/app.js:42` to retry")
.replace("**Task 1.5:** Do 1.5", "**Task 1.5:** Change `src/app.js:~42` (approximate) to retry")
.replace("## Acceptance Criteria", "## Notes\n\n- [ ] Ask about colors\n\n## Acceptance Criteria")
);
const C = () => runScript("plan2code-2-document", "specs.mjs", ["check", "clean", "--root", root]);
const codes = (r) => r.json.problems.filter((p) => p.file === "specs/clean/phase-1.md").map((p) => [p.level, p.code]);
const old = C();
assert.equal(old.code, 0, old.stdout);
assert.equal(old.json.format, null);
assert.deepEqual(codes(old), [["warn", "no-status"], ["warn", "notes-checkbox"], ["warn", "bare-blocked"], ["warn", "line-reference"]], "an unmarked spec only warns; the reasoned blocker and the ~ reference pass");
write(root, "specs/clean/overview.md", read(root, "specs/clean/overview.md") + "\n<!-- plan2code-format: 2 -->\n");
const marked = C();
assert.equal(marked.code, 4, marked.stdout);
assert.equal(marked.json.format, 2);
assert.deepEqual(codes(marked), [["error", "no-status"], ["error", "notes-checkbox"], ["error", "bare-blocked"], ["error", "line-reference"]]);
assert.match(marked.json.problems.find((p) => p.code === "bare-blocked").message, /Task 1\.2/);
assert.match(marked.json.problems.find((p) => p.code === "line-reference").message, /Task 1\.4/);
// The clean phase file passes the same rules under the marker.
assert.ok(!marked.json.problems.some((p) => p.file === "specs/clean/phase-2.md"));
});
test("specs check: a bad task line, a checklist row with no phase file, a loop token and a bare metric word each fail", () => {
const root = cleanSpec(specFixture());
write(root, "specs/clean/overview.md", read(root, "specs/clean/overview.md") + "- [ ] [Phase 3: Docs](./phase-3.md)\n");
@@ -869,6 +971,23 @@ test("specs mark: a plain or bold Status: line is updated; a missing one is repo
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[x\] \[Phase 2: API\]/);
});
test("specs archive: a copy that does not match the source by name and size keeps the source", () => {
const root = specFixture();
const S = (env, ...a) => runScript("plan2code-4-finalize", "specs.mjs", [...a, "--root", root], { env });
const bad = S({ PLAN2CODE_ARCHIVE_FAULT: "truncate" }, "archive", "lunch-vote");
assert.equal(bad.code, 4, bad.stdout);
assert.equal(bad.json.error, "copy-unverified");
assert.match(bad.json.message, /PLAN-DRAFT-20260801\.md is \d+ bytes, not \d+/, "the short file is named with both sizes");
assert.ok(fs.existsSync(path.join(root, "specs/lunch-vote/phase-4.md")), "the source stays when the copy is short");
assert.match(bad.json.next, /Delete the partial specs--completed\/lunch-vote\//);
// The same move through the copy path, intact, removes the source.
fs.rmSync(path.join(root, "specs--completed/lunch-vote"), { recursive: true });
const good = S({ PLAN2CODE_ARCHIVE_FAULT: "copy" }, "archive", "lunch-vote");
assert.equal(good.code, 0, good.stdout);
assert.equal(good.json.sourceRemoved, true);
assert.ok(!fs.existsSync(path.join(root, "specs/lunch-vote")));
});
test("specs: only a folder directly under specs/ is a spec; archive verification fails loudly", () => {
const root = specFixture();
write(root, "src/app.js", "x\n");
@@ -901,7 +1020,6 @@ test("commit-msg: @ and - paths are quoted, git add ends its options, risky subj
assert.equal(files.json.add, "git add -- '@types/x.d.ts' '-weird.md' src/a@b.js");
assert.equal(files.json.commit, 'git commit -m "Fix" -m "AI Assisted"');
assert.equal(files.json.command, `${files.json.add} && ${files.json.commit}`);
assert.equal(C("--subject", "Fix", "--add-all").json.add, "git add -A");
const bare = C("--subject", "Fix").json;
assert.equal(bare.add, null);
assert.equal(bare.command, bare.commit);
+43 -6
View File
@@ -9,10 +9,10 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync, spawn } from "node:child_process";
import { execFileSync, spawn, spawnSync } from "node:child_process";
import http from "node:http";
import { meterView } from "../src/web-console/public/meter.js";
import { STATE_LOCK_FILE } from "../src/web-console/files.mjs";
import { STATE_LOCK_FILE, lockStale } from "../src/web-console/files.mjs";
import { cwdHash, readLedger, repoRoots } from "../src/web-console/sessions.mjs";
import { validate } from "../src/web-console/patches.mjs";
import { WORKSPACE_FILE } from "../src/web-console/workspace.mjs";
@@ -241,6 +241,34 @@ test("a lock left by a writer that died is broken rather than waited on for good
}
});
// Age alone used to break a lock: a writer slowed past LOCK_STALE_MS by a busy
// machine lost its lock to the next writer, and both wrote. The holder's pid
// decides now; age only breaks a lock that names no live holder.
test("a lock whose holder is still running is kept past the stale age; age breaks only an unnamed one", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-lock-"));
const lock = path.join(dir, STATE_LOCK_FILE);
const holder = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore", windowsHide: true });
try {
await new Promise((r) => holder.once("spawn", r));
const old = new Date(Date.now() - 60000);
fs.writeFileSync(lock, String(holder.pid));
fs.utimesSync(lock, old, old);
assert.equal(lockStale(lock), false, "a live holder keeps its lock, however old");
holder.kill();
await new Promise((r) => (holder.exitCode !== null || holder.signalCode ? r() : holder.once("exit", r)));
assert.equal(lockStale(lock), true, "a gone holder frees it");
fs.writeFileSync(lock, "");
assert.equal(lockStale(lock), false, "an unnamed young lock is a holder mid-create");
fs.utimesSync(lock, old, old);
assert.equal(lockStale(lock), true, "an unnamed old lock is a crash left behind");
} finally {
holder.kill();
fs.rmSync(dir, { recursive: true, force: true });
}
});
// A young handle and a live pid are what a server that died a minute ago
// leaves behind for any process to inherit. Only /health is proof.
test("stop never kills a live process that does not answer /health as ours", () => {
@@ -345,7 +373,7 @@ test("wait reads --seconds 6s as six seconds, not as nothing", () => {
}
});
test("only open leaves the console-dir pointer; status, help and a bad command do not", () => {
test("only an installed console's open leaves the console-dir pointer; status, help, a bad command and a source checkout's open do not", () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pointer-"));
const env = { PLAN2CODE_CONSOLE_HOME: home, PLAN2CODE_MODELS_DIR: path.join(home, "plan2code") };
const pointer = path.join(home, "console-dir");
@@ -356,9 +384,18 @@ test("only open leaves the console-dir pointer; status, help and a bad command d
const usage = cli(["nope"], { env, expectFail: true });
assert.match(usage.stderr, /keep/, "the usage line names every command");
assert.equal(fs.existsSync(pointer), false);
const opened = cli(["open", "--no-open"], { env });
assert.equal(fs.readFileSync(pointer, "utf8").trim(), path.join(ROOT, "src", "web-console"));
cli(["stop", "--session", opened.json.sid, "--force"], { env });
// A source checkout never points every skill stub at itself.
const fromSource = cli(["open", "--no-open"], { env });
assert.equal(fs.existsSync(pointer), false, "a source checkout leaves no pointer");
cli(["stop", "--session", fromSource.json.sid, "--force"], { env });
// An installed console (a version folder) does.
const installed = path.join(home, "9.9.9");
fs.cpSync(path.join(ROOT, "src", "web-console"), installed, { recursive: true });
const res = spawnSync(process.execPath, [path.join(installed, "console.mjs"), "open", "--no-open"], { env: { ...ENV, ...env }, encoding: "utf8", cwd: ROOT });
assert.equal(res.status, 0, res.stderr);
assert.equal(fs.readFileSync(pointer, "utf8").trim(), installed);
const sid = JSON.parse(res.stdout.trim().split(/\r?\n/)[0]).sid;
spawnSync(process.execPath, [path.join(installed, "console.mjs"), "stop", "--session", sid, "--force"], { env: { ...ENV, ...env }, encoding: "utf8", cwd: ROOT });
} finally {
fs.rmSync(home, { recursive: true, force: true });
}
+130 -3
View File
@@ -7,6 +7,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { pathToFileURL } from "node:url";
import { parseArgs } from "../src/web-console/files.mjs";
import { BASE, cli, consoleSession, cookieFor, ENV, HOME, payload, ROOT } from "./web-console-test-helpers.mjs";
@@ -102,7 +103,7 @@ test("a token that starts with -- survives the trip to the server", async () =>
windowsHide: true,
});
assert.equal(res.status, 2, `refused: ${JSON.stringify(tokenArgs)}`);
assert.match(res.stderr, /--token=<token> is required/);
assert.match(res.stderr, /a token is required/);
}
const child = spawn(process.execPath, [SERVER_JS, `--session=${dir}`, "--token=--dashy", `--project=${dir}`], {
@@ -120,8 +121,8 @@ test("a token that starts with -- survives the trip to the server", async () =>
});
child.on("exit", () => reject(new Error("server exited before it was ready")));
});
assert.ok(ready.url.endsWith("/s/--dashy/"));
const res = await fetch(ready.url, { redirect: "manual" });
assert.equal(ready.url, `http://127.0.0.1:${ready.port}/`, "the ready line carries no token");
const res = await fetch(`${ready.url}s/--dashy/`, { redirect: "manual" });
assert.equal(res.status, 302);
assert.ok(res.headers.get("set-cookie").startsWith(`p2c_console_${ready.port}=--dashy;`));
} finally {
@@ -129,6 +130,56 @@ test("a token that starts with -- survives the trip to the server", async () =>
}
});
// The command line of a process is readable by anyone on the machine (ps,
// Task Manager), and server.log is the server's stdout. Neither may carry the
// session token: `open` hands it over in a one-shot file the server deletes.
function commandLineOf(pid) {
const res =
process.platform === "win32"
? spawnSync("powershell", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`], {
encoding: "utf8",
windowsHide: true,
})
: spawnSync("ps", ["-o", "args=", "-p", String(pid)], { encoding: "utf8" });
return String(res.stdout || "");
}
test("the session token is in neither the server's arguments nor server.log", async () => {
const s = consoleSession(["--file", payload("token-off-argv.json", BASE)]);
try {
const token = s.opened.url.match(/\/s\/([^/]+)\//)[1];
let handle = null;
const runtime = path.join(HOME, "runtime");
for (const bucket of fs.readdirSync(runtime)) {
const file = path.join(runtime, bucket, s.sid + ".json");
if (fs.existsSync(file)) handle = JSON.parse(fs.readFileSync(file, "utf8"));
}
assert.ok(handle?.pid, "the server wrote its handle");
assert.equal(handle.token, token, "the server took the token open made");
const args = commandLineOf(handle.pid);
assert.match(args, /server\.mjs/, "read the server's own command line");
assert.match(args, /--token-file=server-token-/);
assert.ok(!args.includes(token), "the token is not on the command line");
const log = fs.readFileSync(path.join(s.session, "server.log"), "utf8");
assert.match(log, /"ready"/, "the server logged its ready line");
assert.ok(!log.includes(token), "the token is not in server.log");
assert.deepEqual(
fs.readdirSync(s.session).filter((f) => f.startsWith("server-token-")),
[],
"the one-shot token file is gone once read"
);
// The page still signs in with it.
const res = await fetch(s.base + "/state", { headers: { cookie: cookieFor(s.base, token), connection: "close" } });
assert.equal(res.status, 200);
await res.arrayBuffer();
} finally {
cli(["stop", "--session", s.sid, "--force"]);
}
});
test("a cancel that could not be written answers 500 and tells nobody", async () => {
const s = consoleSession(["--file", payload("cancel-500.json", BASE)]);
try {
@@ -226,3 +277,79 @@ test("an image block outside the session's shots folder, or not an image, is ref
cli(["stop", "--session", s.sid, "--force"]);
}
});
// A route callback that threw used to run twice (readBody's catch fed the
// throw back in as a parse error) or leave the request hanging (readRaw). It
// now answers once with 400, runs once, and the throw still reaches the
// process's uncaughtException handler, which the real server logs. Run in a
// child so that rethrow lands on a handler like the server's, not the runner's.
test("a route callback that throws answers once with 400 and runs once", () => {
const routes = path.join(ROOT, "src", "web-console", "routes.mjs");
const script = `
import http from "node:http";
import { readBody, readRaw } from ${JSON.stringify(pathToFileURL(routes).href)};
const caught = [];
process.on("uncaughtException", (e) => caught.push(e.message));
const calls = { body: 0, raw: 0 };
const server = http.createServer((req, res) => {
if (req.url === "/body") return readBody(req, res, () => { calls.body++; throw new Error("body boom"); });
if (req.url === "/half") return readBody(req, res, () => { calls.body++; res.writeHead(200); res.write("x"); throw new Error("half boom"); });
return readRaw(req, res, 1024, () => { calls.raw++; throw new Error("raw boom"); });
});
server.listen(0, "127.0.0.1", async () => {
const base = "http://127.0.0.1:" + server.address().port;
const out = {};
for (const p of ["/body", "/raw", "/half"]) {
const r = await fetch(base + p, { method: "POST", body: p === "/raw" ? "bytes" : "{}" });
out[p] = { status: r.status, text: await r.text() };
}
await new Promise((r) => setTimeout(r, 50));
process.stdout.write(JSON.stringify({ out, calls, caught }));
server.close();
});
`;
const res = spawnSync(process.execPath, ["--input-type=module", "-e", script], { encoding: "utf8", timeout: 15000, windowsHide: true });
assert.equal(res.status, 0, res.stderr);
const { out, calls, caught } = JSON.parse(res.stdout);
assert.equal(out["/body"].status, 400);
assert.match(out["/body"].text, /bad request/);
assert.equal(out["/raw"].status, 400);
assert.deepEqual([out["/half"].status, out["/half"].text], [200, "x"], "a started answer is ended, not answered twice");
assert.deepEqual(calls, { body: 2, raw: 1 }, "each callback ran once");
assert.deepEqual(caught.sort(), ["body boom", "half boom", "raw boom"], "every throw still reaches the process handler");
});
// ── The metrics scrape pattern: one shared source, no drift ──────────────────
test("the bait scanner, the skill scripts and the collector read one metrics pattern", async () => {
const { SCRAPE } = await import("../src/skill-scripts/common.mjs");
const shared = JSON.parse(fs.readFileSync(path.join(ROOT, "src", "web-console", "metrics-pattern.json"), "utf8"));
const collectorCopy = fs.readFileSync(path.join(ROOT, "plan2code-metrics", "src", "metrics-pattern.json"), "utf8");
assert.equal(
collectorCopy,
fs.readFileSync(path.join(ROOT, "src", "web-console", "metrics-pattern.json"), "utf8"),
"plan2code-metrics/src/metrics-pattern.json must be a byte-for-byte copy of src/web-console/metrics-pattern.json",
);
const bySource = (re) => `${re.source}/${re.flags}`;
const scripts = new Map(SCRAPE.map((s) => [s.name, bySource(s.re)]));
for (const c of shared.confidence) assert.equal(scripts.get(c.name), `${c.source}/${c.flags}`, `skill scripts' "${c.name}" drifted from the shared pattern`);
for (const b of shared.breakdown) assert.equal(scripts.get(`bare ${b.name} + number`), `${b.source}/${b.flags}`, `skill scripts' ${b.name} pattern drifted from the shared pattern`);
assert.equal(SCRAPE.length, shared.confidence.length + shared.breakdown.length);
});
test("an ordinary table row that pairs Risk with a number is accepted, the real scrape shapes are refused", async () => {
const { proseProblems } = await import("../src/web-console/patches.mjs");
for (const ok of [
"| Risk | 3 | High |",
"| Requirements | 7 | Medium | Owner |",
"| R2 | Slow build | A risk to the plan | High |",
"Risk-assessment 22/25",
]) {
assert.deepEqual(proseProblems(ok), [], ok);
}
for (const bad of ["Risk: 3", "Risk 3", "Requirements 22 of 25", "| Requirements | 24 |", "| Integration | 23/25 |", "- Feasibility: 23"]) {
const found = proseProblems(bad);
assert.equal(found.length, 1, bad);
assert.match(found[0], /metrics collector scrapes that pattern/);
}
});
+42
View File
@@ -9,6 +9,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import http from "node:http";
import { spawn } from "node:child_process";
// The page's pure answer-shaping logic. app.js itself cannot be imported here
// (it touches `document` at module scope and starts a session on import), which
// is exactly why this lives in its own file.
@@ -24,8 +25,10 @@ import {
} from "../src/web-console/public/answers.js";
import { WORKFLOWS } from "../src/web-console/public/skills.js";
import {
ENV,
HOME,
MODELS_DIR,
ROOT,
cookieFor,
cli,
payload,
@@ -1251,3 +1254,42 @@ test("a finish posted while stopWarning is set is refused naming stopWarning, an
cli(["stop", "--session", opened.json.sid, "--force"]);
}
});
// The four-hour cap used to exit with answers nobody had collected, stranding
// the person's send. A pending result now holds the server past the cap; once
// a wait collects it (consumedAt), the cap applies again. A control server
// with a collected result shows when a 20s tick has passed.
test("a pending result holds the server past its lifetime cap; once collected it exits", async () => {
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
const start = (label, consumed) => {
const dir = fs.mkdtempSync(path.join(HOME, `max-life-${label}-`));
fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting" }));
const result = { actions: [{ i: "q1", type: "answer", kind: "choice", k: "A" }], reply: "Export format: a", ...(consumed ? { consumedAt: new Date().toISOString() } : {}) };
fs.writeFileSync(path.join(dir, "result.json"), JSON.stringify(result));
const child = spawn(process.execPath, [SERVER_JS, `--session=${dir}`, "--token=t", `--project=${dir}`, "--max-life-ms=300"], {
env: ENV,
stdio: "ignore",
windowsHide: true,
});
const exited = new Promise((r) => child.once("exit", r));
return { dir, child, exited, gone: false };
};
const held = start("held", false);
const control = start("control", true);
held.exited.then(() => (held.gone = true));
try {
// The control exits on the first tick past its cap...
await Promise.race([control.exited, new Promise((_, no) => setTimeout(() => no(new Error("the control server never hit its cap")), 45000))]);
assert.match(fs.readFileSync(path.join(control.dir, "events.ndjson"), "utf8"), /"reason":"max-life"/);
// ...and that same tick left the held server running.
assert.equal(held.gone, false, "a pending result keeps the server past its cap");
const file = path.join(held.dir, "result.json");
fs.writeFileSync(file, JSON.stringify({ ...JSON.parse(fs.readFileSync(file, "utf8")), consumedAt: new Date().toISOString() }));
await Promise.race([held.exited, new Promise((_, no) => setTimeout(() => no(new Error("the collected server never exited")), 45000))]);
assert.match(fs.readFileSync(path.join(held.dir, "events.ndjson"), "utf8"), /"reason":"max-life"/);
} finally {
held.child.kill();
control.child.kill();
}
});
+46
View File
@@ -83,6 +83,52 @@ test("a Quick question typed in Ask reaches the agent under chat, and the agent'
assert.match(await textOf(s.page.locator(".ask-counter")), /1/);
});
// What a person hears break: every redraw rewrote the Ask log and the footer
// summary, both live regions, so a screen reader read the whole conversation
// and the summary again on each agent post or tick, not only what was new.
test("a redraw leaves the Ask log and the footer summary untouched, and a new message only appends its row", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openAsk(s);
await askQuestion(s, "Where does the export live?");
const [asked] = messages(collect(s));
s.post({ chat: { replies: [{ id: "r1", re: asked.seq, conversation: 1, md: "It lives in `exports/`." }] } });
await s.page.locator(".ask-row.agent").getByText("It lives in").waitFor();
await settled(s.page, ".ask-list");
// Count every change inside both live regions from here on, and tag the rows on the page.
await s.page.evaluate(() => {
window.__live = { list: 0, footer: 0 };
const list = document.querySelector(".ask-list");
for (const row of list.children) row.__kept = true;
new MutationObserver((records) => (window.__live.list += records.length)).observe(list, {
subtree: true,
childList: true,
attributes: true,
characterData: true,
});
new MutationObserver((records) => (window.__live.footer += records.length)).observe(document.getElementById("footer-summary"), {
subtree: true,
childList: true,
attributes: true,
characterData: true,
});
});
// An agent post that changes nothing in the log or the summary redraws the page all the same:
// the new document gets its tab, and the Ask tab stays open on the same list.
s.post({ docs: [{ id: "notes", title: "Export notes", blocks: [{ id: "b1", state: "settled", md: "Nothing yet." }] }] });
await s.page.locator("nav").getByRole("button", { name: "Export notes" }).waitFor();
await settled(s.page, "#main");
assert.equal(await s.page.evaluate(() => [...document.querySelector(".ask-list").children].every((row) => row.__kept)), true, "the Ask tab shows the same rows");
assert.deepEqual(await s.page.evaluate(() => window.__live), { list: 0, footer: 0 }, "the redraw rewrote a live region");
// A second question appends one row; the two already there stay the same nodes.
await askQuestion(s, "And the importer?");
await s.page.locator(".ask-row.person").getByText("And the importer?").waitFor();
const rows = await s.page.evaluate(() => [...document.querySelector(".ask-list").children].map((row) => Boolean(row.__kept)));
assert.deepEqual(rows, [true, true, false], "only the new message's row is new");
});
// What a person sees break: a prompt the agent wrote for a new conversation with no
// Copy button, or one that tells them to "paste it into the Ask tab" as though it
// were a terminal command.
+50
View File
@@ -408,6 +408,36 @@ test("on a sign-off card, approve and yes are outlined in the accent until picke
assert.notEqual(await outlineOf(card.getByRole("button", { name: "Not yet" })), accent);
});
// What a person hears break: a screen reader names the verdicts on a sign-off
// card but never says which one is picked.
test("a sign-off card's verdicts expose aria-pressed, kept in step with each click", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "implement" });
const card = await ask(s, {
id: "so1",
kind: "review",
title: "Sign off",
body: "Read it.",
verdicts: [{ id: "approve", label: "Approve this phase" }, { id: "changes", label: "I want changes" }],
});
const approve = card.getByRole("button", { name: "Approve this phase" });
const changes = card.getByRole("button", { name: "I want changes" });
const pressed = async () => [await approve.getAttribute("aria-pressed"), await changes.getAttribute("aria-pressed")];
assert.deepEqual(await pressed(), ["false", "false"], "nothing picked yet");
await approve.click();
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
assert.deepEqual(await pressed(), ["true", "false"], "approve picked");
assert.equal(await card.getByRole("button", { name: "Approve this phase", pressed: true }).count(), 1);
await changes.click();
await s.page.waitForFunction(() => document.querySelector('[data-item="so1"] button[aria-pressed="true"]')?.textContent.includes("I want changes"));
assert.deepEqual(await pressed(), ["false", "true"], "the pick moved to changes");
await changes.click();
await s.page.waitForFunction(() => !document.querySelector('[data-item="so1"] button[aria-pressed="true"]'));
assert.deepEqual(await pressed(), ["false", "false"], "a second click takes the pick back");
});
// What a person sees break: Skip this one turns into a full-size button, or
// the quick answer under a note box does.
test("Skip this one and a comment box's quick answer are the same small accent button", async (t) => {
@@ -666,6 +696,26 @@ test("Clear on a one-answer question takes back the pick and the words, and a se
assert.equal(await clear.count(), 0, "a sent card cannot be cleared");
});
// What a person sees break: on a question taller than the window, Clear sat at
// the card's foot, out of sight until the options were scrolled past.
test("Clear on a tall question reads \"Clear answer\" and stays on screen while the options scroll", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
await s.page.setViewportSize({ width: 1280, height: 520 });
const options = Array.from({ length: 14 }, (_, i) => opt(String.fromCharCode(65 + i), `Choice ${i + 1}`));
const card = await ask(s, { id: "c1", kind: "choice", title: "Which", body: "Which one?", options });
const clear = card.getByRole("button", { name: "Clear your answer to this question" });
assert.equal((await clear.innerText()).trim(), "Clear answer");
assert.equal(await clear.locator("svg").count(), 1, "an icon leads the label");
const visible = () => clear.evaluate((b) => {
const c = b.getBoundingClientRect();
const card = b.closest(".card").getBoundingClientRect();
return c.top >= card.top && c.bottom <= card.bottom + 1 && c.bottom <= window.innerHeight;
});
assert.equal(await visible(), true, "in view with the card scrolled to the top");
await scrollCard(card, "end");
assert.equal(await visible(), true, "still in view at the foot of the card");
});
// What a person sees break: a note typed on a card is dropped by the verdict,
// or is lost when the verdict comes first.
test("a note's comment field rides along with the answer, typed before or after the pick", async (t) => {
+25
View File
@@ -671,6 +671,31 @@ test("Cleanup scans the console home and lists an old session folder with its si
assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true);
});
// The server refuses to delete a completed spec git does not track as it
// stands, so the list shows it apart as kept, never as something to delete.
test("Cleanup lists an untracked completed spec as kept, out of the total and out of Delete", async (t) => {
noSavedLooks(t);
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
const spec = path.join(s.project, "specs--completed", "old-spec");
fs.mkdirSync(spec, { recursive: true });
fs.writeFileSync(path.join(spec, "overview.md"), "x".repeat(2000));
backdate(path.join(spec, "overview.md"));
backdate(spec);
await s.page.click("#btn-looks");
await s.page.click("#prefs-tab-system");
await s.page.click("#cleanup-scan");
const list = s.page.locator("#cleanup-list");
const kept = list.locator(".cleanup-kept").filter({ hasText: "old-spec" });
await kept.waitFor();
assert.match(await textOf(kept), /specs--completed\/old-spec\/\s*kept: git does not track it as it stands/);
assert.equal(await list.locator(".cleanup-row:not(.cleanup-kept)").filter({ hasText: "old-spec" }).count(), 0, "not listed to delete");
const summary = list.locator(".cleanup-summary");
if (await summary.count()) assert.doesNotMatch(await textOf(summary), /completed spec/, "not counted in the summary");
assert.match(await textOf(s.page.locator("#cleanup-status")), /1 old completed spec is kept: git does not track it as it stands\./);
assert.equal(fs.existsSync(spec), true);
});
/* ------------------------------------------------------------- the tabs */
const tabNames = async (s) => (await s.page.locator("#prefs-tabs [role=tab] .prefs-tab-label").allInnerTexts()).map((x) => x.trim());
+92 -3
View File
@@ -37,6 +37,8 @@ import {
terminalLine,
} from "../src/web-console/sessions.mjs";
import { validate } from "../src/web-console/patches.mjs";
// Scrubs this process's git config, so the Cleanup fixtures and git-repo.mjs agree.
import { gitInit } from "./skill-script-helpers.mjs";
import { joinedCss } from "./css-helpers.mjs";
import {
ROOT,
@@ -439,6 +441,13 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
];
stray(path.join(consoleDir, "p1.json"), "12345");
put(path.join(consoleDir, "runtime", "x.json"));
// The shared console install, one folder per version, however old: never a stray.
const installed = stray(path.join(consoleDir, "3.0.4", "console.mjs"), "x");
backdate(path.dirname(installed));
kept.push(installed);
// A folder that is not a version stays a stray.
backdate(put(path.join(consoleDir, "3.0", "x.txt")));
backdate(path.join(consoleDir, "3.0"));
backdate(put(path.join(plan2code, "console-dev", "sessions", "x.txt"), "abc"));
backdate(path.join(plan2code, "console-dev"));
// An old folder with a file rewritten just now: the folder's own mtime
@@ -463,6 +472,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
const opts = { consoleDir, plan2codeDir: plan2code, skipSid: "20250801-101010-bbbbbb" };
const { items, bytes } = await cleanupFindings(opts);
assert.deepEqual(items.map((i) => i.id).sort(), [
"console:3.0",
"console:looks.json.456.tmp",
"console:p1.json",
"root:console-dev",
@@ -478,7 +488,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
// A console running from another home never reaches the folder above it.
const elsewhere = await cleanupFindings({ ...opts, plan2codeDir: path.join(plan2code, "other") });
assert.deepEqual(elsewhere.items.map((i) => i.where).sort(), ["console", "console", "session"]);
assert.deepEqual(elsewhere.items.map((i) => i.where).sort(), ["console", "console", "console", "session"]);
// Only ids a fresh scan still finds are removed; anything else is ignored.
const done = await removeCleanup(
@@ -510,6 +520,8 @@ test("cleanup lists the project's completed specs untouched for 30 days, and rem
return p;
};
fs.mkdirSync(consoleDir, { recursive: true });
fs.mkdirSync(project, { recursive: true });
const g = gitInit(project);
const opts = { consoleDir, plan2codeDir: path.join(base, "home"), skipSid: "x", project };
// No specs--completed/ at all is just nothing to list.
@@ -523,6 +535,9 @@ test("cleanup lists the project's completed specs untouched for 30 days, and rem
put(path.join(completed, "touched-spec", "overview.md"));
backdate(put(path.join(completed, "README.md")));
backdate(put(path.join(project, "specs", "live-spec", "overview.md")));
// Committed, so Cleanup may delete it (an untracked one is refused: see the next test).
g("add", "specs--completed/old-spec");
g("commit", "-q", "-m", "archive old-spec");
const { items } = await cleanupFindings(opts);
assert.deepEqual(items.map((i) => i.id), ["completed:old-spec"]);
@@ -544,6 +559,78 @@ test("cleanup lists the project's completed specs untouched for 30 days, and rem
}
});
test("cleanup refuses a completed spec git does not track, says why, and still deletes a tracked one and everything else", async () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-cleanup-guard-"));
const home = path.join(base, "home");
const consoleDir = path.join(home, "console");
const project = path.join(base, "project");
const completed = path.join(project, "specs--completed");
try {
const put = (p, body = "{}") => {
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, body);
return p;
};
const oldSpec = (name, file = "overview.md") => {
backdate(put(path.join(completed, name, file), "abc"));
backdate(path.join(completed, name));
};
fs.mkdirSync(consoleDir, { recursive: true });
fs.mkdirSync(project, { recursive: true });
const g = gitInit(project);
// The default: Init gitignores the archive, so only a forced add tracks a spec.
put(path.join(project, ".gitignore"), "specs--completed/\n");
oldSpec("tracked-spec");
oldSpec("untracked-spec");
oldSpec("partly-spec");
oldSpec("edited-spec");
g("add", ".gitignore");
g("add", "-f", "specs--completed/tracked-spec", "specs--completed/partly-spec", "specs--completed/edited-spec");
g("commit", "-q", "-m", "archive");
// A file added after the commit: git could not give it back.
oldSpec("partly-spec", "notes.md");
// A tracked file edited after the commit: git could give back only the old text.
backdate(put(path.join(completed, "edited-spec", "overview.md"), "edited"));
backdate(path.join(completed, "edited-spec"));
// Not a spec: removed as before, in the same call.
backdate(put(path.join(consoleDir, "stray.json")));
const opts = { consoleDir, plan2codeDir: home, skipSid: "x", project };
const ids = ["completed:tracked-spec", "completed:untracked-spec", "completed:partly-spec", "completed:edited-spec", "console:stray.json"];
assert.deepEqual((await cleanupFindings(opts)).items.map((i) => i.id).sort(), [...ids].sort(), "the scan still lists all of them");
const done = await removeCleanup(ids, opts);
assert.deepEqual(done.removed.sort(), ["completed:tracked-spec", "console:stray.json"]);
assert.deepEqual(done.refused.sort(), ["completed:edited-spec", "completed:partly-spec", "completed:untracked-spec"]);
assert.deepEqual(done.failed, []);
assert.equal(fs.existsSync(path.join(completed, "tracked-spec")), false, "a tracked spec is deleted");
assert.equal(fs.existsSync(path.join(consoleDir, "stray.json")), false);
for (const name of ["untracked-spec", "partly-spec", "edited-spec"]) assert.ok(fs.existsSync(path.join(completed, name, "overview.md")), name + " is kept");
assert.ok(fs.existsSync(path.join(completed, "partly-spec", "notes.md")));
assert.match(done.refusal, /^Kept 3 completed specs git does not track as they stand, so deleting them would lose them for good: /);
assert.ok(done.refusal.includes("specs--completed/untracked-spec/"), done.refusal);
assert.ok(done.refusal.includes("specs--completed/partly-spec/"), done.refusal);
assert.ok(done.refusal.includes("specs--completed/edited-spec/"), done.refusal);
assert.equal(fs.readFileSync(path.join(completed, "edited-spec", "overview.md"), "utf8"), "edited", "the uncommitted edit survives");
assert.equal(done.refusal.includes("specs--completed/tracked-spec/"), false, "the deleted spec is not named");
// A project that is not a repository at all: nothing there is tracked.
const loose = path.join(base, "loose");
backdate(put(path.join(loose, "specs--completed", "only-spec", "overview.md")));
backdate(path.join(loose, "specs--completed", "only-spec"));
const alone = await removeCleanup(["completed:only-spec"], { ...opts, project: loose });
assert.deepEqual(alone.removed, []);
assert.deepEqual(alone.refused, ["completed:only-spec"]);
assert.equal(alone.refusal, "Kept specs--completed/only-spec/: git does not track it as it stands, so deleting it would lose it for good. Commit it first, or delete it yourself once it is backed up.");
assert.ok(fs.existsSync(path.join(loose, "specs--completed", "only-spec")));
// Nothing refused: no line.
assert.equal((await removeCleanup([], opts)).refusal, "");
} finally {
fs.rmSync(base, { recursive: true, force: true });
}
});
test("User Preferences: wider, its body scrolls and the button bar stays put, without touching dialogs that borrow .looks", () => {
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
const css = joinedCss();
@@ -871,9 +958,11 @@ test("/app.css is the style files joined in CSS_ORDER with the accent rules last
// The skills the build writes carry public/styles/ with every file in CSS_ORDER,
// and a console started from that tree serves the same /app.css as this one.
test("the built skills tree serves the same /app.css as the source console", async (t) => {
test("the built shared console serves the same /app.css as the source console", async (t) => {
const { CSS_ORDER, asset } = await import("../src/web-console/static.mjs");
const built = path.join(ROOT, "skills", "plan2code", "references", "web-console");
// The console is built once, as skills/_console/<version>/, and every skill forwards to it.
const version = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version;
const built = path.join(ROOT, "skills", "_console", version);
// npm test builds first; a bare run of this file may not have.
if (!fs.existsSync(path.join(built, "console.mjs"))) return t.skip("skills/ is not built: run npm run build:skills");
for (const f of CSS_ORDER) assert.ok(fs.existsSync(path.join(built, "public", "styles", f)), `the build is missing public/styles/${f}`);
+3 -2
View File
@@ -39,7 +39,7 @@ import { DEFAULT_LOOKS, looks, resetLooks } from "../src/web-console/public/look
import { ROLE_NOT_SET } from "../src/web-console/public/starters.js";
import { RED_AT, YELLOW_AT } from "../src/web-console/public/meter.js";
import { REMOTE_FOLD } from "../src/web-console/public/git-board.js";
import { readLedger, SESSION_MAX_AGE_MS, sweepUploads, UPLOAD_MAX_AGE_MS } from "../src/web-console/sessions.mjs";
import { readLedger, SERVER_MAX_LIFE_MS, SESSION_MAX_AGE_MS, sweepUploads, UPLOAD_MAX_AGE_MS } from "../src/web-console/sessions.mjs";
import { applyPatch, validate } from "../src/web-console/patches.mjs";
import { joinedCss } from "./css-helpers.mjs";
import {
@@ -897,7 +897,8 @@ const helpFacts = () => ({
adriftMinutes: sourceConst("public/selectors.js", /const ADRIFT_MS = ([^;]+);/, "ADRIFT_MS") / 60000,
maxUploadMb: sourceConst("public/uploads.js", /const MAX_UPLOAD_BYTES = ([^;]+);/, "MAX_UPLOAD_BYTES") / 1024 / 1024,
idleMinutes: sourceConst("server.mjs", /const IDLE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "IDLE_MS") / 60000,
maxLifeHours: sourceConst("server.mjs", /const MAX_LIFE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "MAX_LIFE_MS") / 3600000,
// server.mjs and stop share this one constant (sessions.mjs).
maxLifeHours: SERVER_MAX_LIFE_MS / 3600000,
closedTabMinutes: sourceConst("server.mjs", /\(IDLE_MS - ([^)]+)\)/, "the closed-tab shutdown") / 60000,
accentCount: Object.keys(ACCENTS).length,
// The one fact quoted as several numbers: each span holds one of the widths.
+40 -7
View File
@@ -1,5 +1,6 @@
// Web console tests, the shape of the source: no console file grows past
// 3,000 lines, and the files lib.mjs split into stand on their own.
// 3,000 lines, the files lib.mjs split into stand on their own, and the
// light theme's faintest ink meets WCAG AA contrast.
// Run with: node --test scripts/test-web-console-shape.mjs
import test from "node:test";
@@ -293,11 +294,19 @@ test("shape: CSS_ORDER names every file in public/styles/ once, and none is serv
for (const rel of SERVABLE) assert.ok(!rel.startsWith("styles/") && !CSS_ORDER.includes(rel), `${rel} must not be served on its own`);
});
// The files table in AGENTS-architecture.md gives every console file a row,
// The files tables in the AGENTS-architecture-*.md area files give every console file a row,
// so a contributor finds where a job lives without searching. A row's first
// cell names the file by its path under src/web-console/ (backticked; one cell
// may name several files, joined by "·").
const ARCHITECTURE_DOC = path.join(ROOT, ".agents-docs", "AGENTS-architecture.md");
const DOCS_DIR = path.join(ROOT, ".agents-docs");
// Every architecture file (the index and its area files): the tables run across several.
function architectureMarkdown() {
return fs.readdirSync(DOCS_DIR)
.filter((f) => /^AGENTS-architecture(-[a-z-]+)?\.md$/.test(f))
.sort()
.map((f) => fs.readFileSync(path.join(DOCS_DIR, f), "utf8"))
.join("\n");
}
// The paths the files table names, from the first cell of each table row.
function tableFiles(markdown) {
@@ -315,11 +324,11 @@ function undocumented(dir, markdown) {
const named = tableFiles(markdown);
return sourceFiles(dir)
.filter((p) => !named.has(p))
.map((p) => `${p} has no row in the files table of AGENTS-architecture.md: add one with its one-line job`);
.map((p) => `${p} has no row in the files tables of the AGENTS-architecture area files: add one with its one-line job`);
}
test("shape: every console file has a row in the files table of AGENTS-architecture.md", () => {
const problems = undocumented(CONSOLE_DIR, fs.readFileSync(ARCHITECTURE_DOC, "utf8"));
test("shape: every console file has a row in the files tables of the AGENTS-architecture area files", () => {
const problems = undocumented(CONSOLE_DIR, architectureMarkdown());
assert.deepEqual(problems, []);
});
@@ -331,7 +340,7 @@ test("shape: the docs-table check names a file with no row, and passes one that
fs.writeFileSync(path.join(dir, "public", "b.js"), "");
const table = "| File | Role |\n|---|---|\n| `a.mjs` | the first |\n";
assert.deepEqual(undocumented(dir, table), [
"public/b.js has no row in the files table of AGENTS-architecture.md: add one with its one-line job",
"public/b.js has no row in the files tables of the AGENTS-architecture area files: add one with its one-line job",
]);
assert.deepEqual(undocumented(dir, `${table}| \`public/b.js\` · \`x.js\` | the second |\n`), []);
} finally {
@@ -384,3 +393,27 @@ test("shape: the redraw-safe check names a locator's style read and scroll, and
].join("\n");
assert.deepEqual(racyPageReads("x.mjs", fine), []);
});
// The WCAG 2 contrast ratio of two "#rrggbb" colors.
function contrastRatio(a, b) {
const lum = (hex) => {
const [r, g, bl] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));
return 0.2126 * r + 0.7152 * g + 0.0722 * bl;
};
const [hi, lo] = [lum(a), lum(b)].sort((x, y) => y - x);
return (hi + 0.05) / (lo + 0.05);
}
test("shape: the light theme's faintest ink, --ink-3, reads at 4.5:1 or better on --bg", () => {
const css = fs.readFileSync(path.join(CONSOLE_DIR, "public", "styles", "tokens.css"), "utf8");
// The first :root block is the light theme; the dark ones sit under their own selectors.
const light = css.match(/^:root \{([^}]*)\}/m);
assert.ok(light, "tokens.css opens with a :root block");
const token = (name) => {
const m = light[1].match(new RegExp(`--${name}:\\s*(#[0-9a-fA-F]{6})\\s*;`));
assert.ok(m, `--${name} is a #rrggbb color in the light :root block`);
return m[1];
};
const ratio = contrastRatio(token("ink-3"), token("bg"));
assert.ok(ratio >= 4.5, `--ink-3 ${token("ink-3")} on --bg ${token("bg")} is ${ratio.toFixed(2)}:1, under 4.5:1`);
});
+96 -4
View File
@@ -8,11 +8,13 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { SPEC_STATES as TABLE, stateFor } from "../src/web-console/public/spec-states.js";
import { SKILLS } from "../src/web-console/public/skills.js";
import { SKILL_CATALOG, cardAvailability, defaultSpec, launchVariant } from "../src/web-console/public/answers.js";
import { scanProject } from "../src/web-console/scan.mjs";
import { MARKERS, TASK_LINE_RE, TASK_ID_RE, CHECKBOX_RE, STATUS_RE, statusOf, countTasks } from "../src/web-console/spec-files.mjs";
import { MARKERS, TASK_LINE_RE, TASK_ID_RE, CHECKBOX_RE, STATUS_RE, statusOf, countTasks, deriveSpecState, pickPhaseFiles } from "../src/web-console/spec-files.mjs";
// The task pattern specs.mjs used before spec-files.mjs: TASK_ID_RE must take
// a `-` task line apart into the same groups.
@@ -68,10 +70,11 @@ test("spec files: countTasks() counts task lines only when there are any, every
"- [ ] It works",
"- [x] It is fast",
].join("\r\n");
assert.deepEqual(countTasks(phase), { done: 1, assumed: 1, open: 3, total: 5 });
// [~] is an unknown marker: not done, so it counts as open.
assert.deepEqual(countTasks(phase), { done: 1, assumed: 1, open: 3, blocked: 1, bare: 1, total: 6 });
const older = "# Phase 1\n\n- [x] Make it\n- [ ] Ship it\n- [?] Check it\n";
assert.deepEqual(countTasks(older), { done: 1, assumed: 1, open: 1, total: 3 });
assert.deepEqual(countTasks(""), { done: 0, assumed: 0, open: 0, total: 0 });
assert.deepEqual(countTasks(older), { done: 1, assumed: 1, open: 1, blocked: 0, bare: 0, total: 3 });
assert.deepEqual(countTasks(""), { done: 0, assumed: 0, open: 0, blocked: 0, bare: 0, total: 0 });
});
// What the picker labels each state and which card each state lights, as
@@ -487,6 +490,95 @@ test("the scan: an assumed task counts as done and is named, and numbered task l
}
});
// The seven cases where the dashboard scan and specs.mjs once disagreed
// (recorded in the hardening spec's Phase 5 notes; the same cases are in
// test-skill-scripts.mjs). Each is a spec folder and the
// [state, detail, finalizeReady] both must now report.
const DESYNC_CHECKLIST = (...marks) => `# Overview\n\n## Phase Checklist\n\n${marks.map((m, i) => `- [${m}] [Phase ${i + 1}: Step ${i + 1}](./phase-${i + 1}.md)`).join("\n")}\n`;
const DESYNC_PHASE = (n, lines) => `# Phase ${n}: Step ${n}\n\n**Status:** In Progress\n\n## Tasks\n\n${lines.join("\n")}\n\n## Acceptance Criteria\n\n- It works\n`;
const DESYNC_CASES = {
"blocked-reasoned": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two", " > BLOCKED: needs admin access. User action: create the app."]) },
want: ["building", "1 of 2 tasks done, 1 blocked", true],
},
"unknown-marker": {
files: { "overview.md": DESYNC_CHECKLIST("/"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [~] **Task 1.2:** Two"]) },
want: ["building", "1 of 2 tasks done", false],
},
"row-without-file": {
files: { "overview.md": DESYNC_CHECKLIST("x", " "), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [x] **Task 1.2:** Two"]) },
want: ["building", "2 of 2 tasks done, Phase 2 not written up", false],
},
"phase-without-tasks": {
files: { "overview.md": DESYNC_CHECKLIST("x", " "), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-2.md": DESYNC_PHASE(2, ["To be written."]) },
want: ["building", "1 of 1 tasks done, Phase 2 not written up", false],
},
"stale-duplicate": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-1-old.md": DESYNC_PHASE(1, ["- [ ] **Task 1.1:** One", "- [ ] **Task 1.2:** Two"]) },
want: ["built", "all tasks done", false],
},
"not-a-phase-file": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-notes.md": "# Notes\n\n- [ ] Ask about colors\n" },
want: ["built", "all tasks done", false],
},
"blocked-bare": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two"]) },
want: ["building", "1 of 2 tasks done, 1 blocked", false],
},
};
const SPECS_SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "src", "skill-scripts", "specs.mjs");
test("the scan: the dashboard and specs.mjs status report the same state on the seven desync cases", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-desync-"));
try {
for (const [name, c] of Object.entries(DESYNC_CASES))
for (const [rel, text] of Object.entries(c.files)) {
fs.mkdirSync(path.join(root, "specs", name), { recursive: true });
fs.writeFileSync(path.join(root, "specs", name, rel), text);
}
const by = Object.fromEntries(scanProject(root).specs.map((sp) => [sp.name, sp]));
for (const [name, c] of Object.entries(DESYNC_CASES)) {
assert.deepEqual([by[name].state, by[name].detail, Boolean(by[name].finalizeReady)], c.want, `${name}: the dashboard scan`);
const r = spawnSync(process.execPath, [SPECS_SCRIPT, "status", name, "--root", root], { encoding: "utf8" });
assert.equal(r.status, 0, r.stderr);
const st = JSON.parse(r.stdout);
assert.deepEqual([st.state, st.stateDetail, st.finalizeReady], c.want, `${name}: specs.mjs status`);
}
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test("deriveSpecState: blocked tasks keep a spec building, and finalizeReady needs a reason on each", () => {
const phase = (lines) => [{ number: 1, text: `# Phase 1\n\n${lines.join("\n")}\n` }];
const ready = deriveSpecState({ phases: phase(["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two Blocked: no key yet", "- [!] **Task 1.3:** Three", " Reason: waiting on legal"]) });
assert.deepEqual([ready.state, ready.detail, ready.finalizeReady, ready.blocked, ready.bare], ["building", "1 of 3 tasks done, 2 blocked", true, 2, 0]);
const open = deriveSpecState({ phases: phase(["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two", " > BLOCKED: no key.", "- [ ] **Task 1.3:** Three"]) });
assert.deepEqual([open.state, open.finalizeReady], ["building", false], "an open task left keeps Finalize dark");
// A reason belongs to its own task: the next task's line does not lend one.
const borrowed = deriveSpecState({ phases: phase(["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two", "- [x] **Task 1.3:** Blocked: on purpose"]) });
assert.deepEqual([borrowed.bare, borrowed.finalizeReady], [1, false]);
assert.equal(deriveSpecState({ phases: phase(["- [!] **Task 1.1:** One", " > BLOCKED: no key."]) }).state, "documented", "nothing done yet is still documented");
// An approved phase with no task lines is not waiting to be written up.
const approved = deriveSpecState({ overview: "## Phase Checklist\n\n- [x] Phase 1: One\n- [x] Phase 2: Two\n", phases: [...phase(["- [x] **Task 1.1:** One"]), { number: 2, text: "# Phase 2\n" }] });
assert.deepEqual([approved.state, approved.unwritten], ["built", []]);
});
test("pickPhaseFiles: one file per phase number, the exact phase-N.md first, the rest listed as extra", () => {
const picked = pickPhaseFiles(["phase-2-old.md", "phase-2.md", "phase-1-setup.md", "phase-notes.md", "overview.md", "phase-10.md"]);
assert.deepEqual([...picked.entries()].sort((a, b) => a[0] - b[0]), [[1, "phase-1-setup.md"], [2, "phase-2.md"], [10, "phase-10.md"]]);
assert.deepEqual([...picked.extra.entries()], [[2, ["phase-2-old.md"]]]);
});
test("card rules: Finalize lights for a building spec only when the scan says finalizeReady", () => {
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-4-finalize");
const spec = (extra) => ({ dir: "specs/x", name: "x", state: "building", ...extra });
assert.equal(cardAvailability(entry, SCAN, spec({ finalizeReady: true })).on, true);
assert.equal(cardAvailability(entry, SCAN, spec({})).on, false);
assert.equal(cardAvailability(entry, SCAN, { dir: "specs/x", name: "x", state: "documented", finalizeReady: true }).on, false, "only a building spec");
});
test("the scan: planChange is true for a waiting Plan change brief, and absent once it is applied or dropped", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-brief-"));
const notes = (line) => "# Phase 1\n\n- [x] **Task 1.1:** One\n- [ ] **Task 1.2:** Two\n\n## Notes\n\n### Paused 2026-10-27\n" + line + "\n\n## Phase Completion Summary\n";
+20 -3
View File
@@ -412,8 +412,25 @@ test("a launch, a dashboard press, Commit it now and Update CHANGELOG first each
test("the built skills name the skill file to follow after a hop", async () => {
const builtCli = path.join(ROOT, "skills", "plan2code", "references", "web-console", "console.mjs");
if (!fs.existsSync(builtCli)) return;
// The built console.mjs is a stub that forwards to the shared install, so
// point it at the console this build produced, in a throwaway console home.
const sharedRoot = path.join(ROOT, "skills", "_console");
const sharedVersion = fs.existsSync(sharedRoot) ? fs.readdirSync(sharedRoot)[0] : undefined;
if (!sharedVersion) return;
const stubHome = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-speed-home-"));
fs.writeFileSync(path.join(stubHome, "console-dir"), path.join(sharedRoot, sharedVersion));
// A shared console finds skill files in the agent skills store under the home folder.
const storeHome = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-speed-store-"));
const storeSkill = (name) => {
const dir = path.join(storeHome, ".agents", "skills", name);
fs.mkdirSync(dir, { recursive: true });
fs.copyFileSync(path.join(ROOT, "skills", name, "SKILL.md"), path.join(dir, "SKILL.md"));
return path.join(dir, "SKILL.md");
};
const reviewFile = storeSkill("plan2code-review");
const handoffFile = storeSkill("plan2code-handoff");
const run = (args) => {
const res = spawnSync(process.execPath, [builtCli, ...args], { env: ENV, encoding: "utf8", cwd: ROOT });
const res = spawnSync(process.execPath, [builtCli, ...args], { env: { ...ENV, PLAN2CODE_CONSOLE_HOME: stubHome, HOME: storeHome, USERPROFILE: storeHome }, encoding: "utf8", cwd: ROOT });
return { ...res, json: JSON.parse(res.stdout.trim().split("\n").pop()) };
};
const opened = run(["open", "--no-open", "--workflow", "dashboard"]).json;
@@ -428,7 +445,7 @@ test("the built skills name the skill file to follow after a hop", async () => {
});
assert.equal(res.status, 200);
const got = run(["wait", "--session", opened.sid, "--seconds", "10"]).json;
assert.equal(got.skillFile, path.join(ROOT, "skills", "plan2code-review", "SKILL.md"));
assert.equal(got.skillFile, reviewFile);
assert.equal(got.handoffSkill, undefined, "a launch is not a handoff stop");
const stopRes = await fetch(`${m[1]}/submit`, {
method: "POST",
@@ -437,7 +454,7 @@ test("the built skills name the skill file to follow after a hop", async () => {
});
assert.equal(stopRes.status, 200);
const stopped = run(["wait", "--session", opened.sid, "--seconds", "10"]).json;
assert.equal(stopped.handoffSkill, path.join(ROOT, "skills", "plan2code-handoff", "SKILL.md"), "a handoff stop in a built skill names the Handoff skill file");
assert.equal(stopped.handoffSkill, handoffFile, "a handoff stop in a built skill names the Handoff skill file");
} finally {
run(["stop", "--session", opened.sid, "--force"]);
}