mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Port upstream skill scripts into v2.4.1: deterministic workflow steps run as Node scripts beside each SKILL.md (specs, pathfinder, feedback payload, commit message, review scope, agent files, handoff path) with tests, the prompt limit rises to 20,000 chars, upstream review fixes are folded in (linked agent files never overwrite AGENTS.md, review stops with no base, paste-safe commit commands, Pathfinder number high-water mark and dry runs), and web console workspace folders are remembered per project and spec, with Finalize forgetting an archived spec's list
AI Assisted
This commit is contained in:
1 parent
5cbc6edce2
commit
7d54941b75
243 files changed
+23698
-1607
No files matched your search
@@ -0,0 +1,61 @@
|
||||
// Shared helpers for the skill-script tests (scripts/test-*script*.mjs).
|
||||
//
|
||||
// The tests run the scripts the way an agent does: as `node <skill>/scripts/x.mjs`
|
||||
// from the built skills/ tree, against throwaway fixtures in the OS temp dir,
|
||||
// with the clock pinned by PLAN2CODE_NOW. They live in scripts/ so nothing
|
||||
// here ships.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync, execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
export const SKILLS = path.join(ROOT, "skills");
|
||||
export const NOW = "2026-08-03 14:05";
|
||||
|
||||
// Rebuild skills/ on every import, not only when it is missing: a test file run
|
||||
// directly after an edit to src/ must not test a stale tree. The build is
|
||||
// idempotent and takes well under a second.
|
||||
execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" });
|
||||
|
||||
export function runScript(skill, script, args, { cwd, env } = {}) {
|
||||
const r = spawnSync(process.execPath, [path.join(SKILLS, skill, "scripts", script), ...args], {
|
||||
cwd: cwd || ROOT,
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, PLAN2CODE_NOW: NOW, GIT_CONFIG_NOSYSTEM: "1", ...env },
|
||||
});
|
||||
let json = null;
|
||||
try {
|
||||
json = JSON.parse(r.stdout);
|
||||
} catch {}
|
||||
return { code: r.status, json, stdout: r.stdout, stderr: r.stderr };
|
||||
}
|
||||
|
||||
export function tmp(name) {
|
||||
return fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), `p2c-${name}-`));
|
||||
}
|
||||
|
||||
export function write(root, rel, content) {
|
||||
const p = path.join(root, rel);
|
||||
fs.mkdirSync(path.dirname(p), { recursive: true });
|
||||
fs.writeFileSync(p, content);
|
||||
return p;
|
||||
}
|
||||
|
||||
export const read = (root, rel) => fs.readFileSync(path.join(root, rel), "utf8");
|
||||
|
||||
export function gitInit(dir, branch = "main") {
|
||||
const g = (...a) => execFileSync("git", a, { cwd: dir, stdio: "pipe", encoding: "utf8" });
|
||||
g("init", "-q", "-b", branch);
|
||||
g("config", "user.email", "t@example.com");
|
||||
g("config", "user.name", "Test");
|
||||
g("config", "commit.gpgsign", "false");
|
||||
return g;
|
||||
}
|
||||
|
||||
/** A phase-N.md in the Documentation template's shape. tasks: [[marker, id], ...] */
|
||||
export function phase(n, status, tasks, extra = "") {
|
||||
return `# Phase ${n}: Name ${n}\n\n**Status:** ${status}\n**Estimated Tasks:** ${tasks.length}\n\n## Overview\n\nPhase ${n} builds the thing. More words here.\n\n## Prerequisites\n\n- Something exists\n\n## Tasks\n\n${tasks.map(([m, id]) => `- [${m}] **Task ${id}:** Do ${id}`).join("\n")}\n${extra}\n## Acceptance Criteria\n\n- It works\n`;
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// Tests for plan2code-4-finalize's scripts/feedback-payload.mjs.
|
||||
//
|
||||
// See skill-script-helpers.mjs for how these run.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import crypto from "node:crypto";
|
||||
import { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
|
||||
|
||||
/* ========================================================= feedback-payload.mjs */
|
||||
|
||||
test("feedback-payload: payload from the archive, real prompt hashes, size and truncation", () => {
|
||||
const root = tmp("fb");
|
||||
const spec = "specs--completed/lunch-vote";
|
||||
write(root, `${spec}/PLAN-DRAFT-20260801.md`, '# Plan\n\n<!-- METRICS_JSON {"confidence": 92, "clarification_rounds": 1, "functional_requirements_count": 5, "non_functional_requirements_count": 2, "risk_count": 3, "phase_count": 2, "verification_gaps_found": 0, "confidence_breakdown": {"requirements": 24, "feasibility": 23, "integration": 23, "risk": 22}} -->\n');
|
||||
write(root, `${spec}/overview.md`, '# O\n\n<!-- METRICS_JSON {"step": "document", "total_tasks": 3, "tasks_per_phase": [2, 1], "phase_count": 2, "parallel_groups_identified": 0, "verification_items_added": 1} -->\n\n## User Feedback\n| Field | Value |\n|-------|-------|\n| Rating | 8 |\n| Reason | Good \\| fast |\n| Went Well | Specs |\n| Went Poorly | Review |\n');
|
||||
write(root, `${spec}/phase-1.md`, phase(1, "Complete", [["x", "1.1"], ["x", "1.T"]]));
|
||||
write(root, `${spec}/phase-2.md`, phase(2, "Complete", [["!", "2.1"]]));
|
||||
const outDir = path.join(root, "out");
|
||||
const F = (...a) => runScript("plan2code-4-finalize", "feedback-payload.mjs", [...a, "--root", root]);
|
||||
assert.equal(F("build", "lunch-vote", "--out", outDir).code, 2, "the two judgment counts are required");
|
||||
const b = F("build", "lunch-vote", "--out", outDir, "--set", "verification_failures_found=1", "--set", "documentation_updates_needed=2");
|
||||
assert.equal(b.code, 0, b.stderr);
|
||||
const p = b.json.payload;
|
||||
assert.match(p.run_id, /^run-20260803-140500-[0-9a-f]{4}$/);
|
||||
assert.equal(p.plan2code_version, JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version);
|
||||
const srcHash = crypto.createHash("sha256").update(fs.readFileSync(path.join(ROOT, "src", "plan2code-1-plan.md"), "utf8")).digest("hex").slice(0, 12);
|
||||
assert.equal(p.prompt_versions_short.plan, srcHash, "the hash is the src prompt's, recovered from the installed SKILL.md");
|
||||
assert.ok(Object.values(p.prompt_versions_short).every((v) => /^[0-9a-f]{12}$/.test(v)));
|
||||
assert.deepEqual(p.step1.confidence_breakdown, { requirements: 24, feasibility: 23, integration: 23, risk: 22 });
|
||||
assert.equal(p.step1.final_confidence, 92);
|
||||
assert.equal(p.step2.total_tasks, 3);
|
||||
assert.deepEqual(p.step3, { task_completion_rate: 0.67, tasks_completed: 2, tasks_total: 3, blocker_count: 1 });
|
||||
assert.deepEqual(p.step4, { completion_rate_at_audit: 0.67, verification_failures_found: 1, documentation_updates_needed: 2, archival_succeeded: true });
|
||||
assert.deepEqual(p.user_feedback, { overall_rating: 8, rating_reason: "Good | fast", what_went_well: "Specs", what_went_poorly: "Review" });
|
||||
assert.equal(b.json.title, `[Feedback] v${p.plan2code_version} - rating 8/10`);
|
||||
assert.match(b.json.body, /<!-- METRICS_JSON \{"schema_version":"1\.0"/);
|
||||
assert.ok(!/[—]/.test(b.json.title), "no em dash in the issue title");
|
||||
assert.equal(b.json.oversize, false);
|
||||
assert.ok(fs.existsSync(path.join(outDir, "body.md")));
|
||||
// The ingest side parses the body back.
|
||||
const parsed = JSON.parse(b.json.body.match(/<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/)[1]);
|
||||
assert.equal(parsed.schema_version, "1.0");
|
||||
// Oversize, then truncate.
|
||||
const ov = path.join(root, spec, "overview.md");
|
||||
fs.writeFileSync(ov, fs.readFileSync(ov, "utf8").replace("| Good \\| fast |", `| ${"long reason ".repeat(500)} |`));
|
||||
const big = F("build", "lunch-vote", "--out", outDir, "--set", "verification_failures_found=1", "--set", "documentation_updates_needed=2");
|
||||
assert.equal(big.json.oversize, true);
|
||||
assert.match(big.json.next, /--truncate/);
|
||||
const cut = F("build", "lunch-vote", "--out", outDir, "--set", "verification_failures_found=1", "--set", "documentation_updates_needed=2", "--truncate");
|
||||
assert.equal(cut.json.oversize, false);
|
||||
assert.deepEqual(cut.json.truncated, ["rating_reason"]);
|
||||
const dry = runScript("plan2code-4-finalize", "feedback-payload.mjs", ["submit", "--from", outDir, "--dry-run"]);
|
||||
assert.equal(dry.code, 0);
|
||||
assert.match(dry.json.tiers[0], /^gh issue create --repo jparkerweb\/plan2code .*--label community-feedback$/);
|
||||
assert.equal(dry.json.oversize, false);
|
||||
assert.equal(dry.json.urlBytes, cut.json.urlBytes);
|
||||
fs.writeFileSync(ov, "# O\n");
|
||||
assert.equal(F("build", "lunch-vote", "--set", "verification_failures_found=1", "--set", "documentation_updates_needed=2").code, 3, "no feedback table, nothing to submit");
|
||||
});
|
||||
|
||||
/* ================================================= verification regressions */
|
||||
|
||||
test("feedback-payload: truncation always ends, '-->' survives ingest, lenient rating, absent steps are null", () => {
|
||||
const root = tmp("fb2");
|
||||
const spec = "specs--completed/x";
|
||||
const long = (w) => `${w} `.repeat(400).trim();
|
||||
// The visible answers carry markup that must stay text: a stray comment
|
||||
// opener, and a fake payload comment an ingest regex could match first.
|
||||
const fake = '<!-- METRICS_JSON {"schema_version":"1.0"} -->';
|
||||
const inputs = { rating_reason: `see {a} --> b <!-- x ${long("reason")}`, what_went_well: `${fake} ${long("well")}`, what_went_poorly: long("poorly") };
|
||||
write(root, `${spec}/overview.md`, `# O\n\n## User Feedback\n| field | value |\n|---|---|\n| rating | 8/10 |\n| reason | ${inputs.rating_reason} |\n| went well | ${inputs.what_went_well} |\n| went poorly | ${inputs.what_went_poorly} |\n`);
|
||||
write(root, `${spec}/phase-1.md`, phase(1, "Complete", [["x", "1.1"]]));
|
||||
const F = (...a) => runScript("plan2code-4-finalize", "feedback-payload.mjs", [...a, "--root", root]);
|
||||
const sets = ["--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0"];
|
||||
assert.equal(F("build", "x", ...sets, "--set", "bogus=1").code, 2);
|
||||
// Untruncated, the first METRICS_JSON match is the real payload: its answers
|
||||
// come back exactly as typed, not the fake's bare schema_version.
|
||||
const whole = F("build", "x", ...sets, "--out", path.join(root, "whole"));
|
||||
assert.equal(whole.code, 0, whole.stderr);
|
||||
const first = JSON.parse(whole.json.body.match(/<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/)[1]);
|
||||
assert.deepEqual(first.user_feedback, { overall_rating: 8, ...inputs });
|
||||
assert.equal(whole.json.body.split("<!--").length - 1, 1, "the payload's is the only comment that opens");
|
||||
assert.ok(!/<!--(?! METRICS_JSON \{"schema_version":"1\.0","run_id")/.test(whole.json.body), "no comment opens before the payload's");
|
||||
const r = spawnSync(process.execPath, [path.join(SKILLS, "plan2code-4-finalize", "scripts", "feedback-payload.mjs"), "build", "x", ...sets, "--truncate", "--out", path.join(root, "out"), "--root", root], { encoding: "utf8", timeout: 20000, env: { ...process.env, PLAN2CODE_NOW: NOW } });
|
||||
assert.equal(r.status, 0, "build --truncate finishes with every field long");
|
||||
const j = JSON.parse(r.stdout);
|
||||
assert.equal(j.oversize, false);
|
||||
assert.deepEqual(j.truncated, ["rating_reason", "what_went_well", "what_went_poorly"]);
|
||||
assert.equal(j.payload.user_feedback.overall_rating, 8, "8/10 reads as 8, field names in any case");
|
||||
assert.equal(j.payload.step1, null);
|
||||
assert.equal(j.payload.step2, null);
|
||||
// The ingest side's own extraction regex (plan2code-metrics collector.ts).
|
||||
const m = j.body.match(/<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/);
|
||||
const back = JSON.parse(m[1]);
|
||||
assert.match(back.user_feedback.rating_reason, /^see \{a\} --> b <!-- x/);
|
||||
assert.equal(back.user_feedback.what_went_well, j.payload.user_feedback.what_went_well);
|
||||
assert.match(back.user_feedback.what_went_well, /^<!-- METRICS_JSON/, "the fake comment is still just text in the real payload");
|
||||
assert.ok(!/<!--(?! METRICS_JSON \{"schema_version":"1\.0","run_id")/.test(j.body), "no comment opens before the payload's");
|
||||
});
|
||||
|
||||
test("feedback-payload: --truncate never splits an emoji", () => {
|
||||
const root = tmp("fb3");
|
||||
const spec = "specs--completed/x";
|
||||
const reason = "a" + "\u{1F44D}".repeat(400);
|
||||
write(root, `${spec}/overview.md`, `# O\n\n## User Feedback\n| Field | Value |\n|---|---|\n| Rating | 9 |\n| Reason | ${reason} |\n| Went Well | ok |\n| Went Poorly | none |\n`);
|
||||
write(root, `${spec}/phase-1.md`, phase(1, "Complete", [["x", "1.1"]]));
|
||||
const r = runScript("plan2code-4-finalize", "feedback-payload.mjs", ["build", "x", "--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0", "--truncate", "--out", path.join(root, "out"), "--root", root]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.equal(r.json.oversize, false);
|
||||
assert.deepEqual(r.json.truncated, ["rating_reason"]);
|
||||
const back = JSON.parse(r.json.body.match(/<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/)[1]);
|
||||
assert.equal(back.user_feedback.rating_reason, r.json.payload.user_feedback.rating_reason);
|
||||
assert.ok(!/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(back.user_feedback.rating_reason), "no lone high surrogate");
|
||||
assert.match(back.user_feedback.rating_reason, /^a(\u{1F44D})+\.\.\.$/u);
|
||||
});
|
||||
|
||||
test("feedback-payload: task counts read the same phase files specs.mjs does, never a stale sibling", () => {
|
||||
const root = tmp("fb5");
|
||||
const spec = "specs--completed/x";
|
||||
write(root, `${spec}/overview.md`, "# O\n\n## User Feedback\n| Field | Value |\n|---|---|\n| Rating | 7 |\n| Reason | r |\n| Went Well | w |\n| Went Poorly | p |\n");
|
||||
write(root, `${spec}/phase-1.md`, phase(1, "Complete", [["x", "1.1"], ["x", "1.2"]]));
|
||||
write(root, `${spec}/phase-1-old.md`, phase(1, "Not Started", [[" ", "1.1"], [" ", "1.2"], [" ", "1.3"]]));
|
||||
const r = runScript("plan2code-4-finalize", "feedback-payload.mjs", ["build", "x", "--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0", "--out", path.join(root, "out"), "--root", root]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.deepEqual(r.json.payload.step3, { task_completion_rate: 1, tasks_completed: 2, tasks_total: 2, blocker_count: 0 });
|
||||
const m = runScript("plan2code-4-finalize", "specs.mjs", ["metrics", spec, "--step", "finalize", "--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0", "--root", root]);
|
||||
assert.equal(m.code, 0, m.stderr);
|
||||
assert.equal(m.json.metrics.tasks_total, r.json.payload.step3.tasks_total);
|
||||
assert.equal(m.json.metrics.tasks_completed, r.json.payload.step3.tasks_completed);
|
||||
});
|
||||
|
||||
test("feedback-payload: a bare name in both specs/ and specs--completed/ is ambiguous", () => {
|
||||
const root = tmp("fb4");
|
||||
const table = (rating) => `# O\n\n## User Feedback\n| Field | Value |\n|---|---|\n| Rating | ${rating} |\n| Reason | r |\n| Went Well | w |\n| Went Poorly | p |\n`;
|
||||
write(root, "specs--completed/x/overview.md", table(3));
|
||||
write(root, "specs/x/overview.md", table(7));
|
||||
const sets = ["--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0"];
|
||||
const F = (...a) => runScript("plan2code-4-finalize", "feedback-payload.mjs", [...a, ...sets, "--out", path.join(root, "out"), "--root", root]);
|
||||
const bare = F("build", "x");
|
||||
assert.equal(bare.code, 5);
|
||||
assert.equal(bare.json.error, "ambiguous-spec");
|
||||
assert.match(bare.json.next, /specs\/x/);
|
||||
const live = F("build", "specs/x");
|
||||
assert.equal(live.code, 0, live.stderr);
|
||||
assert.equal(live.json.payload.user_feedback.overall_rating, 7, "the exact path reads this run, not the old archive");
|
||||
assert.equal(live.json.payload.step4.archival_succeeded, false);
|
||||
});
|
||||
|
||||
test("feedback-payload: submit refuses an oversize URL when gh fails, and dry-run says so", () => {
|
||||
const root = tmp("fb5");
|
||||
write(root, "specs--completed/x/overview.md", `# O\n\n## User Feedback\n| Field | Value |\n|---|---|\n| Rating | 6 |\n| Reason | ${"long reason ".repeat(800)} |\n| Went Well | w |\n| Went Poorly | p |\n`);
|
||||
const outDir = path.join(root, "out");
|
||||
const b = runScript("plan2code-4-finalize", "feedback-payload.mjs", ["build", "x", "--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0", "--out", outDir, "--root", root]);
|
||||
assert.equal(b.json.oversize, true);
|
||||
const dry = runScript("plan2code-4-finalize", "feedback-payload.mjs", ["submit", "--from", outDir, "--dry-run"]);
|
||||
assert.equal(dry.code, 0);
|
||||
assert.equal(dry.json.oversize, true);
|
||||
assert.equal(dry.json.urlBytes, b.json.urlBytes);
|
||||
// gh must never succeed here: no PATH but node's own folder (so gh is not
|
||||
// found), and should one turn up anyway, an empty config, no token and a
|
||||
// host that does not resolve.
|
||||
const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^(path|gh_|github_token$)/i.test(k)));
|
||||
Object.assign(env, { PATH: path.dirname(process.execPath), GH_CONFIG_DIR: tmp("fb5-gh"), GH_HOST: "gh.invalid", PLAN2CODE_NOW: NOW });
|
||||
const r = spawnSync(process.execPath, [path.join(SKILLS, "plan2code-4-finalize", "scripts", "feedback-payload.mjs"), "submit", "--from", outDir], { cwd: root, encoding: "utf8", timeout: 70000, env });
|
||||
assert.equal(r.status, 4, r.stderr);
|
||||
const j = JSON.parse(r.stdout);
|
||||
assert.equal(j.error, "oversize");
|
||||
assert.match(j.next, /--truncate/);
|
||||
assert.match(j.next, /gh/);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
// Tests for plan2code-handoff's scripts/handoff-path.mjs.
|
||||
//
|
||||
// See skill-script-helpers.mjs for how these run.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
|
||||
|
||||
/* =========================================================== handoff-path.mjs */
|
||||
|
||||
test("handoff-path: timestamped name, no overwrite, git ignore check", () => {
|
||||
const repo = tmp("handoff");
|
||||
gitInit(repo);
|
||||
const H = (...a) => runScript("plan2code-handoff", "handoff-path.mjs", a, { cwd: repo });
|
||||
const first = H("--dir", "handoffs");
|
||||
assert.equal(first.code, 0, first.stderr);
|
||||
assert.equal(path.basename(first.json.path), "2026-08-03-1405-handoff.md");
|
||||
assert.equal(first.json.created, true);
|
||||
assert.equal(first.json.git.inRepo, true);
|
||||
assert.equal(first.json.git.ignored, false);
|
||||
assert.match(first.json.warning, /handoffs\//);
|
||||
fs.writeFileSync(first.json.path, "x");
|
||||
assert.equal(path.basename(H("--dir", "handoffs").json.path), "2026-08-03-1405-2-handoff.md");
|
||||
write(repo, ".gitignore", "handoffs/\n");
|
||||
assert.equal(H("--dir", "handoffs").json.git.ignored, true);
|
||||
const temp = H();
|
||||
assert.equal(temp.json.git.inRepo, false);
|
||||
assert.equal(temp.json.git.ignored, null);
|
||||
const dry = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "later", "--dry-run"], { cwd: repo });
|
||||
assert.equal(dry.json.created, false);
|
||||
assert.ok(!fs.existsSync(path.join(repo, "later")));
|
||||
});
|
||||
|
||||
/* ================================================= verification regressions */
|
||||
|
||||
test("handoff-path: the repo root itself is never the line to ignore", () => {
|
||||
const repo = tmp("handoff2");
|
||||
gitInit(repo);
|
||||
const j = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "."], { cwd: repo }).json;
|
||||
assert.equal(j.git.inRepo, true);
|
||||
assert.equal(j.git.ignoreLine, "*-handoff.md");
|
||||
});
|
||||
|
||||
test("handoff-path: --dir naming an existing file is refused", () => {
|
||||
const repo = tmp("handoff3");
|
||||
write(repo, "notes.txt", "x");
|
||||
const r = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "notes.txt"], { cwd: repo });
|
||||
assert.equal(r.code, 5);
|
||||
assert.equal(r.json.ok, false);
|
||||
assert.equal(r.json.error, "not-a-folder");
|
||||
assert.match(r.json.next, /--dir temp/);
|
||||
assert.equal(runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "notes.txt", "--dry-run"], { cwd: repo }).code, 5, "dry-run refuses it too");
|
||||
});
|
||||
@@ -0,0 +1,545 @@
|
||||
// Tests for plan2code-0-pathfinder's scripts/pathfinder.mjs.
|
||||
//
|
||||
// See skill-script-helpers.mjs for how these run.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
|
||||
|
||||
/* ============================================================ pathfinder.mjs */
|
||||
|
||||
const B = "> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.";
|
||||
|
||||
function q(name, { type = "grill · HITL", state = "open", blocked = "none", claimed = "none", resolved = "none", locked = "no", answer = null, evidence = null, skipResolved = false } = {}) {
|
||||
return [
|
||||
B, "", `# ${name}`, "", `Type: ${type}`, `State: ${state}`, `Blocked by: ${blocked}`, `Claimed: ${claimed}`,
|
||||
...(skipResolved ? [] : [`Resolved: ${resolved}`]), `Locked: ${locked}`, "", "## Question", "", `What about ${name}?`, "",
|
||||
...(answer ? ["## Answer", "", answer, ""] : []),
|
||||
...(evidence ? ["## Evidence", "", evidence, ""] : []),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
const MAP = `${B}
|
||||
|
||||
# Map: audit-export
|
||||
|
||||
*Decisions live in \`questions/\` — one file each. This file is just the index.*
|
||||
|
||||
**Status:** Working
|
||||
**Updated:** 2026-08-01
|
||||
**Confidence:** Requirements-clarity 19/25 · Feasibility-technical 14/25 · Integration-points 20/25 · Risk-assessment 18/25
|
||||
|
||||
## Destination
|
||||
|
||||
A locked plan for exporting audit events.
|
||||
|
||||
## Ground rules
|
||||
|
||||
- \`AGENTS.md\` exists and governs.
|
||||
|
||||
## Question Checklist
|
||||
|
||||
<!-- Rebuilt from questions/ every session. -->
|
||||
|
||||
- [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
|
||||
ceiling](./questions/02-row-count-ceiling.md)
|
||||
- [ ] [Testing posture](./questions/03-testing-posture.md)
|
||||
- [ ] [Delivery channel](./questions/04-delivery-channel.md)
|
||||
- [ ] [Gone question](./questions/09-gone.md)
|
||||
|
||||
## Not yet specified
|
||||
|
||||
- How far back an export may reach.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Redesign of the schema.
|
||||
`;
|
||||
|
||||
function mapFixture() {
|
||||
const root = tmp("pf");
|
||||
write(root, "AGENTS.md", "# AGENTS.md\n");
|
||||
const pf = "specs/audit-export/pathfinder";
|
||||
write(root, `${pf}/map.md`, MAP);
|
||||
write(root, `${pf}/questions/00-codebase-context.md`, q("Codebase context", { type: "legwork · AFK", state: "resolved", claimed: "2026-08-01 09:00", resolved: "2026-08-01", answer: "Node.\n\n**Gist:** Node and Postgres." }));
|
||||
// An answer under State: open (a crash after writing the answer): reconcile resolves it and backfills the date.
|
||||
write(root, `${pf}/questions/01-export-format.md`, q("Export format", { claimed: "2026-08-02 10:00", locked: "yes", answer: "**Decision.** CSV.\n\n**Rejected**\n\n- *JSONL* - recipients use Excel.\n\n**Gist:** CSV with a BOM.", skipResolved: true }));
|
||||
// A stale claim with no answer: reset.
|
||||
write(root, `${pf}/questions/02-row-count-ceiling.md`, q("Row-count ceiling", { type: "research · AFK", state: "claimed", claimed: "2026-08-02 11:00", evidence: "- half done" }));
|
||||
write(root, `${pf}/questions/03-testing-posture.md`, q("Testing posture"));
|
||||
write(root, `${pf}/questions/04-delivery-channel.md`, q("Delivery channel", { blocked: "02" }));
|
||||
write(root, `${pf}/questions/05-siem-push.md`, q("SIEM push", { state: "out-of-scope" }));
|
||||
return { root, pf };
|
||||
}
|
||||
|
||||
test("pathfinder reconcile: files win, dates backfill, stale claims reset, rows keep their words", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
const dry = P("reconcile", "audit-export", "--dry-run");
|
||||
assert.equal(dry.code, 0, dry.stderr);
|
||||
assert.equal(read(root, `${pf}/map.md`), MAP, "dry-run writes nothing");
|
||||
const r = P("reconcile", "audit-export");
|
||||
assert.deepEqual(r.json.repairs.map((x) => [x.nn, x.repair]), [["01", "state-resolved"], ["01", "resolved-backfilled"], ["02", "stale-claim-reset"]]);
|
||||
assert.match(r.json.repairs[1].detail, /2026-08-02 \(from Claimed:\)/);
|
||||
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, /- \[ \] \[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.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`);
|
||||
assert.match(q1, /State: resolved\nBlocked by: none\nClaimed: 2026-08-02 10:00\nResolved: 2026-08-02\nLocked: yes/, "Resolved: inserted in schema order");
|
||||
assert.match(read(root, `${pf}/questions/02-row-count-ceiling.md`), /State: open\nBlocked by: none\nClaimed: none/);
|
||||
const again = P("reconcile", "audit-export");
|
||||
assert.deepEqual([again.json.repairs.length, again.json.mapChanges.length, again.json.mapWritten], [0, 0, false], "idempotent");
|
||||
});
|
||||
|
||||
test("pathfinder frontier, claim, resolve, rule-out", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
P("reconcile", "audit-export");
|
||||
let f = P("frontier", `${pf}`).json;
|
||||
assert.deepEqual(f.frontier.map((x) => x.nn), ["02", "03"]);
|
||||
assert.deepEqual(f.blocked.map((x) => [x.nn, x.blockedBy.map((b) => b.nn)]), [["04", ["02"]]]);
|
||||
assert.equal(f.nextNN, "10", "09 was linked from the map before reconcile dropped its row: never reissued");
|
||||
assert.match(read(root, `${pf}/map.md`), /^\*\*Confidence:\*\*.*\n\*\*Next NN:\*\* 10$/m, "reconcile keeps the high-water mark at the end of the header block");
|
||||
assert.deepEqual(f.counts, { resolved: 2, total: 5, outOfScope: 1, fog: 1 });
|
||||
assert.deepEqual(f.drift, []);
|
||||
assert.equal(P("claim", "audit-export", "04").code, 5, "blocked");
|
||||
assert.equal(P("claim", "audit-export", "05").code, 5, "out of scope");
|
||||
assert.equal(P("claim", "audit-export", "77").code, 3);
|
||||
const c = P("claim", "audit-export", "2");
|
||||
assert.equal(c.code, 0, c.stderr);
|
||||
assert.equal(c.json.claimed, NOW);
|
||||
assert.match(read(root, `${pf}/questions/02-row-count-ceiling.md`), /State: claimed\nBlocked by: none\nClaimed: 2026-08-03 14:05/);
|
||||
assert.match(read(root, `${pf}/map.md`), /- \[\/\] \[Row-count\n ceiling\]/);
|
||||
assert.equal(P("claim", "audit-export", "03").json.error, "claim-open", "one claim at a time");
|
||||
assert.equal(P("resolve", "audit-export", "02").json.error, "no-answer");
|
||||
const qp = path.join(root, pf, "questions/02-row-count-ceiling.md");
|
||||
fs.appendFileSync(qp, "\n## Answer\n\nFacts.\n");
|
||||
assert.equal(P("resolve", "audit-export", "02").json.error, "no-gist");
|
||||
fs.appendFileSync(qp, "\n**Gist:** 2M rows at the 99th percentile.\n");
|
||||
const res = P("resolve", "audit-export", "02");
|
||||
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, /- \[ \] \[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.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");
|
||||
});
|
||||
|
||||
test("pathfinder trail: exact footer for forms A, B and C", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
P("reconcile", "audit-export");
|
||||
P("claim", "audit-export", "03");
|
||||
const b = P("trail", "audit-export", "--form", "B", "--item", "Q1 Types", "--item", "Q2 Cadence", "--text");
|
||||
assert.equal(b.code, 0, b.stderr);
|
||||
assert.equal(b.stdout, [
|
||||
"🧭 audit-export · Working · 2/5 cleared",
|
||||
" START ●━●··○━◉··⊘··⊝ ····⚑",
|
||||
" ● 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.",
|
||||
"",
|
||||
"WAITING ON YOU · answer here, in this conversation:",
|
||||
"Q1 Types · Q2 Cadence",
|
||||
"",
|
||||
].join("\n"));
|
||||
assert.equal(P("trail", "audit-export", "--form", "B").code, 2, "Form B names its items");
|
||||
assert.equal(P("trail", "audit-export", "--form", "B", "--item", "1", "--item", "2", "--item", "3", "--item", "4").code, 5, "three-probe cap");
|
||||
assert.equal(P("trail", "audit-export", "--form", "C").json.error, "claim-open", "no menu while a claim is open");
|
||||
const a = P("trail", "audit-export", "--form", "A", "--text").stdout;
|
||||
assert.ok(a.endsWith("NEXT STEP · start a new conversation and run:\n`/plan2code-0-pathfinder specs/audit-export/pathfinder --web`\n"), a);
|
||||
fs.appendFileSync(path.join(root, pf, "questions/03-testing-posture.md"), "\n## Answer\n\nUnit; `Run after each phase`; `Critical paths`.\n\n**Gist:** Unit tests, run after each phase.\n");
|
||||
P("resolve", "audit-export", "03");
|
||||
const c = P("trail", "audit-export", "--form", "C", "--resolved-this-session", "3");
|
||||
assert.equal(c.code, 0, c.stderr);
|
||||
assert.ok(c.json.text.endsWith("OR START FRESH · new conversation, paste:\n`/plan2code-0-pathfinder specs/audit-export/pathfinder --web`"));
|
||||
assert.deepEqual(c.json.menu.options.map((o) => o.label), ["Row-count ceiling", "Start fresh"]);
|
||||
assert.equal(c.json.menu.recommended, "Start fresh", "the checkpoint after ~3 decisions");
|
||||
assert.equal(P("trail", "audit-export", "--form", "C").json.menu.recommended, "Row-count ceiling");
|
||||
});
|
||||
|
||||
test("pathfinder trail: a cleared map arrives; init first only while AGENTS.md is still missing", () => {
|
||||
const root = tmp("pfc");
|
||||
const pf = "specs/done/pathfinder";
|
||||
write(root, `${pf}/map.md`, MAP.replace("**Status:** Working", "**Status:** Cleared").replace("- `AGENTS.md` exists and governs.", "- `AGENTS.md` is absent; continued without it.").replace(/## Not yet specified\n\n- How far back an export may reach\.\n/, "## Not yet specified\n\n").replace("Feasibility-technical 14/25", "Feasibility-technical 22/25"));
|
||||
write(root, `${pf}/questions/00-codebase-context.md`, q("Codebase context", { state: "resolved", resolved: "2026-08-01", answer: "**Gist:** Node." }));
|
||||
write(root, `${pf}/questions/01-export-format.md`, q("Export format", { state: "resolved", resolved: "2026-08-02", answer: "**Gist:** CSV." }));
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
P("reconcile", "done");
|
||||
assert.equal(P("trail", "done", "--form", "A", "--text").stdout, [
|
||||
"🧭 done · Cleared · 2/2 cleared",
|
||||
" START ●━●━⚑ arrived",
|
||||
" Confidence: solid, but Requirements, Risk are borderline.",
|
||||
"",
|
||||
"NEXT STEP · start a new conversation and run:",
|
||||
"`/plan2code-init`, then `/plan2code-1-plan --web`",
|
||||
"",
|
||||
].join("\n"));
|
||||
write(root, "AGENTS.md", "# AGENTS.md\n");
|
||||
assert.match(P("trail", "done", "--form", "A", "--text").stdout, /run:\n`\/plan2code-1-plan --web`\n$/);
|
||||
assert.equal(P("trail", "done", "--form", "C").code, 5, "no menu on a cleared map");
|
||||
});
|
||||
|
||||
test("pathfinder gate: mechanical checks and hard caps", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
P("reconcile", "audit-export");
|
||||
let g = P("gate", "audit-export").json;
|
||||
assert.equal(g.mechanicalPass, false);
|
||||
const failed = g.checks.filter((c) => !c.pass).map((c) => c.id);
|
||||
assert.deepEqual(failed, ["no-open-claimed-blocked", "fog-empty", "hard-caps", "scores-at-least-18"]);
|
||||
assert.ok(g.caps.some((c) => c.dimension === "Requirements" && /not resolved/.test(c.why)));
|
||||
assert.ok(g.caps.some((c) => c.dimension === "Risk" && /Export format records no consequences/.test(c.why)));
|
||||
assert.equal(g.planDraftPath, "specs/audit-export/PLAN-DRAFT-20260803.md");
|
||||
// Settle everything.
|
||||
const qd = path.join(root, pf, "questions");
|
||||
fs.writeFileSync(path.join(qd, "01-export-format.md"), q("Export format", { state: "resolved", resolved: "2026-08-02", locked: "yes", answer: "CSV.\n\n**Consequences**\n\n- Excel.\n\n**Gist:** CSV." }));
|
||||
fs.writeFileSync(path.join(qd, "02-row-count-ceiling.md"), q("Row-count ceiling", { type: "research · AFK", state: "resolved", resolved: "2026-08-02", answer: "**Gist:** 2M." }));
|
||||
fs.writeFileSync(path.join(qd, "03-testing-posture.md"), q("Testing posture", { state: "resolved", resolved: "2026-08-02", answer: "Unit and integration. `Dedicated phase only`. `Moderate (~60-80%)`.\n\n**Gist:** Unit." }));
|
||||
fs.writeFileSync(path.join(qd, "04-delivery-channel.md"), q("Delivery channel", { state: "resolved", resolved: "2026-08-03", blocked: "02", answer: "**Gist:** Link." }));
|
||||
const mp = path.join(root, pf, "map.md");
|
||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- How far back an export may reach.\n", "").replace("Feasibility-technical 14/25", "Feasibility-technical 20/25"));
|
||||
P("reconcile", "audit-export");
|
||||
g = P("gate", "audit-export").json;
|
||||
assert.deepEqual(g.checks.filter((c) => !c.pass).map((c) => c.id), ["hard-caps"]);
|
||||
assert.match(g.caps[0].why, /research 02 Row-count ceiling is resolved with an empty ## Evidence/);
|
||||
fs.appendFileSync(path.join(qd, "02-row-count-ceiling.md"), "\n## Evidence\n\n- Query plan.\n\n**Research complete:** 2026-08-02\n");
|
||||
g = P("gate", "audit-export").json;
|
||||
assert.equal(g.mechanicalPass, true, JSON.stringify(g.checks));
|
||||
assert.ok(g.judgment.length >= 2, "the gate names what stays judgment");
|
||||
});
|
||||
|
||||
test("pathfinder lint: loop tokens, checkboxes, reserved names, schema, cycles, scraper bait", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
P("reconcile", "audit-export");
|
||||
let l = P("lint", "audit-export");
|
||||
assert.equal(l.code, 0, JSON.stringify(l.json.problems));
|
||||
const qd = path.join(root, pf, "questions");
|
||||
fs.appendFileSync(path.join(qd, "03-testing-posture.md"), "\n- [ ] a checkbox\nTASK_COMPLETE\n");
|
||||
fs.writeFileSync(path.join(qd, "06-loop-a.md"), q("Loop A", { blocked: "07" }));
|
||||
fs.writeFileSync(path.join(qd, "07-loop-b.md"), q("Loop B", { blocked: "06", type: "chat · HITL" }));
|
||||
write(root, `${pf}/overview.md`, "nope");
|
||||
write(root, `${pf}/briefs/brief-20260803.md`, "Requirements 18 and 90%\n");
|
||||
write(root, "specs/audit-export/PLAN-DRAFT-20260803.md", "**Charted by:** `/plan2code-0-pathfinder`\n**Confidence:** 85%\n| Requirements | 11 |\n");
|
||||
l = P("lint", "audit-export");
|
||||
assert.equal(l.code, 4);
|
||||
const msgs = l.json.problems.map((p) => `${p.file}: ${p.message}`).join("\n");
|
||||
for (const re of [/03-testing-posture\.md: has a checkbox/, /03-testing-posture\.md: contains the loop completion token TASK_COMPLETE/, /cycle 06 -> 07 -> 06|cycle 07 -> 06 -> 07/, /Type: "chat · HITL"/, /overview\.md is a reserved name/, /brief-20260803\.md: metrics-scraper bait \(bare Requirements/, /brief-20260803\.md: contains %/, /PLAN-DRAFT-20260803\.md: metrics-scraper bait \(overall confidence with %/, /PLAN-DRAFT-20260803\.md: metrics-scraper bait \(bare Requirements/]) {
|
||||
assert.match(msgs, re);
|
||||
}
|
||||
});
|
||||
|
||||
test("pathfinder brief-data: range filtering, frontier notes, plain sections", () => {
|
||||
const { root } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
P("reconcile", "audit-export");
|
||||
const today = P("brief-data", "audit-export").json;
|
||||
assert.equal(today.file, "specs/audit-export/pathfinder/briefs/brief-20260803.md");
|
||||
assert.deepEqual(today.decided, []);
|
||||
assert.equal(today.note, "No decisions were recorded in this period.");
|
||||
const full = P("brief-data", "audit-export", "--range", "full").json;
|
||||
assert.deepEqual(full.decided.map((d) => d.name), ["Codebase context", "Export format"]);
|
||||
assert.deepEqual(full.decided[1].rejected, ["*JSONL* - recipients use Excel."]);
|
||||
assert.equal(full.decided[1].hardToReverse, true);
|
||||
assert.equal(full.progress, "2 of 5 decisions made");
|
||||
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.");
|
||||
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"]);
|
||||
assert.equal(P("brief-data", "audit-export", "--range", "2026-08-05..2026-08-01").code, 2);
|
||||
assert.equal(P("brief-data", "audit-export", "--range", "yesterday").code, 2);
|
||||
assert.equal(P("brief-data", "nope").code, 3);
|
||||
});
|
||||
|
||||
/* ================================================= verification regressions */
|
||||
|
||||
test("pathfinder: a ## Answer inside a fenced sketch is content, not an answer", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const qd = path.join(root, pf, "questions");
|
||||
fs.writeFileSync(path.join(qd, "03-testing-posture.md"), q("Testing posture", { type: "sketch · HITL", evidence: "```markdown\n## Answer\n\n**Gist:** fake\n```" }));
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
const r = P("reconcile", "audit-export");
|
||||
assert.ok(!r.json.repairs.some((x) => x.nn === "03"), JSON.stringify(r.json.repairs));
|
||||
assert.match(read(root, `${pf}/questions/03-testing-posture.md`), /State: open/);
|
||||
});
|
||||
|
||||
test("pathfinder reconcile: an unrepairable file is skipped and named, nothing half-written, its row kept", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
write(root, `${pf}/questions/07-bare.md`, `${B}\n\n# Bare\n\n## Answer\n\nYes.\n`);
|
||||
const mp = path.join(root, pf, "map.md");
|
||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- [ ] [Gone question]", "- [ ] [Bare](./questions/07-bare.md)\n- [ ] [Gone question]"));
|
||||
const r = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["reconcile", "audit-export", "--root", root]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.deepEqual(r.json.findings.map((f) => [f.file, f.finding]), [["07-bare.md", "unrepairable"]]);
|
||||
assert.match(read(root, `${pf}/questions/01-export-format.md`), /State: resolved/, "the other repairs still landed");
|
||||
assert.equal(read(root, `${pf}/questions/07-bare.md`), `${B}\n\n# Bare\n\n## Answer\n\nYes.\n`, "left untouched");
|
||||
assert.ok(!r.json.mapChanges.some((c) => c.file === "07-bare.md"), JSON.stringify(r.json.mapChanges));
|
||||
assert.match(read(root, `${pf}/map.md`), /^- \[.\] \[Bare\]\(\.\/questions\/07-bare\.md\)$/m, "its row survives");
|
||||
});
|
||||
|
||||
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(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"));
|
||||
const map = read(root, `${pf}/map.md`);
|
||||
assert.match(map, /### Group two\n\n- \[ \] \[Export format\]\(\.\/questions\/01-export-format\.md\)\n/, "the group heading keeps its place and the row its old tail is gone");
|
||||
});
|
||||
|
||||
test("pathfinder gate: testing posture by keyword (never from Rejected), research-style consequences count", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const qd = path.join(root, pf, "questions");
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
fs.writeFileSync(path.join(qd, "03-testing-posture.md"), q("Testing posture", { state: "resolved", resolved: "2026-08-02", answer: "Unit + integration, run after each phase, moderate coverage.\n\n**Gist:** Unit." }));
|
||||
fs.writeFileSync(path.join(qd, "01-export-format.md"), q("Export format", { state: "resolved", resolved: "2026-08-02", locked: "yes", answer: "### What this implies\n\n- Excel only.\n\n**Gist:** CSV." }));
|
||||
P("reconcile", "audit-export");
|
||||
let caps = P("gate", "audit-export").json.caps;
|
||||
assert.ok(!caps.some((c) => c.dimension === "Requirements"), JSON.stringify(caps));
|
||||
assert.ok(!caps.some((c) => c.dimension === "Risk"), JSON.stringify(caps));
|
||||
fs.writeFileSync(path.join(qd, "03-testing-posture.md"), q("Testing posture", { state: "resolved", resolved: "2026-08-02", answer: "Unit tests.\n\n**Rejected**\n\n- Run after each phase with Moderate coverage: too slow.\n\n**Gist:** Unit." }));
|
||||
caps = P("gate", "audit-export").json.caps;
|
||||
assert.ok(caps.some((c) => c.dimension === "Requirements" && /cadence/.test(c.why)), "a cadence named only as rejected does not count");
|
||||
});
|
||||
|
||||
test("pathfinder: Form C needs a frontier; names come from the rows; NN is never handed out twice", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
P("reconcile", "audit-export");
|
||||
const mp = path.join(root, pf, "map.md");
|
||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("[Testing posture](", "[How we test]("));
|
||||
const c = P("trail", "audit-export", "--form", "C").json;
|
||||
assert.deepEqual(c.menu.options.map((o) => o.label), ["Row-count ceiling", "How we test", "Start fresh"]);
|
||||
fs.rmSync(path.join(root, pf, "questions/05-siem-push.md"));
|
||||
// Without the high-water line (an older map), the links alone still count.
|
||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace(/^\*\*Next NN:\*\*.*\n/m, ""));
|
||||
assert.equal(P("frontier", "audit-export").json.nextNN, "06", "05 is still linked from the map");
|
||||
const qd = path.join(root, pf, "questions");
|
||||
fs.writeFileSync(path.join(qd, "02-row-count-ceiling.md"), q("Row-count ceiling", { blocked: "04" }));
|
||||
fs.writeFileSync(path.join(qd, "03-testing-posture.md"), q("Testing posture", { blocked: "04 (needs the channel)" }));
|
||||
P("reconcile", "audit-export");
|
||||
const none = P("trail", "audit-export", "--form", "C");
|
||||
assert.equal(none.code, 5);
|
||||
assert.equal(none.json.error, "no-frontier");
|
||||
});
|
||||
|
||||
test("pathfinder lint: map %, brief scores and checkboxes, Planning Metrics in a pathfinder draft", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["reconcile", "audit-export", "--root", root]);
|
||||
const mp = path.join(root, pf, "map.md");
|
||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8") + "\n80% sure.\n");
|
||||
write(root, `${pf}/briefs/brief-20260803.md`, "Solid at 22/25.\n- [ ] todo\n");
|
||||
write(root, "specs/audit-export/PLAN-DRAFT-20260803.md", "**Charted by:** `/plan2code-0-pathfinder`\n\n## Planning Metrics\n");
|
||||
const l = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["lint", "audit-export", "--root", root]).json;
|
||||
const msgs = l.problems.map((p) => `${p.level} ${p.message}`).join("\n");
|
||||
assert.match(msgs, /warn contains %; the map/);
|
||||
assert.match(msgs, /error contains a raw NN\/25 score/);
|
||||
assert.match(msgs, /error has a checkbox line/);
|
||||
assert.match(msgs, /error has a ## Planning Metrics section/);
|
||||
});
|
||||
|
||||
test("pathfinder brief-data: calendar dates only, no future since, no NNs or links in what a brief prints", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
P("reconcile", "audit-export");
|
||||
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(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.waiting.find((w) => w.name === "Delivery channel").waitingOn, ["a question that no longer exists"]);
|
||||
});
|
||||
|
||||
/* ===================================================== review-fix regressions */
|
||||
|
||||
test("pathfinder: claim, resolve and rule-out honour --dry-run", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
P("reconcile", "audit-export");
|
||||
const snap = () => fs.readdirSync(path.join(root, pf, "questions")).map((n) => read(root, `${pf}/questions/${n}`)).concat(read(root, `${pf}/map.md`));
|
||||
const before = snap();
|
||||
const c = P("claim", "audit-export", "03", "--dry-run");
|
||||
assert.equal(c.code, 0, c.stderr);
|
||||
assert.deepEqual([c.json.dryRun, c.json.mapWritten], [true, false]);
|
||||
assert.deepEqual(snap(), before, "claim --dry-run leaves every file unchanged");
|
||||
fs.appendFileSync(path.join(root, pf, "questions/03-testing-posture.md"), "\n## Answer\n\nUnit.\n\n**Gist:** Unit.\n");
|
||||
const withAnswer = snap();
|
||||
const r = P("resolve", "audit-export", "03", "--dry-run");
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.deepEqual([r.json.dryRun, r.json.mapWritten], [true, false]);
|
||||
assert.deepEqual(snap(), withAnswer, "resolve --dry-run writes nothing");
|
||||
const o = P("rule-out", "audit-export", "02", "--reason", "not ours", "--dry-run");
|
||||
assert.equal(o.code, 0, o.stderr);
|
||||
assert.deepEqual([o.json.dryRun, o.json.mapWritten], [true, false]);
|
||||
assert.deepEqual(snap(), withAnswer, "rule-out --dry-run writes nothing");
|
||||
const real = P("claim", "audit-export", "02");
|
||||
assert.deepEqual([real.json.dryRun, real.json.mapWritten], [false, true]);
|
||||
});
|
||||
|
||||
test("pathfinder: a deleted top NN is never reissued, linked from an answer or not", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
const qd = path.join(root, pf, "questions");
|
||||
const mp = path.join(root, pf, "map.md");
|
||||
// Start from a map with no high-water line and no stale 09 link: reconcile adds the line.
|
||||
fs.writeFileSync(mp, MAP.replace("- [ ] [Gone question](./questions/09-gone.md)\n", ""));
|
||||
fs.writeFileSync(path.join(qd, "06-subsumed.md"), q("Subsumed"));
|
||||
let r = P("reconcile", "audit-export");
|
||||
assert.deepEqual(r.json.mapChanges.find((c) => c.change === "next-nn"), { change: "next-nn", from: null, to: "07" });
|
||||
assert.match(read(root, `${pf}/map.md`), /^\*\*Next NN:\*\* 07$/m);
|
||||
// resolve.md: delete the subsumed file, reconcile drops its row, the absorbing answer links to it.
|
||||
fs.rmSync(path.join(qd, "06-subsumed.md"));
|
||||
fs.appendFileSync(path.join(qd, "04-delivery-channel.md"), "\n## Answer\n\nAbsorbed [Subsumed](./questions/06-subsumed.md).\n\n**Gist:** Link.\n");
|
||||
r = P("reconcile", "audit-export");
|
||||
assert.ok(r.json.mapChanges.some((c) => c.change === "row-dropped" && c.file === "06-subsumed.md"));
|
||||
assert.ok(!read(root, `${pf}/map.md`).includes("06-subsumed"), "the map no longer links it");
|
||||
assert.equal(P("frontier", "audit-export").json.nextNN, "07", "linked from an answer");
|
||||
// Even with the answer's link gone, the high-water mark holds.
|
||||
fs.writeFileSync(path.join(qd, "04-delivery-channel.md"), q("Delivery channel", { blocked: "02" }));
|
||||
assert.equal(P("frontier", "audit-export").json.nextNN, "07", "the **Next NN:** line");
|
||||
assert.equal(P("reconcile", "audit-export").json.nextNN, "07", "reconcile never lowers it");
|
||||
assert.equal(P("lint", "audit-export").code, 0, "lint accepts the line");
|
||||
});
|
||||
|
||||
test("pathfinder: a name with brackets round-trips; reconcile is stable", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
write(root, `${pf}/questions/06-retention.md`, q("Retention [legal] hold"));
|
||||
for (let i = 0; i < 3; i++) assert.equal(P("reconcile", "audit-export").code, 0);
|
||||
const map = read(root, `${pf}/map.md`);
|
||||
assert.equal(map.split("\n").filter((l) => l.includes("06-retention.md")).length, 1, map);
|
||||
assert.match(map, /^- \[ \] \[Retention \[legal\] hold\]\(\.\/questions\/06-retention\.md\)$/m);
|
||||
assert.deepEqual(P("frontier", "audit-export").json.drift, []);
|
||||
assert.equal(P("reconcile", "audit-export").json.mapWritten, false);
|
||||
});
|
||||
|
||||
test("pathfinder: an author's sub-bullet under a row survives resolve, rule-out and a marker change", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
const mp = path.join(root, pf, "map.md");
|
||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8")
|
||||
.replace("- [ ] [Testing posture](./questions/03-testing-posture.md)", "- [ ] [Testing posture](./questions/03-testing-posture.md)\n - note: ask Dana first")
|
||||
.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");
|
||||
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.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.deepEqual(P("frontier", "audit-export").json.drift, []);
|
||||
});
|
||||
|
||||
test("pathfinder: AGENTS.md absent reads in the canonical and the skill's own wording", () => {
|
||||
for (const line of ["- `AGENTS.md` is absent.", "- No `AGENTS.md`.", "- No AGENTS.md; init skipped."]) {
|
||||
const { root, pf } = mapFixture();
|
||||
fs.rmSync(path.join(root, "AGENTS.md"));
|
||||
const mp = path.join(root, pf, "map.md");
|
||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- `AGENTS.md` exists and governs.", line));
|
||||
const g = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["gate", "audit-export", "--root", root]).json;
|
||||
assert.deepEqual([g.agentsAbsent, g.initFirst], [true, true], line);
|
||||
}
|
||||
});
|
||||
|
||||
test("pathfinder lint: a failure carries error, message and next, on stderr too", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["reconcile", "audit-export", "--root", root]);
|
||||
fs.appendFileSync(path.join(root, pf, "questions/03-testing-posture.md"), "\n- [ ] a checkbox\n");
|
||||
const l = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["lint", "audit-export", "--root", root]);
|
||||
assert.equal(l.code, 4);
|
||||
assert.deepEqual([l.json.ok, l.json.error, l.json.message, l.json.next], [false, "lint-failed", "lint found 1 error.", "Fix each error in problems, then rerun lint."]);
|
||||
assert.equal(l.json.errors, 1);
|
||||
assert.equal(l.json.problems.filter((p) => p.level === "error").length, 1);
|
||||
assert.match(l.stderr, /^error: lint found 1 error\.\nnext: Fix each error in problems, then rerun lint\.\n$/);
|
||||
});
|
||||
|
||||
test("pathfinder lint: densely blocked questions check in linear time", () => {
|
||||
const root = tmp("pfd");
|
||||
const pf = "specs/dense/pathfinder";
|
||||
write(root, `${pf}/map.md`, MAP);
|
||||
write(root, `${pf}/questions/00-codebase-context.md`, q("Codebase context", { type: "legwork · AFK", state: "resolved", resolved: "2026-08-01", answer: "**Gist:** Node." }));
|
||||
for (let i = 1; i < 40; i++) {
|
||||
const nn = String(i).padStart(2, "0");
|
||||
const blocked = i === 1 ? "00" : [i - 1, i - 2].map((n) => String(n).padStart(2, "0")).join(", ");
|
||||
write(root, `${pf}/questions/${nn}-q${nn}.md`, q(`Q ${nn}`, { blocked }));
|
||||
}
|
||||
const t0 = Date.now();
|
||||
const l = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["lint", "dense", "--root", root]);
|
||||
const ms = Date.now() - t0;
|
||||
assert.ok(!(l.json.problems || []).some((p) => /cycle/.test(p.message)), JSON.stringify(l.json.problems));
|
||||
assert.ok(ms < 2000, `lint took ${ms} ms`);
|
||||
// A cycle is still found, once, in the same format.
|
||||
write(root, `${pf}/questions/01-q01.md`, q("Q 01", { blocked: "39" }));
|
||||
const c = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["lint", "dense", "--root", root]).json;
|
||||
const cycles = c.problems.filter((p) => /cycle/.test(p.message));
|
||||
assert.ok(cycles.length >= 1, JSON.stringify(c.problems));
|
||||
assert.match(cycles[0].message, /^Blocked by: cycle (\d\d)( -> \d\d)+ -> \1;/);
|
||||
});
|
||||
|
||||
test("pathfinder: a one-digit NN is question 0N everywhere, and lint asks for the rename", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
write(root, `${pf}/questions/6-short.md`, q("Short"));
|
||||
write(root, `${pf}/questions/07-after.md`, q("After", { blocked: "06" }));
|
||||
P("reconcile", "audit-export");
|
||||
const f = P("frontier", "audit-export").json;
|
||||
assert.ok(f.frontier.some((x) => x.nn === "06" && x.name === "Short"), JSON.stringify(f.frontier));
|
||||
assert.deepEqual(f.blocked.find((x) => x.nn === "07").blockedBy, [{ nn: "06", name: "Short", state: "open" }]);
|
||||
assert.equal(P("claim", "audit-export", "6").json.nn, "06");
|
||||
const l = P("lint", "audit-export").json;
|
||||
assert.ok(l.problems.some((p) => p.level === "error" && /6-short\.md$/.test(p.file) && /rename it to 06-short\.md/.test(p.message)), JSON.stringify(l.problems));
|
||||
});
|
||||
|
||||
test("pathfinder: a duplicate map row is reported as drift and dropped by name", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
P("reconcile", "audit-export");
|
||||
const mp = path.join(root, pf, "map.md");
|
||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- [ ] [Testing posture](./questions/03-testing-posture.md)", "- [ ] [Testing posture](./questions/03-testing-posture.md)\n- [ ] [Testing again](./questions/03-testing-posture.md)"));
|
||||
assert.ok(P("frontier", "audit-export").json.drift.includes("map row 03-testing-posture.md appears 2 times"));
|
||||
const r = P("reconcile", "audit-export");
|
||||
assert.deepEqual(r.json.mapChanges, [{ change: "row-dropped", file: "03-testing-posture.md", name: "Testing again", why: "duplicate row" }]);
|
||||
assert.equal(read(root, `${pf}/map.md`).split("\n").filter((l) => l.includes("03-testing-posture.md")).length, 1);
|
||||
assert.deepEqual(P("frontier", "audit-export").json.drift, []);
|
||||
});
|
||||
|
||||
test("pathfinder lint: the chart.md map template lints clean", () => {
|
||||
const chart = fs.readFileSync(path.join(SKILLS, "plan2code-0-pathfinder", "references", "chart.md"), "utf8");
|
||||
const template = chart.split("## The `map.md` template")[1].match(/```markdown\r?\n([\s\S]*?)\r?\n```/)[1];
|
||||
assert.match(template, /^\*\*Next NN:\*\* \d+$/m, "the template carries the high-water line");
|
||||
const root = tmp("pft");
|
||||
write(root, "specs/audit-log-export/pathfinder/map.md", template + "\n");
|
||||
const l = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["lint", "audit-log-export", "--root", root]);
|
||||
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));
|
||||
});
|
||||
@@ -0,0 +1,625 @@
|
||||
// Tests for the skill-script plumbing (installer) and the shared scripts in src/skill-scripts/.
|
||||
//
|
||||
// See skill-script-helpers.mjs for how these run.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
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";
|
||||
|
||||
/* ================================================================ install */
|
||||
|
||||
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")));
|
||||
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}`);
|
||||
}
|
||||
assert.ok(!fs.existsSync(path.join(SKILLS, "plan2code", "scripts")), "the dashboard needs no scripts");
|
||||
const v = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version;
|
||||
assert.equal(JSON.parse(fs.readFileSync(path.join(SKILLS, "plan2code-4-finalize", "scripts", "version.json"), "utf8")).version, v);
|
||||
});
|
||||
|
||||
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)) {
|
||||
const dir = path.join(SKILLS, skill);
|
||||
const texts = [];
|
||||
const walk = (d) => {
|
||||
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
||||
const p = path.join(d, e.name);
|
||||
if (e.isDirectory()) {
|
||||
if (e.name !== "web-console" && e.name !== "scripts") walk(p);
|
||||
} else if (e.name.endsWith(".md")) texts.push(fs.readFileSync(p, "utf8"));
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
const named = new Set();
|
||||
for (const t of texts) for (const m of t.matchAll(/<S>\/([a-z-]+\.mjs)/g)) named.add(m[1]);
|
||||
for (const script of named) {
|
||||
const p = path.join(dir, "scripts", script);
|
||||
assert.ok(fs.existsSync(p), `${skill} names <S>/${script} but scripts/${script} is not shipped`);
|
||||
const r = spawnSync(process.execPath, [p, "--help"], { encoding: "utf8" });
|
||||
assert.equal(r.status, 0, `${skill}/${script} --help`);
|
||||
assert.match(r.stdout, /Exit:/, `${skill}/${script} --help documents its exit codes`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("scripts are self-contained: built-ins and siblings only", () => {
|
||||
for (const dir of [path.join(ROOT, "src", "skill-scripts"), ...fs.readdirSync(path.join(ROOT, "src")).filter((n) => n.endsWith("-scripts")).map((n) => path.join(ROOT, "src", n))]) {
|
||||
for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".mjs"))) {
|
||||
const t = fs.readFileSync(path.join(dir, f), "utf8");
|
||||
for (const m of t.matchAll(/^import .* from "([^"]+)";$/gm)) {
|
||||
assert.ok(m[1].startsWith("node:") || m[1] === "./common.mjs", `${f} imports ${m[1]}`);
|
||||
}
|
||||
assert.ok(!/[\u0000-\u0008]/.test(t), `${f} contains a control character (an escape lost in an edit?)`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/* ================================================================ specs.mjs */
|
||||
|
||||
const OVERVIEW = `# Lunch vote
|
||||
|
||||
## Phase Checklist
|
||||
|
||||
- [x] **[Phase 1: Data model](./phase-1.md)** - 3 tasks.
|
||||
- [/] [Phase 2: API](./phase-2.md) _(2 tasks)_
|
||||
- [ ] **Phase 3 — Web UI** — see [phase-3.md](./phase-3.md)
|
||||
- [ ] [Phase 4: Docs](./phase-4.md): readme **[Milestone 1]**
|
||||
|
||||
## Parallel Execution Groups
|
||||
|
||||
| Group | Phases | Reason |
|
||||
|-------|--------|--------|
|
||||
| A | 3, 4 | Separate files |
|
||||
| B (sequential) | 1, 2 | Not parallel |
|
||||
|
||||
## Quick Reference
|
||||
`;
|
||||
|
||||
function specFixture() {
|
||||
const root = tmp("specs");
|
||||
write(root, "AGENTS.md", "# AGENTS.md\n");
|
||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW);
|
||||
write(root, "specs/lunch-vote/PLAN-DRAFT-20260801.md", "# Plan\n\n**Status:** Complete\n");
|
||||
write(root, "specs/lunch-vote/phase-1.md", phase(1, "Complete", [["x", "1.1"], ["x", "1.2"], ["x", "1.T"]]));
|
||||
write(root, "specs/lunch-vote/phase-2.md", phase(2, "In Progress", [["x", "2.1"], [" ", "2.2"]]));
|
||||
write(root, "specs/lunch-vote/phase-3.md", phase(3, "Not Started", [[" ", "3.1"], [" ", "3.2"], [" ", "3.2a"], [" ", "3.4"]], "\n## Phase Testing\n\n- [ ] Run unit tests\n"));
|
||||
write(root, "specs/lunch-vote/phase-4.md", phase(4, "Not Started", [["!", "4.1"], ["?", "4.2"]]));
|
||||
write(root, "specs/idea-only/pathfinder/map.md", "# Map\n\n**Status:** Working\n");
|
||||
write(root, "specs--completed/old-one/overview.md", "# Old\n");
|
||||
return root;
|
||||
}
|
||||
|
||||
test("specs list: active specs with state, drafts and archives, never specs--completed", () => {
|
||||
const root = specFixture();
|
||||
const r = runScript("plan2code-1-plan", "specs.mjs", ["list", "--root", root]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
const names = r.json.specs.map((s) => s.name).sort();
|
||||
assert.deepEqual(names, ["idea-only", "lunch-vote"]);
|
||||
const lv = r.json.specs.find((s) => s.name === "lunch-vote");
|
||||
assert.equal(lv.state, "building");
|
||||
assert.deepEqual(lv.planDrafts, [{ file: "PLAN-DRAFT-20260801.md", archived: false, status: "Complete" }]);
|
||||
assert.equal(lv.phaseFiles, 4);
|
||||
assert.deepEqual(r.json.completed, ["old-one"]);
|
||||
assert.equal(r.json.hasAgents, true);
|
||||
});
|
||||
|
||||
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]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
const j = r.json;
|
||||
assert.deepEqual(j.phases.map((p) => [p.number, p.name, p.checklist]), [
|
||||
[1, "Data model", "complete"],
|
||||
[2, "API", "in-progress"],
|
||||
[3, "Web UI", "pending"],
|
||||
[4, "Docs", "pending"],
|
||||
]);
|
||||
assert.deepEqual(j.parallelGroups.map((g) => [g.id, g.phases]), [["A", [3, 4]]], "a group labelled sequential is not a parallel group");
|
||||
assert.deepEqual(j.totals, { total: 11, complete: 4, assumed: 1, pending: 5, "in-progress": 0, blocked: 1, unknown: 0, completed: 5, incomplete: 5 });
|
||||
assert.equal(j.completionPercent, 45);
|
||||
assert.equal(j.phases[0].tasks.total, 3, "a named testing task (1.T) counts");
|
||||
assert.equal(j.phases[0].goal, "Phase 1 builds the thing.");
|
||||
const codes = j.checks.map((c) => c.code);
|
||||
assert.ok(j.checks.some((c) => c.code === "task-numbering" && /expected 3\.3, found 3\.4/.test(c.message)), JSON.stringify(j.checks));
|
||||
assert.ok(!codes.includes("criteria-checkbox"), "a Phase Testing checkbox block is the template's own");
|
||||
assert.ok(j.checks.some((c) => c.code === "unchecked-with-done-tasks" && /Phase 4/.test(c.message)), "an assumed [?] task counts as done, so a [ ] phase holding one is flagged");
|
||||
assert.equal(j.next.action, "ask-resume");
|
||||
assert.equal(j.next.phase.number, 2);
|
||||
assert.deepEqual(j.pending.map((p) => p.number), [2, 3, 4]);
|
||||
});
|
||||
|
||||
test("specs status: the implement selection table", () => {
|
||||
const root = specFixture();
|
||||
const ov = (m1, m2, m3, m4) => OVERVIEW.replace("- [x] **[Phase 1", `- [${m1}] **[Phase 1`).replace("- [/] [Phase 2", `- [${m2}] [Phase 2`).replace("- [ ] **Phase 3", `- [${m3}] **Phase 3`).replace("- [ ] [Phase 4", `- [${m4}] [Phase 4`);
|
||||
const next = (...m) => {
|
||||
write(root, "specs/lunch-vote/overview.md", ov(...m));
|
||||
return runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json.next;
|
||||
};
|
||||
assert.deepEqual(next("x", "x", " ", " ").action, "choose");
|
||||
assert.deepEqual(next("x", "x", " ", " ").options.map((o) => o.number), [3, 4]);
|
||||
assert.ok(next("x", "x", "/", "/").warning, "all options already [/] warns about duplicated work");
|
||||
assert.equal(next("x", " ", " ", " ").action, "auto-start");
|
||||
assert.equal(next("x", "x", "x", " ").action, "auto-start");
|
||||
assert.equal(next("x", "x", "x", "x").action, "none");
|
||||
assert.equal(next("x", "x", "x", "x").reason, "every phase is complete");
|
||||
});
|
||||
|
||||
test("specs status: drift between the checklist and the phase files is an error", () => {
|
||||
const root = specFixture();
|
||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("- [/] [Phase 2", "- [x] [Phase 2"));
|
||||
write(root, "specs/lunch-vote/phase-5.md", phase(5, "Not Started", [[" ", "5.1"]]));
|
||||
const j = runScript("plan2code-1b-revise-plan", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
assert.ok(j.checks.some((c) => c.code === "checked-with-open-tasks" && /Phase 2/.test(c.message)));
|
||||
assert.ok(j.checks.some((c) => c.code === "missing-checklist-row" && /phase-5/.test(c.message)));
|
||||
});
|
||||
|
||||
test("specs status: errors are actionable and exit-coded", () => {
|
||||
const root = specFixture();
|
||||
const miss = runScript("plan2code-1-plan", "specs.mjs", ["status", "nope", "--root", root]);
|
||||
assert.equal(miss.code, 3);
|
||||
assert.equal(miss.json.error, "spec-not-found");
|
||||
assert.match(miss.json.next, /specs\.mjs list/);
|
||||
assert.equal(runScript("plan2code-1-plan", "specs.mjs", ["frobnicate"]).code, 2);
|
||||
assert.equal(runScript("plan2code-1-plan", "specs.mjs", ["status", "lunch-vote", "--bogus"]).code, 2);
|
||||
const archived = runScript("plan2code-4-finalize", "specs.mjs", ["mark", "specs--completed/old-one", "--phase", "1", "--to", "done", "--root", root]);
|
||||
assert.equal(archived.code, 5);
|
||||
});
|
||||
|
||||
test("specs mark: transitions, the no-reset rule, dry-run and idempotence", () => {
|
||||
const root = specFixture();
|
||||
const S = (...a) => runScript("plan2code-3-implement", "specs.mjs", [...a, "--root", root]);
|
||||
const dry = S("mark", "lunch-vote", "--phase", "3", "--to", "in-progress", "--dry-run");
|
||||
assert.equal(dry.code, 0);
|
||||
assert.equal(dry.json.changed, true);
|
||||
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.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);
|
||||
assert.equal(reset.json.error, "no-reset");
|
||||
const done = S("mark", "lunch-vote", "--phase", "2", "--to", "done");
|
||||
assert.equal(done.code, 0);
|
||||
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[x\] \[Phase 2: API\]/);
|
||||
assert.match(read(root, "specs/lunch-vote/phase-2.md"), /^\*\*Status:\*\* Complete$/m);
|
||||
assert.equal(S("mark", "lunch-vote", "--phase", "9", "--to", "done").code, 3);
|
||||
assert.equal(S("mark", "lunch-vote", "--phase", "1", "--to", "open").code, 0, "re-opening a complete phase (revise-plan) is allowed");
|
||||
});
|
||||
|
||||
test("specs metrics: document and finalize comments, judgment fields from --set", () => {
|
||||
const root = specFixture();
|
||||
const S = (...a) => runScript("plan2code-2-document", "specs.mjs", [...a, "--root", root]);
|
||||
assert.equal(S("metrics", "lunch-vote", "--step", "document").code, 2, "verification_items_added is the agent's number");
|
||||
write(root, "specs/lunch-vote/phase-3.md", read(root, "specs/lunch-vote/phase-3.md") + "\n<!-- VERIFICATION: Added (FR-2) -->\n");
|
||||
const doc = S("metrics", "lunch-vote", "--step", "document", "--set", "verification_items_added=1");
|
||||
assert.equal(doc.code, 0, doc.stderr);
|
||||
assert.equal(doc.json.comment, '<!-- METRICS_JSON {"step": "document", "total_tasks": 11, "tasks_per_phase": [3, 2, 4, 2], "phase_count": 4, "parallel_groups_identified": 1, "verification_items_added": 1} -->');
|
||||
assert.equal(doc.json.verificationCommentsFound, 1);
|
||||
assert.equal(S("metrics", "lunch-vote", "--step", "finalize").code, 2);
|
||||
const fin = S("metrics", "lunch-vote", "--step", "finalize", "--set", "verification_failures_found=1", "--set", "documentation_updates_needed=2");
|
||||
assert.equal(fin.json.comment, '<!-- METRICS_JSON {"step": "finalize", "completion_rate_at_audit": 0.45, "tasks_completed": 5, "tasks_total": 11, "verification_failures_found": 1, "documentation_updates_needed": 2} -->');
|
||||
});
|
||||
|
||||
test("specs archive: dry-run, move, refuse to clobber", () => {
|
||||
const root = specFixture();
|
||||
const S = (...a) => runScript("plan2code-4-finalize", "specs.mjs", [...a, "--root", root]);
|
||||
const dry = S("archive", "lunch-vote", "--dry-run");
|
||||
assert.equal(dry.code, 0);
|
||||
assert.ok(dry.json.files.includes("overview.md"));
|
||||
assert.ok(fs.existsSync(path.join(root, "specs/lunch-vote")));
|
||||
const moved = S("archive", "lunch-vote");
|
||||
assert.equal(moved.code, 0, moved.stdout);
|
||||
assert.equal(moved.json.sourceRemoved, true);
|
||||
assert.equal(moved.json.filesAtTarget, dry.json.files.length);
|
||||
assert.ok(fs.existsSync(path.join(root, "specs--completed/lunch-vote/phase-4.md")));
|
||||
write(root, "specs/idea-only/x.md", "x");
|
||||
fs.mkdirSync(path.join(root, "specs--completed/idea-only"));
|
||||
const clash = S("archive", "idea-only");
|
||||
assert.equal(clash.code, 5);
|
||||
assert.ok(fs.existsSync(path.join(root, "specs/idea-only/x.md")), "nothing moved on refusal");
|
||||
const after = S("status", "specs--completed/lunch-vote");
|
||||
assert.equal(after.code, 0, "status reads an archived spec (Finalize after Step 6)");
|
||||
});
|
||||
|
||||
/* ============================================================ commit-msg.mjs */
|
||||
|
||||
test("commit-msg: ticket from the branch, the three -m flags, subject rules", () => {
|
||||
const repo = tmp("commit");
|
||||
const g = gitInit(repo, "feature/ABC-10968-export-csv");
|
||||
write(repo, "a.txt", "a");
|
||||
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");
|
||||
assert.equal(ok.code, 0, ok.stderr);
|
||||
assert.equal(ok.json.ticket, "ABC-10968");
|
||||
assert.equal(ok.json.command, 'git add -A && git commit -m "Add the export endpoint" -m "ABC-10968" -m "AI Assisted"');
|
||||
assert.equal(ok.json.message, "Add the export endpoint\n\nABC-10968\nAI Assisted");
|
||||
assert.equal(C("--subject", "x".repeat(101)).code, 4);
|
||||
assert.equal(C("--subject", 'say "hi"').code, 4);
|
||||
assert.equal(C("--subject", "costs $5").code, 4);
|
||||
assert.equal(C().code, 2);
|
||||
assert.match(C("--subject", "Fix it", "--files", "src/a.ts", "--files", "my file.md").json.command, /^git add -- src\/a\.ts 'my file\.md' && git commit/);
|
||||
g("checkout", "-q", "-b", "chore/no-ticket-here");
|
||||
const none = C("--subject", "Fix it");
|
||||
assert.equal(none.code, 4);
|
||||
assert.equal(none.json.error, "no-ticket");
|
||||
assert.equal(C("--subject", "Fix it", "--ticket", "ABC-1").json.ticket, "ABC-1");
|
||||
assert.equal(C("--subject", "Fix it", "--ticket", "abc-1").code, 4);
|
||||
g("checkout", "-q", "-b", "PROJ2-7_underscore");
|
||||
assert.equal(C("--subject", "Fix it").json.ticket, "PROJ2-7");
|
||||
const notRepo = runScript("plan2code-review", "commit-msg.mjs", ["--subject", "x"], { cwd: tmp("norepo") });
|
||||
assert.equal(notRepo.code, 3);
|
||||
});
|
||||
|
||||
/* ============================================================ agent-files.mjs */
|
||||
|
||||
test("agent-files: detect, apply only what was chosen, rules folders, idempotent", () => {
|
||||
const root = tmp("agentfiles");
|
||||
write(root, "AGENTS.md", "# AGENTS.md\n");
|
||||
write(root, "CLAUDE.md", Array.from({ length: 12 }, (_, i) => `line ${i}`).join("\n") + "\n");
|
||||
write(root, "GEMINI.md", "# Gemini\nshort\n");
|
||||
write(root, ".github/copilot-instructions.md", "copilot\n");
|
||||
write(root, ".cursor/rules/a.md", "a\n");
|
||||
write(root, ".cursor/rules/b.md", "b\n");
|
||||
const A = (...a) => runScript("plan2code-init", "agent-files.mjs", [...a, "--root", root]);
|
||||
const d = A("detect");
|
||||
assert.equal(d.code, 0);
|
||||
assert.deepEqual(d.json.found.map((f) => f.id), ["CLAUDE.md", "GEMINI.md", ".github/copilot-instructions.md", ".cursor/rules"]);
|
||||
assert.equal(d.json.found[0].lines, 12);
|
||||
assert.equal(d.json.found[0].custom, true);
|
||||
assert.equal(d.json.found[1].custom, false);
|
||||
assert.match(d.json.warnings[0], /CLAUDE\.md has custom content/);
|
||||
const dry = A("apply", "CLAUDE.md", "--dry-run");
|
||||
assert.equal(dry.code, 0);
|
||||
assert.match(read(root, "CLAUDE.md"), /^line 0/, "dry-run writes nothing");
|
||||
assert.equal(A("apply", "CLAUDE.md", ".cursor/rules/", ".github/copilot-instructions.md").code, 0);
|
||||
assert.match(read(root, "CLAUDE.md"), /CRITICAL — MANDATORY FIRST STEP: You MUST read \[AGENTS\.md\]\(\.\/AGENTS\.md\)/);
|
||||
assert.match(read(root, ".github/copilot-instructions.md"), /^# Copilot Instructions\n\nSee \[AGENTS\.md\]\(\.\.\/AGENTS\.md\)/);
|
||||
for (const f of ["CLAUDE.md", ".github/copilot-instructions.md"]) {
|
||||
assert.match(read(root, f), /for complete project documentation including:\n- Development commands and setup\n[\s\S]*- Keeping this file current \/ Failure log\n- Section details in \.agents-docs\//, `${f} uses the bullet-list pointer`);
|
||||
}
|
||||
assert.deepEqual(fs.readdirSync(path.join(root, ".cursor/rules")), ["reference.md"]);
|
||||
assert.match(read(root, ".cursor/rules/reference.md"), /\]\(\.\.\/\.\.\/AGENTS\.md\)/);
|
||||
assert.match(read(root, "GEMINI.md"), /^# Gemini/, "unchosen files are untouched");
|
||||
const again = A("apply", "CLAUDE.md");
|
||||
assert.deepEqual(again.json.actions, [{ action: "unchanged", path: "CLAUDE.md" }]);
|
||||
assert.equal(A("detect").json.found.find((f) => f.id === "CLAUDE.md").alreadyPointer, true);
|
||||
fs.writeFileSync(path.join(root, "CLAUDE.md"), read(root, "CLAUDE.md").replace(/\n/g, "\r\n"));
|
||||
assert.equal(A("detect").json.found.find((f) => f.id === "CLAUDE.md").alreadyPointer, true, "a CRLF copy of the pointer still counts");
|
||||
assert.equal(A("apply", "GEMINI.md", "nope.md").code, 3);
|
||||
fs.rmSync(path.join(root, "AGENTS.md"));
|
||||
assert.equal(A("apply", "--all").code, 3);
|
||||
const empty = runScript("plan2code-init", "agent-files.mjs", ["detect", "--root", tmp("none")]);
|
||||
assert.deepEqual(empty.json.found, []);
|
||||
assert.match(empty.json.note, /skip this step silently/);
|
||||
});
|
||||
|
||||
/* ============================================================== agents-md.mjs */
|
||||
|
||||
test("agents-md: structure, budget, orphans, broken links, inline rules", () => {
|
||||
const root = tmp("agentsmd");
|
||||
write(root, "AGENTS.md", [
|
||||
"# AGENTS.md", "", "## Project Overview", "", "Thing.", "",
|
||||
"## Architecture", "", "Summary.", "", "Details: [Architecture](./.agents-docs/AGENTS-architecture.md)", "",
|
||||
"## Testing", "", "Details: [Testing](./.agents-docs/AGENTS-testing.md)", "",
|
||||
"## Failure log", "", "Details: [Git](./.agents-docs/AGENTS-git.md)", "",
|
||||
"```", "## not a heading inside a fence", "```", "",
|
||||
].join("\n"));
|
||||
write(root, ".agents-docs/AGENTS-architecture.md", "# Architecture\n> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.\n");
|
||||
write(root, ".agents-docs/AGENTS-git.md", "# Git\nno breadcrumb\n");
|
||||
write(root, ".agents-docs/AGENTS-orphan.md", "# Orphan\n> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.\n");
|
||||
const r = runScript("plan2code-init-update", "agents-md.mjs", ["inspect", "--root", root]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
const j = r.json;
|
||||
assert.equal(j.structure, "progressive");
|
||||
assert.equal(j.budget, `${j.lines}/500`);
|
||||
assert.deepEqual(j.sections.map((s) => s.name), ["Project Overview", "Architecture", "Testing", "Failure log"]);
|
||||
assert.deepEqual(j.brokenLinks, [".agents-docs/AGENTS-testing.md"]);
|
||||
assert.deepEqual(j.orphans, [".agents-docs/AGENTS-orphan.md"]);
|
||||
assert.ok(j.problems.some((p) => /Failure log must stay inline/.test(p)));
|
||||
assert.ok(j.problems.some((p) => /AGENTS-git\.md lacks the/.test(p)));
|
||||
const missing = runScript("plan2code-init", "agents-md.mjs", ["inspect", "--root", tmp("noagents")]);
|
||||
assert.equal(missing.json.exists, false);
|
||||
const fn = runScript("plan2code-init", "agents-md.mjs", ["filename", "Development Commands"]);
|
||||
assert.equal(fn.json.file, ".agents-docs/AGENTS-development-commands.md");
|
||||
assert.equal(fn.json.link, "Details: [Development Commands](./.agents-docs/AGENTS-development-commands.md)");
|
||||
});
|
||||
|
||||
/* ============================================================ review-scope.mjs */
|
||||
|
||||
test("review-scope: base detection, committed + staged + untracked, doc share", () => {
|
||||
const repo = tmp("scope");
|
||||
const g = gitInit(repo, "main");
|
||||
write(repo, "src/a.js", "1\n2\n");
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "init");
|
||||
g("checkout", "-q", "-b", "feature/X-1-thing");
|
||||
write(repo, "src/a.js", "1\n2\n3\n");
|
||||
write(repo, "README.md", "# r\n");
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "work");
|
||||
write(repo, "docs/new.md", "a\nb\n");
|
||||
write(repo, "src/b.js", "x\n");
|
||||
g("add", "src/b.js");
|
||||
const r = runScript("plan2code-review", "review-scope.mjs", [], { cwd: repo });
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
const j = r.json;
|
||||
assert.equal(j.base, "main");
|
||||
assert.equal(j.branch, "feature/X-1-thing");
|
||||
assert.deepEqual(j.files.map((f) => [f.path, f.status.join("+")]), [["docs/new.md", "untracked"], ["README.md", "committed"], ["src/a.js", "committed"], ["src/b.js", "staged"]]);
|
||||
assert.deepEqual(j.counts, { files: 4, lines: 5, added: 5, deleted: 0, docs: 2, code: 2 });
|
||||
assert.equal(j.mix, "mixed");
|
||||
assert.equal(j.commits.length, 1);
|
||||
assert.equal(j.empty, false);
|
||||
assert.equal(runScript("plan2code-review", "review-scope.mjs", ["--base", "nope"], { cwd: repo }).code, 3);
|
||||
assert.equal(runScript("plan2code-review", "review-scope.mjs", [], { cwd: tmp("plain") }).code, 3);
|
||||
});
|
||||
|
||||
/* ================================================= verification regressions */
|
||||
|
||||
test("specs: duplicate phase files and checklist rows are reported, and mark will not guess", () => {
|
||||
const root = specFixture();
|
||||
write(root, "specs/lunch-vote/phase-1-old.md", "# Old\n");
|
||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("- [/] [Phase 2: API](./phase-2.md) _(2 tasks)_", "- [/] [Phase 2: API](./phase-2.md) _(2 tasks)_\n- [ ] Phase 2 again"));
|
||||
const j = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
assert.equal(j.phases[0].file, "phase-1.md", "the exact phase-N.md wins over phase-1-old.md");
|
||||
assert.ok(j.checks.some((c) => c.code === "duplicate-phase-file" && /phase-1-old\.md/.test(c.message)));
|
||||
assert.ok(j.checks.some((c) => c.code === "duplicate-checklist-row" && /Phase 2/.test(c.message)));
|
||||
const m = runScript("plan2code-3-implement", "specs.mjs", ["mark", "lunch-vote", "--phase", "2", "--to", "done", "--root", root]);
|
||||
assert.equal(m.code, 5);
|
||||
assert.equal(m.json.error, "duplicate-row");
|
||||
});
|
||||
|
||||
test("specs: group ranges expand, chains are not parallel, [?] phases count as done, a blocked phase is skipped aloud", () => {
|
||||
const root = specFixture();
|
||||
const groups = (cells) => OVERVIEW.replace("| A | 3, 4 | Separate files |", cells);
|
||||
write(root, "specs/lunch-vote/overview.md", groups("| A | 2-4 | Separate files |"));
|
||||
assert.deepEqual(runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json.parallelGroups[0].phases, [2, 3, 4]);
|
||||
write(root, "specs/lunch-vote/overview.md", groups("| A | 3 → 4 | 4 needs 3 |"));
|
||||
assert.deepEqual(runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json.parallelGroups, []);
|
||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("- [/] [Phase 2", "- [?] [Phase 2").replace("- [ ] **Phase 3", "- [?] **Phase 3").replace("- [ ] [Phase 4", "- [?] [Phase 4"));
|
||||
const done = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
assert.equal(done.next.reason, "every phase is complete");
|
||||
assert.deepEqual(done.pending, []);
|
||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("- [/] [Phase 2", "- [!] [Phase 2"));
|
||||
const skip = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json.next;
|
||||
assert.equal(skip.action, "choose");
|
||||
assert.deepEqual(skip.skipped.map((p) => p.number), [2]);
|
||||
assert.match(skip.warning, /skipping Phase 2 \[blocked\]/);
|
||||
});
|
||||
|
||||
test("specs: blocked tasks may stand at approval; a re-opened phase is normal; done warns on unfinished work", () => {
|
||||
const root = specFixture();
|
||||
write(root, "specs/lunch-vote/phase-1.md", phase(1, "Complete", [["x", "1.1"], ["!", "1.2"]]));
|
||||
let j = runScript("plan2code-1b-revise-plan", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
assert.ok(!j.checks.some((c) => c.code === "checked-with-open-tasks"), JSON.stringify(j.checks));
|
||||
assert.ok(j.checks.some((c) => c.code === "approved-with-blocked"));
|
||||
write(root, "specs/lunch-vote/phase-1.md", phase(1, "Complete", [["x", "1.1"], ["x", "1.2"], [" ", "1.3"]]));
|
||||
const reopen = runScript("plan2code-1b-revise-plan", "specs.mjs", ["mark", "lunch-vote", "--phase", "1", "--to", "open", "--root", root]);
|
||||
assert.deepEqual(reopen.json.changes.map((c) => c.to), ["[ ]", "In Progress"]);
|
||||
j = runScript("plan2code-1b-revise-plan", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
assert.ok(j.checks.some((c) => c.code === "partly-done-unchecked" && c.level === "info"));
|
||||
const done = runScript("plan2code-3-implement", "specs.mjs", ["mark", "lunch-vote", "--phase", "2", "--to", "done", "--root", root]);
|
||||
assert.deepEqual(done.json.unfinished, ["2.2"]);
|
||||
assert.match(done.json.warning, /unfinished/);
|
||||
});
|
||||
|
||||
test("specs: --set cannot override computed fields; empty overview exists; uncounted task lines are flagged", () => {
|
||||
const root = specFixture();
|
||||
assert.equal(runScript("plan2code-2-document", "specs.mjs", ["metrics", "lunch-vote", "--step", "document", "--set", "verification_items_added=1", "--set", "total_tasks=99", "--root", root]).code, 2);
|
||||
write(root, "specs/lunch-vote/phase-2.md", read(root, "specs/lunch-vote/phase-2.md") + "- [ ] **Task 2.4A:** odd\n1. [ ] **Task 2.5:** numbered\n");
|
||||
const j = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
assert.equal(j.checks.filter((c) => c.code === "uncounted-task").length, 2);
|
||||
write(root, "specs/lunch-vote/overview.md", "");
|
||||
const e = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
assert.equal(e.overview, "overview.md");
|
||||
assert.ok(e.checks.some((c) => c.code === "no-checklist"));
|
||||
assert.ok(!e.checks.some((c) => c.code === "no-overview"));
|
||||
});
|
||||
|
||||
test("commit-msg: a repo with no commits, stray arguments, and paths quoted for every shell", () => {
|
||||
const repo = tmp("commit2");
|
||||
gitInit(repo, "feature/ABC-12-x");
|
||||
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
|
||||
assert.equal(C("--subject", "Add x").json.ticket, "ABC-12", "no commits yet");
|
||||
const stray = C("--subject", "Fix", "--files", "a.js", "b.js");
|
||||
assert.equal(stray.code, 2);
|
||||
assert.equal(stray.json.error, "stray-argument");
|
||||
assert.equal(C("--subject", "Fix", "--files", "src\\a.js", "--files", "my $file.md").json.command.split(" && ")[0], "git add -- src/a.js 'my $file.md'");
|
||||
assert.equal(C("--subject", "Fix", "--files", "it's.md").code, 4);
|
||||
});
|
||||
|
||||
test("review-scope: non-ASCII paths, empty untracked files, .txt is not a doc", () => {
|
||||
const repo = tmp("scope2");
|
||||
const g = gitInit(repo, "main");
|
||||
write(repo, "a.js", "1\n");
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "init");
|
||||
write(repo, "café.md", "a\nb\n");
|
||||
write(repo, "empty.js", "");
|
||||
write(repo, "requirements.txt", "x\n");
|
||||
const j = runScript("plan2code-review", "review-scope.mjs", [], { cwd: repo }).json;
|
||||
const byPath = Object.fromEntries(j.files.map((f) => [f.path, f]));
|
||||
assert.equal(byPath["café.md"].added, 2);
|
||||
assert.equal(byPath["empty.js"].added, 0);
|
||||
assert.equal(j.counts.docs, 1, "only café.md is a doc");
|
||||
});
|
||||
|
||||
test("agents-md and agent-files: indirect links are not orphans, accents fold, Cursor .mdc rules are replaced", () => {
|
||||
const root = tmp("agents2");
|
||||
write(root, "AGENTS.md", "# AGENTS.md\n\n## Architecture\n\nDetails: [A](./.agents-docs/AGENTS-architecture.md)\n");
|
||||
write(root, ".agents-docs/AGENTS-architecture.md", "# Architecture\n> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.\n\nSee [deep](./AGENTS-deep.md).\n");
|
||||
write(root, ".agents-docs/AGENTS-deep.md", "# Deep\n> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.\n");
|
||||
const j = runScript("plan2code-init-update", "agents-md.mjs", ["inspect", "--root", root]).json;
|
||||
assert.deepEqual(j.orphans, []);
|
||||
assert.deepEqual(j.indirect, [".agents-docs/AGENTS-deep.md"]);
|
||||
assert.equal(runScript("plan2code-init", "agents-md.mjs", ["filename", "Café Ünïcode"]).json.file, ".agents-docs/AGENTS-cafe-unicode.md");
|
||||
write(root, ".cursor/rules/style.mdc", "---\nalwaysApply: true\n---\nrule\n");
|
||||
const d = runScript("plan2code-init", "agent-files.mjs", ["detect", "--root", root]).json;
|
||||
assert.deepEqual(d.found.find((f) => f.id === ".cursor/rules").files.map((f) => f.path), [".cursor/rules/style.mdc"]);
|
||||
runScript("plan2code-init", "agent-files.mjs", ["apply", ".cursor/rules", "--root", root]);
|
||||
assert.deepEqual(fs.readdirSync(path.join(root, ".cursor/rules")), ["reference.md"]);
|
||||
});
|
||||
|
||||
/* ================================================== code-review regressions */
|
||||
|
||||
test("agent-files: an entry that is AGENTS.md through a link is never written through", () => {
|
||||
const root = tmp("agentlink");
|
||||
const agents = "# AGENTS.md\n\nThe real instructions.\n";
|
||||
write(root, "AGENTS.md", agents);
|
||||
fs.linkSync(path.join(root, "AGENTS.md"), path.join(root, "CLAUDE.md"));
|
||||
write(root, "GEMINI.md", Array.from({ length: 12 }, (_, i) => `line ${i}`).join("\n") + "\n");
|
||||
const A = (...a) => runScript("plan2code-init", "agent-files.mjs", [...a, "--root", root]);
|
||||
const d = A("detect").json;
|
||||
assert.equal(d.found.find((f) => f.id === "CLAUDE.md").linkedToAgents, true, "a hard link to AGENTS.md is AGENTS.md");
|
||||
assert.equal(d.found.find((f) => f.id === "GEMINI.md").linkedToAgents, false);
|
||||
assert.ok(!d.warnings.some((w) => /CLAUDE\.md/.test(w)), "a linked entry is not warned as custom content");
|
||||
const refused = A("apply", "CLAUDE.md", "GEMINI.md");
|
||||
assert.equal(refused.code, 5);
|
||||
assert.equal(refused.json.error, "linked-to-agents");
|
||||
assert.match(refused.json.next, /already serves AGENTS\.md/);
|
||||
assert.equal(read(root, "AGENTS.md"), agents, "refused before anything was written");
|
||||
assert.match(read(root, "GEMINI.md"), /^line 0/, "a refusal writes nothing at all");
|
||||
const all = A("apply", "--all");
|
||||
assert.equal(all.code, 0, all.stderr);
|
||||
assert.ok(all.json.actions.some((a) => a.action === "skipped-linked" && a.path === "CLAUDE.md"));
|
||||
assert.deepEqual(all.json.updated, ["GEMINI.md"]);
|
||||
assert.equal(read(root, "AGENTS.md"), agents, "--all skips the linked entry");
|
||||
assert.match(read(root, "GEMINI.md"), /^# GEMINI\.md\n\nSee \[AGENTS\.md\]/);
|
||||
|
||||
// Symlinks need admin (or Developer Mode) on Windows: run this part only where they work.
|
||||
const sroot = tmp("agentsym");
|
||||
write(sroot, "AGENTS.md", agents);
|
||||
write(sroot, "shared/other.md", "someone else's file\n");
|
||||
try {
|
||||
fs.symlinkSync(path.join(sroot, "AGENTS.md"), path.join(sroot, "CLAUDE.md"));
|
||||
fs.symlinkSync(path.join(sroot, "shared/other.md"), path.join(sroot, "GEMINI.md"));
|
||||
} catch (err) {
|
||||
if (err.code === "EPERM" || err.code === "EACCES") return;
|
||||
throw err;
|
||||
}
|
||||
const S = (...a) => runScript("plan2code-init", "agent-files.mjs", [...a, "--root", sroot]);
|
||||
assert.equal(S("detect").json.found.find((f) => f.id === "CLAUDE.md").linkedToAgents, true);
|
||||
assert.equal(S("apply", "CLAUDE.md").code, 5);
|
||||
assert.equal(S("apply", "GEMINI.md").code, 0);
|
||||
assert.equal(read(sroot, "shared/other.md"), "someone else's file\n", "a symlink to another file is replaced, not written through");
|
||||
assert.equal(fs.lstatSync(path.join(sroot, "GEMINI.md")).isSymbolicLink(), false);
|
||||
assert.equal(read(sroot, "AGENTS.md"), agents);
|
||||
});
|
||||
|
||||
test("agent-files: a CRLF checkout of a pointer is still the pointer", () => {
|
||||
const root = tmp("agentcrlf");
|
||||
write(root, "AGENTS.md", "# AGENTS.md\n");
|
||||
write(root, "GEMINI.md", "x\n");
|
||||
write(root, ".windsurf/rules/a.md", "a\n");
|
||||
const A = (...a) => runScript("plan2code-init", "agent-files.mjs", [...a, "--root", root]);
|
||||
assert.equal(A("apply", "--all").code, 0);
|
||||
for (const f of ["GEMINI.md", ".windsurf/rules/reference.md"]) write(root, f, read(root, f).replace(/\n/g, "\r\n"));
|
||||
const d = A("detect").json;
|
||||
assert.equal(d.found.find((f) => f.id === "GEMINI.md").alreadyPointer, true);
|
||||
assert.equal(d.found.find((f) => f.id === ".windsurf/rules").alreadyPointer, true);
|
||||
assert.deepEqual(A("apply", "GEMINI.md", ".windsurf/rules").json.actions.map((a) => a.action), ["unchanged", "unchanged"]);
|
||||
assert.match(read(root, "GEMINI.md"), /\r\n/, "an unchanged CRLF pointer is left as it is");
|
||||
});
|
||||
|
||||
test("specs mark: a plain or bold Status: line is updated; a missing one is reported", () => {
|
||||
const root = specFixture();
|
||||
const S = (...a) => runScript("plan2code-3-implement", "specs.mjs", [...a, "--root", root]);
|
||||
write(root, "specs/lunch-vote/phase-3.md", phase(3, "x", [["x", "3.1"]]).replace("**Status:** x", "Status: In Progress"));
|
||||
const plain = S("mark", "lunch-vote", "--phase", "3", "--to", "done");
|
||||
assert.equal(plain.code, 0, plain.stderr);
|
||||
assert.match(read(root, "specs/lunch-vote/phase-3.md"), /^Status: Complete$/m, "the plain form is kept as written");
|
||||
assert.ok(!plain.json.warning);
|
||||
write(root, "specs/lunch-vote/phase-4.md", phase(4, "x", [["x", "4.1"]]).replace("**Status:** x", "- **Status**: Not Started"));
|
||||
assert.equal(S("status", "lunch-vote").json.phases[3].status, "Not Started");
|
||||
assert.equal(S("mark", "lunch-vote", "--phase", "4", "--to", "done").code, 0);
|
||||
assert.match(read(root, "specs/lunch-vote/phase-4.md"), /^- \*\*Status\*\*: Complete$/m);
|
||||
write(root, "specs/lunch-vote/phase-2.md", phase(2, "x", [["x", "2.1"]]).replace("**Status:** x\n", ""));
|
||||
const none = S("mark", "lunch-vote", "--phase", "2", "--to", "done");
|
||||
assert.equal(none.code, 0);
|
||||
assert.match(none.json.warning, /phase-2\.md has no Status line, so only the Phase Checklist checkbox changed/);
|
||||
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[x\] \[Phase 2: API\]/);
|
||||
});
|
||||
|
||||
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");
|
||||
const S = (...a) => runScript("plan2code-4-finalize", "specs.mjs", [...a, "--root", root]);
|
||||
for (const arg of [".", "./src", "./specs", "specs/lunch-vote/.."]) {
|
||||
const r = S("archive", arg, "--dry-run");
|
||||
assert.equal(r.code, 5, `archive ${arg}: ${r.stdout}`);
|
||||
assert.equal(r.json.error, "not-a-spec");
|
||||
assert.match(r.json.next, /specs\/<name>/);
|
||||
}
|
||||
assert.ok(fs.existsSync(path.join(root, "specs/lunch-vote/overview.md")));
|
||||
assert.equal(S("archive", "./specs/lunch-vote", "--dry-run").code, 0);
|
||||
assert.equal(S("archive", path.join(root, "specs", "lunch-vote"), "--dry-run").code, 0, "an absolute path under specs/ is fine");
|
||||
assert.equal(S("status", "specs--completed/old-one").code, 0, "a read may name an archived spec");
|
||||
assert.equal(S("status", "./src").json.error, "not-a-spec");
|
||||
});
|
||||
|
||||
test("specs: an em dash in a group range expands like a hyphen", () => {
|
||||
const root = specFixture();
|
||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("| A | 3, 4 | Separate files |", "| A | 2\u20144 | Separate files |"));
|
||||
assert.deepEqual(runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json.parallelGroups[0].phases, [2, 3, 4]);
|
||||
});
|
||||
|
||||
test("commit-msg: @ and - paths are quoted, git add ends its options, risky subjects are refused, add and commit apart", () => {
|
||||
const repo = tmp("commit3");
|
||||
gitInit(repo, "feature/ABC-12-x");
|
||||
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
|
||||
const files = C("--subject", "Fix", "--files", "@types/x.d.ts", "--files", "-weird.md", "--files", "src/a@b.js");
|
||||
assert.equal(files.code, 0, files.stderr);
|
||||
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 "ABC-12" -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);
|
||||
for (const bad of ["back\\slash", "wow!", "a\rb", "say \u201Chi\u201D"]) {
|
||||
assert.equal(C("--subject", bad).code, 4, JSON.stringify(bad));
|
||||
}
|
||||
assert.equal(C("--subject", "wow!").json.error, "unsafe-subject");
|
||||
assert.equal(C("--subject", "Fix", "--files", "it\u2019s.md").json.error, "unsafe-path");
|
||||
});
|
||||
|
||||
test("review-scope: no main or master is no-base unless the repo has no commits; a move up a level keeps one slash", () => {
|
||||
const repo = tmp("scope3");
|
||||
const g = gitInit(repo, "develop");
|
||||
write(repo, "d/sub/f.txt", "1\n");
|
||||
write(repo, "top/h.txt", "3\n");
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "init");
|
||||
g("checkout", "-q", "-b", "feature/X-2-thing");
|
||||
write(repo, "src/new.js", "x\n");
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "feature work");
|
||||
const R = (...a) => runScript("plan2code-review", "review-scope.mjs", a, { cwd: repo });
|
||||
const none = R();
|
||||
assert.equal(none.code, 3);
|
||||
assert.equal(none.json.error, "no-base");
|
||||
assert.match(none.json.next, /--base <trunk>/);
|
||||
const dev = R("--base", "develop");
|
||||
assert.equal(dev.code, 0, dev.stderr);
|
||||
assert.deepEqual(dev.json.files.map((f) => f.path), ["src/new.js"]);
|
||||
g("mv", "d/sub/f.txt", "d/f.txt");
|
||||
g("mv", "top/h.txt", "h.txt");
|
||||
const moved = R("--base", "develop").json.files.map((f) => f.path);
|
||||
assert.ok(moved.includes("d/f.txt") && moved.includes("h.txt"), JSON.stringify(moved));
|
||||
assert.ok(!moved.some((p) => p.includes("//") || p.startsWith("/")), JSON.stringify(moved));
|
||||
const fresh = tmp("scope4");
|
||||
gitInit(fresh, "develop");
|
||||
write(fresh, "a.js", "1\n");
|
||||
const unborn = runScript("plan2code-review", "review-scope.mjs", [], { cwd: fresh });
|
||||
assert.equal(unborn.code, 0, unborn.stderr);
|
||||
assert.equal(unborn.json.base, null);
|
||||
assert.match(unborn.json.note, /No commits yet/);
|
||||
assert.deepEqual(unborn.json.files.map((f) => f.path), ["a.js"]);
|
||||
});
|
||||
@@ -3384,7 +3384,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe
|
||||
return p;
|
||||
};
|
||||
const removable = [file("p2.json"), file("helper.mjs")];
|
||||
const kept = [file("looks.json"), file("console-dir"), file("notes.txt"), file("p3.json", false)];
|
||||
const kept = [file("looks.json"), file("workspaces.json"), file("console-dir"), file("notes.txt"), file("p3.json", false)];
|
||||
const subdir = path.join(dir, "x.json");
|
||||
fs.mkdirSync(subdir);
|
||||
backdate(subdir);
|
||||
@@ -3393,12 +3393,12 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe
|
||||
const stale = staleScratch(dir, Date.now(), SESSION_MAX_AGE_MS).sort();
|
||||
assert.deepEqual(stale, ["helper.mjs", "p2.json"]);
|
||||
assert.deepEqual(
|
||||
(await removeScratch(dir, [...stale, "looks.json", "../p.json", "console-dir"])).sort(),
|
||||
(await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "../p.json", "console-dir"])).sort(),
|
||||
["helper.mjs", "p2.json"]
|
||||
);
|
||||
for (const p of removable) assert.equal(fs.existsSync(p), false, p);
|
||||
for (const p of kept) assert.ok(fs.existsSync(p), p);
|
||||
assert.deepEqual([...PROTECTED_CONSOLE_FILES].sort(), ["console-dir", "looks.json"]);
|
||||
assert.deepEqual([...PROTECTED_CONSOLE_FILES].sort(), ["console-dir", "looks.json", "workspaces.json"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -3594,6 +3594,8 @@ const RESULT_KEYS = ["type", "at", "sid", "rev", "actions", "reply", "consumedAt
|
||||
const WAITING_KEYS = ["status", "sid", "elapsed", "answered", "total", "staged", "url", "message", "next", "terminalLine"];
|
||||
|
||||
function openSession(extra = {}) {
|
||||
// A fresh page, and no folders remembered from an earlier test.
|
||||
fs.rmSync(path.join(HOME, "workspaces.json"), { force: true });
|
||||
const res = cli(["open", "--file", payload(`pin-${Date.now()}.json`, { ...BASE, ...extra }), "--no-open"]);
|
||||
const s = sessionUrl(res.json.url);
|
||||
const send = (pathname, body) =>
|
||||
@@ -4926,7 +4928,20 @@ test("initialWorkspace names the original folder after itself and marks it origi
|
||||
|
||||
/* ------------------------------------ workspace and meter: end to end */
|
||||
|
||||
// The folders remembered across console sessions (workspaces.json) are
|
||||
// cleared for every new test session unless it asks to keep them, so one
|
||||
// test's additions never seed the next one's workspace.
|
||||
const REMEMBERED = path.join(HOME, "workspaces.json");
|
||||
const remembered = () => JSON.parse(fs.readFileSync(REMEMBERED, "utf8"));
|
||||
const rememberedFor = (spec) => {
|
||||
const projects = Object.values(remembered().projects);
|
||||
const project = projects.find((p) => path.resolve(p.path).toLowerCase() === ROOT.toLowerCase());
|
||||
if (!project) return undefined;
|
||||
return spec ? (project.specs || {})[spec] : project.project;
|
||||
};
|
||||
|
||||
function consoleSession(openArgs, opts = {}) {
|
||||
if (!opts.keepRemembered) fs.rmSync(REMEMBERED, { force: true });
|
||||
const res = cli(["open", "--no-open", ...openArgs], opts);
|
||||
const s = sessionUrl(res.json.url);
|
||||
const send = (pathname, body) =>
|
||||
@@ -4974,9 +4989,18 @@ test("workspace: a folder added on the dashboard survives dashboard → plan →
|
||||
assert.equal(meterView(ledger).points, 2);
|
||||
assert.equal((await s.get("/state")).meter.points, 2, "the frame carries the meter");
|
||||
|
||||
const fresh = consoleSession(["--workflow", "dashboard"]);
|
||||
assert.deepEqual(
|
||||
rememberedFor("").folders.map((f) => [f.path, f.description]),
|
||||
[[extra, "the design notes"]],
|
||||
"the add was remembered for the project, outside the session folder"
|
||||
);
|
||||
const fresh = consoleSession(["--workflow", "dashboard"], { keepRemembered: true });
|
||||
try {
|
||||
assert.equal(fresh.opened.workspace.folders.length, 1, "a new console session starts with only the original folder");
|
||||
assert.deepEqual(
|
||||
fresh.opened.workspace.folders.map((f) => f.path),
|
||||
[ROOT, extra],
|
||||
"a new console session in the same folder opens with the remembered folders"
|
||||
);
|
||||
assert.equal(meterView(readLedger(fresh.session)).points, 0);
|
||||
} finally {
|
||||
cli(["stop", "--session", fresh.sid]);
|
||||
@@ -4987,6 +5011,78 @@ test("workspace: a folder added on the dashboard survives dashboard → plan →
|
||||
}
|
||||
});
|
||||
|
||||
test("workspace: a spec starts from the project's list, then stands alone, and the scope swaps lists with logged changes", async () => {
|
||||
const s = consoleSession(["--workflow", "dashboard"]);
|
||||
const shared = tempFolder();
|
||||
const specOnly = tempFolder();
|
||||
try {
|
||||
assert.equal((await addFolder(s, { path: shared })).status, 200);
|
||||
const toSpec = await s.send("/workspace/scope", { spec: "specs/demo" });
|
||||
assert.equal(toSpec.status, 200);
|
||||
const view = await toSpec.json();
|
||||
assert.equal(view.scope, "specs/demo");
|
||||
assert.deepEqual(view.folders.map((f) => f.path), [ROOT, shared], "seeded from the project's list");
|
||||
assert.equal(rememberedFor("specs/demo"), undefined, "nothing is saved for the spec until it changes");
|
||||
|
||||
assert.equal((await addFolder(s, { path: specOnly })).status, 200);
|
||||
assert.deepEqual(rememberedFor("specs/demo").folders.map((f) => f.path), [shared, specOnly]);
|
||||
assert.deepEqual(rememberedFor("").folders.map((f) => f.path), [shared], "the project's list is untouched");
|
||||
|
||||
const before = wsFile(s).version;
|
||||
const back = await (await s.send("/workspace/scope", { spec: "" })).json();
|
||||
assert.deepEqual([back.scope, back.folders.map((f) => f.path)], ["", [ROOT, shared]]);
|
||||
assert.deepEqual(
|
||||
wsFile(s).changes.filter((c) => c.version > before).map((c) => [c.kind, c.path]),
|
||||
[["removed", specOnly]],
|
||||
"the swap is logged, so the agent hears of it"
|
||||
);
|
||||
const again = await (await s.send("/workspace/scope", { spec: "specs/demo/" })).json();
|
||||
assert.deepEqual(again.folders.map((f) => f.path), [ROOT, shared, specOnly], "the spec's own list comes back");
|
||||
assert.equal((await s.send("/workspace/scope", { spec: "../elsewhere" })).status, 400);
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
fs.rmSync(shared, { recursive: true, force: true });
|
||||
fs.rmSync(specOnly, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("workspace: open --spec starts on that spec's list, a posted specDir takes the list with it, and forget drops only that spec", async () => {
|
||||
const s = consoleSession(["--workflow", "dashboard"]);
|
||||
const shared = tempFolder();
|
||||
const specOnly = tempFolder();
|
||||
let other = null;
|
||||
let planned = null;
|
||||
try {
|
||||
await addFolder(s, { path: shared });
|
||||
await s.send("/workspace/scope", { spec: "specs/demo" });
|
||||
await addFolder(s, { path: specOnly });
|
||||
cli(["stop", "--session", s.sid]);
|
||||
|
||||
other = consoleSession(["--workflow", "implement", "--spec", "specs/demo"], { keepRemembered: true });
|
||||
assert.deepEqual(other.opened.workspace.folders.map((f) => f.path), [ROOT, shared, specOnly]);
|
||||
assert.equal((await other.get("/workspace")).scope, "specs/demo");
|
||||
|
||||
planned = consoleSession(["--workflow", "plan"], { keepRemembered: true });
|
||||
assert.deepEqual(planned.opened.workspace.folders.map((f) => f.path), [ROOT, shared], "no spec: the project's list");
|
||||
cli(["post", "--session", planned.sid, "--file", payload("ws-spec.json", { specDir: "specs/brand-new" })]);
|
||||
let saved;
|
||||
for (let i = 0; i < 40 && !(saved = rememberedFor("specs/brand-new")); i++) await sleep(100);
|
||||
assert.deepEqual(saved && saved.folders.map((f) => f.path), [shared], "the list in force became the new spec's");
|
||||
|
||||
const forgot = cli(["forget", "--spec", "specs/demo/overview.md"]);
|
||||
assert.deepEqual(forgot.json, { ok: true, spec: "specs/demo", forgot: true });
|
||||
assert.equal(cli(["forget", "--spec", "specs/demo"]).json.forgot, false, "a second forget finds nothing");
|
||||
assert.equal(rememberedFor("specs/demo"), undefined);
|
||||
assert.ok(rememberedFor("specs/brand-new"), "other specs are kept");
|
||||
assert.ok(rememberedFor(""), "the project's list is kept");
|
||||
assert.equal(cli(["forget"], { expectFail: true }).status, 2);
|
||||
} finally {
|
||||
for (const x of [s, other, planned]) if (x) cli(["stop", "--session", x.sid]);
|
||||
fs.rmSync(shared, { recursive: true, force: true });
|
||||
fs.rmSync(specOnly, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("workspace: add resolves from the session's folder and refuses a file, a missing path, a duplicate and a name clash", async () => {
|
||||
// Opened from scripts/: the worktree is still the repo root, but the CLI
|
||||
// (and so the server it spawns) runs from elsewhere.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const CHAR_LIMIT = 11500;
|
||||
const CHAR_LIMIT = 20000;
|
||||
const srcDir = path.join(__dirname, '..', 'src');
|
||||
|
||||
// Note: readdirSync is non-recursive, so files in subdirectories like
|
||||
|
||||
Reference in new issue
Block a user