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

+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://...)"}]}]}