Tighten PR Prep and Test after their first runs

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-04 10:24:07 -08:00
1 parent ff1c793633
commit bf23d7eeea
22 files changed
+261 -109

No files matched your search

@@ -76,6 +76,7 @@ The full `npm test` takes minutes and drives a browser per page suite. When a ch
| The launcher (`src/launcher/`) | `node --test scripts/test-launcher.mjs` |
| A skill's script | `npm run build:skills`, then `node --test scripts/test-script-<skill>.mjs` (and `test-skill-scripts.mjs` for the shared plumbing) |
| A workflow prompt (`src/plan2code-*.md`) | `node scripts/validate-char-count.js` and `node scripts/check-skill-table.mjs` |
| A new skill or console workflow | First update the hand-written tables that list every workflow: the `SUBAGENT_WORKFLOWS` count and the meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS` in `test-web-console-logic.mjs`, `notesFor` in `test-web-console-speed.mjs`, the event list in `src/web-console/console-meter.md` (checked by `test-web-console-chat-stress.mjs`) and a `BUDGETS.notes` entry in `test-console-wire-budgets.mjs`. Then run those four suites plus `test-web-console-skills.mjs` and `test-web-console-spec-states.mjs`; the PR Prep and Test build missed all five tables and only the full suite caught them |
| Docs or comments only | `node --test scripts/test-us-english.mjs scripts/test-line-endings.mjs` |
Run the full `npm test` when the change touches something many suites lean on: `web-console-test-helpers.mjs` or `page-test-helpers.mjs`, `looks.js` / `prefs.js` / `static.mjs` (the `SERVABLE` list), `skills.js`, `install.js`, the server's shared modules (`console.mjs`, `routes.mjs`); after a sync merge or a version bump; before opening a PR or cutting a release; and whenever you cannot say which suites a change reaches.
+3 -1
View File
@@ -36,12 +36,14 @@ export const BUDGETS = {
"handoff.md": 300,
"implement.md": 5700,
"init.md": 300,
"loop.md": 11100,
"loop.md": 11600,
"pathfinder.md": 2400,
"plan.md": 700,
"pr-prep.md": 4500,
"quick-task.md": 4000,
"review.md": 1000,
"revise-plan.md": 1200,
"test.md": 5400,
"xray.md": 2500,
},
// One printed line each, for a session with one choice card.
+10
View File
@@ -135,6 +135,16 @@ test("coverage read --go-func: functions grouped by file, the module path droppe
});
});
test("coverage read --go-func: a nested module's files read from its own folder", () => {
const dir = tmp("cov-go-nested");
write(dir, "go.mod", "module example.com/shop\n\ngo 1.22\n");
write(dir, "tools/go.mod", "module example.com/shop/tools\n\ngo 1.22\n");
write(dir, "cover.txt", "example.com/shop/tools/gen/gen.go:5:\t\tRun\t\t50.0%\nexample.com/shop/cart/cart.go:3:\t\tAdd\t\t100.0%\n");
const r = C(dir, "read", "--go-func", "cover.txt");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.files.map((f) => f.file), ["cart/cart.go", "tools/gen/gen.go"]);
});
test("coverage read: a missing file is exit 3", () => {
const dir = tmp("cov-missing");
const r = C(dir, "read", "--lcov", "nope.info");
+5
View File
@@ -50,6 +50,11 @@ test("run-check: not-started for a made-up command and for a missing --cwd", ()
assert.equal(c.code, 0, c.stderr);
assert.equal(c.json.outcome, "not-started");
assert.equal(c.json.reason, "cwd-missing");
const folder = tmp("check-log-dir");
const l = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} -e "process.exit(0)"`, "--log", folder]);
assert.equal(l.code, 0, l.stderr);
assert.equal(l.json.outcome, "not-started", "a --log that is a folder stops the check with JSON, not a crash");
assert.equal(l.json.reason, "log-unwritable");
});
test("run-check: timeout kills the whole process tree", async () => {
+12 -4
View File
@@ -23,7 +23,7 @@ test("npm project: suite, lint, types and build checks", () => {
{ kind: "types", cmd: "npm run typecheck" },
{ kind: "build", cmd: "npm run build" },
]);
assert.deepEqual(r.coverage, [{ runner: "node", cmd: "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=<out>", cwd: ".", reads: "lcov" }]);
assert.deepEqual(r.coverage, [{ runner: "node", cmd: "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=\"<out>\"", cwd: ".", reads: "lcov" }]);
assert.equal(r.builtin, null);
});
@@ -75,6 +75,14 @@ test("pnpm workspace: packages lines and the { packages } form", () => {
{ cmd: "pnpm test", cwd: "libs/core", covers: ["libs/core/**"] },
], "a ! line excludes its folders");
assert.deepEqual(r.coverage, [{ runner: "jest", cmd: "npx jest --coverage --coverageReporters=lcov", cwd: "libs/core", reads: "lcov" }]);
const inline = discover({
"package.json": { name: "root" },
"pnpm-lock.yaml": "",
"pnpm-workspace.yaml": "packages: ['apps/*', \"!apps/skip\"]\n",
"apps/web/package.json": { scripts: { test: "vitest" } },
"apps/skip/package.json": { scripts: { test: "vitest" } },
});
assert.deepEqual(inline.runners, [{ cmd: "pnpm test", cwd: "apps/web", covers: ["apps/web/**"] }], "an inline packages list works too");
const obj = discover({ "package.json": { workspaces: { packages: ["pkgs/*"] } }, "pkgs/x/package.json": { scripts: { test: "t" } } });
assert.deepEqual(obj.runners, [{ cmd: "npm test", cwd: "pkgs/x", covers: ["pkgs/x/**"] }]);
});
@@ -85,7 +93,7 @@ test("Go module with a nested second module", () => {
{ cmd: "go test ./...", cwd: ".", covers: ["**"] },
{ cmd: "go test ./...", cwd: "tools", covers: ["tools/**"] },
]);
assert.deepEqual(r.coverage[0], { runner: "go", cmd: "go test -coverprofile=<out> ./... && go tool cover -func=<out>", cwd: ".", reads: "go-func" });
assert.deepEqual(r.coverage[0], { runner: "go", cmd: "go test -coverprofile=\"<out>\" ./... && go tool cover -func=\"<out>\"", cwd: ".", reads: "go-func" });
assert.equal(r.builtin, null);
});
@@ -127,10 +135,10 @@ test("coverage is listed only with its add-on present", () => {
assert.deepEqual(vitest({}).coverage, []);
const pytest = (deps) => discover({ "pyproject.toml": `[project]\ndependencies = [${deps}]\n` });
assert.deepEqual(pytest('"pytest", "pytest-cov"').coverage, [{ runner: "pytest", cmd: "python -m pytest --cov --cov-report=lcov:<out>", cwd: ".", reads: "lcov" }]);
assert.deepEqual(pytest('"pytest", "pytest-cov"').coverage, [{ runner: "pytest", cmd: "python -m pytest --cov --cov-report=lcov:\"<out>\"", cwd: ".", reads: "lcov" }]);
assert.deepEqual(pytest('"pytest"').coverage, []);
const nested = discover({ "requirements-dev.txt": "pytest-cov\n", "svc/setup.cfg": "[tool:pytest]\n" });
assert.deepEqual(nested.coverage, [{ runner: "pytest", cmd: "python -m pytest --cov --cov-report=lcov:<out>", cwd: "svc", reads: "lcov" }], "pytest-cov listed in a folder above the runner");
assert.deepEqual(nested.coverage, [{ runner: "pytest", cmd: "python -m pytest --cov --cov-report=lcov:\"<out>\"", cwd: "svc", reads: "lcov" }], "pytest-cov listed in a folder above the runner");
const dotnet = (ref) => discover({ "App.Tests/App.Tests.csproj": `<Project><ItemGroup>${ref}</ItemGroup></Project>` });
assert.deepEqual(dotnet('<PackageReference Include="coverlet.collector" Version="6" />').coverage, [{ runner: "dotnet", cmd: 'dotnet test --collect:"XPlat Code Coverage"', cwd: "App.Tests", reads: "lcov" }]);
+32
View File
@@ -59,6 +59,24 @@ test("test-map read: a section linking to .agents-docs/AGENTS-test-map.md reads
assert.equal(r.json.rows[0].area, "Launcher", "follows exactly one link, never a link from the linked file");
const bare = project("## Test map\n\nSee [map](.agents-docs/AGENTS-test-map.md).\n", { ".agents-docs/AGENTS-test-map.md": TABLE });
assert.equal(T(bare, ["read"]).json.source, ".agents-docs/AGENTS-test-map.md", "the ](.agents-docs/...) form works too");
const nested = project("## Test map\n\nSee [map](./.agents-docs/testing/map.md).\n", { ".agents-docs/testing/map.md": TABLE });
const n = T(nested, ["read"]);
assert.equal(n.json.source, ".agents-docs/testing/map.md", "a link into a subfolder of .agents-docs/ is inside it");
assert.deepEqual(n.json.problems, []);
const escape = project("## Test map\n\nSee [map](./.agents-docs/../docs/map.md).\n", { "docs/map.md": TABLE });
assert.match(T(escape, ["read"]).json.problems[0], /outside \.agents-docs\//, "a link that climbs out is still outside");
const prose = project("## Test map\n\nSee [contributing](./CONTRIBUTING.md), then [map](./.agents-docs/AGENTS-test-map.md).\n", { ".agents-docs/AGENTS-test-map.md": TABLE });
const p = T(prose, ["read"]);
assert.equal(p.json.source, ".agents-docs/AGENTS-test-map.md", "a prose link before the docs link does not hide it");
assert.deepEqual(p.json.problems, []);
});
test("test-map write: a new nested linked file links back to AGENTS.md from its own depth", () => {
const dir = project("## Test map\n\nSee [map](./.agents-docs/testing/map.md).\n");
rowsFile(dir, ROWS);
const w = T(dir, ["write", "--rows", "rows.json"]);
assert.equal(w.code, 0, w.stderr);
assert.match(read(dir, ".agents-docs/testing/map.md"), /\[AGENTS\.md\]\(\.\.\/\.\.\/AGENTS\.md\)/);
});
test("test-map read and write: a link outside .agents-docs/ is a problem, and write refuses", () => {
@@ -176,6 +194,10 @@ test("test-map write: a heading with no table gets one after its first paragraph
rowsFile(bare, ROWS);
assert.equal(T(bare, ["write", "--rows", "rows.json"]).code, 0);
assert.match(read(bare, "AGENTS.md"), /^## Test map\n\n\| Area [\s\S]*\| yes \|\n\n## Next\n$/, "directly under a heading with no paragraph");
const tag = project("## Test map\n\n#123 tracks this.\n\n## Next\n");
rowsFile(tag, ROWS);
assert.equal(T(tag, ["write", "--rows", "rows.json"]).code, 0);
assert.match(read(tag, "AGENTS.md"), /^## Test map\n\n#123 tracks this\.\n\n\| Area /, "a line like #123 is a paragraph, not a heading");
});
test("test-map write: an existing table is replaced in place, every other line byte-identical", () => {
@@ -236,6 +258,16 @@ test("test-map write: invalid rows are exit 4 with the row index; no AGENTS.md i
assert.equal(T(none, ["write", "--rows", "rows.json"]).code, 3);
assert.ok(!fs.existsSync(path.join(none, "AGENTS.md")));
assert.equal(T(dir, ["write"]).code, 2, "--rows is required");
for (const [row, why] of [
[{ area: "A", paths: ["src/[ab]/**"], run: "x", shared: false }, /unsupported glob/],
[{ area: "A", paths: ["src/**"], run: "npm `t`", shared: false }, /backtick or line break/],
[{ area: "A\nB", paths: ["src/**"], run: "x", shared: false }, /backtick or line break/],
]) {
rowsFile(dir, [row]);
const w = T(dir, ["write", "--rows", "rows.json"]);
assert.equal(w.code, 4);
assert.match(w.json.message, why);
}
});
/* ------------------------------------------------------------------ glob */
+19
View File
@@ -113,6 +113,10 @@ test("test-match covers --stdin: real review-scope.mjs output", () => {
assert.deepEqual(r.json.matched.map((m) => m.area), ["Launcher"]);
assert.deepEqual(r.json.unmatched, [{ file: "src/app/util.js", tests: ["src/app/util.test.js"], method: "name" }]);
assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--stdin"], { cwd: dir, input: "not json" }).code, 2);
const odd = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--stdin"], { cwd: dir, input: JSON.stringify({ files: [{}, null, { path: "src/launcher/a.js" }] }) });
assert.equal(odd.code, 0, odd.stderr);
assert.deepEqual(odd.json.unmatched, [], "an entry with no path is dropped, never read as a file named undefined");
assert.deepEqual(odd.json.matched[0].files, ["src/launcher/a.js"]);
assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["covers"], { cwd: dir }).code, 2);
});
@@ -165,6 +169,10 @@ test("test-match gaps --scope path and --scope branch", () => {
const p = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "path", "--path", "src/sub"], { cwd: dir });
assert.equal(p.code, 0, p.stderr);
assert.deepEqual(p.json.gaps.map((x) => x.file), ["src/sub/c.js"]);
const all = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "all"], { cwd: dir });
const dot = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "path", "--path", "."], { cwd: dir });
assert.equal(dot.code, 0, dot.stderr);
assert.deepEqual(dot.json.gaps, all.json.gaps, "--path . is the whole project");
assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "path"], { cwd: dir }).code, 2, "--scope path needs --path");
gitIn(dir)("checkout", "-q", "-b", "feature");
@@ -205,6 +213,17 @@ test("test-match gaps: any matching row with a run covers a file; a row without
assert.equal(r.json.covered, 2, "x.js by the second row, m.ts by its .mts test");
});
test("test-match gaps: a test in another language never covers a file by name", () => {
const dir = tmp("match-lang");
write(dir, "src/foo.js", "f\n");
write(dir, "src/foo.test.py", "t\n");
write(dir, "src/bar.ts", "b\n");
write(dir, "src/bar.test.js", "t\n");
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "all"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.gaps.map((g) => g.file), ["src/foo.js"], "foo.test.py does not cover foo.js; a JS test still covers a TS file");
});
test("test-match gaps: capped at 2,000 source files", () => {
const dir = tmp("match-cap");
for (let i = 0; i < 2005; i++) write(dir, `src/f${String(i).padStart(4, "0")}.js`, "x\n");
+6 -4
View File
@@ -2019,8 +2019,8 @@ test("workspace cursor never moves backwards, and only changes past it are pendi
}
});
test("subagents: only the thirteen opted-in workflows offer the switch", () => {
for (const w of ["init", "init-update", "pathfinder", "plan", "revise-plan", "document", "implement", "implement-review", "quick-task", "review", "finalize", "xray", "diagnose"]) {
test("subagents: only the fifteen opted-in workflows offer the switch", () => {
for (const w of ["init", "init-update", "pathfinder", "plan", "revise-plan", "document", "implement", "implement-review", "quick-task", "review", "finalize", "xray", "diagnose", "pr-prep", "test"]) {
assert.equal(offered(w), true, w);
assert.ok(defaultInstruction(w).length > 0, `${w} has a default instruction`);
}
@@ -2028,7 +2028,7 @@ test("subagents: only the thirteen opted-in workflows offer the switch", () => {
assert.equal(offered(w), false, String(w));
assert.equal(defaultInstruction(w), "");
}
assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 13);
assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 15);
assert.deepEqual(defaultSetting("review"), { workflow: "review", on: true, instruction: null, max: 3, strength: "balanced" });
assert.equal(defaultSetting("changelog").on, false, "a skill without the switch is never on");
assert.equal(effectiveInstruction({ workflow: "review", instruction: " " }), defaultInstruction("review"));
@@ -2318,13 +2318,14 @@ test("meter: the weights and labels built from the skill list are the ones writt
"pathfinder-chart": 2, "pathfinder-question": 0, "pathfinder-research": 1,
plan: 2, "revise-plan": 1, document: 2, "implement-phase": 2, "implement-review-phase": 3,
review: 2, "quick-task": 1, init: 2, "init-update": 2, finalize: 1, handoff: 0, git: 1,
"git-commits": 0, "git-conflict": 1, changelog: 1, xray: 1, diagnose: 1,
"git-commits": 0, "git-conflict": 1, changelog: 1, xray: 1, diagnose: 1, "pr-prep": 1, test: 1,
});
assert.deepEqual({ ...LAUNCH_LABELS }, {
plan: "Plan started", "revise-plan": "Revise plan started", document: "Document started",
review: "Review started", "quick-task": "Quick task started", init: "Init started",
"init-update": "Init update started", finalize: "Finalize started", git: "Git started",
changelog: "Changelog started", xray: "X-ray started", diagnose: "Diagnose started",
"pr-prep": "PR Prep started", test: "Test started",
});
assert.deepEqual({ ...RUN_LABELS }, {
"pathfinder-chart": "Pathfinder map written", "pathfinder-question": "Pathfinder question settled",
@@ -2334,6 +2335,7 @@ test("meter: the weights and labels built from the skill list are the ones writt
"quick-task": "Quick task built", init: "Init run", "init-update": "Init update run",
finalize: "Finalize run", handoff: "Handoff written", git: "Git run", "git-commits": "Commits in Git",
"git-conflict": "Git conflict help", changelog: "Changelog run", xray: "X-ray run", diagnose: "Diagnose run",
"pr-prep": "PR Prep run", test: "Test run",
});
for (const t of [WEIGHTS, LAUNCH_LABELS, RUN_LABELS]) assert.ok(Object.isFrozen(t));
});
+2 -2
View File
@@ -481,7 +481,7 @@ test("every console workflow has its notes, and its skill's Interface reads them
init: "init", "init-update": "init", pathfinder: "pathfinder", plan: "plan", "revise-plan": "revise-plan",
document: "document", implement: "implement", "implement-review": "implement", "quick-task": "quick-task",
review: "review", finalize: "finalize", handoff: "handoff", changelog: "changelog", git: "git", xray: "xray",
diagnose: "diagnose",
diagnose: "diagnose", "pr-prep": "pr-prep", test: "test",
};
const skills = fs.readdirSync(path.join(ROOT, "src")).filter((f) => /^plan2code(-.*)?\.md$/.test(f));
for (const f of skills) {
@@ -750,7 +750,7 @@ test("long task lines, long words, a narrow board and a narrow Ask pane never wi
test("over the git board a note box grows with its text, and the no-repo note only points above when a card is there", () => {
const css = joinedCss();
assert.match(css, /\.git-cards > \.card textarea \{ field-sizing: content; max-height: 50vh; \}/);
assert.match(css, /\.git-cards > \.card \.md-host \{ min-height: 0; max-height: 50vh; \}/);
const view = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board-view.js"), "utf8");
const fn = view.slice(view.indexOf("export function drawGitBoard("), view.indexOf("function header("));
assert.ok(fn.includes("ctx.hasCard"), "the note checks for a card first");
+25 -9
View File
@@ -9,7 +9,8 @@
import fs from "node:fs";
import path from "node:path";
import { EXIT, consoleModule, fail, gitRepo, out, parseArgs, run } from "./common.mjs";
import { fileURLToPath } from "node:url";
import { EXIT, consoleModule, fail, gitRepo, out, parseArgs, readText, run } from "./common.mjs";
const USAGE = `
pr-prep.mjs: read-only facts for PR Prep. JSON on stdout.
@@ -32,7 +33,9 @@ pr-prep.mjs: read-only facts for PR Prep. JSON on stdout.
The create-a-pull-request link for --branch (the current branch) into
--base (the default branch). Prints { ok, pushed: true, url, host, kind,
needsKind, branch, base, ahead }; needsKind: the host is unknown and has
no saved answer, so url is null. A branch not on a remote yet prints
no saved answer, so url is null. url is also null for a remote no link
can be built for (a path or ssh alias, or a host saved as none). A
branch not on a remote yet prints
{ ok, pushed: false, branch, next } with exit 0.
node pr-prep.mjs spec [--branch <b>] [--base <b>] [--root <dir>]
@@ -46,8 +49,9 @@ pr-prep.mjs: read-only facts for PR Prep. JSON on stdout.
none: nothing fits; match is null
Exit: 0 ok · 1 crash · 2 bad arguments · 3 not a git repository (pr-url,
spec) · 4 no such branch, no base, or the branch is the base (pr-url) ·
5 detached HEAD or git too old (pr-url).
spec) or an unreadable template (template) · 4 no such branch, no base,
or the branch is the base (pr-url) · 5 detached HEAD (pr-url) or git
missing or too old (pr-url, spec).
`;
/* ------------------------------------------------------------- template */
@@ -117,7 +121,9 @@ function template({ root }) {
for (const m of mds) if (!found.includes(m)) found.push(m);
}
if (!found.length) return out({ ok: true, found: false, path: null, headings: [], hasTesting: false, others: [] });
const headings = headingsOf(fs.readFileSync(path.join(root, found[0]), "utf8"));
const text = readText(path.join(root, found[0]));
if (text === null) fail(EXIT.NOT_FOUND, "unreadable-template", `Cannot read ${found[0]}.`, "Check the file's permissions, or write the description without the template.");
const headings = headingsOf(text);
out({ ok: true, found: true, path: found[0], headings, hasTesting: headings.some((h) => TESTING.test(h)), others: found.slice(1) });
}
@@ -126,14 +132,14 @@ function template({ root }) {
let R;
function repoRoot(root) {
const floor = R.gitFloor();
if (!floor.ok) fail(EXIT.REFUSED, "git-too-old", floor.message, "Install or update git (2.23 or newer), then try again.");
const top = R.git(["rev-parse", "--show-toplevel"], root);
if (!top.ok || !top.out) fail(EXIT.NOT_FOUND, "not-a-repo", `${root} is not inside a git repository.`, "Run PR Prep from inside the project's git repository.");
return path.resolve(top.out);
}
async function prUrlCmd({ root, branch, base }) {
const floor = R.gitFloor();
if (!floor.ok) fail(EXIT.REFUSED, "git-too-old", floor.message, "Install or update git (2.23 or newer), then try again.");
const repo = repoRoot(root);
let link;
try {
@@ -228,7 +234,7 @@ function spec({ root, branch, base }) {
const COMMANDS = { template, "pr-url": prUrlCmd, spec };
run(USAGE, async (argv) => {
async function main(argv) {
const args = parseArgs(argv, { values: ["root", "branch", "base"] });
const [cmd, ...extra] = args._;
const names = Object.keys(COMMANDS).join(", ");
@@ -238,4 +244,14 @@ run(USAGE, async (argv) => {
args.root = path.resolve(args.root || ".");
if (cmd !== "template") R = await gitRepo();
return COMMANDS[cmd](args);
});
}
// Run as a script; imported, do nothing.
const isMain = (() => {
try {
return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
} catch {
return false;
}
})();
if (isMain) run(USAGE, main);
+8 -8
View File
@@ -18,9 +18,9 @@ Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-pr-prep/scripts/` globally). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
- `node "<S>/review-scope.mjs" [--base <branch>]`: the branch's changes against main (or master): `files` (each with `status`: `committed`, `staged`, `unstaged`, `untracked`), `counts`, `mix` (`docs`, `code`, `mixed`), `empty`, `commits`.
- `node "<S>/review-scope.mjs" [--base <branch>]`: the branch's changes against main (or master): `files` (each with `status`: a list of one or more of `committed`, `staged`, `unstaged`, `untracked`), `counts`, `mix` (`docs`, `code`, `mixed`), `empty`, `commits`.
- `node "<S>/test-map.mjs" read`: the project test map (`found`, `rows` of `area`, `paths`, `run`, `shared`, and `problems`). `write --rows <file.json>` saves one, only on a yes.
- `node "<S>/test-commands.mjs" discover`: the project's commands from its config files: `suite` (the whole-suite command or null), `runners` (`cmd`, `cwd`, `covers`), `checks` (`kind` lint, types or build, with `cmd`), `builtin` (the language's own runner, only when nothing else was found).
- `node "<S>/test-commands.mjs" discover`: the project's commands from its config files: `suite` (the whole-suite command or null), `runners` (`cmd`, `cwd`, `covers`), `checks` (`kind` lint, types or build, with `cmd`), `builtin` (the language's own runner, only when there is no suite and no runner).
- `node "<S>/test-match.mjs" covers --stdin`: pipe review-scope's JSON in. `matched` (test map rows with their `run` and `files`), `unmatched` (`file`, `tests`, `method`), `sharedHits` (`file`, `why`).
- `node "<S>/run-check.mjs" --cmd <c> --cwd <d> --timeout <s> --log <file>`: runs one check and prints `outcome` (`passed`, `failed`, `timeout`, `not-started` with a `reason`), `exit`, `seconds` and `tail`.
- `node "<S>/pr-prep.mjs" template`: the repo's pull-request template: `found`, `path`, `headings`, `hasTesting`, `others`.
@@ -52,22 +52,22 @@ When your tool can start helpers (subagents) and they are not switched off for t
Run `review-scope.mjs`. `empty: true` → say there is nothing on this branch to prepare, and end. A `no-base` exit → ask which branch is the trunk and rerun with `--base`.
Files with a `staged`, `unstaged` or `untracked` status are uncommitted. When there are any, list them up front on one card and ask: **Include them in this run** or **Commit first**. Commit first → say the git skill commits them (`/plan2code-git`, or its dashboard card), then come back to PR Prep; end the run. Remember which was picked: the report says whether uncommitted work was included.
Files whose `status` includes `staged`, `unstaged` or `untracked` are uncommitted. When there are any, list them up front on one card and ask: **Include them in this run** or **Commit first**. Commit first → say the git skill commits them (`/plan2code-git`, or its dashboard card), then come back to PR Prep; end the run. Remember which was picked: the report says whether uncommitted work was included.
### Step 2: Commands
Run `test-map.mjs read`. With a map (`found: true`), its rows are the project's checks; mention any `problems` in one line.
With no map, run `test-commands.mjs discover`. List every command it found with the folders each covers (`suite`, each of `runners` with its `cwd` and `covers`, each of `checks`), and confirm them on one card before anything runs. A correction from the person replaces what the script found. Only `builtin` found → offer it on that card as the one candidate (`cmd`, for its `language`), run only on a yes; it runs whatever tests already exist and installs nothing. Nothing found at all → ask how the project runs its tests, or go on with the checks you can see and say so.
With no map, run `test-commands.mjs discover`. List every command it found with the folders each covers (`suite`, each of `runners` with its `cwd` and `covers`, each of `checks`), and confirm them on one card before anything runs. A correction from the person replaces what the script found. No suite or runner but a `builtin` → offer it on that card as the test candidate, beside any `checks` (`cmd`, for its `language`), run only on a yes; it runs whatever tests already exist and installs nothing. Nothing found at all → ask how the project runs its tests, or go on with the checks you can see and say so.
### Step 3: Check plan
Pipe review-scope's JSON to `test-match.mjs covers --stdin`. Build the plan:
Pipe review-scope's JSON to `test-match.mjs covers --stdin`. With a map, run `discover` once now too, for its `suite` and `checks`. Build the plan:
1. **Matched rows:** every `matched` row is its own check, running its own `run`, with the files it covers as its reason.
2. **Unmatched files:** pick checks for each `unmatched` file following `references/test-runs.md`, using its `tests` and `method` when present; mark these "picked by the agent" so the person knows they were judged. A file with no test anywhere stays a note for Step 6.
3. **Shared ground:** any `sharedHits` entry with `why: "row"`, or a `config`, `test-helper` or `fixture` hint you judge to be real shared ground (or a widely imported module you spot), plans the full suite: the `suite` command when `discover` found one, else every map row's `run` as separate checks. Name the file and why it reaches wide.
4. **Project checks:** add every `checks` entry from `discover` (lint, types, build) unless review-scope's `mix` is `docs`. With a map and no discover run yet, run `discover` once for them.
4. **Project checks:** add every `checks` entry from `discover` (lint, types, build) unless review-scope's `mix` is `docs`.
5. Every check carries a one-line reason. Drop exact duplicates (the same command in the same folder), keeping both reasons.
6. **More than one runner** (several `runners`, or map rows run by different tools): group the plan by runner, and keep the grouping in the report.
@@ -110,7 +110,7 @@ Post it as its own doc holding one fenced block (` ```markdown `), so the page's
Run `pr-prep.mjs pr-url`.
- `pushed: true`: put the create-a-PR `url` under the description. `needsKind: true` (an unknown host, so `url` is null): say the link cannot be built for this host here, and that the git skill (`/plan2code-git`) asks what kind of host it is once and remembers it for next time.
- `pushed: true`: put the create-a-PR `url` under the description. `url` null (`needsKind: true` for an unknown host, or a remote no link can be built for): say the link cannot be built for this host here; with `needsKind`, add that the git skill (`/plan2code-git`) asks what kind of host it is once and remembers it for next time.
- `pushed: false`: say the branch is not pushed yet and offer to hand over to the git skill (`/plan2code-git`), which asks before it pushes. PR Prep never pushes.
- Any other failure: say why in one line (detached HEAD, the branch is the default branch) and leave the link out.
@@ -124,7 +124,7 @@ Use Step 8's `spec` answer.
### Step 11: Test map offer
When the run had no map, or found commands or areas the map lacks, offer to write or update it (one table under `## Test map` in `AGENTS.md`, columns `Area`, `Paths`, `Run`, `Shared`). On a yes, write the rows to a JSON file in the session folder (or the OS temp folder) and run `test-map.mjs write --rows <file>`. Never without a yes.
When the run had no map, or found commands or areas the map lacks, offer to write or update it (one table under `## Test map` in `AGENTS.md`, columns `Area`, `Paths`, `Run`, `Shared`). On a yes, write the rows to a JSON file in the session folder (or the OS temp folder) and run `test-map.mjs write --rows <file>`. Never without a yes. No `AGENTS.md` (`write` refuses with `no-agents-md`) → offer Init (`/plan2code-init`) instead.
## Session End
+46 -13
View File
@@ -8,6 +8,7 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
const USAGE = `
@@ -25,8 +26,10 @@ coverage.mjs: per-file coverage from a coverage tool's output. JSON on stdout.
sums every file.
go-func "<import path>/<file>.go:<line>: <func> <pct>%" lines,
grouped by file: pct is the mean of the file's functions,
lines and hit are null. The module path from --root's go.mod
is dropped so files read as project paths. The "total:" line
lines and hit are null. The module path of the go.mod that
owns each file (any under --root, four folders deep) is
swapped for that go.mod's folder, so files read as project
paths, a nested module's included. The "total:" line
is not a file: it is reported as total.
A file with no lines has pct null.
@@ -90,19 +93,38 @@ function readLcov(text, root) {
const GO_LINE = /^(.+\.go):\d+:\s+\S+\s+([\d.]+)%\s*$/;
const GO_TOTAL = /^total:\s+(?:\(statements\)\s+)?([\d.]+)%\s*$/;
function goModule(root) {
try {
const m = fs.readFileSync(path.join(root, "go.mod"), "utf8").match(/^\s*module\s+(\S+)/m);
return m ? m[1].replace(/^"|"$/g, "") : null;
} catch {
return null;
}
const GO_SKIP = new Set([".git", "node_modules", "vendor", "testdata"]);
// Every Go module under root (four folders deep, as discover walks), longest
// module path first, so a nested module (tools/go.mod) owns its own files.
function goModules(root) {
const found = [];
const walk = (dir, depth) => {
let entries;
try {
entries = fs.readdirSync(path.join(root, dir), { withFileTypes: true });
} catch {
return;
}
for (const e of entries) {
if (e.isFile() && e.name === "go.mod") {
try {
const m = fs.readFileSync(path.join(root, dir, e.name), "utf8").match(/^\s*module\s+(\S+)/m);
if (m) found.push({ dir, mod: m[1].replace(/^"|"$/g, "") });
} catch {}
} else if (e.isDirectory() && depth < 4 && !GO_SKIP.has(e.name) && !e.name.startsWith(".")) {
walk(dir ? `${dir}/${e.name}` : e.name, depth + 1);
}
}
};
walk("", 0);
return found.sort((a, b) => b.mod.length - a.mod.length);
}
function readGoFunc(text, root) {
const lines = text.split(/\r?\n/).map((l) => l.trim());
if (!lines.some((l) => GO_LINE.test(l))) return null;
const mod = goModule(root);
const mods = goModules(root);
const groups = new Map();
let total = null;
for (const line of lines) {
@@ -114,7 +136,8 @@ function readGoFunc(text, root) {
const m = line.match(GO_LINE);
if (!m) continue;
let file = slash(m[1]);
if (mod && file.startsWith(`${mod}/`)) file = file.slice(mod.length + 1);
const own = mods.find((g) => file.startsWith(`${g.mod}/`));
if (own) file = `${own.dir ? `${own.dir}/` : ""}${file.slice(own.mod.length + 1)}`;
else file = relTo(root, m[1]);
(groups.get(file) || groups.set(file, []).get(file)).push(Number(m[2]));
}
@@ -125,7 +148,7 @@ function readGoFunc(text, root) {
/* ------------------------------------------------------------------ main */
run(USAGE, async (argv) => {
async function main(argv) {
const args = parseArgs(argv, { values: ["lcov", "go-func", "root"] });
const [cmd, ...extra] = args._;
if (!cmd) fail(EXIT.USAGE, "missing-command", "A subcommand is required: read.", "Run with --help for usage.");
@@ -152,4 +175,14 @@ run(USAGE, async (argv) => {
);
}
out({ ok: true, format, ...read });
});
}
// Run as a script; imported, do nothing.
const isMain = (() => {
try {
return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
} catch {
return false;
}
})();
if (isMain) run(USAGE, main);
+4 -4
View File
@@ -19,7 +19,7 @@ Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-test/scripts/` globally). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
- `node "<S>/test-map.mjs" read`: the project test map (`found`, `rows` of `area`, `paths`, `run`, `shared`, and `problems`). `write --rows <file.json>` saves one, only on a yes.
- `node "<S>/test-commands.mjs" discover`: the project's commands from its config files: `suite`, `runners` (`cmd`, `cwd`, `covers`), `checks`, `coverage` (`runner`, `cmd`, some with an `<out>` placeholder, `cwd`, `reads`: `lcov` or `go-func`), `builtin` (the language's own runner, only when nothing else was found).
- `node "<S>/test-commands.mjs" discover`: the project's commands from its config files: `suite`, `runners` (`cmd`, `cwd`, `covers`), `checks`, `coverage` (`runner`, `cmd`, some with an `<out>` placeholder, `cwd`, `reads`: `lcov` or `go-func`), `builtin` (the language's own runner, only when there is no suite and no runner).
- `node "<S>/test-match.mjs" gaps --scope branch|path|all [--path <p>]`: source files no test covers (`file`, `area`, `runner`, `commits90d`, `lastTouched`), ranked newest first, then by recent commits; `capped` when it stopped at 2,000 files.
- `node "<S>/test-match.mjs" nearest --file <f>`: up to three existing test files to read for the project's style.
- `node "<S>/run-check.mjs" --cmd <c> --cwd <d> --timeout <s> --log <file>`: runs one command and prints `outcome` (`passed`, `failed`, `timeout`, `not-started` with a `reason`), `exit`, `seconds` and `tail`.
@@ -64,7 +64,7 @@ Every run, ask where to look, on one card:
Run `test-map.mjs read` and `test-commands.mjs discover`. With a map (`found: true`), its rows are the project's runners; mention any `problems` in one line.
- **No map:** list every command `discover` found with the folders each covers (`suite`, each of `runners` with its `cwd` and `covers`), and confirm them on one card before anything runs. A correction from the person replaces what the script found.
- **No runner at all, `builtin` set:** offer that runner, naming it and the command it would add (for Node, a `"test": "node --test"` script in `package.json`; for Python `python -m unittest`, Go `go test ./...`, Rust `cargo test`). Go ahead only on a yes; on a yes add that one command and nothing else.
- **No runner at all, `builtin` set:** offer that runner, naming it and the command it would add (for Node, a `"test": "node --test"` script in `package.json`; for Python `python -m unittest`). Go ahead only on a yes; on a yes add that one command and nothing else.
- **No runner and no `builtin`:** stop. Say the project has no test runner and none built into its language, so there is nothing to write tests for here; end the run.
### Step 3: Gaps
@@ -73,7 +73,7 @@ Run `test-match.mjs gaps --scope <branch|path|all>` (with `--path <p>` for a nam
**Coverage, only when the project already has it.** When `discover` lists a `coverage` entry for a runner in scope, offer it on one card naming the command and what it covers. Never run it without a yes.
- **Yes:** when `cmd` has an `<out>` placeholder, fill it with a file in the session folder (`open` printed it; in the terminal, the OS temp folder). Run it with `run-check.mjs` in its `cwd`, with a `--log` file. Then read the output with `coverage.mjs read`, per `reads`: `--lcov <out>` when the command wrote to `<out>`, else `--lcov <cwd>/coverage/lcov.info` (Jest's and Vitest's default); `--go-func <log>` for Go, whose `go tool cover -func` table is printed into the run's log. Files at 0% or under 50% that matching called covered become extra gaps, method `coverage`. A coverage run that fails or times out, or a `coverage.mjs read` that fails (exit 3 or 4, as for .NET's Cobertura output): say so in one line, and matching alone continues.
- **Yes:** when `cmd` has an `<out>` placeholder (already quoted), replace just `<out>` with a file in the session folder (`open` printed it; in the terminal, the OS temp folder). Run it with `run-check.mjs` in its `cwd`, with a `--log` file. Then read the output with `coverage.mjs read`, per `reads`: `--lcov <out>` when the command wrote to `<out>`, else `--lcov <cwd>/coverage/lcov.info` (Jest's and Vitest's default); `--go-func <log>` for Go, whose `go tool cover -func` table is printed into the run's log. Files at 0% or under 50% that matching called covered become extra gaps, method `coverage`. A coverage run that fails or times out, or a `coverage.mjs read` that fails (exit 3 or 4, as for .NET's Cobertura output): say so in one line, and matching alone continues.
- **No:** matching alone continues, and the plan says coverage was skipped.
Every gap carries the method that found it (`matching` or `coverage`), ranked as `gaps` ranks them; coverage gaps follow the matching ones, lowest percent first. No gaps at all → say every source file in scope has a test, offer the test map (Step 8) when the run had none, and end.
@@ -179,7 +179,7 @@ A new test that fails because the source is wrong is never "fixed" by changing t
### Step 8: Test map offer
When the run had no map, or found runners or areas the map lacks, offer to write or update it (one table under `## Test map` in `AGENTS.md`, columns `Area`, `Paths`, `Run`, `Shared`). On a yes, write the rows to a JSON file in the session folder (or the OS temp folder) and run `test-map.mjs write --rows <file>`. Never without a yes.
When the run had no map, or found runners or areas the map lacks, offer to write or update it (one table under `## Test map` in `AGENTS.md`, columns `Area`, `Paths`, `Run`, `Shared`). On a yes, write the rows to a JSON file in the session folder (or the OS temp folder) and run `test-map.mjs write --rows <file>`. Never without a yes. No `AGENTS.md` (`write` refuses with `no-agents-md`) → offer Init (`/plan2code-init`) instead.
## Session End
+1 -1
View File
@@ -1,5 +1,5 @@
# Choosing what to run
> Read by Document, Implement, Implement + Review, Quick Task, Review and Finalize before they write, run or offer tests. Never invoked as a skill.
> Read by Document, Implement, Implement + Review, Quick Task, Review, Finalize, PR Prep and Test before they write, run or offer tests. Never invoked as a skill.
## Three tiers
+7 -2
View File
@@ -102,8 +102,13 @@ export function globToRegExp(glob) {
return new RegExp(`^${out}$`);
}
// Compiled globs, by glob text (null for an unsupported one): a map's few
// globs are tested against every file in a run.
const compiled = new Map();
/** Does the path match the glob? Unsupported globs match nothing. */
export function matchGlob(glob, p) {
if (unsupported(glob)) return false;
return globToRegExp(glob).test(fold(toPosix(p)));
if (!compiled.has(glob)) compiled.set(glob, unsupported(glob) ? null : globToRegExp(glob));
const re = compiled.get(glob);
return re !== null && re.test(fold(toPosix(p)));
}
+20 -6
View File
@@ -23,7 +23,7 @@ run-check.mjs: run one command and classify its outcome. JSON on stdout.
{ ok, cmd, cwd, outcome, exit, signal, seconds, tail, log }.
outcome passed (exit 0) · failed (any other exit) · timeout ·
not-started (with reason: spawn-error, command-not-found,
cwd-missing)
cwd-missing, log-unwritable)
tail the output's last 60 lines, stdout and stderr interleaved,
each cut at 400 characters
log the file holding the full output, when --log was given
@@ -71,9 +71,22 @@ export function runCheck({ cmd, cwd, timeout, log }) {
let timedOut = false;
let done = false;
let logStream = null;
let logFailed = false;
if (logFile) {
fs.mkdirSync(path.dirname(logFile), { recursive: true });
logStream = fs.createWriteStream(logFile);
// Opened before the run, so a log that cannot be written stops the
// check up front instead of crashing it halfway with no JSON.
let fd;
try {
fs.mkdirSync(path.dirname(logFile), { recursive: true });
fd = fs.openSync(logFile, "w");
} catch {
resolve({ ...base, outcome: "not-started", reason: "log-unwritable", exit: null, signal: null, seconds: 0, tail: [], log: null });
return;
}
logStream = fs.createWriteStream(null, { fd });
logStream.on("error", () => {
logFailed = true;
});
}
const child = spawn(cmd, { cwd: abs, shell: true, windowsHide: true, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] });
const take = (chunk, isErr) => {
@@ -83,7 +96,7 @@ export function runCheck({ cmd, cwd, timeout, log }) {
// the Windows "not recognized" check.
if (output.length > 1_000_000) output = output.slice(-TAIL_LINES * LINE_CAP * 4);
if (isErr && stderrHead.length < 65536) stderrHead += s;
if (logStream) logStream.write(chunk);
if (logStream && !logFailed) logStream.write(chunk);
};
child.stdout.on("data", (c) => take(c, false));
child.stderr.on("data", (c) => take(c, true));
@@ -105,8 +118,9 @@ export function runCheck({ cmd, cwd, timeout, log }) {
else if (code === 0) outcome = "passed";
else if (code === 127 || code === 9009 || NOT_RECOGNIZED.test(stderrHead)) [outcome, reason] = ["not-started", "command-not-found"];
else outcome = "failed";
const result = { ...base, outcome, ...(reason ? { reason } : {}), exit: typeof code === "number" ? code : null, signal: signal || null, seconds, tail: tailOf(output), log: logFile };
if (logStream) logStream.end(() => resolve(result));
const result = { ...base, outcome, ...(reason ? { reason } : {}), exit: typeof code === "number" ? code : null, signal: signal || null, seconds, tail: tailOf(output), log: logFailed ? null : logFile };
// An errored stream never finishes, so it is not waited on.
if (logStream && !logFailed) logStream.end(() => resolve(result));
else resolve(result);
};
+15 -10
View File
@@ -26,10 +26,12 @@ test-commands.mjs: a project's test and check commands. JSON on stdout.
the root folder's is cwd "." and covers "**"
checks [{ kind, cmd }] kind is lint, types or build
coverage [{ runner, cmd, cwd, reads }] only for tools already present;
<out> in cmd is a placeholder for the output file; reads is
<out> in cmd (already in quotes, so a path with spaces
works) is a placeholder for the output file; reads is
lcov or go-func
builtin { language, cmd, others? } the language's own runner, only when
there is no suite and no runner; otherwise null
builtin { language, cmd, others? } the language's own runner (node or
python; Go and Rust always show as runners), only when there
is no suite and no runner; otherwise null
Only reads files. Exit: 0 ok · 2 bad arguments · 3 no such folder.
`;
@@ -43,7 +45,8 @@ const LANG_EXT = {
go: [".go"],
rust: [".rs"],
};
const BUILTIN = { node: "node --test", python: "python -m unittest", go: "go test ./...", rust: "cargo test" };
// Node and Python only: a go.mod or a Cargo.toml always gives a runner above.
const BUILTIN = { node: "node --test", python: "python -m unittest" };
function readJson(file) {
const text = readText(file);
@@ -115,7 +118,11 @@ function workspaceFolders(root, pkg, dirs) {
if (pnpm !== null) {
let inPackages = false;
for (const line of pnpm.split(/\r?\n/)) {
if (/^packages\s*:/.test(line)) inPackages = true;
const inline = line.match(/^packages\s*:\s*\[([^\]]*)\]/);
if (inline) {
globs.push(...inline[1].split(",").map((g) => g.trim().replace(/^['"]|['"]$/g, "")));
inPackages = false;
} else if (/^packages\s*:/.test(line)) inPackages = true;
else if (/^\S/.test(line)) inPackages = false;
else if (inPackages) {
const m = line.match(/^\s*-\s*['"]?([^'"#]+?)['"]?\s*(?:#.*)?$/);
@@ -183,7 +190,7 @@ export function discover(root) {
add(runners, { cmd: `${pm} test`, cwd, covers: covers(cwd) });
const d = deps(p);
if (/\bnode\s+--test\b/.test(test)) {
add(coverage, { runner: "node", cmd: "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=<out>", cwd, reads: "lcov" });
add(coverage, { runner: "node", cmd: "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=\"<out>\"", cwd, reads: "lcov" });
}
if (d.jest || /\bjest\b/.test(test)) add(coverage, { runner: "jest", cmd: "npx jest --coverage --coverageReporters=lcov", cwd, reads: "lcov" });
if (Object.keys(d).some((k) => k.startsWith("@vitest/coverage-"))) add(coverage, { runner: "vitest", cmd: "npx vitest run --coverage --coverage.reporter=lcov", cwd, reads: "lcov" });
@@ -197,7 +204,7 @@ export function discover(root) {
const before = runners.length;
if (files.includes("go.mod")) {
add(runners, { cmd: "go test ./...", cwd, covers: covers(cwd) });
add(coverage, { runner: "go", cmd: "go test -coverprofile=<out> ./... && go tool cover -func=<out>", cwd, reads: "go-func" });
add(coverage, { runner: "go", cmd: "go test -coverprofile=\"<out>\" ./... && go tool cover -func=\"<out>\"", cwd, reads: "go-func" });
}
if (files.includes("Cargo.toml")) {
const cargo = readText(path.join(abs, "Cargo.toml")) || "";
@@ -210,7 +217,7 @@ export function discover(root) {
if (["pyproject.toml", "setup.cfg", "pytest.ini", "tox.ini"].some((f) => files.includes(f))) {
if (usesPytest(abs, files)) {
add(runners, { cmd: "python -m pytest", cwd, covers: covers(cwd) });
if (usesPytestCov(root, cwd, dirs)) add(coverage, { runner: "pytest", cmd: "python -m pytest --cov --cov-report=lcov:<out>", cwd, reads: "lcov" });
if (usesPytestCov(root, cwd, dirs)) add(coverage, { runner: "pytest", cmd: "python -m pytest --cov --cov-report=lcov:\"<out>\"", cwd, reads: "lcov" });
} else add(runners, { cmd: "python -m unittest", cwd, covers: covers(cwd) });
}
const dotnet = files.some((f) => /\.(csproj|sln)$/i.test(f));
@@ -234,8 +241,6 @@ export function discover(root) {
const present = [];
if (pkg || rootFiles.includes("package.json")) present.push("node");
if (counts.python) present.push("python");
if ([...dirs.values()].some((f) => f.includes("go.mod"))) present.push("go");
if ([...dirs.values()].some((f) => f.includes("Cargo.toml"))) present.push("rust");
if (present.length) {
present.sort((a, b) => counts[b] - counts[a]);
const [first, ...rest] = present;
+15 -7
View File
@@ -156,21 +156,22 @@ function parseTable(lines, table) {
}
/**
* The first relative .md link in the section body. `docs` is the path under
* .agents-docs/ when it points there, else `outside` holds the target.
* The section body's link into .agents-docs/ (`docs`, the path under it);
* with none, `outside` holds the first other relative .md link.
*/
function linkIn(lines, fenced, start, end) {
let outside = null;
for (let i = start; i < end; i++) {
if (fenced[i]) continue;
for (const m of lines[i].matchAll(/\]\(([^)\s]+)\)/g)) {
const target = m[1].replace(/#.*$/, "");
if (/^[a-z][a-z0-9+.-]*:/i.test(target) || !/\.md$/i.test(target)) continue;
const norm = path.posix.normalize(toPosix(target));
if (/^\.agents-docs\/[^/]+\.md$/i.test(norm)) return { docs: norm };
return { outside: target };
if (/^\.agents-docs\/.+\.md$/i.test(norm)) return { docs: norm };
outside ??= target;
}
}
return null;
return outside === null ? null : { outside };
}
/**
@@ -222,6 +223,13 @@ function validRows(data) {
if (typeof r.area !== "string" || !r.area.trim()) bad("has no area");
if (typeof r.run !== "string" || !r.run.trim()) bad("has no run command");
if (!Array.isArray(r.paths) || !r.paths.length || r.paths.some((p) => typeof p !== "string" || !p.trim())) bad("has no paths");
// A backtick or line break would break the table; an unsupported glob
// would be written, then dropped by the next read.
if ([r.area, r.run, ...r.paths].some((s) => /[`\r\n]/.test(s))) bad("has a backtick or line break in a cell");
for (const p of r.paths) {
const why = unsupported(p.trim());
if (why) bad(`has an unsupported glob "${p.trim()}": ${why}`);
}
return { area: r.area.trim(), paths: r.paths.map((p) => toPosix(p.trim())), run: r.run.trim(), shared: r.shared === true };
});
}
@@ -254,7 +262,7 @@ function placeIn(text, table, { linked }) {
let i = section.start;
while (i < section.end && lines[i].trim() === "") i++;
let at = section.start;
if (i < section.end && !fenced[i] && !/^#/.test(lines[i])) {
if (i < section.end && !fenced[i] && !/^#{1,6}(\s|$)/.test(lines[i])) {
while (i < section.end && lines[i].trim() !== "") i++;
at = i;
}
@@ -283,7 +291,7 @@ function write(root, rowsFile, dryRun) {
const current = readText(file);
next =
current === null
? ["# Test map", "", "> Part of [AGENTS.md](../AGENTS.md): which checks cover which files.", "", ...table, ""].join(eol(readText(path.join(root, "AGENTS.md")) || "\n"))
? ["# Test map", "", `> Part of [AGENTS.md](${"../".repeat(map.source.split("/").length - 1)}AGENTS.md): which checks cover which files.`, "", ...table, ""].join(eol(readText(path.join(root, "AGENTS.md")) || "\n"))
: placeIn(current, table, { linked: true });
} else {
file = path.join(root, "AGENTS.md");
+25 -33
View File
@@ -37,7 +37,8 @@ test-match.mjs: match files to tests, both ways. JSON on stdout.
node test-match.mjs nearest --file <f> [--root <dir>]
Up to 3 existing test files to read for the project's test style.
Exit: 0 ok · 2 bad arguments · 3 not a git repository (gaps --scope branch).
Exit: 0 ok · 2 bad arguments · 3 not a git repository, or review-scope.mjs
not beside this script (gaps --scope branch).
`;
/* ------------------------------------------------------------- files */
@@ -143,6 +144,8 @@ function nameMatch(source, test) {
if (ext === "py") return extOf(test) === "py" && (same(tname, `test_${stem}`) || same(tname, `${stem}_test`));
if (ext === "go") return same(test, `${dirOf(source) ? `${dirOf(source)}/` : ""}${stem}_test.go`);
if (ext === "cs" || ext === "java" || ext === "kt") return extOf(test) === ext && (same(tname, `${stem}Tests`) || same(tname, `${stem}Test`));
const text = extOf(test);
if (JS_EXT.has(ext) ? !JS_EXT.has(text) : text !== ext) return false;
return same(tname, `${stem}.test`) || same(tname, `${stem}.spec`);
}
@@ -373,42 +376,30 @@ function readStdin() {
/* ------------------------------------------------------------------ gaps */
/**
* The branch's changed files, relative to root: review-scope.mjs's list when
* it ships beside this script, else the same git commands it runs.
* The branch's changed files, relative to root, from review-scope.mjs, which
* every skill that ships this script ships beside it. One list, never a copy
* of its git commands that could drift from it.
*/
export function branchFiles(root, base) {
const top = git(root, ["rev-parse", "--show-toplevel"]);
if (top === null) fail(EXIT.NOT_FOUND, "not-a-repo", `${root} is not inside a git repository.`, "Use --scope all or --scope path, or ask which files to look at.");
const prefix = (git(root, ["rev-parse", "--show-prefix"]) || "").trim();
let list;
const scope = path.join(HERE, "review-scope.mjs");
if (fs.existsSync(scope)) {
let stdout;
try {
stdout = execFileSync(process.execPath, [scope, "--root", root, ...(base ? ["--base", base] : [])], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 });
} catch (err) {
stdout = err.stdout;
}
let json;
try {
json = JSON.parse(stdout);
} catch {
fail(EXIT.CRASH, "review-scope-failed", "review-scope.mjs printed no JSON.", "Run review-scope.mjs on its own to see why.");
}
if (!json.ok) fail(EXIT.NOT_FOUND, json.error, json.message, json.next);
list = json.files.map((f) => f.path);
} else {
const pick = base ? [base, `origin/${base}`] : ["main", "origin/main", "master", "origin/master"];
const ref = pick.find((r) => git(root, ["rev-parse", "--verify", "--quiet", `${r}^{commit}`]) !== null);
if (base && !ref) fail(EXIT.NOT_FOUND, "no-base", `No branch named ${base} (or origin/${base}).`, "Pass an existing --base, or omit it to use main / master.");
const lines = (args) => (git(top.trim(), args) || "").split("\n").filter(Boolean);
list = [
...(ref ? lines(["diff", "--name-only", `${ref}...HEAD`]) : []),
...lines(["diff", "--name-only", "--cached"]),
...lines(["diff", "--name-only"]),
...lines(["ls-files", "--others", "--exclude-standard"]),
];
if (!fs.existsSync(scope)) fail(EXIT.NOT_FOUND, "review-scope-missing", "review-scope.mjs is not beside test-match.mjs.", "Reinstall the skill, or use --scope all or --scope path.");
let stdout;
try {
stdout = execFileSync(process.execPath, [scope, "--root", root, ...(base ? ["--base", base] : [])], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 });
} catch (err) {
stdout = err.stdout;
}
let json;
try {
json = JSON.parse(stdout);
} catch {
fail(EXIT.CRASH, "review-scope-failed", "review-scope.mjs printed no JSON.", "Run review-scope.mjs on its own to see why.");
}
if (!json.ok) fail(EXIT.NOT_FOUND, json.error, json.message, json.next);
const list = json.files.map((f) => f.path);
return [...new Set(list.map(toPosix))]
.filter((f) => f.startsWith(prefix))
.map((f) => f.slice(prefix.length))
@@ -451,8 +442,9 @@ function gaps(root, { scope, sub, base }) {
else {
files = allFiles(root);
if (scope === "path") {
const p = toPosix(sub).replace(/\/+$/, "");
files = files.filter((f) => fold(f) === fold(p) || fold(f).startsWith(`${fold(p)}/`));
const p = path.posix.normalize(toPosix(sub)).replace(/\/+$/, "");
// The project root (".") is every file.
if (p !== "." && p !== "") files = files.filter((f) => fold(f) === fold(p) || fold(f).startsWith(`${fold(p)}/`));
}
}
let sources = [...new Set(files)].filter(isSource).sort();
@@ -560,7 +552,7 @@ async function main(argv) {
fail(EXIT.USAGE, "bad-stdin", "--stdin needs review-scope.mjs JSON.", "Pipe review-scope.mjs output in, or pass --files.");
}
if (!json || !Array.isArray(json.files)) fail(EXIT.USAGE, "bad-stdin", "The JSON on stdin has no files list.", "Pipe review-scope.mjs output in, or pass --files.");
files = json.files.map((f) => toPosix(f.path)).filter(Boolean);
files = json.files.filter((f) => f && typeof f.path === "string" && f.path).map((f) => toPosix(f.path)).filter(Boolean);
} else fail(EXIT.USAGE, "missing-files", "covers needs --files <a,b,...> or --stdin.", "Run with --help for usage.");
out(covers(root, [...new Set(files)]));
return;
+2 -2
View File
@@ -2,11 +2,11 @@
Read only if a `run` was refused; your workflow notes give the exact `run` to post.
The meter is advice and never blocks. The console scores these launches itself when their session opens (post nothing for them): Plan, Revise plan, Document, Review, Quick task, Init, Init update, Finalize, Git, Changelog, X-ray, Diagnose. It also counts answers: every 2 cards answered in a send add a point; notes, Quick questions and buttons do not count.
The meter is advice and never blocks. The console scores these launches itself when their session opens (post nothing for them): Plan, Revise plan, Document, Review, Quick task, Init, Init update, Finalize, Git, Changelog, X-ray, Diagnose, PR Prep, Test. It also counts answers: every 2 cards answered in a send add a point; notes, Quick questions and buttons do not count.
Per-unit work is yours: `{"run":{"event":"implement-phase","id":"phase-2","tasks":9}}`, one `run` per post, never reaching the page state.
- `event`: `pathfinder-chart`, `pathfinder-question` (scores nothing now), `pathfinder-research`, `plan`, `revise-plan`, `document`, `implement-phase`, `implement-review-phase`, `review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`, `git-commits`, `git-conflict`. An unknown event is exit 3. Post only the events your notes name: a launch the console scores already has its points.
- `event`: `pathfinder-chart`, `pathfinder-question` (scores nothing now), `pathfinder-research`, `plan`, `revise-plan`, `document`, `implement-phase`, `implement-review-phase`, `review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`, `pr-prep`, `test`, `git-commits`, `git-conflict`. An unknown event is exit 3. Post only the events your notes name: a launch the console scores already has its points.
- `id`: the unit (a question's slug, `phase-N`, `map`), non-empty. The same id in the same skill run is ignored.
- `tasks`: only with `implement-phase` and `implement-review-phase`; the tasks completed (`[x]`, not blocked), a whole number 1 to 999. A phase scores one point per 3 tasks rounded up (Implement + Review one more for the review); without it, a flat 2 (or 3). It takes over the count from `headline.cleared`, never adding to it.
- `commits`: only with `git-commits`; commits made, 1 to 999, one point per 2 rounded down.
+1 -1
View File
@@ -1,6 +1,6 @@
# Helpers (Subagents)
The console points here when a `Subagents:` block reaches you. On the skills that offer it (`init`, `init-update`, `pathfinder`, `plan`, `revise-plan`, `document`, `implement`, `implement-review`, `quick-task`, `review`, `finalize`, `xray`, `diagnose`) the person turns helpers on or off from the top bar's Subagents button, per project and skill. It reaches you as a standing instruction, only when it changes.
The console points here when a `Subagents:` block reaches you. On the skills that offer it (`init`, `init-update`, `pathfinder`, `plan`, `revise-plan`, `document`, `implement`, `implement-review`, `quick-task`, `review`, `finalize`, `xray`, `diagnose`, `pr-prep`, `test`) the person turns helpers on or off from the top bar's Subagents button, per project and skill. It reaches you as a standing instruction, only when it changes.
## What arrives
+2 -2
View File
@@ -2,7 +2,7 @@
## Uncommitted changes
Only when review-scope lists `staged`, `unstaged` or `untracked` files. One `choice`, `--wait`, the files in `body`:
Only when a review-scope file's `status` includes `staged`, `unstaged` or `untracked`. One `choice`, `--wait`, the files in `body`:
```jsonc
{"title":"Get a PR ready","headline":{"stage":"Changes","cleared":0,"total":4},"items":[{"id":"uncommitted","kind":"choice","title":"Uncommitted work","allowOther":false,"body":"These files are not committed yet:\n\n- `src/a.js` (unstaged)\n- `notes.txt` (untracked)\n\nRun the checks with them, or commit first?","options":[{"text":"Include them in this run","recommended":true},{"text":"Commit first","detail":"The git skill commits them; then run PR Prep again."}]}]}
@@ -38,7 +38,7 @@ Logs go in `<session>/checks/<n>.log`. Run the `chat` check between checks, as a
## The report and the description
Doc `report`: one `md` block with the verdict first (Ready, Ready with notes or Not ready), then the checks grouped by runner (outcome, seconds, reason), then the notes. Doc `description`: one `md` block holding a single ` ```markdown ` fence, so its copy button copies the raw Markdown; the create-a-PR link (or the not-pushed line) goes in a second block under it, outside the fence. With `needsKind` (an unknown host) that block says the link cannot be built here and names `/plan2code-git`, whose board asks the host's kind once and remembers it; this page cannot save it.
Doc `report`: one `md` block with the verdict first (Ready, Ready with notes or Not ready), then the checks grouped by runner (outcome, seconds, reason), then the notes. Doc `description`: one `md` block holding a single ` ```markdown ` fence, so its copy button copies the raw Markdown; the create-a-PR link (or the not-pushed or no-link line) goes in a second block under it, outside the fence. With `needsKind` or a null `url`, that block says the link cannot be built here and names `/plan2code-git`, whose board asks an unknown host's kind once and remembers it; this page cannot save it.
```jsonc
{"headline":{"stage":"Ready","cleared":4},"docs":[{"id":"report","title":"Readiness","blocks":[{"id":"verdict","md":"## Ready with notes\n\n..."}]},{"id":"description","title":"PR description","blocks":[{"id":"text","md":"```markdown\n## Summary\n\n...\n```"},{"id":"link","md":"[Open the pull request](https://...)"}]}]}