From d8b1d2992f49618b851323c1682bc3ee82a3998b Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Sun, 8 Nov 2026 16:44:53 +0200 Subject: [PATCH 1/3] feat(agents): PRs get labels, milestone and reviewer; branches keep up with main MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - scripts/pr-meta.mjs works out a PR's labels (commit types and changed paths), milestone (the closed issue's, else the story's tracker) and reviewer (the other collaborator); `--apply` adds them to the open PR. - AGENTS.md § Git: two standing instructions. Merge `origin/main` in at the start of work, before finalizer validates and before any push, fixing conflicts. Run pr-meta after a PR opens or a story closes. - finalizer, pipeline, pr-desc and release point at both. --- .agents/finalizer.md | 20 ++- .agents/skills/pipeline/SKILL.md | 5 +- .agents/skills/pr-desc/SKILL.md | 2 +- .agents/skills/release/SKILL.md | 3 +- AGENTS.md | 16 +++ apps/dox/scripts/pr-meta/plan.test.ts | 171 ++++++++++++++++++++++ scripts/lib/affected.mjs | 2 +- scripts/lib/pr-meta-plan.mjs | 130 +++++++++++++++++ scripts/pr-meta.mjs | 200 ++++++++++++++++++++++++++ 9 files changed, 539 insertions(+), 10 deletions(-) create mode 100644 apps/dox/scripts/pr-meta/plan.test.ts create mode 100644 scripts/lib/pr-meta-plan.mjs create mode 100644 scripts/pr-meta.mjs diff --git a/.agents/finalizer.md b/.agents/finalizer.md index 2fc42750a..50f0f25c0 100644 --- a/.agents/finalizer.md +++ b/.agents/finalizer.md @@ -1,6 +1,6 @@ --- name: finalizer -description: Closes a @northguild/gmt story after tdd-dev and tester — TanStack Intent skills, the changeset, READMEs, the dox reference corpus and stats, the tracker Status, validate — and drafts the commit message and PR description for the owner. Never commits, opens PRs, versions or publishes. +description: Closes a @northguild/gmt story after tdd-dev and tester — TanStack Intent skills, the changeset, READMEs, the dox reference corpus and stats, the tracker Status, validate — and drafts the commit message and PR description for the owner. Merges `origin/main` in and labels an open PR; otherwise never commits, opens PRs, versions or publishes. model: sonnet disallowedTools: Agent --- @@ -13,7 +13,7 @@ You are the Finalizer for the `@northguild/gmt` project. You close stories by ha **Temporal type system:** Full working knowledge across all GMT types and their public string contracts. -**GMT rules:** [AGENTS.md § Core Rules](../AGENTS.md#core-rules-quick-reference) and [§ Git — Only on an Explicit Instruction](../AGENTS.md#git--only-on-an-explicit-instruction). You do not stage, commit, push, branch or open a PR unless the user asks you to. +**GMT rules:** [AGENTS.md § Core Rules](../AGENTS.md#core-rules-quick-reference) and [§ Git — Only on an Explicit Instruction](../AGENTS.md#git--only-on-an-explicit-instruction). You do not stage, commit, push, branch or open a PR unless the user asks you to. The two standing instructions there are yours to carry out: merge `origin/main` in (step 9) and label an open PR (step 11). **Release workflow:** Deep familiarity with `PUBLISHING.md`. This agent's release output is exactly one thing: a well-written `.changeset/*.md` on the feature branch. Versioning and publishing are both `release.yml`'s job — never run `changeset version`, `npm publish`, `changeset publish`, or `gh release create`. @@ -23,11 +23,11 @@ You are the Finalizer for the `@northguild/gmt` project. You close stories by ha ## Role -Story closer. Called after `tdd-dev` (and optionally `tester`) complete. Produces all release-intent artifacts and hands off. It never publishes — see step 11. +Story closer. Called after `tdd-dev` (and optionally `tester`) complete. Produces all release-intent artifacts and hands off. It never publishes — see step 12. ## Workflow -1. **Read `context/domination/tracker.md`** to identify the current story, its GitHub issue number, and its row. No release decision is yours to make — see step 11. +1. **Read `context/domination/tracker.md`** to identify the current story, its GitHub issue number, and its row. No release decision is yours to make — see step 12. 2. **If public API surface changed:** update the TanStack Intent agent skills in `packages/gmt/skills/` (new functions, renamed functions, new options, new domain concept). See `PUBLISHING.md` contributor flow step 2. @@ -120,7 +120,11 @@ Story closer. Called after `tdd-dev` (and optionally `tester`) complete. Produce - Report each item to the main session, so the fix loops back through `tdd-dev`. - Never describe a known defect in a changeset, issue file, JSDoc, README or PR description as something that ships. It gets fixed instead. -9. **Verify before handing off.** `node scripts/verdict.mjs validate` must print PASS — it is the +9. **Verify before handing off.** First bring in `main`, as [AGENTS.md § Git](../AGENTS.md#git--only-on-an-explicit-instruction) + says: `git fetch origin main`, then `git merge origin/main` if the branch is behind. Resolve + each conflict so both sides' changes survive, and commit the merge. If git refuses because the + story's uncommitted work touches the incoming files, stop and name those files to the main + session. Then `node scripts/verdict.mjs validate` must print PASS — it is the epic's Definition of Done. It runs the same checks as `pnpm run validate`: every check that reads a file the branch changed, against `origin/main`, one row each; `--full` runs them all. Do not report a story closed on a run that stopped early. @@ -160,7 +164,11 @@ Story closer. Called after `tdd-dev` (and optionally `tester`) complete. Produce of `plan_gate.py`'s tests use the deleted spec, and run `pnpm run validate` again: a comment edit can still break a file's syntax. -11. **Stop.** There is no publish step to run. Merging the feature PR publishes +11. **Label the PR.** If the branch has an open PR, run `node scripts/pr-meta.mjs --apply`: it + adds the labels, the milestone and the other collaborator as reviewer. With no PR yet, run it + without `--apply` and put its plan in the hand-off, so whoever opens the PR applies it. + +12. **Stop.** There is no publish step to run. Merging the feature PR publishes nothing; the changeset sits on `main` until a human opens a release PR carrying the output of `pnpm run changeset:version`, and merging that PR is what ships to npm. diff --git a/.agents/skills/pipeline/SKILL.md b/.agents/skills/pipeline/SKILL.md index 8d3c571b2..6cb563c0f 100644 --- a/.agents/skills/pipeline/SKILL.md +++ b/.agents/skills/pipeline/SKILL.md @@ -100,7 +100,10 @@ disputed reading of a standard. Say so in the report. The agent files' defaults refuses to close a story that carries one ([Core Rule 12](../../../AGENTS.md#core-rules-quick-reference)). 4. **Escalate blockers** — an ambiguous spec, a design conflict, tests that cannot pass: stop and report to the user with full context. No step fails or is skipped silently. -5. **Nothing is committed.** The pipeline ends with unstaged changes plus drafted commit and PR +5. **Nothing is committed** but a merge from `main`. Bring `origin/main` in when the story starts + and again before `finalizer` ([AGENTS.md § Git](../../../AGENTS.md#git--only-on-an-explicit-instruction) + has the two standing instructions); `finalizer` labels an open PR with `scripts/pr-meta.mjs`. + The pipeline ends with unstaged changes plus drafted commit and PR text for the owner. Never run `changeset version`, `changeset publish`, `npm publish` or `gh release create` (see `PUBLISHING.md`). diff --git a/.agents/skills/pr-desc/SKILL.md b/.agents/skills/pr-desc/SKILL.md index 2972d3a45..f4cadf407 100644 --- a/.agents/skills/pr-desc/SKILL.md +++ b/.agents/skills/pr-desc/SKILL.md @@ -80,7 +80,7 @@ The changeset(s) in `.changeset/` and their bump level, per [coding-standards § ## Delivery -Output the full description in a plain fenced code block (no language tag) so it can be copied. Do not write it to a file unless the user asks for one and names the path. Never create the PR yourself — the repository owner opens every PR. +Output the full description in a plain fenced code block (no language tag) so it can be copied. Do not write it to a file unless the user asks for one and names the path. Never create the PR yourself — the repository owner opens every PR. End with the output of `node scripts/pr-meta.mjs` (labels, milestone, reviewer); once the PR exists, `node scripts/pr-meta.mjs --apply` sets them. ## Rules diff --git a/.agents/skills/release/SKILL.md b/.agents/skills/release/SKILL.md index 94f1f6218..7c733b740 100644 --- a/.agents/skills/release/SKILL.md +++ b/.agents/skills/release/SKILL.md @@ -132,7 +132,8 @@ Node, so it catches a failure that only happens in CI (#453). is in the tree and has not been pushed. - **`gh pr create --base main --head release/ --title "" --label release --body-file `**, with the body file outside the tree. If the label does not exist, open the - PR without it and say so. + PR without it and say so. Then run `node scripts/pr-meta.mjs --apply` to ask the other + collaborator for review. Write the body in plain English (the [`plain-english` skill](../plain-english/SKILL.md)): diff --git a/AGENTS.md b/AGENTS.md index 151941dd7..0a846a1eb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,6 +58,22 @@ does not authorise force-pushing it. If one of these seems genuinely necessary and nobody has asked for it, stop and ask in plain words. +**Two standing instructions from the owner.** These need no new word each time: + +- **Keep the branch up to date with `main`.** Do this when work on a branch starts, before + `finalizer` runs `validate`, and before any push. Run `git fetch origin main`, then + `git merge origin/main` when the branch is behind. Never rebase, because the branch is + published. Resolve every conflict so both sides' changes survive, run + `node scripts/verdict.mjs validate`, and commit the merge. If uncommitted work touches the + incoming files, git refuses the merge. Do not stash (the stash is shared): name the files to + the owner and merge once the work is committed. Pushing the merge still needs the owner's word. + On an open PR, `gh pr view --json mergeable` shows whether GitHub sees a conflict. +- **A PR gets its labels, milestone and reviewer.** Run `node scripts/pr-meta.mjs --apply` right + after a PR is opened, and when `finalizer` closes a story whose PR is already open. It only + adds: labels from the commit types and changed paths, the closed issue's milestone (else the + story's tracker), and the other collaborator as reviewer. A run without `--apply` changes + nothing and shows the plan. + ## Core Rules (Quick Reference) These are the non-negotiables. Full detail is in the context files above. diff --git a/apps/dox/scripts/pr-meta/plan.test.ts b/apps/dox/scripts/pr-meta/plan.test.ts new file mode 100644 index 000000000..7da209f4b --- /dev/null +++ b/apps/dox/scripts/pr-meta/plan.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it } from "vitest"; + +import { planMeta, storyIdOf } from "../../../../scripts/lib/pr-meta-plan.mjs"; + +/** The pure planner behind `scripts/pr-meta.mjs`. Branches and paths are from merged northguild/gmt PRs. */ + +const TRACKERS = { + "context/dox/tracker.md": "| DOX-G6 | Done | #448 |\n", + "context/domination/tracker.md": + "| SPA-46 | Done | #227 |\n| CORE-105 | Done | #437 |\n", +}; + +const facts = (over: Partial[0]>) => ({ + branch: "x", + subjects: [], + paths: [], + closingIssues: [], + trackers: TRACKERS, + milestones: ["Dox", "Domination", "Ultimation"], + viewer: "craig-o-curtis", + author: null, + collaborators: ["baldurpan", "craig-o-curtis"], + ...over, +}); + +describe("storyIdOf", () => { + it.each([ + ["448-dox-g6-research-and-improve-how-search-engines", "DOX-G6"], + ["feature/227-spa-46-tai64-text-labels", "SPA-46"], + ["core-109-hero-sun-one-camera", "CORE-109"], + ["437-core-105-split-zonedwallclockdiffere", "CORE-105"], + ["447-featdox-unify-entrance-of-gmt-docs-w", null], + ["chore/add-worktree-config", null], + ["release/2026-11-03", null], + ])("%s → %s", (branch, id) => { + expect(storyIdOf(branch)).toBe(id); + }); +}); + +describe("planMeta labels", () => { + it("reads commit types and paths, as #476 (feat, library, Intent skills, docs) was labelled", () => { + const plan = planMeta( + facts({ + branch: "feature/227-spa-46-tai64-text-labels", + subjects: [ + "feat(domination): TAI64N text labels, toTai64n and fromTai64n (SPA-46)", + ], + paths: [ + "packages/gmt/src/timescale/convert/toTai64n.ts", + "packages/gmt/skills/gmt-timescale/SKILL.md", + "context/domination/tracker.md", + "apps/dox/src/content/docs/guides/tai64.mdx", + ], + }), + ); + expect(plan.labels).toEqual([ + "documentation", + "enhancement", + "gmt", + "skills", + ]); + }); + + it("labels workflows pipes, tooling gmt monorepo and agent files ai skills, as #439 was", () => { + const plan = planMeta( + facts({ + branch: "chore/add-release-skill", + subjects: ["chore: add the release skill"], + paths: [ + ".agents/skills/release/SKILL.md", + "AGENTS.md", + ".github/workflows/release.yml", + "scripts/changelog.mjs", + ], + }), + ); + expect(plan.labels).toEqual(["ai skills", "gmt monorepo", "pipes"]); + }); + + it("counts Dox build scripts as tooling, not documentation", () => { + const plan = planMeta( + facts({ + paths: [ + "apps/dox/scripts/pr-meta/plan.test.ts", + "apps/dox/src/pages/index.astro", + ], + }), + ); + expect(plan.labels).toEqual(["documentation", "gmt monorepo"]); + expect( + planMeta(facts({ paths: ["apps/dox/scripts/build-guides.mjs"] })).labels, + ).toEqual(["gmt monorepo"]); + }); + + it("gives a fix bug, and a breaking feat! enhancement", () => { + expect( + planMeta(facts({ subjects: ["fix(dox): one option per unit"] })).labels, + ).toEqual(["bug"]); + expect( + planMeta(facts({ subjects: ["feat(gmt)!: split the type"] })).labels, + ).toEqual(["enhancement"]); + }); + + it("gives a release branch only `release`, whatever it touches", () => { + const plan = planMeta( + facts({ + branch: "release/2026-11-03", + subjects: ["release: v1.21.0"], + paths: ["packages/gmt/CHANGELOG.md"], + }), + ); + expect(plan.labels).toEqual(["release"]); + }); +}); + +describe("planMeta milestone", () => { + it("takes the closed issue's milestone first", () => { + const plan = planMeta( + facts({ + branch: "448-dox-g6-x", + closingIssues: [ + { number: 456, milestone: null }, + { number: 448, milestone: "Dox" }, + ], + }), + ); + expect([plan.milestone, plan.milestoneFrom]).toEqual(["Dox", "#448"]); + }); + + it("falls back to the tracker that holds the story's row", () => { + const plan = planMeta( + facts({ + branch: "437-core-105-split", + closingIssues: [{ number: 437, milestone: null }], + }), + ); + expect([plan.milestone, plan.milestoneFrom]).toEqual([ + "Domination", + "context/domination/tracker.md", + ]); + }); + + it("is none for a branch with no story and no milestoned issue", () => { + expect( + planMeta(facts({ branch: "chore/add-worktree-config" })).milestone, + ).toBeNull(); + }); + + it("leaves off a milestone that is not open", () => { + const plan = planMeta( + facts({ + closingIssues: [{ number: 1, milestone: "Dox" }], + milestones: ["Domination"], + }), + ); + expect(plan.milestone).toBeNull(); + expect(plan.milestoneFrom).toContain("not an open milestone"); + }); +}); + +describe("planMeta reviewer", () => { + it("asks the other collaborator: baldurpan for the viewer's new PR", () => { + expect(planMeta(facts({})).reviewers).toEqual(["baldurpan"]); + }); + + it("follows the PR's author, not the viewer, once the PR exists", () => { + expect(planMeta(facts({ author: "baldurpan" })).reviewers).toEqual([ + "craig-o-curtis", + ]); + }); +}); diff --git a/scripts/lib/affected.mjs b/scripts/lib/affected.mjs index 7b56a617a..1c6a1c96b 100644 --- a/scripts/lib/affected.mjs +++ b/scripts/lib/affected.mjs @@ -397,7 +397,7 @@ export const RULES = [ checks: ["typecheck:dox", ...SCRIPT_TESTS], }, { - test: /^scripts\/(?:verdict|lib\/(?:verdict-(?:format|parse)|pr-status-plan))\.mjs$/, + test: /^scripts\/(?:verdict|pr-meta|lib\/(?:verdict-(?:format|parse)|pr-status-plan|pr-meta-plan))\.mjs$/, checks: ["typecheck:dox", ...SCRIPT_TESTS], }, { diff --git a/scripts/lib/pr-meta-plan.mjs b/scripts/lib/pr-meta-plan.mjs new file mode 100644 index 000000000..6355f02b5 --- /dev/null +++ b/scripts/lib/pr-meta-plan.mjs @@ -0,0 +1,130 @@ +/** + * The labels, milestone and reviewer a pull request gets, from facts `scripts/pr-meta.mjs` + * gathers: the branch, its commit subjects, its changed paths, the issues it closes, the trackers, + * the viewer and the repo's collaborators. + * + * Pure: no file system, no git, no process. + */ + +/** + * Path rules: a changed path adds every label whose test it matches. Status and workflow labels + * (`parked`, `ready to build`, `waiting: *`, `canary`, `dox-gate`, `craig-review`) are a person's + * call or a workflow's, so no rule adds them. + * @type {ReadonlyArray<{ label: string, test: RegExp }>} + */ +export const PATH_RULES = [ + { label: "gmt", test: /^packages\/gmt\/(?!skills\/)/ }, + { label: "skills", test: /^packages\/gmt\/skills\// }, + { label: "gmt-biome", test: /^packages\/gmt-biome\// }, + { label: "gmt-eslint", test: /^packages\/gmt-eslint\// }, + { label: "gmt-oxlint", test: /^packages\/gmt-oxlint\// }, + { label: "pipes", test: /^\.github\/workflows\// }, + { + label: "ai skills", + test: /^(?:\.agents\/|\.claude\/|AGENTS\.md$|CLAUDE\.md$|context\/skills\.md$)/, + }, + { + label: "gmt monorepo", + test: /^(?:scripts\/|apps\/dox\/scripts\/|package\.json$|pnpm-(?:lock|workspace)\.yaml$|\.worktree\.yml$|\.oxfmtrc\.json$|\.gitignore$|tsconfig[\w.]*\.json$|vitest[\w.]*\.[cm]?ts$|\.github\/renovate\.json5$)/, + }, + { + label: "documentation", + test: /^(?:context\/(?!skills\.md$)|apps\/dox\/(?!scripts\/)|README\.md$|CONTRIBUTING\.md$|PUBLISHING\.md$|SECURITY\.md$|packages\/[\w-]+\/README\.md$)/, + }, +]; + +/** Conventional-commit type → label. Other types (chore, ci, test, build) add none. */ +export const TYPE_LABELS = /** @type {const} */ ({ + feat: "enhancement", + fix: "bug", + refactor: "refactor", + docs: "documentation", +}); + +/** Tracker file → the milestone its stories belong to. */ +export const TRACKER_MILESTONES = /** @type {const} */ ({ + "context/dox/tracker.md": "Dox", + "context/domination/tracker.md": "Domination", +}); + +/** + * The story id a branch name carries: `448-dox-g6-research…` → `DOX-G6`, + * `feature/227-spa-46-tai64…` → `SPA-46`. Null when it carries none. + * @param {string} branch + */ +export function storyIdOf(branch) { + const name = branch.slice(branch.lastIndexOf("/") + 1).replace(/^\d+-/, ""); + const match = /^([a-z]+)-([a-z]?\d+[a-z0-9]*)(?:-|$)/.exec(name); + return match ? `${match[1]}-${match[2]}`.toUpperCase() : null; +} + +/** + * @typedef {{ + * branch: string, + * subjects: string[], + * paths: string[], + * closingIssues: Array<{ number: number, milestone: string | null }>, + * trackers: Record, + * milestones: string[], + * viewer: string, + * author: string | null, + * collaborators: string[], + * }} Facts + * `trackers` maps a tracker path to its text; `milestones` lists the repo's open milestones; + * `author` is the open PR's author, or null before the PR exists (the viewer opens it then). + */ + +/** + * @param {Facts} facts + * @returns {{ labels: string[], milestone: string | null, milestoneFrom: string, reviewers: string[], storyId: string | null }} + */ +export function planMeta(facts) { + const storyId = storyIdOf(facts.branch); + const labels = new Set(); + + if (facts.branch.startsWith("release/")) { + labels.add("release"); + } else { + for (const subject of facts.subjects) { + const type = /^(\w+)(?:\([^)]*\))?!?:/.exec(subject)?.[1]; + if (type && type in TYPE_LABELS) + labels.add(TYPE_LABELS[/** @type {keyof typeof TYPE_LABELS} */ (type)]); + } + for (const path of facts.paths) { + for (const rule of PATH_RULES) + if (rule.test.test(path)) labels.add(rule.label); + } + } + + let milestone = null; + let milestoneFrom = "none"; + const fromIssue = facts.closingIssues.find((issue) => issue.milestone); + if (fromIssue?.milestone) { + milestone = fromIssue.milestone; + milestoneFrom = `#${fromIssue.number}`; + } else if (storyId) { + const row = new RegExp(`^\\|[^\\n]*\\b${storyId}\\b`, "m"); + for (const [path, title] of Object.entries(TRACKER_MILESTONES)) { + if (row.test(facts.trackers[path] ?? "")) { + milestone = title; + milestoneFrom = path; + break; + } + } + } + if (milestone && !facts.milestones.includes(milestone)) { + milestoneFrom = `${milestoneFrom} (not an open milestone, left off)`; + milestone = null; + } + + const author = facts.author ?? facts.viewer; + const reviewers = facts.collaborators.filter((login) => login !== author); + + return { + labels: [...labels].sort(), + milestone, + milestoneFrom, + reviewers, + storyId, + }; +} diff --git a/scripts/pr-meta.mjs b/scripts/pr-meta.mjs new file mode 100644 index 000000000..4a202e89f --- /dev/null +++ b/scripts/pr-meta.mjs @@ -0,0 +1,200 @@ +#!/usr/bin/env node +/** + * The labels, milestone and reviewer a pull request should carry, and (with `--apply`) setting + * them on its open PR. + * + * - Labels: from the commit types since `origin/main` and the paths the branch changes, + * committed or not. + * - Milestone: the milestone of the issue the PR closes (or the branch's leading issue number), + * else the tracker that holds the branch's story id. + * - Reviewer: every collaborator who is not the PR's author. + * + * The rules live in `scripts/lib/pr-meta-plan.mjs`. `--apply` only adds: it never removes a label, + * never replaces a milestone a person set, and never un-requests a reviewer. + * + * Run as: node scripts/pr-meta.mjs [ | ] [--apply] [--json] + * no argument the open PR whose head is the current branch (or, with none open, the plan for + * the PR the current branch would open) + * + * Exit: 0 done, 2 usage error, `gh` or `git` error, or `--apply` with no open PR. + */ +import { spawnSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { planMeta, TRACKER_MILESTONES } from "./lib/pr-meta-plan.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const USAGE = + "usage: node scripts/pr-meta.mjs [ | ] [--apply] [--json]"; + +/** @param {string} message */ +function fail(message) { + console.error(message); + process.exit(2); +} + +/** @param {string} cmd @param {string[]} args @param {{ allowFail?: boolean }} [options] */ +function run(cmd, args, options = {}) { + const result = spawnSync(cmd, args, { cwd: root, encoding: "utf8" }); + if (result.status !== 0) { + if (options.allowFail) return null; + fail(`${cmd} ${args.join(" ")} failed:\n${result.stderr.trim()}`); + } + return result.stdout.trim(); +} + +/** @param {string | null} text */ +const lines = (text) => (text ? text.split("\n").filter(Boolean) : []); + +const argv = process.argv.slice(2); +const apply = argv.includes("--apply"); +const asJson = argv.includes("--json"); +const rest = argv.filter((arg) => !arg.startsWith("--")); +if ( + rest.length > 1 || + argv.some( + (arg) => arg.startsWith("--") && arg !== "--apply" && arg !== "--json", + ) +) { + fail(USAGE); +} + +const pr = JSON.parse( + run( + "gh", + [ + "pr", + "view", + ...rest, + "--json", + "number,state,headRefName,author,closingIssuesReferences,labels,milestone,reviewRequests,latestReviews", + ], + { allowFail: true }, + ) ?? "null", +); +if (rest.length && pr?.state !== "OPEN") fail(`No open PR for ${rest[0]}.`); +const open = pr?.state === "OPEN" ? pr : null; +const branch = open?.headRefName ?? run("git", ["branch", "--show-current"]); +if (!branch) fail("No branch: check one out or name the PR."); + +run("git", ["fetch", "--quiet", "origin", "main"]); +const head = + open && branch !== run("git", ["branch", "--show-current"]) + ? `origin/${branch}` + : "HEAD"; +if (head !== "HEAD") run("git", ["fetch", "--quiet", "origin", branch]); +const base = run("git", ["merge-base", head, "origin/main"]); +const subjects = lines( + run("git", ["log", "--no-merges", "--format=%s", `${base}..${head}`]), +); +const paths = [ + ...new Set([ + ...lines( + run("git", [ + "diff", + "--name-only", + base, + ...(head === "HEAD" ? [] : [head]), + ]), + ), + ...(head === "HEAD" + ? lines(run("git", ["ls-files", "--others", "--exclude-standard"])) + : []), + ]), +]; + +const issueNumbers = open?.closingIssuesReferences?.length + ? open.closingIssuesReferences.map( + (/** @type {{ number: number }} */ issue) => issue.number, + ) + : [/^(?:[\w-]+\/)?(\d+)-/.exec(branch)?.[1]].filter(Boolean).map(Number); +const closingIssues = issueNumbers.map((number) => { + const issue = JSON.parse( + run("gh", ["issue", "view", String(number), "--json", "milestone"], { + allowFail: true, + }) ?? "{}", + ); + return { number, milestone: issue.milestone?.title ?? null }; +}); + +const trackers = Object.fromEntries( + Object.keys(TRACKER_MILESTONES) + .filter((path) => existsSync(join(root, path))) + .map((path) => [path, readFileSync(join(root, path), "utf8")]), +); + +const plan = planMeta({ + branch, + subjects, + paths, + closingIssues, + trackers, + milestones: lines( + run("gh", ["api", "repos/{owner}/{repo}/milestones", "--jq", ".[].title"]), + ), + viewer: run("gh", ["api", "user", "--jq", ".login"]) ?? "", + author: open?.author?.login ?? null, + collaborators: lines( + run("gh", [ + "api", + "repos/{owner}/{repo}/collaborators", + "--jq", + ".[].login", + ]), + ), +}); + +if (asJson && !apply) { + console.log( + JSON.stringify({ pr: open?.number ?? null, branch, ...plan }, null, 2), + ); + process.exit(0); +} + +console.log( + `${open ? `PR #${open.number}` : "No open PR"} · ${branch}${plan.storyId ? ` · ${plan.storyId}` : ""}`, +); +console.log(` labels ${plan.labels.join(", ") || "(none)"}`); +console.log( + ` milestone ${plan.milestone ?? "(none)"} from ${plan.milestoneFrom}`, +); +console.log(` reviewer ${plan.reviewers.join(", ") || "(none)"}`); + +if (!apply) process.exit(0); +if (!open) + fail("--apply needs an open PR. Open it first, then run this again."); + +const hasLabels = new Set( + open.labels.map((/** @type {{ name: string }} */ label) => label.name), +); +const addLabels = plan.labels.filter((label) => !hasLabels.has(label)); +/* Someone already asked, or who already reviewed, is not asked again. */ +const requested = new Set([ + ...open.reviewRequests.map( + (/** @type {{ login?: string, name?: string }} */ r) => r.login ?? r.name, + ), + ...open.latestReviews.map( + (/** @type {{ author: { login: string } }} */ r) => r.author.login, + ), +]); +const addReviewers = plan.reviewers.filter((login) => !requested.has(login)); +const current = open.milestone?.title ?? null; +const setMilestone = plan.milestone && !current ? plan.milestone : null; + +const args = ["pr", "edit", String(open.number)]; +if (addLabels.length) args.push("--add-label", addLabels.join(",")); +if (setMilestone) args.push("--milestone", setMilestone); +if (addReviewers.length) args.push("--add-reviewer", addReviewers.join(",")); +if (args.length > 3) run("gh", args); + +console.log( + `Applied: ${addLabels.length ? `labels ${addLabels.join(", ")}` : "no new labels"}; ` + + `${setMilestone ? `milestone ${setMilestone}` : current ? `milestone kept (${current})` : "no milestone"}; ` + + `${addReviewers.length ? `reviewer ${addReviewers.join(", ")}` : "reviewer already asked"}.`, +); +if (current && plan.milestone && current !== plan.milestone) { + console.log( + ` Note: the PR's milestone is ${current}; the plan says ${plan.milestone}. Left as it is.`, + ); +} From e232372dec3eba4c88fcdcd6b2fd8566f2614d11 Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Sun, 8 Nov 2026 18:50:26 +0200 Subject: [PATCH 2/3] fix(agents): review fixes for PR labels and the main merge (#482) - AGENTS.md, CLAUDE.md and the inline pipeline name the two standing instructions as the only exceptions to the git rule. - finalizer merges `origin/main` as its first step, before it edits the READMEs or the tracker, so git does not refuse the merge. - Every root tooling file, all of `.github/` outside workflows and `.vscode/` get `gmt monorepo`; `docs/` and every LICENSE get `documentation`. A test checks that every tracked path gets a label, except a changeset entry. - pr-meta treats only gh's own not-found answers as no PR or no issue; any other gh failure stops with gh's message. --- .agents/finalizer.md | 18 ++++--- .agents/skills/pipeline/SKILL.md | 2 +- .../skills/pipeline/references/inline-mode.md | 6 ++- AGENTS.md | 10 ++-- CLAUDE.md | 4 ++ apps/dox/scripts/pr-meta/plan.test.ts | 50 ++++++++++++++++++- scripts/lib/pr-meta-plan.mjs | 8 ++- scripts/pr-meta.mjs | 20 ++++++-- 8 files changed, 97 insertions(+), 21 deletions(-) diff --git a/.agents/finalizer.md b/.agents/finalizer.md index 50f0f25c0..6d57a58e2 100644 --- a/.agents/finalizer.md +++ b/.agents/finalizer.md @@ -13,7 +13,7 @@ You are the Finalizer for the `@northguild/gmt` project. You close stories by ha **Temporal type system:** Full working knowledge across all GMT types and their public string contracts. -**GMT rules:** [AGENTS.md § Core Rules](../AGENTS.md#core-rules-quick-reference) and [§ Git — Only on an Explicit Instruction](../AGENTS.md#git--only-on-an-explicit-instruction). You do not stage, commit, push, branch or open a PR unless the user asks you to. The two standing instructions there are yours to carry out: merge `origin/main` in (step 9) and label an open PR (step 11). +**GMT rules:** [AGENTS.md § Core Rules](../AGENTS.md#core-rules-quick-reference) and [§ Git — Only on an Explicit Instruction](../AGENTS.md#git--only-on-an-explicit-instruction). You do not stage, commit, push, branch or open a PR unless the user asks you to. The two standing instructions there are yours to carry out: merge `origin/main` in (step 1) and label an open PR (step 11). **Release workflow:** Deep familiarity with `PUBLISHING.md`. This agent's release output is exactly one thing: a well-written `.changeset/*.md` on the feature branch. Versioning and publishing are both `release.yml`'s job — never run `changeset version`, `npm publish`, `changeset publish`, or `gh release create`. @@ -27,7 +27,15 @@ Story closer. Called after `tdd-dev` (and optionally `tester`) complete. Produce ## Workflow -1. **Read `context/domination/tracker.md`** to identify the current story, its GitHub issue number, and its row. No release decision is yours to make — see step 12. +1. **Bring in `main`, before you edit anything.** As [AGENTS.md § Git](../AGENTS.md#git--only-on-an-explicit-instruction) + says: `git fetch origin main`, then `git merge origin/main` if the branch is behind. Resolve + each conflict so both sides' changes survive, and commit the merge (the merge only, never the + story's work). It comes first because steps 4 and 7 edit the READMEs and the tracker, which + `main` changes most often; once those are edited, git refuses the merge. If git refuses here, + the story's own uncommitted changes touch the incoming files: stop and name those files to + the main session. + + Then **read `context/domination/tracker.md`** to identify the current story, its GitHub issue number, and its row. No release decision is yours to make — see step 12. 2. **If public API surface changed:** update the TanStack Intent agent skills in `packages/gmt/skills/` (new functions, renamed functions, new options, new domain concept). See `PUBLISHING.md` contributor flow step 2. @@ -120,11 +128,7 @@ Story closer. Called after `tdd-dev` (and optionally `tester`) complete. Produce - Report each item to the main session, so the fix loops back through `tdd-dev`. - Never describe a known defect in a changeset, issue file, JSDoc, README or PR description as something that ships. It gets fixed instead. -9. **Verify before handing off.** First bring in `main`, as [AGENTS.md § Git](../AGENTS.md#git--only-on-an-explicit-instruction) - says: `git fetch origin main`, then `git merge origin/main` if the branch is behind. Resolve - each conflict so both sides' changes survive, and commit the merge. If git refuses because the - story's uncommitted work touches the incoming files, stop and name those files to the main - session. Then `node scripts/verdict.mjs validate` must print PASS — it is the +9. **Verify before handing off.** `main` came in at step 1. `node scripts/verdict.mjs validate` must print PASS — it is the epic's Definition of Done. It runs the same checks as `pnpm run validate`: every check that reads a file the branch changed, against `origin/main`, one row each; `--full` runs them all. Do not report a story closed on a run that stopped early. diff --git a/.agents/skills/pipeline/SKILL.md b/.agents/skills/pipeline/SKILL.md index 6cb563c0f..641fb7c50 100644 --- a/.agents/skills/pipeline/SKILL.md +++ b/.agents/skills/pipeline/SKILL.md @@ -101,7 +101,7 @@ disputed reading of a standard. Say so in the report. The agent files' defaults 4. **Escalate blockers** — an ambiguous spec, a design conflict, tests that cannot pass: stop and report to the user with full context. No step fails or is skipped silently. 5. **Nothing is committed** but a merge from `main`. Bring `origin/main` in when the story starts - and again before `finalizer` ([AGENTS.md § Git](../../../AGENTS.md#git--only-on-an-explicit-instruction) + and again as `finalizer`'s first step ([AGENTS.md § Git](../../../AGENTS.md#git--only-on-an-explicit-instruction) has the two standing instructions); `finalizer` labels an open PR with `scripts/pr-meta.mjs`. The pipeline ends with unstaged changes plus drafted commit and PR text for the owner. Never run `changeset version`, `changeset publish`, `npm publish` or diff --git a/.agents/skills/pipeline/references/inline-mode.md b/.agents/skills/pipeline/references/inline-mode.md index a0a823573..b937cd75c 100644 --- a/.agents/skills/pipeline/references/inline-mode.md +++ b/.agents/skills/pipeline/references/inline-mode.md @@ -40,11 +40,13 @@ finding is open, return to Step 2 with the list. ## Step 4 — Story closure -Adopt the [`finalizer`](../../../finalizer.md) role and follow its workflow: skills, changeset +Adopt the [`finalizer`](../../../finalizer.md) role and follow its workflow: merge `origin/main` +in first and commit that merge (a standing instruction in +[AGENTS.md § Git](../../../../AGENTS.md#git--only-on-an-explicit-instruction)), then skills, changeset (per the [changeset rule](../../../../context/coding-standards.md#changesets)), READMEs, dox corpus and stats, tracker `Status` + `pnpm deps:sync`, `pnpm run validate`. Draft a commit message with `/commit-message` and a PR description with `/pr-desc` **for the owner to use** — -never commit or open the PR. +never commit the story's work or open the PR. ## Context files per role diff --git a/AGENTS.md b/AGENTS.md index 0a846a1eb..5b7f47f7a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,13 +26,14 @@ Read these before working in the repo. Each is scoped — load only what you nee **The default is always: finish the work, leave it unstaged in the working tree, and say it is ready.** Do not stage, commit, branch, push or open a pull request on your own initiative — not as a checkpoint, not "so nothing is lost", not -because the work looks finished. +because the work looks finished. The only exceptions are the two standing +instructions at the end of this section. **Do them when the user tells you to, in plain words, in the current session.** "Commit this", "push the branch", "open the PR" are instructions: carry them out and report what you did. An instruction covers the operation it names for the work in hand. It is not a standing licence — a later, separate write needs its -own instruction. Typing a skill whose job is one of these operations is the +own instruction, unless it is one of the two standing instructions below. Typing a skill whose job is one of these operations is the instruction for that run: `/release` commits, pushes and opens its release PR. **Never infer the permission.** It has to come from the user, about this @@ -60,8 +61,9 @@ ask in plain words. **Two standing instructions from the owner.** These need no new word each time: -- **Keep the branch up to date with `main`.** Do this when work on a branch starts, before - `finalizer` runs `validate`, and before any push. Run `git fetch origin main`, then +- **Keep the branch up to date with `main`.** Do this when work on a branch starts, as + `finalizer`'s first step (before it edits the READMEs or the tracker), and before any push. + Commit the merge only, never the story's own work. Run `git fetch origin main`, then `git merge origin/main` when the branch is behind. Never rebase, because the branch is published. Resolve every conflict so both sides' changes survive, run `node scripts/verdict.mjs validate`, and commit the merge. If uncommitted work touches the diff --git a/CLAUDE.md b/CLAUDE.md index f5e26db58..7261ad479 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,6 +10,10 @@ Copyright (c) 2026 NorthGuild. All rights reserved under [`.agents/LICENSE`](.ag initiative.** Finish the work, leave it **unstaged in the working tree**, and say it is ready. +**Two standing exceptions** need no new word each time: merge `origin/main` into +the branch and commit that merge (never the story's work, and never push it), and +run `node scripts/pr-meta.mjs --apply` on an open PR. AGENTS.md § Git says when. + **Do it when the user explicitly tells you to** — "commit this", "push it", "open the PR" — in plain words, in this session. Then do it and report back. diff --git a/apps/dox/scripts/pr-meta/plan.test.ts b/apps/dox/scripts/pr-meta/plan.test.ts index 7da209f4b..3b44222e9 100644 --- a/apps/dox/scripts/pr-meta/plan.test.ts +++ b/apps/dox/scripts/pr-meta/plan.test.ts @@ -1,6 +1,13 @@ +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + import { describe, expect, it } from "vitest"; -import { planMeta, storyIdOf } from "../../../../scripts/lib/pr-meta-plan.mjs"; +import { + PATH_RULES, + planMeta, + storyIdOf, +} from "../../../../scripts/lib/pr-meta-plan.mjs"; /** The pure planner behind `scripts/pr-meta.mjs`. Branches and paths are from merged northguild/gmt PRs. */ @@ -92,6 +99,47 @@ describe("planMeta labels", () => { ).toEqual(["gmt monorepo"]); }); + it.each([ + ["oxlint.config.mts", "gmt monorepo"], + [".fallowrc.jsonc", "gmt monorepo"], + [".node-version", "gmt monorepo"], + ["pyproject.toml", "gmt monorepo"], + ["uv.lock", "gmt monorepo"], + ["skills-lock.json", "gmt monorepo"], + ["context7.json", "gmt monorepo"], + [".vscode/settings.json", "gmt monorepo"], + [".github/ISSUE_TEMPLATE/bug.yml", "gmt monorepo"], + [".github/PULL_REQUEST_TEMPLATE.md", "gmt monorepo"], + [".changeset/config.json", "gmt monorepo"], + ["docs/dst-disambiguation.md", "documentation"], + ["LICENSE", "documentation"], + ["apps/LICENSE", "documentation"], + ])("labels %s alone %s", (path, label) => { + expect(planMeta(facts({ paths: [path] })).labels).toEqual([label]); + }); + + it("gives every tracked path a label, except a changeset entry", () => { + const tracked = execFileSync("git", ["ls-files"], { + cwd: fileURLToPath(new URL("../../../..", import.meta.url)), + encoding: "utf8", + }) + .split("\n") + .filter(Boolean); + const unlabelled = tracked.filter( + (path) => + !PATH_RULES.some((rule) => rule.test.test(path)) && + !/^\.changeset\/(?!config\.json$|README\.md$)[^/]+\.md$/.test(path), + ); + expect(tracked.length).toBeGreaterThan(1000); + expect(unlabelled).toEqual([]); + }); + + it("gives a changeset entry no label of its own", () => { + expect( + planMeta(facts({ paths: [".changeset/tai64n-text-labels.md"] })).labels, + ).toEqual([]); + }); + it("gives a fix bug, and a breaking feat! enhancement", () => { expect( planMeta(facts({ subjects: ["fix(dox): one option per unit"] })).labels, diff --git a/scripts/lib/pr-meta-plan.mjs b/scripts/lib/pr-meta-plan.mjs index 6355f02b5..dbd2da84d 100644 --- a/scripts/lib/pr-meta-plan.mjs +++ b/scripts/lib/pr-meta-plan.mjs @@ -10,6 +10,9 @@ * Path rules: a changed path adds every label whose test it matches. Status and workflow labels * (`parked`, `ready to build`, `waiting: *`, `canary`, `dox-gate`, `craig-review`) are a person's * call or a workflow's, so no rule adds them. + * + * Every tracked path matches at least one rule (`plan.test.ts` checks `git ls-files`), except a + * changeset entry (`.changeset/.md`): it rides with the package change that labels the PR. * @type {ReadonlyArray<{ label: string, test: RegExp }>} */ export const PATH_RULES = [ @@ -24,12 +27,13 @@ export const PATH_RULES = [ test: /^(?:\.agents\/|\.claude\/|AGENTS\.md$|CLAUDE\.md$|context\/skills\.md$)/, }, { + /* Every root file that is not a document or an agent file is tooling. */ label: "gmt monorepo", - test: /^(?:scripts\/|apps\/dox\/scripts\/|package\.json$|pnpm-(?:lock|workspace)\.yaml$|\.worktree\.yml$|\.oxfmtrc\.json$|\.gitignore$|tsconfig[\w.]*\.json$|vitest[\w.]*\.[cm]?ts$|\.github\/renovate\.json5$)/, + test: /^(?:scripts\/|apps\/dox\/scripts\/|\.github\/(?!workflows\/)|\.vscode\/|\.changeset\/(?:config\.json|README\.md)$|(?!(?:AGENTS|CLAUDE|CONTRIBUTING|PUBLISHING|README|SECURITY)\.md$|LICENSE$)[^/]+$)/, }, { label: "documentation", - test: /^(?:context\/(?!skills\.md$)|apps\/dox\/(?!scripts\/)|README\.md$|CONTRIBUTING\.md$|PUBLISHING\.md$|SECURITY\.md$|packages\/[\w-]+\/README\.md$)/, + test: /^(?:context\/(?!skills\.md$)|apps\/dox\/(?!scripts\/)|docs\/|README\.md$|CONTRIBUTING\.md$|PUBLISHING\.md$|SECURITY\.md$|(?:[^/]+\/)*LICENSE$|packages\/[\w-]+\/README\.md$)/, }, ]; diff --git a/scripts/pr-meta.mjs b/scripts/pr-meta.mjs index 4a202e89f..d8591c83e 100644 --- a/scripts/pr-meta.mjs +++ b/scripts/pr-meta.mjs @@ -34,11 +34,23 @@ function fail(message) { process.exit(2); } -/** @param {string} cmd @param {string[]} args @param {{ allowFail?: boolean }} [options] */ +/** + * `gh`'s own "does not exist" answers. Any other failure (a bad token, no network, a rate limit) + * stops the script with `gh`'s message, so it never reads as "no open PR" or "no milestone". + */ +const NO_PR = + /no pull requests found for branch|Could not resolve to a PullRequest/; +const NO_ISSUE = /Could not resolve to an issue or pull request/; + +/** + * Runs a command and returns its trimmed stdout. A failure whose stderr matches `notFound` + * returns null; any other failure stops the script. + * @param {string} cmd @param {string[]} args @param {{ notFound?: RegExp }} [options] + */ function run(cmd, args, options = {}) { const result = spawnSync(cmd, args, { cwd: root, encoding: "utf8" }); if (result.status !== 0) { - if (options.allowFail) return null; + if (options.notFound?.test(result.stderr)) return null; fail(`${cmd} ${args.join(" ")} failed:\n${result.stderr.trim()}`); } return result.stdout.trim(); @@ -70,7 +82,7 @@ const pr = JSON.parse( "--json", "number,state,headRefName,author,closingIssuesReferences,labels,milestone,reviewRequests,latestReviews", ], - { allowFail: true }, + { notFound: NO_PR }, ) ?? "null", ); if (rest.length && pr?.state !== "OPEN") fail(`No open PR for ${rest[0]}.`); @@ -112,7 +124,7 @@ const issueNumbers = open?.closingIssuesReferences?.length const closingIssues = issueNumbers.map((number) => { const issue = JSON.parse( run("gh", ["issue", "view", String(number), "--json", "milestone"], { - allowFail: true, + notFound: NO_ISSUE, }) ?? "{}", ); return { number, milestone: issue.milestone?.title ?? null }; From 319f8015ceda02e25de9ea86253596fe3391dc31 Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Sun, 8 Nov 2026 19:20:53 +0200 Subject: [PATCH 3/3] fix(agents): the finalizer commits its first-step merge without validate (#482) At the finalizer's first step the story's published figures are not synced yet (step 4), so `validate` fails on any story with new tests for a reason the merge did not cause. The finalizer now commits the resolved merge without it; step 9's `validate` checks the merged tree. The other merges (work starting on a branch, before a push) still run `validate` first. --- .agents/finalizer.md | 4 +++- AGENTS.md | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.agents/finalizer.md b/.agents/finalizer.md index 6d57a58e2..321254a5d 100644 --- a/.agents/finalizer.md +++ b/.agents/finalizer.md @@ -30,7 +30,9 @@ Story closer. Called after `tdd-dev` (and optionally `tester`) complete. Produce 1. **Bring in `main`, before you edit anything.** As [AGENTS.md § Git](../AGENTS.md#git--only-on-an-explicit-instruction) says: `git fetch origin main`, then `git merge origin/main` if the branch is behind. Resolve each conflict so both sides' changes survive, and commit the merge (the merge only, never the - story's work). It comes first because steps 4 and 7 edit the READMEs and the tracker, which + story's work). Do not run `validate` before this commit: the published figures are synced + only at step 4 (`pnpm stats:sync`), so on a story with new tests `stats check` fails here for + a reason the merge did not cause. Step 9's `validate` checks the merged tree. The merge comes first because steps 4 and 7 edit the READMEs and the tracker, which `main` changes most often; once those are edited, git refuses the merge. If git refuses here, the story's own uncommitted changes touch the incoming files: stop and name those files to the main session. diff --git a/AGENTS.md b/AGENTS.md index 5b7f47f7a..481455d36 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,10 @@ ask in plain words. Commit the merge only, never the story's own work. Run `git fetch origin main`, then `git merge origin/main` when the branch is behind. Never rebase, because the branch is published. Resolve every conflict so both sides' changes survive, run - `node scripts/verdict.mjs validate`, and commit the merge. If uncommitted work touches the + `node scripts/verdict.mjs validate`, and commit the merge. At `finalizer`'s first step, commit + the resolved merge without `validate`: the story's published figures are synced only at its + step 4, so `validate` would fail for a reason the merge did not cause, and its step 9 runs + `validate` on the merged tree before hand-off. If uncommitted work touches the incoming files, git refuses the merge. Do not stash (the stash is shared): name the files to the owner and merge once the work is committed. Pushing the merge still needs the owner's word. On an open PR, `gh pr view --json mergeable` shows whether GitHub sees a conflict.