rungate 0.8.16 → 0.8.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,260 @@
1
+ /**
2
+ * The human steps a scaffold cannot take, printed as one command each —
3
+ * #2051, ADR-014 row 6, SC-2749.
4
+ *
5
+ * The scaffold writes files. Three things the process needs are settings on
6
+ * GitHub that only a person with the right access can make, and nothing told
7
+ * a consumer they were owed:
8
+ *
9
+ * 1. the `RUNGATE_PROJECT_TOKEN` secret — every board step refuses without it;
10
+ * 2. the `RUNGATE_REQUIRE_CLOSING_REF` variable set to `true` — without it
11
+ * `closing-references` warns instead of refusing;
12
+ * 3. every process check that runs on pull requests but is not REQUIRED on
13
+ * the default branch — a check nobody requires blocks nothing.
14
+ *
15
+ * Each is read where the API allows it. A reading that could not be taken is
16
+ * printed `UNMEASURED` with why, never folded into "nothing owed", and the
17
+ * all-clear names what it measured rather than saying "done".
18
+ */
19
+ import { spawnSync } from "child_process";
20
+ import { readFileSync, statSync } from "fs";
21
+ import { join } from "path";
22
+
23
+ import { createGitHubClient, parseOwnerRepo } from "../github";
24
+ import { githubProtectionProbe, jobContextNames, type ProtectionFacts, type ProtectionProbe } from "../branch-protection";
25
+ import { parseRemoteSlug } from "../verified-push";
26
+
27
+ export type Reading<T> = { kind: "READ"; value: T } | { kind: "UNMEASURED"; why: string };
28
+
29
+ export const PROJECT_TOKEN_SECRET = "RUNGATE_PROJECT_TOKEN";
30
+ export const REQUIRE_CLOSING_REF_VARIABLE = "RUNGATE_REQUIRE_CLOSING_REF";
31
+
32
+ /** The process workflows whose jobs report a status on pull requests (ADR-014 decision 6's scope). */
33
+ export const PROCESS_CHECK_WORKFLOWS = ["closing-references.yml"] as const;
34
+
35
+ export interface HumanStepReadings {
36
+ /** `owner/name`, or null when the origin remote names no GitHub repository. */
37
+ slug: string | null;
38
+ secretPresent: Reading<boolean>;
39
+ /** The variable's value, or null when it is not set. */
40
+ requireClosingRef: Reading<string | null>;
41
+ /** The default branch, its required status checks, and which protection state it is in. */
42
+ protection: Reading<{ branch: string; contexts: string[]; statusChecks: NonNullable<ProtectionFacts["statusChecks"]> }>;
43
+ /** Job names of the process checks this tree's workflows define. */
44
+ processChecks: string[];
45
+ /** Process workflows present but unreadable, each with why (#2161). */
46
+ unreadableWorkflows: string[];
47
+ }
48
+
49
+ /** One line per step owed or unread, then a line saying what was measured. Pure. */
50
+ export function humanSteps(r: HumanStepReadings): string[] {
51
+ const unreadWorkflows = r.unreadableWorkflows.map(why => `UNMEASURED: process checks — ${why}`);
52
+ if (r.slug === null) {
53
+ return [
54
+ "UNMEASURED: human steps — the origin remote names no GitHub repository, so the project token, " +
55
+ `${REQUIRE_CLOSING_REF_VARIABLE} and the required checks were not read.`,
56
+ // Read from the tree, not from GitHub, so it is owed whatever the remote is.
57
+ ...unreadWorkflows,
58
+ ];
59
+ }
60
+ const out: string[] = [];
61
+ const measured: string[] = [];
62
+ if (r.secretPresent.kind === "UNMEASURED") out.push(`UNMEASURED: ${PROJECT_TOKEN_SECRET} — ${r.secretPresent.why}`);
63
+ else if (!r.secretPresent.value) {
64
+ out.push(
65
+ `OWED: gh secret set ${PROJECT_TOKEN_SECRET} -R ${r.slug} # a token that can write the project board; every board step refuses without it`,
66
+ );
67
+ } else measured.push(`${PROJECT_TOKEN_SECRET} is set`);
68
+
69
+ if (r.requireClosingRef.kind === "UNMEASURED") {
70
+ out.push(`UNMEASURED: ${REQUIRE_CLOSING_REF_VARIABLE} — ${r.requireClosingRef.why}`);
71
+ } else if (r.requireClosingRef.value !== "true") {
72
+ out.push(
73
+ `OWED: gh variable set ${REQUIRE_CLOSING_REF_VARIABLE} -R ${r.slug} --body true # closing-references refuses instead of warning`,
74
+ );
75
+ } else measured.push(`${REQUIRE_CLOSING_REF_VARIABLE} is true`);
76
+
77
+ out.push(...unreadWorkflows);
78
+
79
+ if (r.processChecks.length > 0) {
80
+ if (r.protection.kind === "UNMEASURED") {
81
+ out.push(`UNMEASURED: required checks (${r.processChecks.join(", ")}) — ${r.protection.why}`);
82
+ } else {
83
+ const { branch, contexts, statusChecks } = r.protection.value;
84
+ const missing = r.processChecks.filter(c => !contexts.includes(c));
85
+ if (missing.length > 0 && statusChecks === "required-checks") {
86
+ for (const check of missing) {
87
+ out.push(
88
+ `OWED: gh api -X POST repos/${r.slug}/branches/${branch}/protection/required_status_checks/contexts ` +
89
+ `-f 'contexts[]=${check}' # ${check} runs on every pull request and blocks nothing until it is required`,
90
+ );
91
+ }
92
+ } else if (missing.length > 0 && statusChecks === "unprotected") {
93
+ // PUT replaces the whole rule, which is safe only because there is no
94
+ // rule yet: it protects the branch and requires the missing checks.
95
+ const body = {
96
+ required_status_checks: { strict: false, contexts: missing },
97
+ enforce_admins: null,
98
+ required_pull_request_reviews: null,
99
+ restrictions: null,
100
+ };
101
+ out.push(
102
+ `OWED: gh api -X PUT repos/${r.slug}/branches/${branch}/protection --input - <<<'${JSON.stringify(body)}'` +
103
+ ` # ${branch} is unprotected; this protects it and requires ${missing.join(", ")}, nothing else`,
104
+ );
105
+ } else if (missing.length > 0) {
106
+ // Protected with no required checks: the POST above 404s here and a
107
+ // PUT would replace the rule's other settings, so no single call is safe.
108
+ out.push(
109
+ `OWED: require ${missing.join(", ")} on ${branch} — in the repository's Settings → Branches, edit the rule ` +
110
+ `for ${branch}, turn on "Require status checks to pass" and add ${missing.join(", ")}` +
111
+ ` # no single API call adds a check here without replacing the rest of the rule`,
112
+ );
113
+ }
114
+ const required = r.processChecks.filter(c => contexts.includes(c));
115
+ if (required.length > 0) measured.push(`${required.join(", ")} required on ${branch}`);
116
+ }
117
+ }
118
+
119
+ if (out.length === 0) out.push(`Human steps: none owed — measured: ${measured.join("; ")}.`);
120
+ return out;
121
+ }
122
+
123
+ /**
124
+ * The job names of the process checks present in `root`'s workflows, and the
125
+ * workflows that are present but could not be read (#2161). A directory, a
126
+ * permission error or a file removed between the two calls throws on read;
127
+ * that is a reading not taken, never a crash and never "nothing owed".
128
+ */
129
+ export function processChecksIn(root: string): { checks: string[]; unreadable: string[] } {
130
+ const checks: string[] = [];
131
+ const unreadable: string[] = [];
132
+ for (const file of PROCESS_CHECK_WORKFLOWS) {
133
+ const rel = `.github/workflows/${file}`;
134
+ const p = join(root, ".github", "workflows", file);
135
+ // The stat decides absence, and only its ENOENT counts: existsSync also
136
+ // answers false for an untraversable directory (round 2 of PR #2162).
137
+ // The read gets its own try, so a file removed after the stat is a reading
138
+ // not taken rather than an absent workflow (round 3).
139
+ try {
140
+ statSync(p);
141
+ } catch (e) {
142
+ if ((e as NodeJS.ErrnoException)?.code === "ENOENT") continue;
143
+ unreadable.push(`${rel} could not be read (${(e as Error).message})`);
144
+ continue;
145
+ }
146
+ try {
147
+ checks.push(...jobContextNames(readFileSync(p, "utf-8")));
148
+ } catch (e) {
149
+ unreadable.push(`${rel} could not be read (${(e as Error).message})`);
150
+ }
151
+ }
152
+ return { checks, unreadable };
153
+ }
154
+
155
+ /**
156
+ * `owner/name` when `url` is a github.com remote, else `null` (#2161).
157
+ *
158
+ * The GitHub client only ever talks to github.com (`lib/github.ts` refuses
159
+ * any other API host), so a remote on another forge has no settings this
160
+ * module can read. `parseRemoteSlug` deliberately ignores the host, because
161
+ * repo identity is its question; which forge to ask is this one's.
162
+ */
163
+ export function githubSlugOf(url: string): string | null {
164
+ const trimmed = url.trim();
165
+ if (!trimmed) return null;
166
+ let host: string | null = null;
167
+ if (/^[a-z+]+:\/\//i.test(trimmed)) {
168
+ try {
169
+ host = new URL(trimmed).hostname;
170
+ } catch {
171
+ return null; // not a URL at all, so it names no GitHub repository
172
+ }
173
+ } else {
174
+ host = trimmed.match(/^(?:[^@/]+@)?([^:/]+):/)?.[1] ?? null;
175
+ }
176
+ return host?.toLowerCase() === "github.com" ? parseRemoteSlug(trimmed) : null;
177
+ }
178
+
179
+ /** The configured `origin` url of `root`, or "" when there is none. */
180
+ function originUrl(root: string): string {
181
+ const r = spawnSync("git", ["config", "--get", "remote.origin.url"], { cwd: root, encoding: "utf-8", timeout: 5000 });
182
+ return r.status === 0 ? r.stdout : "";
183
+ }
184
+
185
+ export interface HumanStepProbes {
186
+ slug: (root: string) => string | null;
187
+ secret: (slug: string) => Promise<Reading<boolean>>;
188
+ variable: (slug: string) => Promise<Reading<string | null>>;
189
+ protection: ProtectionProbe;
190
+ }
191
+
192
+ /** The same bound the protection probe puts on each GET: a hung socket is UNMEASURED, never a hung scaffold. */
193
+ export const PROBE_TIMEOUT_MS = 15_000;
194
+
195
+ /** `p`, or a rejection naming `what` after `ms`. The rejection carries no status, so it reads UNMEASURED. */
196
+ export function timed<T>(p: Promise<T>, what: string, ms: number = PROBE_TIMEOUT_MS): Promise<T> {
197
+ let timer: ReturnType<typeof setTimeout> | undefined;
198
+ const deadline = new Promise<never>((_, reject) => {
199
+ timer = setTimeout(() => reject(new Error(`${what} did not answer within ${ms}ms`)), ms);
200
+ timer.unref?.();
201
+ });
202
+ return Promise.race([p, deadline]).finally(() => clearTimeout(timer));
203
+ }
204
+
205
+ const status = (e: unknown) => (e as { status?: unknown })?.status;
206
+ const why = (e: unknown) => `${typeof status(e) === "number" ? `HTTP ${status(e)}: ` : ""}${(e as Error)?.message ?? e}`;
207
+
208
+ /** The live reads: two GETs here, three in the protection probe. No writes. */
209
+ export const LIVE_PROBES: HumanStepProbes = {
210
+ slug: root => githubSlugOf(originUrl(root)),
211
+ secret: async slug => {
212
+ try {
213
+ const { owner, repo } = parseOwnerRepo(slug);
214
+ await timed(
215
+ createGitHubClient().rest.actions.getRepoSecret({ owner, repo, secret_name: PROJECT_TOKEN_SECRET }),
216
+ `GET the ${PROJECT_TOKEN_SECRET} secret`,
217
+ );
218
+ return { kind: "READ", value: true };
219
+ } catch (e) {
220
+ // 404 is the documented answer for an absent secret; anything else —
221
+ // no credential, 403 for a token without admin — is not a reading.
222
+ return status(e) === 404 ? { kind: "READ", value: false } : { kind: "UNMEASURED", why: why(e) };
223
+ }
224
+ },
225
+ variable: async slug => {
226
+ try {
227
+ const { owner, repo } = parseOwnerRepo(slug);
228
+ const r = await timed(
229
+ createGitHubClient().rest.actions.getRepoVariable({ owner, repo, name: REQUIRE_CLOSING_REF_VARIABLE }),
230
+ `GET the ${REQUIRE_CLOSING_REF_VARIABLE} variable`,
231
+ );
232
+ return { kind: "READ", value: String(r.data?.value ?? "") };
233
+ } catch (e) {
234
+ return status(e) === 404 ? { kind: "READ", value: null } : { kind: "UNMEASURED", why: why(e) };
235
+ }
236
+ },
237
+ protection: githubProtectionProbe,
238
+ };
239
+
240
+ /** Read everything {@link humanSteps} needs for `root`. */
241
+ export async function readHumanSteps(root: string, probes: HumanStepProbes = LIVE_PROBES): Promise<HumanStepReadings> {
242
+ const slug = probes.slug(root);
243
+ const { checks: processChecks, unreadable: unreadableWorkflows } = processChecksIn(root);
244
+ if (slug === null) {
245
+ const none = { kind: "UNMEASURED", why: "no repository" } as const;
246
+ return { slug, secretPresent: none, requireClosingRef: none, protection: none, processChecks, unreadableWorkflows };
247
+ }
248
+ const [secretPresent, requireClosingRef, facts] = await Promise.all([
249
+ probes.secret(slug),
250
+ probes.variable(slug),
251
+ probes.protection(slug),
252
+ ]);
253
+ const protection: HumanStepReadings["protection"] =
254
+ facts.unreadable || facts.branch === null
255
+ ? { kind: "UNMEASURED", why: facts.unreadable ?? "the default branch could not be read" }
256
+ : facts.statusChecks === undefined
257
+ ? { kind: "UNMEASURED", why: "the protection probe did not say whether the branch is protected" }
258
+ : { kind: "READ", value: { branch: facts.branch, contexts: facts.contexts, statusChecks: facts.statusChecks } };
259
+ return { slug, secretPresent, requireClosingRef, protection, processChecks, unreadableWorkflows };
260
+ }
@@ -170,6 +170,26 @@ export const OWNED_FILES: OwnedFile[] = [
170
170
  customize: "Set `ci.runner` in `.claude/rungate/config.json`; add your own jobs alongside the generated `record-unmeasured` job",
171
171
  avoid: "Don't edit the generated `record-unmeasured` job, and don't give it a `merge_group` trigger — it reports no status to the pull request and cannot be a required check",
172
172
  },
