From 88c72dc2cec992cb935e215e43e38d1fe851f901 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Tue, 3 Nov 2026 21:26:10 -0800 Subject: [PATCH] Add the PR Prep skill: check plan, readiness verdict and PR description AI Assisted --- install.js | 15 ++ package.json | 2 +- scripts/skill-script-helpers.mjs | 3 +- scripts/test-script-pr-prep.mjs | 266 ++++++++++++++++++++++ scripts/test-script-run-check.mjs | 38 ++-- scripts/test-script-test-match.mjs | 72 +++--- scripts/test-skill-test-runs.mjs | 3 +- scripts/test-web-console-skills.mjs | 3 +- scripts/test-web-console-spec-states.mjs | 33 +++ src/plan2code-git-scripts/git.mjs | 20 +- src/plan2code-git.md | 2 +- src/plan2code-pr-prep-scripts/pr-prep.mjs | 241 ++++++++++++++++++++ src/plan2code-pr-prep.md | 143 ++++++++++++ src/plan2code.md | 2 + src/web-console/console.md | 2 +- src/web-console/git-repo.mjs | 30 +++ src/web-console/notes/pr-prep.md | 59 +++++ src/web-console/public/index.html | 34 +++ src/web-console/public/skills.js | 22 ++ src/web-console/public/styles/poses.css | 27 +++ 20 files changed, 932 insertions(+), 85 deletions(-) create mode 100644 scripts/test-script-pr-prep.mjs create mode 100644 src/plan2code-pr-prep-scripts/pr-prep.mjs create mode 100644 src/plan2code-pr-prep.md create mode 100644 src/web-console/notes/pr-prep.md diff --git a/install.js b/install.js index 5199d85..0297cef 100644 --- a/install.js +++ b/install.js @@ -332,6 +332,20 @@ const SOURCE_PROMPTS = [ { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' } ] }, + { + source: 'plan2code-pr-prep.md', + stepNumber: 'pr-prep', + name: 'pr-prep', + displayName: 'PR Prep Mode', + description: 'Pick and run the checks a branch needs, give a readiness verdict and write the PR description', + isUtility: true, + scripts: ['review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'test-commands.mjs', 'run-check.mjs'], + additionalReferences: [ + { source: 'web-console', target: 'web-console' }, + { source: 'shared-references/test-runs.md', target: 'test-runs.md' }, + { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' } + ] + }, { source: 'plan2code-changelog.md', stepNumber: 'changelog', @@ -380,6 +394,7 @@ function generateStepLabel(prompt) { if (prompt.stepNumber === 'git') return 'Git'; if (prompt.stepNumber === 'xray') return 'X-ray'; if (prompt.stepNumber === 'diagnose') return 'Diagnose'; + if (prompt.stepNumber === 'pr-prep') return 'PR Prep'; if (prompt.stepNumber === 'changelog') return 'Changelog'; if (prompt.stepNumber === 'quick') return 'Quick Task'; return `Step ${prompt.stepNumber}`; diff --git a/package.json b/package.json index aaeed84..c733ce2 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "fix:eol": "node scripts/fix-line-endings.mjs", "play": "node scripts/play.mjs", "pretest": "node scripts/fix-line-endings.mjs", - "test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs" + "test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs" }, "devDependencies": { "gpt-tokenizer": "2.9.0", diff --git a/scripts/skill-script-helpers.mjs b/scripts/skill-script-helpers.mjs index 8402947..15312a5 100644 --- a/scripts/skill-script-helpers.mjs +++ b/scripts/skill-script-helpers.mjs @@ -64,10 +64,11 @@ export function scrubbedEnv(extra = {}) { for (const k of AMBIENT_GIT_ENV) delete process.env[k]; Object.assign(process.env, { GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG }); -export function runScript(skill, script, args, { cwd, env } = {}) { +export function runScript(skill, script, args, { cwd, env, input } = {}) { const r = spawnSync(process.execPath, [path.join(SKILLS, skill, "scripts", script), ...args], { cwd: cwd || ROOT, encoding: "utf8", + input, env: scrubbedEnv({ PLAN2CODE_NOW: NOW, ...env }), }); let json = null; diff --git a/scripts/test-script-pr-prep.mjs b/scripts/test-script-pr-prep.mjs new file mode 100644 index 0000000..da7af3d --- /dev/null +++ b/scripts/test-script-pr-prep.mjs @@ -0,0 +1,266 @@ +// Tests for plan2code-pr-prep's scripts/pr-prep.mjs: the template lookup, the +// pull-request link and the branch's spec folder. See skill-script-helpers.mjs +// for how these run. + +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; +import { runScript, tmp, write, gitInit, gitIn, slashed, fixtureCleanup } from "./skill-script-helpers.mjs"; + +after(fixtureCleanup); + +// The console home holds pr-hosts.json; keep the real one out of every run. +const HOME = tmp("pr-prep-console-home"); +const P = (cwd, ...a) => runScript("plan2code-pr-prep", "pr-prep.mjs", a, { cwd, env: { PLAN2CODE_CONSOLE_HOME: HOME } }); + +/* --------------------------------------------------------------- template */ + +const LOOKUP = [ + ".github/pull_request_template.md", + ".github/PULL_REQUEST_TEMPLATE.md", + "PULL_REQUEST_TEMPLATE.md", + "docs/pull_request_template.md", + ".github/PULL_REQUEST_TEMPLATE/feature.md", + "docs/PULL_REQUEST_TEMPLATE/feature.md", + ".gitlab/merge_request_templates/Default.md", +]; + +test("pr-prep template: each place in the lookup order is found on its own", () => { + for (const rel of LOOKUP) { + const dir = tmp("pr-tpl"); + write(dir, rel, "## Summary\n"); + const r = P(dir, "template"); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json, { ok: true, found: true, path: rel, headings: ["Summary"], hasTesting: false, others: [] }, rel); + } +}); + +test("pr-prep template: the first in order wins and the rest are others", () => { + const dir = tmp("pr-tpl-order"); + write(dir, "PULL_REQUEST_TEMPLATE.md", "## Root\n"); + write(dir, "docs/pull_request_template.md", "## Docs\n"); + write(dir, ".github/PULL_REQUEST_TEMPLATE/feature.md", "## Feature\n"); + write(dir, ".github/PULL_REQUEST_TEMPLATE/bug.md", "## Bug\n"); + write(dir, ".github/PULL_REQUEST_TEMPLATE/notes.txt", "not a template\n"); + write(dir, ".gitlab/merge_request_templates/Default.md", "## GitLab\n"); + const r = P(dir, "template"); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.path, "PULL_REQUEST_TEMPLATE.md"); + assert.deepEqual(r.json.headings, ["Root"]); + assert.deepEqual(r.json.others, [ + "docs/pull_request_template.md", + ".github/PULL_REQUEST_TEMPLATE/bug.md", + ".github/PULL_REQUEST_TEMPLATE/feature.md", + ".gitlab/merge_request_templates/Default.md", + ]); +}); + +test("pr-prep template: names are compared case-insensitively", () => { + const dir = tmp("pr-tpl-case"); + write(dir, ".GitHub/Pull_Request_Template.MD", "## What\n"); + const r = P(dir, "template"); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.found, true); + assert.equal(r.json.path, ".GitHub/Pull_Request_Template.MD"); +}); + +test("pr-prep template: headings outside code fences only, # to ###, and hasTesting", () => { + const dir = tmp("pr-tpl-headings"); + write( + dir, + ".github/pull_request_template.md", + "# Title\n\n\n## Summary ##\n\n```markdown\n## Not a heading\n```\n\n~~~\n# Also not\n~~~\n\n### How was this tested?\n#### Too deep\n ## indented code\n#No space\n" + ); + const r = P(dir, "template"); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.headings, ["Title", "Summary", "How was this tested?"]); + assert.equal(r.json.hasTesting, true); + + for (const [heading, expected] of [["## Verification", true], ["## QA notes", true], ["## How it was checked", true], ["## Summary\n## Risks", false]]) { + write(dir, ".github/pull_request_template.md", `${heading}\n`); + assert.equal(P(dir, "template").json.hasTesting, expected, heading); + } +}); + +test("pr-prep template: none found", () => { + const dir = tmp("pr-tpl-none"); + write(dir, "README.md", "# Project\n"); + write(dir, ".github/workflows/ci.yml", "on: push\n"); + const r = P(dir, "template"); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json, { ok: true, found: false, path: null, headings: [], hasTesting: false, others: [] }); +}); + +/* ----------------------------------------------------------------- pr-url */ + +function repoOnMain(name) { + const repo = tmp(name); + const g = gitInit(repo); + write(repo, "a.txt", "a\n"); + g("add", "a.txt"); + g("commit", "-q", "-m", "init"); + return { repo, g }; +} + +test("pr-prep pr-url: a pushed branch gives the link, an unpushed one pushed: false with exit 0", () => { + const { repo, g } = repoOnMain("pr-url"); + const bare = tmp("pr-url-origin"); + execFileSync("git", ["init", "-q", "--bare", "-b", "main", bare], { stdio: "pipe" }); + g("remote", "add", "origin", slashed(bare)); + g("push", "-q", "-u", "origin", "main"); + g("switch", "-q", "-c", "feature/x"); + write(repo, "b.txt", "b\n"); + g("add", "b.txt"); + g("commit", "-q", "-m", "b"); + + const unpushed = P(repo, "pr-url"); + assert.equal(unpushed.code, 0, unpushed.stderr); + assert.equal(unpushed.json.ok, true); + assert.equal(unpushed.json.pushed, false); + assert.equal(unpushed.json.branch, "feature/x"); + assert.match(unpushed.json.next, /plan2code-git/); + + g("push", "-q", "-u", "origin", "feature/x"); + // The pushed copy lives in the local bare repo; the link comes from the + // remote's address, so point it at a forge host once the push is done. + g("remote", "set-url", "origin", "git@github.com:owner/repo.git"); + write(repo, "c.txt", "c\n"); + g("add", "c.txt"); + g("commit", "-q", "-m", "c"); + const pushed = P(repo, "pr-url"); + assert.equal(pushed.code, 0, pushed.stderr); + assert.deepEqual(pushed.json, { + ok: true, + pushed: true, + url: "https://github.com/owner/repo/compare/main...feature/x?quick_pull=1", + host: "github.com", + kind: "github", + needsKind: false, + branch: "feature/x", + base: "main", + ahead: 1, + }); +}); + +test("pr-prep pr-url: a detached HEAD fails as git.mjs does; outside a repo is exit 3", () => { + const { repo, g } = repoOnMain("pr-url-detached"); + g("checkout", "-q", "--detach"); + const mine = P(repo, "pr-url"); + const git = runScript("plan2code-git", "git.mjs", ["pr-url"], { cwd: repo, env: { PLAN2CODE_CONSOLE_HOME: HOME } }); + assert.equal(mine.code, 5); + assert.equal(mine.code, git.code); + assert.deepEqual(mine.json, git.json); + assert.equal(mine.json.error, "detached"); + + const plain = tmp("pr-url-plain"); + const r = P(plain, "pr-url"); + assert.equal(r.code, 3); + assert.equal(r.json.error, "not-a-repo"); +}); + +/* ------------------------------------------------------------------- spec */ + +const EARLY = new Date("2026-06-01T12:00:00Z"); +const LATE = new Date("2026-07-15T12:00:00Z"); + +/** Every file under `dir` stamped with `when`. */ +function stamp(dir, when) { + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) stamp(p, when); + else fs.utimesSync(p, when, when); + } +} + +/** A repo whose main commit is dated 2026-07-01, on `branch` from it, with the given spec folders (each stamped EARLY). */ +function specRepo(name, branch, folders) { + const repo = tmp(name); + const g = gitInit(repo); + write(repo, "a.txt", "a\n"); + g("add", "a.txt"); + const env = { ...process.env, GIT_AUTHOR_DATE: "2026-07-01T12:00:00Z", GIT_COMMITTER_DATE: "2026-07-01T12:00:00Z" }; + execFileSync("git", ["commit", "-q", "-m", "init"], { cwd: repo, env, stdio: "pipe" }); + if (branch !== "main") g("switch", "-q", "-c", branch); + for (const f of folders) write(repo, `${f}/overview.md`, "# Spec\n"); + for (const d of ["specs", "specs--completed"]) if (fs.existsSync(path.join(repo, d))) stamp(path.join(repo, d), EARLY); + return repo; +} + +test("pr-prep spec: the branch name matches a folder in specs/", () => { + const repo = specRepo("spec-branch", "feature/pr-prep-and-test-skills", ["specs/pr-prep-and-test-skills", "specs/other-thing", "specs--completed/pr-prep-and-test-skills"]); + const r = P(repo, "spec"); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json, { ok: true, branch: "feature/pr-prep-and-test-skills", match: "specs/pr-prep-and-test-skills", candidates: [], how: "branch" }); +}); + +test("pr-prep spec: a match only in specs--completed/, a user segment, and --branch", () => { + const repo = specRepo("spec-completed", "jane/Lunch_Vote", ["specs--completed/lunch-vote", "specs/unrelated"]); + const r = P(repo, "spec"); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.match, "specs--completed/lunch-vote"); + assert.equal(r.json.how, "branch"); + assert.equal(P(repo, "spec", "--branch", "fix/unrelated-crash").json.match, "specs/unrelated"); +}); + +test("pr-prep spec: two names in the branch is ask", () => { + const repo = specRepo("spec-ask", "feature/auth-and-billing", ["specs/auth", "specs/billing", "specs/search"]); + const r = P(repo, "spec"); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json, { ok: true, branch: "feature/auth-and-billing", match: null, candidates: ["specs/auth", "specs/billing"], how: "ask" }); +}); + +test("pr-prep spec: no name match, one folder touched since the branch began, is recent; several is ask", () => { + const repo = specRepo("spec-recent", "feature/something-else", ["specs/old-work", "specs/new-work", "specs--completed/done-work"]); + stamp(path.join(repo, "specs", "new-work"), LATE); + const r = P(repo, "spec"); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json, { ok: true, branch: "feature/something-else", match: "specs/new-work", candidates: [], how: "recent" }); + + write(repo, "specs--completed/done-work/deep/a/b/c/notes.md", "x\n"); + stamp(path.join(repo, "specs--completed", "done-work"), EARLY); + fs.utimesSync(path.join(repo, "specs--completed/done-work/deep/a/b/c/notes.md"), LATE, LATE); + assert.equal(P(repo, "spec").json.how, "recent", "a file five levels down is past the walk"); + fs.utimesSync(path.join(repo, "specs--completed/done-work/overview.md"), LATE, LATE); + const two = P(repo, "spec").json; + assert.equal(two.how, "ask"); + assert.deepEqual(two.candidates, ["specs/new-work", "specs--completed/done-work"]); +}); + +test("pr-prep spec: --branch measures the recent rule from that branch's start, not HEAD's", () => { + const repo = specRepo("spec-branch-start", "feature/side-work", ["specs/tracker"]); + const g = gitIn(repo); + g("switch", "-q", "main"); + write(repo, "b.txt", "b\n"); + g("add", "b.txt"); + const env = { ...process.env, GIT_AUTHOR_DATE: "2026-08-01T12:00:00Z", GIT_COMMITTER_DATE: "2026-08-01T12:00:00Z" }; + execFileSync("git", ["commit", "-q", "-m", "later on main"], { cwd: repo, env, stdio: "pipe" }); + stamp(path.join(repo, "specs", "tracker"), LATE); + assert.equal(P(repo, "spec").json.how, "none", "on main the start is main's own tip, after the folder changed"); + const r = P(repo, "spec", "--branch", "feature/side-work"); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json, { ok: true, branch: "feature/side-work", match: "specs/tracker", candidates: [], how: "recent" }); +}); + +test("pr-prep spec: nothing fits is none; outside a repo is exit 3", () => { + const repo = specRepo("spec-none", "feature/something-else", ["specs/old-work"]); + const r = P(repo, "spec"); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json, { ok: true, branch: "feature/something-else", match: null, candidates: [], how: "none" }); + const bare = specRepo("spec-empty", "main", []); + assert.equal(P(bare, "spec").json.how, "none"); + + const plain = tmp("spec-plain"); + const out = P(plain, "spec"); + assert.equal(out.code, 3); + assert.equal(out.json.error, "not-a-repo"); +}); + +test("pr-prep: bad arguments exit 2", () => { + const dir = tmp("pr-args"); + assert.equal(P(dir).code, 2); + assert.equal(P(dir, "nope").code, 2); + assert.equal(P(dir, "template", "extra").code, 2); + assert.equal(P(dir, "spec", "--bogus").code, 2); +}); diff --git a/scripts/test-script-run-check.mjs b/scripts/test-script-run-check.mjs index 3d26034..75434cd 100644 --- a/scripts/test-script-run-check.mjs +++ b/scripts/test-script-run-check.mjs @@ -1,26 +1,16 @@ // run-check.mjs: the four outcomes, the process-tree kill on timeout, the log -// and the tail cap. Runs src/skill-scripts/run-check.mjs directly until a -// skill ships it. See skill-script-helpers.mjs for the fixtures. +// and the tail cap, run from the built plan2code-pr-prep skill, which ships +// it. See skill-script-helpers.mjs for the fixtures. import { test } from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; import path from "node:path"; import { spawnSync } from "node:child_process"; -import { ROOT, NOW, scrubbedEnv, tmp, write } from "./skill-script-helpers.mjs"; +import { ROOT, runScript, scrubbedEnv, tmp, write } from "./skill-script-helpers.mjs"; -const SCRIPT = path.join(ROOT, "src", "skill-scripts", "run-check.mjs"); const NODE = `"${process.execPath}"`; -function runShared(args, { cwd } = {}) { - const r = spawnSync(process.execPath, [SCRIPT, ...args], { cwd: cwd || ROOT, encoding: "utf8", env: scrubbedEnv({ PLAN2CODE_NOW: NOW }) }); - let json = null; - try { - json = JSON.parse(r.stdout); - } catch {} - return { code: r.status, json, stdout: r.stdout, stderr: r.stderr }; -} - const alive = (pid) => { try { process.kill(pid, 0); @@ -31,7 +21,7 @@ const alive = (pid) => { }; test("run-check: passed on exit 0", () => { - const r = runShared(["--cmd", `${NODE} -e "process.exit(0)"`]); + const r = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} -e "process.exit(0)"`]); assert.equal(r.code, 0, r.stderr); assert.equal(r.json.outcome, "passed"); assert.equal(r.json.exit, 0); @@ -43,7 +33,7 @@ test("run-check: passed on exit 0", () => { test("run-check: failed on exit 1, with the printed lines in the tail", () => { const dir = tmp("check-fail"); write(dir, "fail.js", "console.log('first line');\nconsole.error('second line');\nprocess.exit(1);\n"); - const r = runShared(["--cmd", `${NODE} fail.js`, "--cwd", dir]); + const r = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} fail.js`, "--cwd", dir]); assert.equal(r.code, 0, r.stderr); assert.equal(r.json.outcome, "failed"); assert.equal(r.json.exit, 1); @@ -52,11 +42,11 @@ test("run-check: failed on exit 1, with the printed lines in the tail", () => { }); test("run-check: not-started for a made-up command and for a missing --cwd", () => { - const r = runShared(["--cmd", "p2c-no-such-command-xyz --flag"]); + const r = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", "p2c-no-such-command-xyz --flag"]); assert.equal(r.code, 0, r.stderr); assert.equal(r.json.outcome, "not-started"); assert.equal(r.json.reason, "command-not-found"); - const c = runShared(["--cmd", `${NODE} -e "process.exit(0)"`, "--cwd", path.join(tmp("check-cwd"), "missing")]); + const c = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} -e "process.exit(0)"`, "--cwd", path.join(tmp("check-cwd"), "missing")]); assert.equal(c.code, 0, c.stderr); assert.equal(c.json.outcome, "not-started"); assert.equal(c.json.reason, "cwd-missing"); @@ -66,7 +56,7 @@ test("run-check: timeout kills the whole process tree", async () => { const dir = tmp("check-timeout"); write(dir, "grandchild.js", "require('fs').writeFileSync(require('path').join(__dirname, 'pid.txt'), String(process.pid));\nsetInterval(() => {}, 1000);\n"); write(dir, "parent.js", "require('child_process').spawn(process.execPath, [require('path').join(__dirname, 'grandchild.js')], { stdio: 'inherit' });\nsetInterval(() => {}, 1000);\n"); - const r = runShared(["--cmd", `${NODE} parent.js`, "--cwd", dir, "--timeout", "2"]); + const r = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} parent.js`, "--cwd", dir, "--timeout", "2"]); assert.equal(r.code, 0, r.stderr); assert.equal(r.json.outcome, "timeout"); const pidFile = path.join(dir, "pid.txt"); @@ -81,7 +71,7 @@ test("run-check: --log holds the full output and the tail keeps 60 lines of at m const dir = tmp("check-log"); write(dir, "many.js", "for (let i = 1; i <= 100; i++) console.log('line ' + i);\nconsole.log('x'.repeat(500));\n"); const log = path.join(dir, "logs", "deep", "run.log"); - const r = runShared(["--cmd", `${NODE} many.js`, "--cwd", dir, "--log", log]); + const r = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} many.js`, "--cwd", dir, "--log", log]); assert.equal(r.code, 0, r.stderr); assert.equal(r.json.outcome, "passed"); assert.equal(r.json.log, log); @@ -95,11 +85,11 @@ test("run-check: --log holds the full output and the tail keeps 60 lines of at m }); test("run-check: bad arguments exit 2", () => { - assert.equal(runShared([]).code, 2); - assert.equal(runShared(["--cmd", "x", "--timeout", "soon"]).code, 2); - assert.equal(runShared(["--cmd", "x", "--timeout", "0"]).code, 2); - assert.equal(runShared(["--cmd", "x", "--timeout", "86401"]).code, 2, "past one day the timer would overflow"); - assert.equal(runShared(["--cmd", "x", "extra"]).code, 2); + assert.equal(runScript("plan2code-pr-prep", "run-check.mjs", []).code, 2); + assert.equal(runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", "x", "--timeout", "soon"]).code, 2); + assert.equal(runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", "x", "--timeout", "0"]).code, 2); + assert.equal(runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", "x", "--timeout", "86401"]).code, 2, "past one day the timer would overflow"); + assert.equal(runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", "x", "extra"]).code, 2); }); test("run-check and test-commands do nothing when imported", () => { diff --git a/scripts/test-script-test-match.mjs b/scripts/test-script-test-match.mjs index 1409a43..8893a6a 100644 --- a/scripts/test-script-test-match.mjs +++ b/scripts/test-script-test-match.mjs @@ -1,29 +1,15 @@ -// Tests for the shared test-match.mjs. -// -// No skill ships test-match.mjs yet, so these run it from src/skill-scripts/, -// where common.mjs, glob.mjs, test-map.mjs and review-scope.mjs sit beside it. -// See skill-script-helpers.mjs for the fixtures and the scrubbed git config. +// Tests for the shared test-match.mjs, run from the built plan2code-pr-prep +// skill, which ships it beside common.mjs, glob.mjs, test-map.mjs and +// review-scope.mjs. See skill-script-helpers.mjs for the fixtures and the +// scrubbed git config. import { test, after } from "node:test"; import assert from "node:assert/strict"; -import path from "node:path"; -import { spawnSync, execFileSync } from "node:child_process"; -import { ROOT, NOW, scrubbedEnv, tmp, write, gitInit, gitIn, copyFixture, fixtureCleanup } from "./skill-script-helpers.mjs"; +import { execFileSync } from "node:child_process"; +import { runScript, tmp, write, gitInit, gitIn, copyFixture, fixtureCleanup } from "./skill-script-helpers.mjs"; after(fixtureCleanup); -const SCRIPT = path.join(ROOT, "src", "skill-scripts", "test-match.mjs"); -const SCOPE = path.join(ROOT, "src", "skill-scripts", "review-scope.mjs"); - -function runShared(args, { cwd, input } = {}) { - const r = spawnSync(process.execPath, [SCRIPT, ...args], { cwd: cwd || ROOT, encoding: "utf8", input, env: scrubbedEnv({ PLAN2CODE_NOW: NOW }) }); - let json = null; - try { - json = JSON.parse(r.stdout); - } catch {} - return { code: r.status, json, stdout: r.stdout, stderr: r.stderr }; -} - // A commit with pinned author and committer dates. function commitAt(dir, date, msg, files = {}) { for (const [rel, content] of Object.entries(files)) write(dir, rel, content); @@ -83,7 +69,7 @@ function matchRepo() { test("test-match covers: map rows, shared hits, hints and the fallback rules", () => { const dir = matchRepo(); const files = ["src/launcher/a.js", "src/launcher/shared.js", "src/web-console/x.js", "src/app/util.js", "src/widget/button.js", "src/lib/math.js", "src/pkgdir/index.js", "src/lib/alias.js", "pkg/mod.py", "gosrc/util/u.go", "package.json", "fixtures/sample.json", "test/helpers/setup.js"]; - const r = runShared(["covers", "--files", files.join(",")], { cwd: dir }); + const r = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--files", files.join(",")], { cwd: dir }); assert.equal(r.code, 0, r.stderr); assert.equal(r.json.mapFound, true); assert.deepEqual(r.json.matched, [ @@ -110,7 +96,7 @@ test("test-match covers: map rows, shared hits, hints and the fallback rules", ( test("test-match covers: Windows-style --files input", () => { const dir = matchRepo(); - const r = runShared(["covers", "--files", "src\\launcher\\a.js"], { cwd: dir }); + const r = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--files", "src\\launcher\\a.js"], { cwd: dir }); assert.equal(r.code, 0, r.stderr); assert.deepEqual(r.json.matched[0].files, ["src/launcher/a.js"]); }); @@ -120,21 +106,21 @@ test("test-match covers --stdin: real review-scope.mjs output", () => { gitIn(dir)("checkout", "-q", "-b", "feature"); commitAt(dir, "2026-07-02T12:00:00Z", "Change", { "src/launcher/a.js": "a2\n" }); write(dir, "src/app/util.js", "u2\n"); - const scope = spawnSync(process.execPath, [SCOPE], { cwd: dir, encoding: "utf8", env: scrubbedEnv() }); - assert.equal(scope.status, 0, scope.stderr); - const r = runShared(["covers", "--stdin"], { cwd: dir, input: scope.stdout }); + const scope = runScript("plan2code-pr-prep", "review-scope.mjs", [], { cwd: dir }); + assert.equal(scope.code, 0, scope.stderr); + const r = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--stdin"], { cwd: dir, input: scope.stdout }); assert.equal(r.code, 0, r.stderr); 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(runShared(["covers", "--stdin"], { cwd: dir, input: "not json" }).code, 2); - assert.equal(runShared(["covers"], { cwd: dir }).code, 2); + assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--stdin"], { cwd: dir, input: "not json" }).code, 2); + assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["covers"], { cwd: dir }).code, 2); }); test("test-match covers: no test map leaves every file unmatched, still exit 0", () => { const dir = tmp("match-nomap"); write(dir, "a.js", "a\n"); write(dir, "a.test.js", "t\n"); - const r = runShared(["covers", "--files", "a.js,b.js"], { cwd: dir }); + const r = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--files", "a.js,b.js"], { cwd: dir }); assert.equal(r.code, 0, r.stderr); assert.equal(r.json.mapFound, false); assert.deepEqual(r.json.matched, []); @@ -160,7 +146,7 @@ function gapsRepo() { test("test-match gaps --scope all: untested source files ranked by last change, then churn", () => { const dir = gapsRepo(); - const r = runShared(["gaps", "--scope", "all"], { cwd: dir }); + 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, [ { file: "src/sub/c.js", area: null, runner: null, commits90d: 1, lastTouched: "2026-07-25" }, @@ -176,15 +162,15 @@ test("test-match gaps --scope all: untested source files ranked by last change, test("test-match gaps --scope path and --scope branch", () => { const dir = gapsRepo(); - const p = runShared(["gaps", "--scope", "path", "--path", "src/sub"], { cwd: dir }); + 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"]); - assert.equal(runShared(["gaps", "--scope", "path"], { cwd: dir }).code, 2, "--scope path needs --path"); + 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"); commitAt(dir, "2026-07-30T12:00:00Z", "Feature", { "src/feat.js": "f\n", "src/feat2.js": "g\n" }); write(dir, "src/new.js", "n\n"); - const b = runShared(["gaps", "--scope", "branch"], { cwd: dir }); + const b = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "branch"], { cwd: dir }); assert.equal(b.code, 0, b.stderr); assert.deepEqual(b.json.gaps, [ { file: "src/feat.js", area: null, runner: null, commits90d: 1, lastTouched: "2026-07-30" }, @@ -197,13 +183,13 @@ test("test-match gaps: a non-git folder walks the tree; --scope branch is exit 3 const dir = tmp("match-nogit"); write(dir, "src/a.js", "a\n"); write(dir, "node_modules/x/i.js", "x\n"); - const r = runShared(["gaps", "--scope", "all"], { cwd: dir }); + 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, [{ file: "src/a.js", area: null, runner: null, commits90d: null, lastTouched: null }]); - const b = runShared(["gaps", "--scope", "branch"], { cwd: dir }); + const b = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "branch"], { cwd: dir }); assert.equal(b.code, 3); assert.equal(b.json.error, "not-a-repo"); - assert.equal(runShared(["gaps"], { cwd: dir }).code, 2); + assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["gaps"], { cwd: dir }).code, 2); }); test("test-match gaps: any matching row with a run covers a file; a row without one only names its area", () => { @@ -213,7 +199,7 @@ test("test-match gaps: any matching row with a run covers a file; a row without write(dir, "src/y.js", "y\n"); write(dir, "src/m.ts", "m\n"); write(dir, "src/m.test.mts", "t\n"); - const r = runShared(["gaps", "--scope", "all"], { cwd: dir }); + 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, [{ file: "src/y.js", area: "Source", runner: null, commits90d: null, lastTouched: null }]); assert.equal(r.json.covered, 2, "x.js by the second row, m.ts by its .mts test"); @@ -222,7 +208,7 @@ test("test-match gaps: any matching row with a run covers a file; a row without 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"); - const r = runShared(["gaps", "--scope", "all"], { cwd: dir }); + const r = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "all"], { cwd: dir }); assert.equal(r.code, 0, r.stderr); assert.equal(r.json.capped, true); assert.equal(r.json.scanned, 2000); @@ -234,21 +220,21 @@ test("test-match gaps: capped at 2,000 source files", () => { test("test-match nearest: own tests, then the same folder, then the mirrored folder, at most 3", () => { const dir = matchRepo(); - const r = runShared(["nearest", "--file", "src/app/util.js"], { cwd: dir }); + const r = runScript("plan2code-pr-prep", "test-match.mjs", ["nearest", "--file", "src/app/util.js"], { cwd: dir }); assert.equal(r.code, 0, r.stderr); assert.deepEqual(r.json, { ok: true, file: "src/app/util.js", tests: ["src/app/util.test.js", "src/app/other.test.js", "tests/app/mirror.test.js"] }); - const m = runShared(["nearest", "--file", "src/app/new.js"], { cwd: dir }); + const m = runScript("plan2code-pr-prep", "test-match.mjs", ["nearest", "--file", "src/app/new.js"], { cwd: dir }); assert.deepEqual(m.json.tests, ["src/app/other.test.js", "src/app/util.test.js", "tests/app/mirror.test.js"]); - assert.equal(runShared(["nearest"], { cwd: dir }).code, 2); + assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["nearest"], { cwd: dir }).code, 2); }); test("test-match nearest: the area's run path, then the nearest by shared folders", () => { const dir = matchRepo(); - const r = runShared(["nearest", "--file", "src/web-console/x.js"], { cwd: dir }); + const r = runScript("plan2code-pr-prep", "test-match.mjs", ["nearest", "--file", "src/web-console/x.js"], { cwd: dir }); assert.equal(r.code, 0, r.stderr); assert.deepEqual(r.json.tests.slice(0, 2), ["tests/console/page.test.js", "tests/console/server.test.js"], "the Console row's run names tests/console"); assert.equal(r.json.tests.length, 3); - const deep = runShared(["nearest", "--file", "src/widget/deep/z.js"], { cwd: dir }); + const deep = runScript("plan2code-pr-prep", "test-match.mjs", ["nearest", "--file", "src/widget/deep/z.js"], { cwd: dir }); assert.equal(deep.json.tests[0], "src/widget/__tests__/button.js", "the test file sharing the most folders"); }); @@ -281,7 +267,7 @@ test("test-match covers: AGENTS.md's Targeted tests first table, saved as a test "Workflow prompt": "src/plan2code-3-implement.md", Docs: ".readme/web-console.md", }; - const r = runShared(["covers", "--files", Object.values(samples).join(",")], { cwd: dir }); + const r = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--files", Object.values(samples).join(",")], { cwd: dir }); assert.equal(r.code, 0, r.stderr); assert.deepEqual(r.json.unmatched, []); for (const [area, file] of Object.entries(samples)) { diff --git a/scripts/test-skill-test-runs.mjs b/scripts/test-skill-test-runs.mjs index beb7666..046aa0e 100644 --- a/scripts/test-skill-test-runs.mjs +++ b/scripts/test-skill-test-runs.mjs @@ -47,7 +47,7 @@ test("Document writes Targeted, Quick checks and Full suite lines and reads test assert.match(doc, /no Full Suite row: ask/); }); -test("test-runs.md ships in the six skills that run, write or offer tests, and in no other", () => { +test("test-runs.md ships in the seven skills that run, write or offer tests, and in no other", () => { // npm test has just built skills/; a direct run builds it so the check never reads a stale tree. if (process.env.npm_lifecycle_event !== "test") { execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" }); @@ -59,6 +59,7 @@ test("test-runs.md ships in the six skills that run, write or offer tests, and i "plan2code-3-implement", "plan2code-3-implement-review", "plan2code-4-finalize", + "plan2code-pr-prep", "plan2code-quick-task", "plan2code-review", ]); diff --git a/scripts/test-web-console-skills.mjs b/scripts/test-web-console-skills.mjs index 0e76bd8..5870eb7 100644 --- a/scripts/test-web-console-skills.mjs +++ b/scripts/test-web-console-skills.mjs @@ -399,7 +399,7 @@ test("Implement's card launches Implement + Review when Review is ticked", () => assert.equal(launchVariant(quick, true), quick, "a card with no Review box is unchanged"); }); -test("helper-strength.md ships in the thirteen skills that start helpers, and in no other", () => { +test("helper-strength.md ships in the fourteen skills that start helpers, and in no other", () => { // npm test has just built skills/; a direct run builds it so the check never reads a stale tree. if (process.env.npm_lifecycle_event !== "test") { execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" }); @@ -417,6 +417,7 @@ test("helper-strength.md ships in the thirteen skills that start helpers, and in "plan2code-diagnose", "plan2code-init", "plan2code-init-update", + "plan2code-pr-prep", "plan2code-quick-task", "plan2code-review", "plan2code-xray", diff --git a/scripts/test-web-console-spec-states.mjs b/scripts/test-web-console-spec-states.mjs index a4d97d1..3d3ab71 100644 --- a/scripts/test-web-console-spec-states.mjs +++ b/scripts/test-web-console-spec-states.mjs @@ -275,6 +275,18 @@ const CARDS = { built: { on: true }, unrecognized: { on: true }, }, + "plan2code-pr-prep": { + "none": { on: true }, + diagnosed: { on: true }, + fixed: { on: true }, + exploring: { on: true }, + mapped: { on: true }, + planned: { on: true }, + documented: { on: true }, + building: { on: true }, + built: { on: true }, + unrecognized: { on: true }, + }, "plan2code-changelog": { "none": { on: true }, diagnosed: { on: true }, @@ -418,6 +430,27 @@ test("the scan: every state it can return is in the table, and a fixture reaches assert.deepEqual(scanProblems(FIXTURES, known), ["the scan returns unrecognized, which spec-states.js lacks"]); }); +test("the scan: a PR-READINESS report changes no spec's state, and alone it stays unrecognized", () => { + const scanOf = (fixtures) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-readiness-")); + try { + for (const [name, files] of Object.entries(fixtures)) + for (const [rel, text] of Object.entries(files)) { + const file = path.join(root, "specs", name, rel); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, text); + } + return Object.fromEntries(scanProject(root).specs.map((sp) => [sp.name, [sp.state, sp.detail]])); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }; + const REPORT = { "PR-READINESS-20261103.md": "# PR readiness\n\n**Verdict:** Ready\n\n- [x] Unit tests\n- [ ] Lint (trimmed)\n" }; + const withReport = Object.fromEntries(Object.entries(FIXTURES).map(([name, files]) => [name, { ...files, ...REPORT }])); + assert.deepEqual(scanOf(withReport), scanOf(FIXTURES)); + assert.equal(scanOf({ only: REPORT }).only[0], "unrecognized"); +}); + test("the scan: an assumed task counts as done and is named, and numbered task lines count", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-assumed-")); const specs = { diff --git a/src/plan2code-git-scripts/git.mjs b/src/plan2code-git-scripts/git.mjs index 767ac4c..5fd3717 100644 --- a/src/plan2code-git-scripts/git.mjs +++ b/src/plan2code-git-scripts/git.mjs @@ -828,18 +828,14 @@ function classifyError({ file }) { } async function prUrlCmd({ root, branch, base }) { - const s = repoState(root); - const b = (branch || "").trim() || s.branch; - if (!b) fail(EXIT.REFUSED, "detached", "HEAD is detached, so there is no branch to open a pull request for.", "Switch to a branch, or pass --branch."); - const row = localBranch(s, b); - if (!row) fail(EXIT.INVALID, "unknown-branch", `There is no local branch named "${b}".`, "Pick a branch from the list."); - const into = (base || "").trim() || s.def.name; - if (!into) fail(EXIT.INVALID, "no-base", "There is no default branch to open the pull request against.", "Pass --base ."); - // A pull request from a branch into itself is no pull request (a push to main). - if (into === b) fail(EXIT.INVALID, "is-base", `${b} is the branch pull requests go into, so there is nothing to open.`, "Post no link for this push."); - const remote = row.upstream && !row.gone ? R.readRemotes(root, await prHosts()).find((r) => r.name === row.upstreamRemote) : null; - if (!remote) fail(EXIT.INVALID, "not-pushed", `${b} is not on a remote yet.`, "Publish it first (plan publish)."); - out({ ok: true, url: R.prUrl(remote, { base: into, head: b }), host: remote.host, kind: remote.kind, needsKind: !!remote.host && !remote.kind }); + let link; + try { + link = R.prLink(root, { branch, base, prHosts: await prHosts() }); + } catch (e) { + if (!R.PR_LINK_CODES.has(e?.code)) throw e; + fail(e.code === "detached" ? EXIT.REFUSED : EXIT.INVALID, e.code, e.message, e.next); + } + out({ ok: true, url: link.url, host: link.host, kind: link.kind, needsKind: link.needsKind }); } /* ------------------------------------------------------------------ main */ diff --git a/src/plan2code-git.md b/src/plan2code-git.md index 524afa4..7d4ed1a 100644 --- a/src/plan2code-git.md +++ b/src/plan2code-git.md @@ -103,7 +103,7 @@ In the terminal the same stops are asked in prose, with the diff printed. ## Terminal - **No instruction:** print the status from `state` (branch, ahead/behind, changed files) and ask what to do, `next` first. -- **After an action:** show the new state and one line naming the likely next step, then stop. A follow-up reply runs it; there is no "what next?" loop. +- **After an action:** show the new state and one line naming the likely next step, then stop. A follow-up reply runs it; there is no "what next?" loop. After a push or publish (or when the branch is pushed with nothing left to commit), that next step may be `/plan2code-pr-prep`: run the checks and write the PR description. - **Several actions in one instruction** (`commit and push`): state the plan in one line, run each step in order, ask each ask-first confirm at its own step with the same `confirm` text the board shows, and stop at the first failure with git's error and `classify-error`'s `next`. - **An unclear instruction:** offer the two or three likely readings through the question tool, the state-based guess first. Never run on a guess. - Print the pull-request link from `pr-url` after a push or publish (`needsKind` → ask the host's kind once and say it is remembered). diff --git a/src/plan2code-pr-prep-scripts/pr-prep.mjs b/src/plan2code-pr-prep-scripts/pr-prep.mjs new file mode 100644 index 0000000..97231a8 --- /dev/null +++ b/src/plan2code-pr-prep-scripts/pr-prep.mjs @@ -0,0 +1,241 @@ +#!/usr/bin/env node +// pr-prep.mjs: the facts only PR Prep needs. +// +// Where the repository's pull-request template is and which headings it asks +// for, the create-a-pull-request link (through git-repo.mjs, the same code the +// git skill uses, so the two never disagree), and which spec folder belongs to +// the branch, for the save offer. It only reads: it never commits, pushes or +// writes a file. + +import fs from "node:fs"; +import path from "node:path"; +import { EXIT, consoleModule, fail, gitRepo, out, parseArgs, run } from "./common.mjs"; + +const USAGE = ` +pr-prep.mjs: read-only facts for PR Prep. JSON on stdout. + + node pr-prep.mjs template [--root ] + The pull-request template, looked for in this order (names compared + case-insensitively): .github/pull_request_template.md, + .github/PULL_REQUEST_TEMPLATE.md, PULL_REQUEST_TEMPLATE.md, + docs/pull_request_template.md, then the first .md in + .github/PULL_REQUEST_TEMPLATE/, docs/PULL_REQUEST_TEMPLATE/ and + .gitlab/merge_request_templates/. + Prints { ok, found, path, headings, hasTesting, others }. + headings the template's # to ### headings in order, text only, + outside code fences + hasTesting a heading is about testing (test, verify, how it was + checked, QA) + others every further template found, to mention to the person + + node pr-prep.mjs pr-url [--branch ] [--base ] [--root ] + 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 + { ok, pushed: false, branch, next } with exit 0. + + node pr-prep.mjs spec [--branch ] [--base ] [--root ] + The branch's spec folder, for the save offer. Prints { ok, branch, + match, candidates, how }. + how branch: a folder in specs/ (then specs--completed/) whose name + is a whole dash-separated run of the branch name + recent: no name matched; the one folder with a file changed + since the branch left --base (default main, else master) + ask: several folders fit; candidates lists them + 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). +`; + +/* ------------------------------------------------------------- template */ + +const TEMPLATE_FILES = [ + ".github/pull_request_template.md", + ".github/PULL_REQUEST_TEMPLATE.md", + "PULL_REQUEST_TEMPLATE.md", + "docs/pull_request_template.md", +]; +const TEMPLATE_DIRS = [".github/PULL_REQUEST_TEMPLATE", "docs/PULL_REQUEST_TEMPLATE", ".gitlab/merge_request_templates"]; +const TESTING = /test|testing|verif|how .*checked|qa/i; + +function entries(dir) { + try { + return fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return []; + } +} + +/** `relPath` under root with every segment matched case-insensitively (an exact match first); the real relative path, or null. */ +function findCI(root, relPath, want) { + let at = ""; + const parts = relPath.split("/"); + for (let i = 0; i < parts.length; i++) { + const list = entries(path.join(root, at)); + const last = i === parts.length - 1; + const fits = (e) => (last ? (want === "dir" ? e.isDirectory() : e.isFile()) : e.isDirectory()); + const hit = list.find((e) => e.name === parts[i] && fits(e)) || list.find((e) => e.name.toLowerCase() === parts[i].toLowerCase() && fits(e)); + if (!hit) return null; + at = at ? `${at}/${hit.name}` : hit.name; + } + return at; +} + +function headingsOf(text) { + const headings = []; + let fence = null; + for (const line of text.split(/\r?\n/)) { + const f = line.match(/^\s{0,3}(`{3,}|~{3,})/); + if (f) { + if (!fence) fence = f[1][0]; + else if (f[1][0] === fence) fence = null; + continue; + } + if (fence) continue; + const m = line.match(/^\s{0,3}#{1,3}\s+(.*?)\s*#*\s*$/); + if (m && m[1]) headings.push(m[1]); + } + return headings; +} + +function template({ root }) { + const found = []; + for (const f of TEMPLATE_FILES) { + const hit = findCI(root, f, "file"); + if (hit && !found.includes(hit)) found.push(hit); + } + for (const d of TEMPLATE_DIRS) { + const dir = findCI(root, d, "dir"); + if (!dir) continue; + const mds = entries(path.join(root, dir)) + .filter((e) => e.isFile() && /\.md$/i.test(e.name)) + .map((e) => `${dir}/${e.name}`) + .sort((a, b) => a.localeCompare(b)); + 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")); + out({ ok: true, found: true, path: found[0], headings, hasTesting: headings.some((h) => TESTING.test(h)), others: found.slice(1) }); +} + +/* --------------------------------------------------------------- the repo */ + +let R; + +function repoRoot(root) { + 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 { + link = R.prLink(repo, { branch, base, prHosts: (await consoleModule("settings.mjs")).readPrHosts() }); + } catch (e) { + if (!R.PR_LINK_CODES.has(e?.code)) throw e; + if (e.code === "not-pushed") { + return out({ ok: true, pushed: false, branch: e.branch, next: "Say the branch is not pushed yet, and offer to hand over to the git skill (/plan2code-git), which asks before it pushes." }); + } + fail(e.code === "detached" ? EXIT.REFUSED : EXIT.INVALID, e.code, e.message, e.next); + } + out({ ok: true, pushed: true, ...link }); +} + +/* ------------------------------------------------------------------- spec */ + +const SPEC_DIRS = ["specs", "specs--completed"]; +const PREFIX = /^(feature|fix|bugfix|chore|hotfix)\//i; + +/** The branch name as one kebab-case run, with a leading feature/, fix/ ... or / segment dropped. */ +function branchKebab(branch) { + let b = branch.replace(PREFIX, ""); + if (b === branch && b.includes("/")) b = b.slice(b.indexOf("/") + 1).replace(PREFIX, ""); + return b.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""); +} + +function specFolders(repo) { + const all = []; + for (const d of SPEC_DIRS) { + const names = entries(path.join(repo, d)).filter((e) => e.isDirectory()).map((e) => e.name).sort((a, b) => a.localeCompare(b)); + for (const name of names) all.push({ dir: d, name, path: `${d}/${name}` }); + } + return all; +} + +function newestMtime(dir, depth = 4) { + let newest = 0; + for (const e of entries(dir)) { + const p = path.join(dir, e.name); + if (e.isFile()) { + try { + newest = Math.max(newest, fs.statSync(p).mtimeMs); + } catch {} + } else if (e.isDirectory() && depth > 1) newest = Math.max(newest, newestMtime(p, depth - 1)); + } + return newest; +} + +function pickBase(repo, wanted) { + const candidates = wanted ? [wanted, `origin/${wanted}`] : ["main", "origin/main", "master", "origin/master"]; + return candidates.find((ref) => R.git(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], repo).ok) || null; +} + +/** When `branch` (HEAD when it is not a local branch) left its base, in ms; null when there is no base or no shared commit. */ +function branchStart(repo, base, branch) { + const ref = pickBase(repo, base); + if (!ref) return null; + const local = branch && `refs/heads/${branch}`; + const tip = local && R.git(["rev-parse", "--verify", "--quiet", `${local}^{commit}`], repo).ok ? local : "HEAD"; + const mb = R.git(["merge-base", tip, ref], repo); + if (!mb.ok || !mb.out) return null; + const t = R.git(["show", "-s", "--format=%ct", mb.out], repo); + return t.ok && /^\d+$/.test(t.out) ? Number(t.out) * 1000 : null; +} + +function spec({ root, branch, base }) { + const repo = repoRoot(root); + let b = (branch || "").trim(); + if (!b) { + const head = R.git(["symbolic-ref", "-q", "--short", "HEAD"], repo); + b = head.ok ? head.out : ""; + } + const folders = specFolders(repo); + const verdict = (hits, how) => + hits.length === 1 ? { match: hits[0].path, candidates: [], how } : { match: null, candidates: hits.map((h) => h.path), how: "ask" }; + + const kebab = b ? branchKebab(b) : ""; + if (kebab) { + const named = folders.filter((f) => `-${kebab}-`.includes(`-${f.name.toLowerCase()}-`)); + const open = named.filter((f) => f.dir === "specs"); + const hits = open.length ? open : named; + if (hits.length) return out({ ok: true, branch: b || null, ...verdict(hits, "branch") }); + } + + const since = branchStart(repo, base, b); + const recent = since === null ? [] : folders.filter((f) => newestMtime(path.join(repo, f.path)) > since); + if (recent.length) return out({ ok: true, branch: b || null, ...verdict(recent, "recent") }); + out({ ok: true, branch: b || null, match: null, candidates: [], how: "none" }); +} + +/* ------------------------------------------------------------------ main */ + +const COMMANDS = { template, "pr-url": prUrlCmd, spec }; + +run(USAGE, async (argv) => { + const args = parseArgs(argv, { values: ["root", "branch", "base"] }); + const [cmd, ...extra] = args._; + const names = Object.keys(COMMANDS).join(", "); + if (!cmd) fail(EXIT.USAGE, "missing-command", `A subcommand is required: ${names}.`, "Run with --help for usage."); + if (!Object.hasOwn(COMMANDS, cmd)) fail(EXIT.USAGE, "unknown-command", `Unknown subcommand "${cmd}".`, `Use one of: ${names}.`); + if (extra.length) fail(EXIT.USAGE, "stray-argument", `Unexpected argument(s): ${extra.join(" ")}.`, "Run with --help for usage."); + args.root = path.resolve(args.root || "."); + if (cmd !== "template") R = await gitRepo(); + return COMMANDS[cmd](args); +}); diff --git a/src/plan2code-pr-prep.md b/src/plan2code-pr-prep.md new file mode 100644 index 0000000..c5f4324 --- /dev/null +++ b/src/plan2code-pr-prep.md @@ -0,0 +1,143 @@ +# ✅ PR PREP MODE + +Start all PR PREP MODE responses with '✅ [PR PREP]' + +## Role + +Gets a branch ready for review. Picks the checks its changes need, runs the ones the person keeps, gives a readiness verdict and writes the pull-request description to copy. **Never commits, never pushes, never creates a pull request**, and does no code review of its own (that is the Review skill's job). + +## Interface + +The FIRST thing you do, before anything else in this file, before reading the branch: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "/console.mjs" open --workflow pr-prep` before reading (: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-pr-prep/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read /console.md and /notes/pr-prep.md. Every question, the check plan, the report and the description go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context. + +## Project Context + +Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything it says about slow suites. PR Prep still works without one: the scripts find the project's commands from its config files, and nothing here needs Plan2Code's specs. + +## Scripts + +`` 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 "/review-scope.mjs" [--base ]`: the branch's changes against main (or master): `files` (each with `status`: `committed`, `staged`, `unstaged`, `untracked`), `counts`, `mix` (`docs`, `code`, `mixed`), `empty`, `commits`. +- `node "/test-map.mjs" read`: the project test map (`found`, `rows` of `area`, `paths`, `run`, `shared`, and `problems`). `write --rows ` saves one, only on a yes. +- `node "/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 "/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 "/run-check.mjs" --cmd --cwd --timeout --log `: runs one check and prints `outcome` (`passed`, `failed`, `timeout`, `not-started` with a `reason`), `exit`, `seconds` and `tail`. +- `node "/pr-prep.mjs" template`: the repo's pull-request template: `found`, `path`, `headings`, `hasTesting`, `others`. +- `node "/pr-prep.mjs" pr-url`: the create-a-PR link: `pushed: true` with `url` (`needsKind: true` means the host is unknown and `url` is null), or `pushed: false` for a branch not on a remote yet. +- `node "/pr-prep.mjs" spec`: the branch's spec folder for the save offer: `match`, `candidates`, `how` (`branch`, `recent`, `ask`, `none`). + +## References + +- `references/test-runs.md`: how to pick tests for files no map row covers, and what counts as shared ground. +- `references/helper-strength.md`: helper strength and effort. + +## Rules + +- Follow `./AGENTS.md` when it exists. +- **Never** run `git commit`, `git push`, `git add` or anything that opens a pull request, and never ask a forge CLI (`gh`, `glab`) to. Read-only git is fine. The person copies the description from the page. +- **Nothing runs before the person sends the trimmed plan.** A command found by a script is shown before it runs. +- **Never install anything**: no runner, no package, no service. +- **Record honestly.** A check that did not run is never reported as passed, and nothing unrun is ever Ready. +- No code review and no fixes: a failing check is reported, not repaired. +- Plain words: name the check, the file and the command. + +## Helpers + +When your tool can start helpers (subagents) and they are not switched off for this run (on the web console a `Subagents:` block says which, console-subagents.md): helpers may read the files behind leftover changes (Step 3) and draft the Changes by area section (Step 8). Keep the check plan, the runs, the verdict and every question with you. Light strength, low effort, per references/helper-strength.md. No helpers? Do the same work yourself. + +## Process + +### Step 1: Changes + +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. + +### 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. + +### Step 3: Check plan + +Pipe review-scope's JSON to `test-match.mjs covers --stdin`. 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. +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. + +### Step 4: Trim + +Show the whole plan with every check on offer; the person keeps what to run and drops what to skip. On the console that is one card with an "All of them" quick pick, since a card cannot open ticked; in the terminal, the numbered list, run in full unless they name checks to skip. Nothing runs before they send. A dropped check is a trimmed check: a plain note in the verdict, never a failure. + +### Step 5: Run + +Run each kept check, one at a time: + +``` +node "/run-check.mjs" --cmd "" --cwd --timeout --log /checks/.log +``` + +The timeout is 600 seconds by default, longer when the person or `AGENTS.md` says a suite is slow. On the console the log goes in the `session` folder `open` printed; in the terminal, the OS temp folder. Before each check post one `activity` line ("Check 2 of 5: the launcher tests") with `quietMinutes` sized to its timeout. Record each outcome with its `seconds`, `exit` and `tail`. + +### Step 6: Verdict + +- **Ready:** every planned check ran and passed. +- **Ready with notes:** every check that ran passed, but something did not run or is not covered. Each trimmed check is a plain note. Each `timeout` or `not-started` check is a louder note with its `reason` and the end of its `tail` (a missing command, runner or service is not a failed check). Each changed source file no check covers is a note naming the file and suggesting `/plan2code-test` to write tests for it. +- **Not ready:** any check `failed`. Name it and quote the end of its `tail`. + +Nothing unrun is ever Ready. Say whether uncommitted work was included in the run. + +### Step 7: Report + +On the console, a report doc: the verdict first, then the checks grouped by runner, each with its outcome, seconds and reason, then the notes. In the terminal, the same as a short table. + +### Step 8: PR description + +Run `pr-prep.mjs template` and `pr-prep.mjs spec` (the branch's spec folder: `match`, `candidates`, `how`; Step 10 reuses this answer). + +- **With a template** (`found: true`): fill every heading in `headings`, in order, keeping the template's own words. When `hasTesting` is false, add a `## How it was checked` section. Mention `others` in one line (the person may want a different template). +- **Without one:** five sections: `## Summary` (what the branch does, two or three sentences), `## Why` (the reason, with the spec folder when `spec` gave a `match`, or an issue link when one is known), `## Changes by area` (review-scope's files grouped by test map area, or by top folder), `## How it was checked` (drawn from the report: which checks ran and passed, what was trimmed or could not run), `## Risks` (what could break, what a reviewer should look at). + +Post it as its own doc holding one fenced block (` ```markdown `), so the page's copy button copies the raw Markdown. In the terminal, print the same fenced block. + +### Step 9: Link + +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: 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. + +### Step 10: Save offer + +Use Step 8's `spec` answer. + +- `match`: offer to save the report and the description as `/PR-READINESS-.md`. A file of that name already there → say it will be replaced before asking. Save only on a yes. +- `ask`: ask which of `candidates` (or none), then offer as above. +- `none`: save nothing and say nothing about saving. + +### 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 `. Never without a yes. + +## Session End + +Work summary: the verdict, the checks that ran (passed, failed, timed out, could not start), the trimmed ones, whether uncommitted work was included, the description shown, the link or that the branch is not pushed, and any file written. + +**Next step**, as the closing line: "Optional next (NEW conversation): `/plan2code-review` for a code review before you open the PR." Add `/plan2code-test` when untested files were noted. + +On the console, post `finish` with the verdict in `headline`, `command` `/plan2code-review`, and `"dashboard": true`; mention `/plan2code-test` in `body` when untested files were noted. + +``` +⋅ + ╭───╮ + ╲│ ★ │╱ + │ ◡ │ Ready for review! + ╰┬─┬╯ +``` diff --git a/src/plan2code.md b/src/plan2code.md index f971765..410a251 100644 --- a/src/plan2code.md +++ b/src/plan2code.md @@ -67,6 +67,7 @@ Ground truth for menu notes and Ask-tab answers. For anything beyond this table, | git | git status, branches, diffs, `AGENTS.md` | commits, branches; optional `.gitignore`, push, publish; no spec writes | | xray | the codebase, `git` history, `gh` when present | an answer; `ARCHITECTURE-BRIEF-.md` or `XRAY--.md` when asked | | diagnose | the bug, the codebase, `references/building-habits.md` | `DIAGNOSIS-.md`; no code changes | +| pr-prep | git diff and status, the `AGENTS.md` test map, the project's config files, the PR template | the page report and description; `PR-READINESS-.md` on a yes; the `AGENTS.md` test map on a yes; no commits, no push | ## A pick arrives @@ -102,6 +103,7 @@ If `skill` is not in the table below, say so on the page and stay the dashboard. | plan2code-quick-task | quick-task | | plan2code-handoff | handoff | | plan2code-git | git | | plan2code-changelog | changelog | | plan2code-xray | xray | | plan2code-diagnose | diagnose | +| plan2code-pr-prep | pr-prep | | | | ## A pick-up arrives diff --git a/src/web-console/console.md b/src/web-console/console.md index 3b3fabc..2b5bc9d 100644 --- a/src/web-console/console.md +++ b/src/web-console/console.md @@ -6,7 +6,7 @@ A local page where the person answers your questions, reads your drafts and appr ## Start -`node "" open --workflow ` (add `--spec specs/` when known). `` is one of `dashboard`, `init`, `init-update`, `pathfinder`, `quick-task`, `plan`, `revise-plan`, `document`, `implement`, `implement-review`, `review`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`. Launched from the dashboard? The session is open: run the `resume` command the launch carried instead. +`node "" open --workflow ` (add `--spec specs/` when known). `` is one of `dashboard`, `init`, `init-update`, `pathfinder`, `quick-task`, `plan`, `revise-plan`, `document`, `implement`, `implement-review`, `review`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`, `pr-prep`. Launched from the dashboard? The session is open: run the `resume` command the launch carried instead. Keep `sid`: every later command takes `--session `. `open` failing: carry on in the terminal. When `open` adds `remote` and a `note`, give the link, ask whether it opened, and move to the terminal if not. Tell the person the link (with `"inApp":true`, never print it: only how many questions are waiting) and end every terminal message with the latest `terminalLine`, verbatim. diff --git a/src/web-console/git-repo.mjs b/src/web-console/git-repo.mjs index 78aceb1..50af592 100644 --- a/src/web-console/git-repo.mjs +++ b/src/web-console/git-repo.mjs @@ -451,6 +451,36 @@ export function readRemotes(root, prHosts = {}) { return remotes; } +export const PR_LINK_CODES = new Set(["detached", "unknown-branch", "no-base", "is-base", "not-pushed"]); + +function prLinkError(code, message, next, branch = null) { + throw Object.assign(new Error(message), { code, next, branch }); +} + +/** + * The create-a-pull-request link for `branch` (default: the current branch) + * into `base` (default: the default branch). Returns { url, host, kind, + * needsKind, branch, base, ahead }; ahead is the branch's commits not yet on + * its upstream. Throws an Error tagged { code, message, next, branch }, code + * one of PR_LINK_CODES, when there is no link to give. + */ +export function prLink(root, { branch, base, prHosts = {} } = {}) { + const parsed = parseStatusV2(git(["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=no"], root, { raw: true }).out); + const refs = readRefs(root); + const def = refs.length ? defaultBranchFromRefs(refs, parsed) : defaultBranch(root, parsed); + const b = (branch || "").trim() || parsed.branch; + if (!b) prLinkError("detached", "HEAD is detached, so there is no branch to open a pull request for.", "Switch to a branch, or pass --branch."); + const row = branchesFromRefs(refs, root, { current: parsed.branch, defaultName: def.name }).find((r) => !r.remote && r.name === b); + if (!row) prLinkError("unknown-branch", `There is no local branch named "${b}".`, "Pick a branch from the list.", b); + const into = (base || "").trim() || def.name; + if (!into) prLinkError("no-base", "There is no default branch to open the pull request against.", "Pass --base .", b); + // A pull request from a branch into itself is no pull request (a push to main). + if (into === b) prLinkError("is-base", `${b} is the branch pull requests go into, so there is nothing to open.`, "Post no link for this push.", b); + const remote = row.upstream && !row.gone ? readRemotes(root, prHosts).find((r) => r.name === row.upstreamRemote) : null; + if (!remote) prLinkError("not-pushed", `${b} is not on a remote yet.`, "Publish it first (plan publish).", b); + return { url: prUrl(remote, { base: into, head: b }), host: remote.host, kind: remote.kind, needsKind: !!remote.host && !remote.kind, branch: b, base: into, ahead: row.ahead }; +} + /* ------------------------------------------------- snapshot and the count */ const MARKER = /^(<{7}|={7}|>{7})( |$)/m; diff --git a/src/web-console/notes/pr-prep.md b/src/web-console/notes/pr-prep.md new file mode 100644 index 0000000..77e58a5 --- /dev/null +++ b/src/web-console/notes/pr-prep.md @@ -0,0 +1,59 @@ +# PR Prep + +## Uncommitted changes + +Only when review-scope lists `staged`, `unstaged` or `untracked` files. 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."}]}]} +``` + +## Commands, with no test map + +One `confirm` listing each command found and the folders it covers, `--wait`, before anything runs. A "Not right" answer carries the corrections in its note; with none, ask for them as a `text` card: + +```jsonc +{"id":"commands","kind":"confirm","title":"Commands found","body":"| Command | Folder | Covers |\n| --- | --- | --- |\n| `npm test` | . | everything |\n| `npm run lint` | . | lint |\n\nRun checks with these?","yesLabel":"Use these","noLabel":"Not right"} +``` + +## The check plan + +One `multi`, each check's reason in `detail`, "picked by the agent" on judged ones, and one preset "All of them" naming every check: a card cannot open with its boxes ticked, so the preset is the one press that keeps the whole plan. With more than one runner, group in `body` (a short list per runner) and prefix each option's `text` with its runner. `--wait`: + +```jsonc +{"headline":{"stage":"Check plan","cleared":1},"items":[{"id":"plan","kind":"multi","title":"Checks to run","body":"Tick the checks to run, or press All of them. Anything left unticked is skipped and named in the report. Nothing runs until you send.","options":[{"k":"1","text":"Launcher tests","detail":"`node --test scripts/test-launcher.mjs`: covers src/launcher/plan2code.js."},{"k":"2","text":"Lint","detail":"`npm run lint`: project check."}],"presets":[{"label":"All of them","ks":["1","2"]}]}]} +``` + +A send with nothing ticked runs nothing: every check is trimmed. + +## Running + +One progress post per check, no `--wait`, with `quietMinutes` sized to its timeout (600 s is 10 minutes, plus a margin): + +```jsonc +{"headline":{"stage":"Running","cleared":2},"agent":{"status":"working","activity":"Check 2 of 5: the launcher tests","quietMinutes":12}} +``` + +Logs go in `/checks/.log`. Run the `chat` check between checks, as a build does. + +## 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. + +```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://...)"}]}]} +``` + +## The offers + +Each a `confirm`, `--wait`, `"doc":"report"`: + +- Save: `title` "Save the report", `body` naming `specs//PR-READINESS-.md` (and that a same-day file is replaced), `yesLabel` "Save it", `noLabel` "No". `how: "ask"` first asks which folder as a `choice` (one option per candidate, plus "None"). +- Hand-off when not pushed: `title` "Not pushed yet", `yesLabel` "Open Git", `noLabel` "Not now". Yes: the finish carries `/plan2code-git` instead of `/plan2code-review`. +- Test map: `title` "Save a test map", the rows as a table in `body`, `yesLabel` "Save it", `noLabel` "No". + +## The finish + +`headline` is the verdict ("Ready with notes"), `body` the summary and what was saved, `command` `/plan2code-review`, `doc` `report`, `"dashboard":true`, no `commit`. Mention `/plan2code-test` in `body` when untested files were noted. + +A stop before the run: `body` says nothing ran and nothing was saved, `"command":"/plan2code-pr-prep"`. diff --git a/src/web-console/public/index.html b/src/web-console/public/index.html index e4dfc9d..5e963c6 100644 --- a/src/web-console/public/index.html +++ b/src/web-console/public/index.html @@ -422,6 +422,12 @@ + + + + + + @@ -832,6 +838,34 @@ + +