173
+ {
174
+ // #2046, ADR-014 row 3. Hand-written and caller-owned until ADR-013
175
+ // rule 9 made placing an accepted plan every consumer's step; declared
176
+ // the moment the generator learned to write it, for #631's reason above.
177
+ path: ".github/workflows/adr-accepted.yml",
178
+ strategy: "job-preserving",
179
+ servedBy: "writeManagedFile (lib/scaffold/steps.ts) via mergeManagedWorkflow — the harness owns named jobs, not the file",
180
+ customize: "Set `board.engineSpec` and `board.milestonePrefix` in `.claude/rungate/config.json` and re-scaffold; add your own jobs alongside the generated `place-the-plan` job",
181
+ avoid: "Don't edit the generated `place-the-plan` job",
182
+ },
183
+ {
184
+ // #2045, ADR-014 row 2. Hand-written and NOT-OWNED until ADR-013 rule 9
185
+ // made the check every consumer's policy; declared the moment the
186
+ // generator learned to write it, for #631's reason above.
187
+ path: ".github/workflows/closing-references.yml",
188
+ strategy: "job-preserving",
189
+ servedBy: "writeManagedFile (lib/scaffold/steps.ts) via mergeManagedWorkflow — the harness owns named jobs, not the file",
190
+ customize: "Set the `RUNGATE_REQUIRE_CLOSING_REF` variable to `true` to refuse, not warn, and require the check; add your own jobs alongside the generated `closing-references` job",
191
+ avoid: "Don't edit the generated `closing-references` job",
192
+ },
173
193
  {
174
194
  // `regenerate` until #655, and the declaration was never consulted:
175
195
  // `generateAgentBriefsStep` called `writeFileSync` directly, so the row
@@ -183,6 +203,23 @@ export const OWNED_FILES: OwnedFile[] = [
183
203
  avoid: "Don't hand-edit the generated sections — a re-scaffold rewrites them without reporting it",
184
204
  sections: BRIEF_CONSTRAINTS_SECTION,
185
205
  },
206
+ {
207
+ // #2048, ADR-014 row 5: step 2's command. A provenance file like a rule,
208
+ // because a consumer may tailor it; a hand edit is preserved and reported.
209
+ path: ".claude/commands/dry-run.md",
210
+ strategy: "provenance",
211
+ servedBy: "writeProcessFiles (lib/scaffold/write-steps.ts) via decideRuleWrite — the rule-provenance decision",
212
+ customize: "Edit freely — a hand-edited command is preserved and reported",
213
+ avoid: "Don't delete its `generated-sha` marker, or edits stop surviving",
214
+ },
215
+ {
216
+ // #2048, ADR-014 row 5: step 2's template. Regenerated with no marker,
217
+ // because every ADR is copied from it and a marker would travel into each.
218
+ path: "docs/adr/TEMPLATE.md",
219
+ strategy: "regenerate",
220
+ customize: "Copy it to docs/adr/ADR-<n>-<slug>.md and edit the copy",
221
+ avoid: "Don't edit the template itself — a re-scaffold rewrites it",
222
+ },
186
223
  {
187
224
  path: ".claude/rules/*.md",
188
225
  strategy: "provenance",
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The dry-run command and the ADR template, written by the scaffold — #2048,
3
+ * ADR-014 row 5, SC-2746.
4
+ *
5
+ * Step 2 of the four-step process is "an ADR from `docs/adr/TEMPLATE.md` …
6
+ * `/dry-run` until the owner agrees", and a consumer had neither file: the
7
+ * scaffold created `docs/adr/` empty and installed no `.claude/commands/`.
8
+ * Both are rendered from `templates/process/`, and this repository's copies
9
+ * are the rendered ones.
10
+ *
11
+ * Two differences between a consumer's copy and ours, both in the command:
12
+ *
13
+ * - **The CLI.** `bunx rungate <command>` in a consumer, `bun bin/rungate.ts`
14
+ * here — the switch `commands-routing.md` already makes.
15
+ * - **What Ready holds now.** This repository reads it with
16
+ * `scripts/work-status.ts`, which is not a published command; a consumer
17
+ * reads it with `board-ready --top-up` and no `--write`, which changes
18
+ * nothing and prints what a top-up would move.
19
+ */
20
+ import { existsSync, readFileSync } from "fs";
21
+ import { join } from "path";
22
+
23
+ export const DRY_RUN_COMMAND_PATH = ".claude/commands/dry-run.md";
24
+ export const ADR_TEMPLATE_PATH = "docs/adr/TEMPLATE.md";
25
+
26
+ /** Where the two sources ship. `templates/` is in `package.json` `files[]`. */
27
+ export const PROCESS_TEMPLATES_DIR = join(import.meta.dir, "..", "..", "templates", "process");
28
+
29
+ const TOKEN = 'env -u GH_TOKEN GITHUB_TOKEN="$(env -u GH_TOKEN gh auth token)"';
30
+
31
+ const READY_NOW = {
32
+ harness: ` - what Ready holds now: \`${TOKEN} bun scripts/work-status.ts\` (START HERE section only)`,
33
+ consumer:
34
+ " - what Ready holds now, and what a top-up would move into it (read-only as written): " +
35
+ '`env -u GH_TOKEN BOARD_PROJECT_TOKEN="$(env -u GH_TOKEN gh auth token)" bunx rungate board-ready ' +
36
+ "--repo <owner/name> --project <board id> --actor \"$(env -u GH_TOKEN gh api user -q .login)\" --top-up`",
37
+ };
38
+
39
+ /** A rendered process file, or why it could not be. */
40
+ export type ProcessFile = { path: string; content: string } | { path: string; content: null; why: string };
41
+
42
+ function source(name: string, dir: string): string | null {
43
+ const p = join(dir, name);
44
+ return existsSync(p) ? readFileSync(p, "utf-8") : null;
45
+ }
46
+
47
+ /** Both files, rendered for this repository (`harness`) or a consumer. */
48
+ export function processFiles(harness: boolean, dir: string = PROCESS_TEMPLATES_DIR): ProcessFile[] {
49
+ const missing = (path: string, name: string): ProcessFile => ({
50
+ path,
51
+ content: null,
52
+ why: `templates/process/${name} is missing from this rungate installation`,
53
+ });
54
+ const command = source("dry-run.md", dir);
55
+ const template = source("adr-template.md", dir);
56
+ return [
57
+ command === null
58
+ ? missing(DRY_RUN_COMMAND_PATH, "dry-run.md")
59
+ : {
60
+ path: DRY_RUN_COMMAND_PATH,
61
+ content: command
62
+ .replaceAll("{{CLI}}", harness ? "bun bin/rungate.ts" : "bunx rungate")
63
+ .replace("{{READY_NOW}}", harness ? READY_NOW.harness : READY_NOW.consumer),
64
+ },
65
+ template === null ? missing(ADR_TEMPLATE_PATH, "adr-template.md") : { path: ADR_TEMPLATE_PATH, content: template },
66
+ ];
67
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The four-step process, as an owned rules file — #2049, ADR-014 decision 4,
3
+ * SC-2747.
4
+ *
5
+ * ADR-013 rule 9 lives in AGENTS.md's Hard Constraints, a project-owned
6
+ * section the generator preserves and never writes, so a consumer never got
7
+ * it. The scaffold now writes `.claude/rules/alignment-process.md` from the
8
+ * single source below, and this repository's own rule 9 is CHECKED against
9
+ * the same source ({@link ruleNineViolations}), so the consumer's copy and
10
+ * ours cannot drift: change a step here and AGENTS.md goes red until it
11
+ * agrees; drop a load-bearing phrase from AGENTS.md and the same check fails.
12
+ *
13
+ * ## The check is on load-bearing phrases, not bytes
14
+ *
15
+ * AGENTS.md's rule 9 says "until Jason agrees" and cites #296; a consumer's
16
+ * file cannot. So each step carries the phrases that MAKE it the step — the
17
+ * template path, the workflow, the closing keyword — and the check asks that
18
+ * each appears under the right step number, in order. A rewording is free; a
19
+ * step that loses its mechanism is not.
20
+ *
21
+ * ## Loaded at launch for a consumer, on demand here
22
+ *
23
+ * A consumer's copy carries no `paths:`, so every agent reads the process.
24
+ * This repository's copy is the same body scoped to `docs/adr/**`: AGENTS.md
25
+ * already carries rule 9 at launch, and loading it twice costs every agent
26
+ * here bytes the instruction-surface budget does not have.
27
+ */
28
+
29
+ import { NAMES_NONE } from "../board-mirror";
30
+
31
+ /** The file this module generates, under `.claude/rules/`. */
32
+ export const ALIGNMENT_PROCESS_RULE_FILE = "alignment-process.md";
33
+
34
+ export interface ProcessStep {
35
+ step: 1 | 2 | 3 | 4;
36
+ /** The step as a consumer's rules file states it. */
37
+ text: string;
38
+ /** Phrases that make it this step, each of which must appear in `text` and in AGENTS.md's rule 9 under `(step)`. */
39
+ names: readonly string[];
40
+ }
41
+
42
+ /** The one source. */
43
+ export const PROCESS_STEPS: readonly ProcessStep[] = [
44
+ {
45
+ step: 1,
46
+ text: "Agree and file one issue the same turn, naming its files.",
47
+ names: ["file one issue the same turn", "naming its files"],
48
+ },
49
+ {
50
+ step: 2,
51
+ text:
52
+ "Bigger than one issue, or a rule or gate change: an ADR from `docs/adr/TEMPLATE.md`, its criteria in " +
53
+ "the spec, and `/dry-run` until the repository owner agrees; the owner merges it.",
54
+ names: ["docs/adr/TEMPLATE.md", "/dry-run", "merges it"],
55
+ },
56
+ {
57
+ step: 3,
58
+ text: "On merge, `.github/workflows/adr-accepted.yml` places the plan on the tracker.",
59
+ names: ["adr-accepted.yml", "places the plan"],
60
+ },
61
+ {
62
+ step: 4,
63
+ text:
64
+ "Each pull request says `Fixes #N`; `closing-references` refuses one that closes no issue, or whose " +
65
+ `issue names no criterion nor \`${NAMES_NONE}\`.`,
66
+ names: ["Fixes #N", "closing-references", NAMES_NONE],
67
+ },
68
+ ];
69
+
70
+ /** What the steps do not apply to. */
71
+ export const PROCESS_EXEMPTIONS = {
72
+ text:
73
+ "Step 1 skips work that decides the issues — an ADR, a retro, a review, an audit — as its pull request " +
74
+ "closes the issue it was filed under. Step 4 skips a pull request whose files are all " +
75
+ "`project-state.json`, `PROJECT-STATE.md` and `SUCCESS.md`: the diff decides, never the branch name.",
76
+ names: [
77
+ "an ADR, a retro, a review, an audit",
78
+ "project-state.json",
79
+ "PROJECT-STATE.md",
80
+ "SUCCESS.md",
81
+ "the diff decides, never the branch name",
82
+ ],
83
+ } as const;
84
+
85
+ /** The rules file. `scoped` is this repository's copy — see the module comment. */
86
+ export function alignmentProcessRule(opts: { scoped: boolean }): string {
87
+ const paths = opts.scoped ? 'paths:\n - "docs/adr/**"\n' : "";
88
+ const steps = PROCESS_STEPS.map(s => `${s.step}. ${s.text}`).join("\n");
89
+ return `---
90
+ description: The four-step process — an agreement is not real until it is an issue
91
+ ${paths}---
92
+
93
+ ## An agreement is not real until it is an issue
94
+
95
+ ${steps}
96
+
97
+ **Exempt.** ${PROCESS_EXEMPTIONS.text}
98
+
99
+ Steps 3 and 4 are enforced: \`adr-accepted.yml\` places an accepted ADR's plan,
100
+ and \`closing-references\` is the check that refuses a pull request breaking
101
+ step 4. Steps 1 and 2 are yours.
102
+ `;
103
+ }
104
+
105
+ const flat = (s: string) => s.replace(/\s+/g, " ");
106
+
107
+ /**
108
+ * Where AGENTS.md's rule 9 disagrees with {@link PROCESS_STEPS}: each step's
109
+ * marker `(N)` must appear, in order, and each of its phrases must sit between
110
+ * its marker and the next; each exemption phrase must follow `Exempt`. An
111
+ * absent rule 9 is a violation, never an empty list.
112
+ */
113
+ export function ruleNineViolations(agentsMd: string): string[] {
114
+ const start = agentsMd.search(/^9\. \*\*/m);
115
+ if (start === -1) return ["AGENTS.md has no rule 9 (a line starting `9. **`)"];
116
+ const rest = agentsMd.slice(start);
117
+ const end = rest.search(/^10\. \*\*/m);
118
+ const rule = flat(end === -1 ? rest : rest.slice(0, end));
119
+ const out: string[] = [];
120
+ const marks = PROCESS_STEPS.map(s => rule.indexOf(`(${s.step})`));
121
+ const exempt = rule.indexOf("Exempt");
122
+ PROCESS_STEPS.forEach((s, i) => {
123
+ if (marks[i] === -1) {
124
+ out.push(`rule 9 has no step marker (${s.step})`);
125
+ return;
126
+ }
127
+ if (i > 0 && marks[i] < marks[i - 1]) out.push(`rule 9's step (${s.step}) comes before step (${s.step - 1})`);
128
+ const next = marks.slice(i + 1).find(m => m > marks[i]) ?? (exempt > marks[i] ? exempt : rule.length);
129
+ const body = rule.slice(marks[i], next);
130
+ for (const name of s.names) {
131
+ if (!body.includes(name)) out.push(`rule 9's step (${s.step}) does not say "${name}"`);
132
+ }
133
+ });
134
+ if (exempt === -1) out.push("rule 9 states no exemptions (no `Exempt`)");
135
+ else {
136
+ const tail = rule.slice(exempt);
137
+ for (const name of PROCESS_EXEMPTIONS.names) {
138
+ if (!tail.includes(name)) out.push(`rule 9's exemptions do not say "${name}"`);
139
+ }
140
+ }
141
+ return out;
142
+ }